diff --git a/.gitattributes b/.gitattributes
index 7662d38a40cfa4dbe2fb7906e65684d29901f4bb..859e7a11fffc5e7ba4b4785633573dd388bf58aa 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -4520,3 +4520,20 @@ tool_server/.venv/lib/python3.12/site-packages/transformers/generation/__pycache
tool_server/.venv/lib/python3.12/site-packages/transformers/generation/__pycache__/tf_utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
tool_server/.venv/lib/python3.12/site-packages/transformers/generation/__pycache__/utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
tool_server/.venv/lib/python3.12/site-packages/transformers/integrations/__pycache__/integration_utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/autoformer/__pycache__/modeling_autoformer.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/modeling_big_bird.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/modeling_flax_big_bird.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/bigbird_pegasus/__pycache__/modeling_bigbird_pegasus.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/modeling_conditional_detr.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/modeling_d_fine.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/modeling_deta.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/modeling_jukebox.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__pycache__/modeling_mega.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/modeling_xlm_prophetnet.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/modeling_esmfold.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/modeling_flava.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/modeling_gemma3n.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/modular_gemma3n.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/modeling_grounding_dino.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
+tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/modeling_tf_groupvit.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45988b0f0c9d33f269b810fff2bf91023bce18ca
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b60ce59f1959e421be8b745e1a4eacb1cc81edd3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/configuration_aimv2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/configuration_aimv2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22c72103fb4016a02c58de9334c1f1833976c732
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/configuration_aimv2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/modeling_aimv2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/modeling_aimv2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19d28875567215cfba501cb49c87dafc997e7123
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/modeling_aimv2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/modular_aimv2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/modular_aimv2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d060881d543bbacc85e1d760d8aadabcb148123
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aimv2/__pycache__/modular_aimv2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..460399e60b17d3cada74f50a995d93945cd46a69
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/configuration_albert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/configuration_albert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5bf51bd942dd9bb22c6249908371fc40aaa16340
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/configuration_albert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_albert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_albert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6154d1cd4a6f47f88c6fc851dc39288d5f72ca67
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_albert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_flax_albert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_flax_albert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5f5d11f46301e281d2b7c9df17c6b18f3ce1c89
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_flax_albert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_tf_albert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_tf_albert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b638db3f19e57590a2e69cb611a1f26ca2c9632c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/modeling_tf_albert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/tokenization_albert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/tokenization_albert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8e4968457b0d9e1e81d2f0ee7aa422e4d9d602b9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/tokenization_albert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/tokenization_albert_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/tokenization_albert_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5dec18bd6cc6a92a9a27e0b04850777de13bd995
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/albert/__pycache__/tokenization_albert_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..760e25db629859e4d4a5ae5ff69cf5205900430d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/configuration_align.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/configuration_align.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ac6befdcdf128dc3c4b094b4597beb95b2fad502
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/configuration_align.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/modeling_align.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/modeling_align.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1037ec758b971fd3291ab9538f57b60a81317d23
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/modeling_align.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/processing_align.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/processing_align.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2093e8bfb80e5670be06126eee544e81d7895f39
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/align/__pycache__/processing_align.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8606002fd21cf118175b98a5b6f027d1a14eb31c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/configuration_altclip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/configuration_altclip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8af7e077e074f96ef23cb5ebf26bec0251fa9f8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/configuration_altclip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/modeling_altclip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/modeling_altclip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa4c08bbd095e69e3c09fd99f40ec29eb1a1c6ae
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/modeling_altclip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/processing_altclip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/processing_altclip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f4188f1805612e823c8504d87d2021ac401b71b2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/altclip/__pycache__/processing_altclip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a52c102c644865ba077d57aa39d0f858fb961ea6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/configuration_apertus.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/configuration_apertus.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0589f4699802619538cd22f746192606733731d8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/configuration_apertus.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/modeling_apertus.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/modeling_apertus.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..38e8a6614d3ebc539859d72f720798d3c07bf088
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/modeling_apertus.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/modular_apertus.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/modular_apertus.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f2c2e4d661d210c6f9d2869ba0eb38f64b68820
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/apertus/__pycache__/modular_apertus.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e55bc5676e19c6bb3b064a9a86adc3e87ffeb134
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/configuration_arcee.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/configuration_arcee.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8297cd091e061dad80217cfbac16443dd1628f1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/configuration_arcee.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/modeling_arcee.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/modeling_arcee.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a020929e022087324122d4eb86daf9e8921572a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/modeling_arcee.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/modular_arcee.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/modular_arcee.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..97f11b15c7fe1652a8f49a97b268123cac625afd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/arcee/__pycache__/modular_arcee.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f28ae692355a088338afa7685563149d0ea2c298
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/configuration_aria.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/configuration_aria.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7cadc5c3cc1848568c06176ea730dd2c9990c16f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/configuration_aria.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/image_processing_aria.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/image_processing_aria.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dfe394adaec9eb968138e2165b8321f364119339
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/image_processing_aria.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/modeling_aria.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/modeling_aria.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05ec34a8d8c01c47772ddad2e8360dc0b8864a2e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/modeling_aria.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/modular_aria.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/modular_aria.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf36a840a9259c024e40ccc3f0ee4559f4c68103
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/modular_aria.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/processing_aria.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/processing_aria.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..86d48a1b6f3b3f36d4e40635d31a6e37e0dc4f56
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aria/__pycache__/processing_aria.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c3c710a60f446355a272143d7a96bebd4278b96
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/configuration_audio_spectrogram_transformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/configuration_audio_spectrogram_transformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47ff67d456a20eb3d4f346bfe2fecf1b66093ead
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/configuration_audio_spectrogram_transformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/feature_extraction_audio_spectrogram_transformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/feature_extraction_audio_spectrogram_transformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c32b7181f7f95962f91de8251f83ff77aa5df38f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/feature_extraction_audio_spectrogram_transformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/modeling_audio_spectrogram_transformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/modeling_audio_spectrogram_transformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e4553db1e21c85daec009172ead54e27e2546a26
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/audio_spectrogram_transformer/__pycache__/modeling_audio_spectrogram_transformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45cfa0593e3ecac8f9db1ce89fb939c8903c349c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/auto_factory.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/auto_factory.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e7492a36bd87859e0beb1bf382b8737236600e3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/auto_factory.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/configuration_auto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/configuration_auto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e7eaf9fc5c83df8e4ed859f605a12642798fa7d9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/configuration_auto.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/feature_extraction_auto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/feature_extraction_auto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e109c49761b23f6a8d573755c66b1feee306bb29
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/feature_extraction_auto.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/image_processing_auto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/image_processing_auto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd78637f53d965dbeacd2254a76ede110e1c1e5f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/image_processing_auto.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_auto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_auto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c2a2036ef8cba546d2017a700d0f73fbc7035b7d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_auto.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_flax_auto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_flax_auto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..885d0fa15c21c5cefe6447810064def4b090cde7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_flax_auto.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_tf_auto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_tf_auto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..220f847c56903e02b55cd68f403cdd093d70c284
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/modeling_tf_auto.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/processing_auto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/processing_auto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d58dc3140f6960929fee247569aa3d5ab7fa89ab
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/processing_auto.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/tokenization_auto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/tokenization_auto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c72e269ae965341fc28b30328bb97700efe33a01
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/tokenization_auto.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/video_processing_auto.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/video_processing_auto.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d017d0a50b42ade9c294beedf55408c38e40b4f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/auto/__pycache__/video_processing_auto.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/autoformer/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/autoformer/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..004663a648fd2a550f53492d17fcc77f6f9ec4a7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/autoformer/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/autoformer/__pycache__/configuration_autoformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/autoformer/__pycache__/configuration_autoformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74c6a239aa6c5a9719ed6c12cbf5133e09c32f32
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/autoformer/__pycache__/configuration_autoformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/autoformer/__pycache__/modeling_autoformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/autoformer/__pycache__/modeling_autoformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..41adc86841201cddbff3c7fa333ce419b9d2986e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/autoformer/__pycache__/modeling_autoformer.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3afb0e8ea3225b6061c823b98ce3a8e70a10c7b11b4bbffb9762d87f0e1ec32a
+size 112437
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17b27f7aeb4301587af5c6ab0b6a3ba0bcc5547d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/configuration_aya_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/configuration_aya_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e91303bb233412a892bd8a20bd24cebcbac4947a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/configuration_aya_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/modeling_aya_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/modeling_aya_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..87c6def985f3f214a3de83e2a4e3bb581f88f13b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/modeling_aya_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/modular_aya_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/modular_aya_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c19c77f70c09c3c98329e3987a49fd1f9a51890f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/modular_aya_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/processing_aya_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/processing_aya_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68824468e9578ffe80fca391bdb663b5029569e6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/aya_vision/__pycache__/processing_aya_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f3d908e390143d49f76d5b7c9d1bd4994cea65a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/configuration_bamba.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/configuration_bamba.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..380cdec493e54f2fd4ec746a2dd013c11146de30
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/configuration_bamba.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/modeling_bamba.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/modeling_bamba.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ce507fb75e385f12f7e2e9b3bad83e09d5b77d6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/modeling_bamba.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/modular_bamba.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/modular_bamba.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..781d22635cd8aec1d1f94a1b9814d776e783284e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bamba/__pycache__/modular_bamba.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8edff478e4e7745ee830454a8a4b5b60c618442
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/configuration_bark.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/configuration_bark.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..51893c8e69827512d4679ff4a751bb41be365ffd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/configuration_bark.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/generation_configuration_bark.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/generation_configuration_bark.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91eca3eb7387d1e4b79494643c4742a1df00b60b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/generation_configuration_bark.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/modeling_bark.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/modeling_bark.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af6cafe0157372111edbf2163e22d24a1bd72d41
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/modeling_bark.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/processing_bark.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/processing_bark.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5682204aaba5ded2584fad7420d02d3c782ef25f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bark/__pycache__/processing_bark.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9035d206e4ab0762a8101902238b0fc638ddc522
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/configuration_bart.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/configuration_bart.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84b5444471a5d5f104d2d6cdb74bf4499ec26a28
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/configuration_bart.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_bart.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_bart.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e87cc4db6d2d1c89c0ea864131016c9eedfbcedd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_bart.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_flax_bart.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_flax_bart.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68016ea8f25d7ede8ce50ac75c7216f44cfb0c8c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_flax_bart.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_tf_bart.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_tf_bart.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5713b4371901b2c7a817b0f7f04756e08b21606c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/modeling_tf_bart.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/tokenization_bart.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/tokenization_bart.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10ab58c3658dea89fa1f1cae6f7e812203d26f13
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/tokenization_bart.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/tokenization_bart_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/tokenization_bart_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe8fa05fb95a5f55fc81e8eb3308c6cdbe0f1d0a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bart/__pycache__/tokenization_bart_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/barthez/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/barthez/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..991d809fc8a47c4f6a13472772efe02f23be6f3a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/barthez/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/barthez/__pycache__/tokenization_barthez.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/barthez/__pycache__/tokenization_barthez.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4483107ac583548bb2c127f2658c09bf0b0ab3ef
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/barthez/__pycache__/tokenization_barthez.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/barthez/__pycache__/tokenization_barthez_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/barthez/__pycache__/tokenization_barthez_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb457a2d5881efd6a9111da9e0c2ac2348c69f1a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/barthez/__pycache__/tokenization_barthez_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bartpho/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bartpho/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2659810be82766b5da050ce382c2511fbcb2b2f3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bartpho/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bartpho/__pycache__/tokenization_bartpho.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bartpho/__pycache__/tokenization_bartpho.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed1600b65f2540f7df67f7f178ccfd309028d6f6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bartpho/__pycache__/tokenization_bartpho.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07601102aa8ad073576de8bb6e730c0a8c3d2c4e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/configuration_beit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/configuration_beit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..68a476adf770e45fa0c607cae157ecb260270359
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/configuration_beit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/feature_extraction_beit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/feature_extraction_beit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ec5067e9d033377b8b84d35e48b8617e1573252
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/feature_extraction_beit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/image_processing_beit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/image_processing_beit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de8299d5090dea50dfe721982db54e0f1d78aa09
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/image_processing_beit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/image_processing_beit_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/image_processing_beit_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d70ecb7861575b65c327d5e0110dc64bc10a4dd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/image_processing_beit_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/modeling_beit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/modeling_beit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e56d8c6210190d393d32166dcb370822a5d0310
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/modeling_beit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/modeling_flax_beit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/modeling_flax_beit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d619f84bb3a8d1963dbc67e15e7019bdc7f9031
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/beit/__pycache__/modeling_flax_beit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..809e20fae9a8c2d142dc944e51fd336ee044eb40
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2241d5155d2a4b971ceab1a3782bcddc4d3149b1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/configuration_bert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be6bbcadc7caf427fb1949a0474e041d966bb038
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_bert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_flax_bert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_flax_bert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..818323886e5533a6afe7aa71e559cd86c6430e66
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_flax_bert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_tf_bert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_tf_bert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e854582b18c0058af56abe21eeaac035aeb42177
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/modeling_tf_bert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b24ee8ed415e8a6aed12538403cd7814ec8f1e9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8635d47dca82590f31498d6e954b9e906c50c50
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert_tf.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert_tf.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8bb2cf33187a23d6652d5ae2da4c685fb361d3d3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert/__pycache__/tokenization_bert_tf.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..edd482216e0bef06c1aa846a542985e5aa713ef0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4bbf3e9c0ff3188e2705ceba864d33044fb353bd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/configuration_bert_generation.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b8e4ae5acb7c47975b934d6338c8d2b6fcf8caa8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/modeling_bert_generation.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47e36839ea70bf36763845b8fa7e87f0c75eef76
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_generation/__pycache__/tokenization_bert_generation.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_japanese/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_japanese/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d6702e492ced8af2062a59e91ee01b3d8eab02d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_japanese/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_japanese/__pycache__/tokenization_bert_japanese.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_japanese/__pycache__/tokenization_bert_japanese.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1a9e6448055f34f3b5506a5061feb999d665e6d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bert_japanese/__pycache__/tokenization_bert_japanese.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eeeaf692b558a5a031785e207d544495eb3a434f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bertweet/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..013f9cb41b7a62f27801cdfe5243b1272f9a3ac5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bertweet/__pycache__/tokenization_bertweet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..389d52d30a2a6c805f5b59f1aee94f1138228dfd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/configuration_big_bird.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/configuration_big_bird.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..382671b42bbb9bea1264cc3abf6bcc9ecb109c37
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/configuration_big_bird.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/modeling_big_bird.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/modeling_big_bird.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ccfa83e5ef7df7792d5be97940a3f044490db4a0
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/modeling_big_bird.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b35fcfcc11273a1219bdb7cc8029688d4d265f3606402e3cd5c9ae8e6b08e963
+size 123317
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/modeling_flax_big_bird.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/modeling_flax_big_bird.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59ef49963d7061b0ea77b9e25ebaa56859f464e6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/modeling_flax_big_bird.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:97e6c5bc060284abe0abba6d73f98bdba6297912f288c344b96c23677f2738b5
+size 105598
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..56a84c294d7d0f186b8fceda5730b9d05e3bacd3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ffca5be4c52d5ed089566de3a80a45b4b73895df
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/big_bird/__pycache__/tokenization_big_bird_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bigbird_pegasus/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bigbird_pegasus/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9c3cdda85c8ce5901224bb7a1fc3fa48dee88032
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bigbird_pegasus/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bigbird_pegasus/__pycache__/configuration_bigbird_pegasus.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bigbird_pegasus/__pycache__/configuration_bigbird_pegasus.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e83881350a204fac38d9eced6045320420c31d3c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bigbird_pegasus/__pycache__/configuration_bigbird_pegasus.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bigbird_pegasus/__pycache__/modeling_bigbird_pegasus.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bigbird_pegasus/__pycache__/modeling_bigbird_pegasus.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..676b5fa024c5f17d8b9cc8545be5ca5c8a36dc7d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bigbird_pegasus/__pycache__/modeling_bigbird_pegasus.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:44205a69b5899e5db97e4789cc8c41ecb4ab755cbbb3dd24c9de197cf0f127f9
+size 129834
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..539c1029da81f4c5f922392f431a9752bc103d7b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34acc8e1a67aa58afb7444f1b7fda4c0f2a75a23
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/configuration_biogpt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..007161069bad01062ff7ee2dd37b4639e9b92a03
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/modeling_biogpt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/modular_biogpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/modular_biogpt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..351dfbbe525a009f9221e433994c1f2d00f6c415
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/modular_biogpt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/tokenization_biogpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/tokenization_biogpt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9405bee3ff768e2818600ed0401047accec16ba8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/biogpt/__pycache__/tokenization_biogpt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dcaa30f96619e293b9326f0fd3be08b7522568d1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/configuration_bit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/configuration_bit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d1a981c3706593a68455c5a42fcdc0f96a6d79a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/configuration_bit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/image_processing_bit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/image_processing_bit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64279bbbcd6e987283482898e9f68207f910e86e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/image_processing_bit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/image_processing_bit_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/image_processing_bit_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01fe5193376b2d40aff8505ad85ed1ae4b1f172f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/image_processing_bit_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/modeling_bit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/modeling_bit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..38466ede2971d7e8ec1df1f5e2469da9d52fc7df
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bit/__pycache__/modeling_bit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7bb18c6a7ed02435ee10563983e67a0a6abec673
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/configuration_bitnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/configuration_bitnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..39e976de96d38befebc3baa21807b61a50d8240b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/configuration_bitnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/modeling_bitnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/modeling_bitnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8ffbfbc941477d8db6f2ff488baac076c9e718d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/modeling_bitnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/modular_bitnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/modular_bitnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aefa6d6c88364753fbf7d672557b0d0abd491713
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bitnet/__pycache__/modular_bitnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f4bd1399874793f078ac6c80465347810e41b53d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1fcdce65876bb0e52899f654649bfa4b92132b9b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/configuration_blenderbot.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a2ea741a1f2f852f1e12fd656000d3c1e8c1d078
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_blenderbot.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_flax_blenderbot.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_flax_blenderbot.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71d645cb2227f7b9158a6cbcb1d3b8d258d2d7a7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_flax_blenderbot.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_tf_blenderbot.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_tf_blenderbot.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be02e27ae6fc3d7326ce786eb1b33a51191d21f5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/modeling_tf_blenderbot.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57f70007cab23f972227d4350f061b150816e119
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cc9711530ec20193cf7773e1c3725e880db2255
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot/__pycache__/tokenization_blenderbot_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a6edd0482fffbec1cd8bd0e69706e9ab32571547
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..97e24ae27bc5fea93069ea47b7a2e14fd201ac4a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb41dee5c87dad2bb9302c30a2d6010ae9c290b7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88fce04ae6457fa640f4c109751d8c91cd5dbeba
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..640ffb579859a2e387ead14b1eecf499bc8a67e3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61c70ca78ac822d312ed2560a7f38d461ad420e4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61a05268b00c1d1aa275d611871e71f3a39d86dc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..394de7c1f296ddc147a19a29f249266f8d3a1008
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/configuration_blip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/configuration_blip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2484d6c3aec1bd7b31720bbd861ad106d330b5b0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/configuration_blip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/image_processing_blip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/image_processing_blip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb97d809c5b235fb06ff58b5584e74bdd79e4c74
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/image_processing_blip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/image_processing_blip_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/image_processing_blip_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c0b3308e2aa62a86cfe4fb1848ab8d7f032d3ec
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/image_processing_blip_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_blip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_blip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9404544ebba130380c1b200c0cdd6ad7f80ae25a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_blip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_blip_text.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_blip_text.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..207bb9bf4341e891e96737b7d2c1d0d6d0c16f4f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_blip_text.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa34f6e319155a00bb6476fce7aeafc93408bc6f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip_text.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip_text.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..405817769315f791a59a9fff967b289d748a49d2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/modeling_tf_blip_text.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/processing_blip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/processing_blip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9ea52d941dfc7a29d626d29bfee114beff946cc8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip/__pycache__/processing_blip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34b3134b8c40d10c6ba97b658424636e2ce50cca
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/configuration_blip_2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/configuration_blip_2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e47c5fc27a5570d5843c9c459cc13add0d24f3a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/configuration_blip_2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e27f68c46763e0b8a16bd2709487a4c81f0c9284
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/modeling_blip_2.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:16e79e091cc9d0f48a87d6f414342a2b474d694b752bb14ab68456d77a53da6e
+size 111475
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb1ccdf8ef7d3182e0b5ddaba49772264786ae59
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/blip_2/__pycache__/processing_blip_2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..45232957c5bb3f347dbd00fb0687f1c8469144fd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e2970aa51e31f9dee140638c06402b08656576c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/configuration_bloom.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/modeling_bloom.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/modeling_bloom.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..98ac1d871eb7bd8ec1e4f5aa9ea1d3b8a7e00756
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/modeling_bloom.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/modeling_flax_bloom.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/modeling_flax_bloom.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..19cbb4e5dca1da82571aee0f39544b463d11e315
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/modeling_flax_bloom.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/tokenization_bloom_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/tokenization_bloom_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a8912c0c4370499d8f41be6855d4b604bdfc4de
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bloom/__pycache__/tokenization_bloom_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cc8b5ab38136c9b836fe690f296c66f366d7c78d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/configuration_bridgetower.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/configuration_bridgetower.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..679587372fc0400bea5c2a298f96165eae86ffe8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/configuration_bridgetower.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/image_processing_bridgetower.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/image_processing_bridgetower.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9e04a16f8330f310faab66e5125c3a7e1b2b5d66
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/image_processing_bridgetower.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/image_processing_bridgetower_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/image_processing_bridgetower_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..500a392afed75cc2e63b64a02e37c79ffc18d744
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/image_processing_bridgetower_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/modeling_bridgetower.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/modeling_bridgetower.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ecf1912facb72079d7a0ba8caffb45efa1807fb1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/modeling_bridgetower.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/processing_bridgetower.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/processing_bridgetower.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ad46a574cc135f85d6a03c47d1e23ea59ece70d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bridgetower/__pycache__/processing_bridgetower.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6f454bcb9366faf13a80a0a8bdba5e8a171c2f87
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/configuration_bros.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/configuration_bros.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b7d6547c5451a590c3e4618a38d9a5580063aa3c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/configuration_bros.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/modeling_bros.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/modeling_bros.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b87db419750ea823f081931bf2781a653868146
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/modeling_bros.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/processing_bros.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/processing_bros.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..787879701a1717430d0608a0e4dc48fba941a20f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/bros/__pycache__/processing_bros.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/byt5/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/byt5/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4955c057d0cc940fa95ccf1695d8a554c066f7b9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/byt5/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/byt5/__pycache__/tokenization_byt5.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/byt5/__pycache__/tokenization_byt5.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10e4eae4173c4b467371207ea37236b57975c5c3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/byt5/__pycache__/tokenization_byt5.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5507fb032ce723cc65765dbe629f23269e2add66
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/configuration_camembert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/configuration_camembert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c0a79218a6693ec903b9d369b2848bbfd97f5f5e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/configuration_camembert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/modeling_camembert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/modeling_camembert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c1409d7787037b85265a6fe1ad2ebd7be518fbdb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/modeling_camembert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/modeling_tf_camembert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/modeling_tf_camembert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c6e5647ba11af4f65d4b630c19a15daa0c127cc5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/modeling_tf_camembert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/tokenization_camembert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/tokenization_camembert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..604d0290a74af8c9e2352d5c5acf3501abd68b56
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/tokenization_camembert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/tokenization_camembert_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/tokenization_camembert_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd5b797a8b5a20127f51d4fc3586d19cef0222af
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/camembert/__pycache__/tokenization_camembert_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..309ebecd8fb350a8e282fa267cd214819da6f25e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/configuration_canine.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/configuration_canine.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df5f4c0256feb7c2ef1613741f9a74f74e510a41
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/configuration_canine.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/modeling_canine.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/modeling_canine.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2444aa205bf4396b55dc3f7eee4315fe31058d33
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/modeling_canine.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/tokenization_canine.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/tokenization_canine.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c44b7146dfaa01ab0387175a9ee2ab9304914d29
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/canine/__pycache__/tokenization_canine.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..49ae0091c76910f6e56166d3fe48a23bd51bb486
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/configuration_chameleon.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/configuration_chameleon.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9f1ee241959d4f20375104f7ad09c6f473bfc6f2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/configuration_chameleon.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/image_processing_chameleon.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/image_processing_chameleon.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54b781393971faa8387bbafda6698b714d47f5ec
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/image_processing_chameleon.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/image_processing_chameleon_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/image_processing_chameleon_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f50492728f7bc4957ca979b7885bfc36cb1dc50e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/image_processing_chameleon_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/modeling_chameleon.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/modeling_chameleon.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc7d6aceb58151e31a1ad9364cf4ea15d6bf1bfc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/modeling_chameleon.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/processing_chameleon.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/processing_chameleon.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0cbd00a3f23a0e2398662c21c68b9f7099e6bf0d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chameleon/__pycache__/processing_chameleon.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d554a9498f5a9b249ef0aa673737bb4f29f1f55
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80e85722a46684271e25589c0ad610ecc66f32e7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/configuration_chinese_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/feature_extraction_chinese_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/feature_extraction_chinese_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2f362030021c987eb1afde23ee5c9064e6752ce4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/feature_extraction_chinese_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff658655ec06fc3e967dfc981f4d351fefc67b2d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff75d5dc72a2729cff4b65295076bdd951ebffea
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/image_processing_chinese_clip_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6ec51953b8c67d1cbdb3dc50e0ea7e1b7d8f606
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/modeling_chinese_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/processing_chinese_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/processing_chinese_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd7a628e0d497666c042cd610b96edf84531350d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/chinese_clip/__pycache__/processing_chinese_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd10bf6974249486976b775132d22964e46c0f2c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/configuration_clap.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/configuration_clap.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a01a2be12ad043697459aecc27cafa7385498b3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/configuration_clap.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/feature_extraction_clap.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/feature_extraction_clap.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cbb4f2bcde519ca1b199a260e95cff49e54d9f9c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/feature_extraction_clap.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/modeling_clap.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/modeling_clap.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eec5b56ef962bbc6748a08c2869e942c6f37cfd2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/modeling_clap.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/processing_clap.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/processing_clap.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53300c34bbc99284ada916f49e2cbc76a55a639a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clap/__pycache__/processing_clap.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26ca36b7b03bda10bd3e7550f58af051e449c856
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/configuration_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/configuration_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b2277e37a21d0e667ec9cf35d8c6f0a1a4aec18
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/configuration_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/feature_extraction_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/feature_extraction_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e44caafedf9c347669b4961295fc70480c47146
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/feature_extraction_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/image_processing_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/image_processing_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb64360cbe65bf173795d018a25c2774c1f22a33
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/image_processing_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/image_processing_clip_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/image_processing_clip_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e787e38cdaee4c0a642a45f777fa548aeaf76edd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/image_processing_clip_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/modeling_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/modeling_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b2914247bd463f6084e0a97b82fb66a6733c6f6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/modeling_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/modeling_flax_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/modeling_flax_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a1cc8245322a10e143cb44a3a94e644e63cee611
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/modeling_flax_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/modeling_tf_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/modeling_tf_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..afa5046702a09d014d35b9ecc096a8be795b81f9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/modeling_tf_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/processing_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/processing_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e6ebeca674e61ecdf6ac4cac6fd0e9427611b0f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/processing_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/tokenization_clip.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/tokenization_clip.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3979d19ca1b26dad90dc4fe72bce0796143e5275
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/tokenization_clip.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/tokenization_clip_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/tokenization_clip_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..feb4903ddce5d8118df0715487e230c57184e0ef
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clip/__pycache__/tokenization_clip_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ee46beffde2436f501fd90d26c9e27a06be62fe3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/configuration_clipseg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/configuration_clipseg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04b6997a0efa40160b866c4ac4a58cf5051967ca
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/configuration_clipseg.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/modeling_clipseg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/modeling_clipseg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cbe5b6180cb96f15566f794a1b5592c6912eaf8c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/modeling_clipseg.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/processing_clipseg.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/processing_clipseg.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..981d88e30733101f510c137f004ddefbdd25f021
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/processing_clipseg.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d69903d0f7f36ac70d3d2fa1675e81c40bec927
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/configuration_clvp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/configuration_clvp.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17418779af1f76114174015d8703f7cc6cd9fc1e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/configuration_clvp.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/feature_extraction_clvp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/feature_extraction_clvp.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22104d8938ac5fe387545849b0ca03b08db3661e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/feature_extraction_clvp.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/modeling_clvp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/modeling_clvp.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..796ae345b9c8b676dcee55c8050b39e8bac1dda0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/modeling_clvp.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/number_normalizer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/number_normalizer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8dc2c069cbd1996e4251c9805a3e558c1c61c196
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/number_normalizer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/processing_clvp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/processing_clvp.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3679f28887bbdff91040b335c9b3dbbb03ac9936
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/processing_clvp.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/tokenization_clvp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/tokenization_clvp.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1dd78e971dcc466e6ba463df874cfc3307bc7865
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/clvp/__pycache__/tokenization_clvp.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e71b28d3890e1f86ceaf8f06736833f6b61bbe81
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7501dcdd1f33e837058f239f26902b75a0ec2081
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..185b5bdc50cef9a35c77d85ecc50159c0ea6ff8a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/code_llama/__pycache__/tokenization_code_llama_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34797eb153f582416e256cce4d6aae5f4c202858
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/configuration_codegen.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/configuration_codegen.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7555ea5784d4fdbecc3d48e854daaf9fab943e06
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/configuration_codegen.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/modeling_codegen.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/modeling_codegen.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2592aa9e73102611d6a386690232b0e10937d579
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/modeling_codegen.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/tokenization_codegen.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/tokenization_codegen.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0fc85a98c56eef17c393d9e048685f126c89a9b6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/tokenization_codegen.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/tokenization_codegen_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/tokenization_codegen_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85557aa9d3bf771aacca969dae04ca078e9efb43
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/codegen/__pycache__/tokenization_codegen_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b1dd022797eea763e69796a095cb297b4aaf728
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/configuration_cohere.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/configuration_cohere.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f8072cc8094fbd7e0055f9311490f63284c0128
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/configuration_cohere.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/modeling_cohere.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/modeling_cohere.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d483549bf446e3dfccebd351cb07695a99c7e08e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/modeling_cohere.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/modular_cohere.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/modular_cohere.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..613327c17a1461c1617edd2c637bf22ee9ec90e3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/modular_cohere.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/tokenization_cohere_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/tokenization_cohere_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9bdb505c49c245d887765619ece75e9a7adea56d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere/__pycache__/tokenization_cohere_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb92d53a18f9d7b0a666e2cc3d327bbf411d4ac2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/configuration_cohere2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/configuration_cohere2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c69d09777c07292a1796a89f0bc9117a0779dcfc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/configuration_cohere2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/modeling_cohere2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/modeling_cohere2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c43124c0ac35aa05b616e3912cf6f025d374c4e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/modeling_cohere2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/modular_cohere2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/modular_cohere2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..77565ac0d1761961cc616e56e0be4cccbc66f897
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2/__pycache__/modular_cohere2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec76186722f780ddf3018f83344029159da7a73e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/configuration_cohere2_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/configuration_cohere2_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52bea2f8e01eb2c5ce972df5573d13b814250df4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/configuration_cohere2_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/image_processing_cohere2_vision_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/image_processing_cohere2_vision_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00ec152f8e5ca25b4813f22aa55db2e96ad281ac
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/image_processing_cohere2_vision_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/modeling_cohere2_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/modeling_cohere2_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3198db78dd7a4d9e56dcf56e3f22c7f83179c1a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/modeling_cohere2_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/modular_cohere2_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/modular_cohere2_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85b90488551c6eaa7a5213570745bc252601fbee
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/modular_cohere2_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/processing_cohere2_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/processing_cohere2_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5fd89c5b2f37ba99708897dcd8987b858e4f01a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cohere2_vision/__pycache__/processing_cohere2_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f28bcf900a1d0563bcb8a59a5ee5d867e6a76a57
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/configuration_colpali.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/configuration_colpali.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..61634a1967f7e0909ece299677b9682aad10eb4d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/configuration_colpali.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/modeling_colpali.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/modeling_colpali.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d19ccb0270806b677f67e3d7d7ce4b28ca8b8fad
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/modeling_colpali.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/modular_colpali.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/modular_colpali.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..259b7906d45b5043e163b31959b34a983bced4fd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/modular_colpali.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/processing_colpali.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/processing_colpali.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23eb20d1c85690be6a3afa92e9b162cc8879f7d0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colpali/__pycache__/processing_colpali.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9250f5e0f816c79bbcd87ec43686413f7627fd05
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/configuration_colqwen2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/configuration_colqwen2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb4155c26098bc2997b8c9ee7df93c72b0829f79
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/configuration_colqwen2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/modeling_colqwen2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/modeling_colqwen2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..866f8354bb8a8bc5cec33ce0492eacfc046e5e5e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/modeling_colqwen2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/modular_colqwen2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/modular_colqwen2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e08aa79b90374154cb40d452743f5cb80a78d0a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/modular_colqwen2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/processing_colqwen2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/processing_colqwen2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d596fbc8b9830733baee42b1823c8ed07c6cac1a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/colqwen2/__pycache__/processing_colqwen2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..313cd6c892d5fcb4cf222aefe47a4f8516c29f11
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/configuration_conditional_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/configuration_conditional_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b37adbea8a271c3816627d7ad502ff9c17ebaa7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/configuration_conditional_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/feature_extraction_conditional_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/feature_extraction_conditional_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f88be0fb951fc0d98ad8f7a255ad3b1bc738d5d8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/feature_extraction_conditional_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7c8ef9db5eb036604cf9db9ddecaae96739b8181
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07f2e70ac5cbbdfc2d441bc66ec01b76f968d281
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/modeling_conditional_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/modeling_conditional_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0aec8793d0def87d2d8ae20a5200790608bf7f28
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/modeling_conditional_detr.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:84d4063941211e67be28f07e645609657f019a0c8cd1d28bc6de3360ff6d7fa3
+size 100835
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/modular_conditional_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/modular_conditional_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ebadd4fde4bf6ce4d89ffc762b4e6f13462fa8a7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/modular_conditional_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..22d71d5358380b5bccce0289de798fa30331fc4e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/configuration_convbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/configuration_convbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6efeb53e0ee6b9c1624ee760be2b2c21c65a8028
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/configuration_convbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/modeling_convbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/modeling_convbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26fdccefa338a95a85eb97200a72b76622bed79c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/modeling_convbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/modeling_tf_convbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/modeling_tf_convbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..89992db5ed7c27b0b138540d4f3eefeacb28eaf2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/modeling_tf_convbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/tokenization_convbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/tokenization_convbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34feda2d35f9cf5389a93279e07020257af8960a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/tokenization_convbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/tokenization_convbert_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/tokenization_convbert_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..72f34eab4c1916ccc18766b4f9dd276b6417838c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convbert/__pycache__/tokenization_convbert_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e62f3373479ff6805361c38026b11441a671b2d9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/configuration_convnext.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/configuration_convnext.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2aff7598fb3e2a3086e85e4939d0479873ec232f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/configuration_convnext.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/feature_extraction_convnext.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/feature_extraction_convnext.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29481a3b489132602aec8dbe8cb35ff9c7f752f2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/feature_extraction_convnext.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/image_processing_convnext.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/image_processing_convnext.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eabee18b89bd7765a1e1b061189f56008969fe3c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/image_processing_convnext.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/image_processing_convnext_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/image_processing_convnext_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b24a0d3e18fe887f1fc8d86a08654d54cb63834a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/image_processing_convnext_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/modeling_convnext.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/modeling_convnext.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80cd7626347ba7e7b40a805945e8b700c4a7e154
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/modeling_convnext.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/modeling_tf_convnext.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/modeling_tf_convnext.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30afe913eef5584ef963652ccce888a86f2499d9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnext/__pycache__/modeling_tf_convnext.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..58c17c980ae1d2798ef56771a130f692f9cbe94d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/configuration_convnextv2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/configuration_convnextv2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42f51b63499aab8b87978546f8311898aa00bcfc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/configuration_convnextv2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/modeling_convnextv2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/modeling_convnextv2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3394664932186993cbb16e42de2b2a835a60f56f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/modeling_convnextv2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/modeling_tf_convnextv2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/modeling_tf_convnextv2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ccd1ac1bf340d3a0b0a735f38cf09e6c703e8e56
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/convnextv2/__pycache__/modeling_tf_convnextv2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpm/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpm/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96d159a4b0f1851330b2f4334f928de04dcf305c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpm/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1ad2736dd0cef4fb350110c7c6c5661e4ab4ee1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78a7508670aaf1d5f0b43fee2408bc6713bc0ab0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpm/__pycache__/tokenization_cpm_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..254ec248bf5de6dd8686b27db20d17e70ea2053d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec250954e709529a8988edcd3582d12aee43d4a8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/configuration_cpmant.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b76978dafc4a626638729aba6bd13145aea8664
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/modeling_cpmant.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cd368ec4566adbdc21b2f203e6a631041b035c1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cpmant/__pycache__/tokenization_cpmant.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5a15396e96791f66f72477f127d91172243d122
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/configuration_csm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/configuration_csm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ebf62760a2e32afe0655285ae2d02ff5467bbbbd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/configuration_csm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/generation_csm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/generation_csm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63aa9f22dca4a8147927659de35864c419525a6b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/generation_csm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/modeling_csm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/modeling_csm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4cb54c2b60019a431ededc7de7889f6dbbdd046a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/modeling_csm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/modular_csm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/modular_csm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8a45e80c5a4eb5b0cdbc766fe41ee7a994c71ac
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/modular_csm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/processing_csm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/processing_csm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4704c8ac6e9828c676e87f09e726c883613d905b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/csm/__pycache__/processing_csm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8e4c31fc4b7c73045cf7a8880fadf2497132119
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/configuration_ctrl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/configuration_ctrl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..767297332776551f56664da27acee99f283e550b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/configuration_ctrl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/modeling_ctrl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/modeling_ctrl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..def869e04c24255e826ac56ea873a72dee6e4cd3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/modeling_ctrl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/modeling_tf_ctrl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/modeling_tf_ctrl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc58bc838f3f353eab715f8fe37e511a7f173678
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/modeling_tf_ctrl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/tokenization_ctrl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/tokenization_ctrl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c043cf48f3d8201ecdb6764331b01bb62741592b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ctrl/__pycache__/tokenization_ctrl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eba6df2f21b058612b69b4f5e514b06f098e6b0d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/configuration_cvt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/configuration_cvt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21b5d047d88dedd7847cd0f50a03771899615ee9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/configuration_cvt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/modeling_cvt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/modeling_cvt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f0038574b1be58f8bb8daee14c9256452de5b4d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/modeling_cvt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/modeling_tf_cvt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/modeling_tf_cvt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1aaff2936a768d1a69709f15aeebe46d26d6be05
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/cvt/__pycache__/modeling_tf_cvt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd1cefebc8fc56b6c5092fb435a20cb0f0c713df
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/configuration_d_fine.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/configuration_d_fine.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4471aee702e0df8049acf4d6f134f9d5c8994106
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/configuration_d_fine.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/modeling_d_fine.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/modeling_d_fine.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..60231b87a36928136885d413a90f2130d4aab346
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/modeling_d_fine.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0acf84756d9a660fb6632f8904ff701e0f7c3bbfab1ca264617948b786760129
+size 121155
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/modular_d_fine.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/modular_d_fine.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b32748c635467af162b902276ee32aee01987af1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/d_fine/__pycache__/modular_d_fine.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dab_detr/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dab_detr/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c99e3941d9cb6d63f3cb12ddc1cdddf53993b331
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dab_detr/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dab_detr/__pycache__/configuration_dab_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dab_detr/__pycache__/configuration_dab_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2c54e05bcb927bc4375c037e6087db0c39c2cb6b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dab_detr/__pycache__/configuration_dab_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dab_detr/__pycache__/modeling_dab_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dab_detr/__pycache__/modeling_dab_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e10b2f21ff04b87b45f487d4642a75ef23e9a14
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dab_detr/__pycache__/modeling_dab_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab969e6befccef3783c7111fd19c9201804ca13d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/configuration_dac.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/configuration_dac.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f098080502536a53e5593873478e236468828314
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/configuration_dac.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/feature_extraction_dac.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/feature_extraction_dac.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36a4a32c274b0ee23746a131544a2614300f506b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/feature_extraction_dac.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/modeling_dac.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/modeling_dac.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b727b47228de25ea45392c6e721d5e46ebc7456d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dac/__pycache__/modeling_dac.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..81878e5e151a134f30c2258cec5f35ce24239d5e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_audio.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_audio.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f63752cff55237adda98d4dfdebbadc57f3f3b88
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_audio.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_text.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_text.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ad31612fc075a5ed5cb5334efc299afa297089f5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_text.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f46654d78caaaf26914e584235d33c7e7fb58a8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/configuration_data2vec_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_audio.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_audio.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c4af32406c75dd2f1be6c41fb07fbacb69bee65
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_audio.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_text.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_text.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5550dc2a3bcb68faec784f88648d632cea965faf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_text.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c79a3d992833119a0c451cba78b78ce92895b4c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_data2vec_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_tf_data2vec_vision.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_tf_data2vec_vision.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..73b5c2829f2fe6b37e748f2aaabd500c9e5d8f6b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modeling_tf_data2vec_vision.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modular_data2vec_audio.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modular_data2vec_audio.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fccc8ae53d0898c1b6ccbc06c1595e5551fd41f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/data2vec/__pycache__/modular_data2vec_audio.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb875a56a186f82c315dcd9671a495ebbd5c2877
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/configuration_dbrx.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/configuration_dbrx.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf83ce5b59eb47f2b5257d3c5125739137ec926e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/configuration_dbrx.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/modeling_dbrx.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/modeling_dbrx.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9d904558059397650c2688bc9a878ed9b5cf1f9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dbrx/__pycache__/modeling_dbrx.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d969dd9c2421bbc043933e84aafc7ff84d300696
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/configuration_deberta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/configuration_deberta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4bc05c7a6a629a107761a609d5c4b94d7d31c66e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/configuration_deberta.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/modeling_deberta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/modeling_deberta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8045193a15a5254bf58b538366f9fde3e6a5987a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/modeling_deberta.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/modeling_tf_deberta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/modeling_tf_deberta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64897741733de07d9eef6d15b676408e17d2014f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/modeling_tf_deberta.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/tokenization_deberta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/tokenization_deberta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bf51e17164cc6953e7e02e46744c948975fb0a6a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/tokenization_deberta.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/tokenization_deberta_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/tokenization_deberta_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3084c39dd359babe68866393805d999478a9006b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta/__pycache__/tokenization_deberta_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d0f5628582a43eaadf169ee61b60ae93d4a5daf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/configuration_deberta_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/configuration_deberta_v2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54f9e7e4bfbbeb7eb1a40c5ab146308911386636
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/configuration_deberta_v2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/modeling_deberta_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/modeling_deberta_v2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44f9826552163d90760c7b0a9602533c248b0a7a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/modeling_deberta_v2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/modeling_tf_deberta_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/modeling_tf_deberta_v2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29d02eabf7f262921acd18c3c83dc1caf57e1772
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/modeling_tf_deberta_v2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8c759a2581b63c8457e59b1d2ebf7a5a0d7d5cc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c8bbfab5b7f5b21b5e1161f47051f9ef875412d1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deberta_v2/__pycache__/tokenization_deberta_v2_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/decision_transformer/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/decision_transformer/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..479f30cdf346fa5a7aaca444a2b0214f85530a58
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/decision_transformer/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/decision_transformer/__pycache__/configuration_decision_transformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/decision_transformer/__pycache__/configuration_decision_transformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..53b859f9bf93c810d529961e5a5ec88c2b29c33d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/decision_transformer/__pycache__/configuration_decision_transformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/decision_transformer/__pycache__/modeling_decision_transformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/decision_transformer/__pycache__/modeling_decision_transformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c3cbd05ab61949eeaec68634c37194048e4a22b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/decision_transformer/__pycache__/modeling_decision_transformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f2a6fa1ae3761cef220ab191bcdae762e0d6c8d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/configuration_deepseek_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/configuration_deepseek_v2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..131119be854f507c2da80740e70fc20547e7d798
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/configuration_deepseek_v2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/modeling_deepseek_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/modeling_deepseek_v2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c73249dba178ccd2fe4304a456a64d9108274737
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/modeling_deepseek_v2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/modular_deepseek_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/modular_deepseek_v2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52b137eedefe1d167a7e2712db71324128c2082d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v2/__pycache__/modular_deepseek_v2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de6c8827b15031f1efb4ae8411800fd301c1ce47
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/configuration_deepseek_v3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/configuration_deepseek_v3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dcf1fec09aed37aaff5d31ca87d752ec595b7312
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/configuration_deepseek_v3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/modeling_deepseek_v3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/modeling_deepseek_v3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..134f6801c5ac58ed5c7a2f49885860c02cbe5125
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/modeling_deepseek_v3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/modular_deepseek_v3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/modular_deepseek_v3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7456fc78f6b716344a7ee5bcff358d4f8afae70
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_v3/__pycache__/modular_deepseek_v3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fa2e124b44ef426a339a2b3bf3b6e2082d472b98
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/configuration_deepseek_vl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/configuration_deepseek_vl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b4bcf8180f4ac095aa4f0934a24178bb99851f98
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/configuration_deepseek_vl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/image_processing_deepseek_vl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/image_processing_deepseek_vl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20cdc51757a4f8cf0fd87b23d657f51d9bd84fdf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/image_processing_deepseek_vl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/image_processing_deepseek_vl_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/image_processing_deepseek_vl_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01ddcb1a31fbe7ffa3cb4b0ede929132b128ed8d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/image_processing_deepseek_vl_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/modeling_deepseek_vl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/modeling_deepseek_vl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff09a14c1dc99ebcf2e664ac864434c150808ccd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/modeling_deepseek_vl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/modular_deepseek_vl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/modular_deepseek_vl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6aa0558b6ad9461fc604841721959017fcbaec1c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/modular_deepseek_vl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/processing_deepseek_vl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/processing_deepseek_vl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74d3f67d5bc8bfd41f22407b763dfa67b1f153b8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl/__pycache__/processing_deepseek_vl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c85852ce0e8413ecd08b5ed44d123703213c369e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/configuration_deepseek_vl_hybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/configuration_deepseek_vl_hybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ae2db060265972a1b3f5500f8205ca0d668b69e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/configuration_deepseek_vl_hybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/image_processing_deepseek_vl_hybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/image_processing_deepseek_vl_hybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..27564dc6a245629962680d62623bc1f05aab51fb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/image_processing_deepseek_vl_hybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/image_processing_deepseek_vl_hybrid_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/image_processing_deepseek_vl_hybrid_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1bf6de36fa585f3c9a07083e45c7c44e7ce4173
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/image_processing_deepseek_vl_hybrid_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/modeling_deepseek_vl_hybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/modeling_deepseek_vl_hybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a4ad09fa1b64a3fc076f0394634eeb1c807d483
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/modeling_deepseek_vl_hybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/modular_deepseek_vl_hybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/modular_deepseek_vl_hybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..66a742da166a05fdc0ced62bb632301af969cddd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/modular_deepseek_vl_hybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/processing_deepseek_vl_hybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/processing_deepseek_vl_hybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af743550920cfcd2b415f3e9329cbfb2cbcaaa3c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deepseek_vl_hybrid/__pycache__/processing_deepseek_vl_hybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3a9e6682cc90cc890bbae0ea796dd1518f798e2e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/configuration_deformable_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/configuration_deformable_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2273e49d46b61b2e15f7d04723da9338a0913153
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/configuration_deformable_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/feature_extraction_deformable_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/feature_extraction_deformable_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..46aeb670d9e6cc274094bb72b4a8440e6d084173
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/feature_extraction_deformable_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9dcf56cbeb1965465831b404e38ed3bd54363b32
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7ea0c49d04abce7fef9bc5cecb4a8c3632c11f81
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/image_processing_deformable_detr_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/modeling_deformable_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/modeling_deformable_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a8d2f1e70346af6212f24061141dd95b72fd3a9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/modeling_deformable_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/modular_deformable_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/modular_deformable_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e289721855a432bbba215cb2f58e3467a616d0d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deformable_detr/__pycache__/modular_deformable_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..867b50c8f4e85f46570b867978c0187b9ccf9108
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/configuration_deit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/configuration_deit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..561b73de4c044df55efd9ee98cf45472d414ecf2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/configuration_deit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/feature_extraction_deit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/feature_extraction_deit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7f4bce2aa866d16bc7cc9668beaa1a202e072fe6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/feature_extraction_deit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/image_processing_deit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/image_processing_deit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99756bbc94ef09242d4bfa01cbe936a33e89fd3e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/image_processing_deit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/image_processing_deit_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/image_processing_deit_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e1b9f2318cfa9a48134097c6ff7788320b3e80d3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/image_processing_deit_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/modeling_deit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/modeling_deit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23b49316146bbc79e1dcfa8a8415bc46645c9279
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/modeling_deit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/modeling_tf_deit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/modeling_tf_deit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..92bf2b1e03702838b16e9333de31391dfc393a9a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deit/__pycache__/modeling_tf_deit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d62747f78b5b3911bc27d1685b63cdd947ebb705
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/bort/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/bort/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/bort/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/bort/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f96f472290fc7f4627d6d59fc3372200811879c1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/bort/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e06e186741991b2f9183f30b6591477bc60dfb5
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_deta import *
+ from .image_processing_deta import *
+ from .modeling_deta import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..983b566c816b9e5487de2d7f3623b4ee67e45287
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/configuration_deta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/configuration_deta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5b921ac77e98bd44689c0b360f869884136357ad
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/configuration_deta.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/image_processing_deta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/image_processing_deta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..afe914136dd29d6d01fc486369a88623eab712f1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/image_processing_deta.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/modeling_deta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/modeling_deta.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67c1b94fc021eeb46efc58eb982067b1a23081b3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/__pycache__/modeling_deta.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:7b5bd35ac71bfbb8d01209886d60179115644d7bfbfe11e432da85b2790cda99
+size 153016
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/configuration_deta.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/configuration_deta.py
new file mode 100644
index 0000000000000000000000000000000000000000..2109902ac06546ce4e235403dd3b95bf27486272
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/configuration_deta.py
@@ -0,0 +1,278 @@
+# coding=utf-8
+# Copyright 2022 SenseTime and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""DETA model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+from ...auto import CONFIG_MAPPING
+
+
+logger = logging.get_logger(__name__)
+
+
+class DetaConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`DetaModel`]. It is used to instantiate a DETA
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the DETA
+ [SenseTime/deformable-detr](https://huggingface.co/SenseTime/deformable-detr) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ backbone_config (`PretrainedConfig` or `dict`, *optional*, defaults to `ResNetConfig()`):
+ The configuration of the backbone model.
+ backbone (`str`, *optional*):
+ Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
+ will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
+ is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
+ use_pretrained_backbone (`bool`, *optional*, `False`):
+ Whether to use pretrained weights for the backbone.
+ use_timm_backbone (`bool`, *optional*, `False`):
+ Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
+ library.
+ backbone_kwargs (`dict`, *optional*):
+ Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
+ e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
+ num_queries (`int`, *optional*, defaults to 900):
+ Number of object queries, i.e. detection slots. This is the maximal number of objects [`DetaModel`] can
+ detect in a single image. In case `two_stage` is set to `True`, we use `two_stage_num_proposals` instead.
+ d_model (`int`, *optional*, defaults to 256):
+ Dimension of the layers.
+ encoder_layers (`int`, *optional*, defaults to 6):
+ Number of encoder layers.
+ decoder_layers (`int`, *optional*, defaults to 6):
+ Number of decoder layers.
+ encoder_attention_heads (`int`, *optional*, defaults to 8):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ decoder_attention_heads (`int`, *optional*, defaults to 8):
+ Number of attention heads for each attention layer in the Transformer decoder.
+ decoder_ffn_dim (`int`, *optional*, defaults to 2048):
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
+ encoder_ffn_dim (`int`, *optional*, defaults to 2048):
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
+ activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+ activation_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for activations inside the fully connected layer.
+ init_std (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ init_xavier_std (`float`, *optional*, defaults to 1):
+ The scaling factor used for the Xavier initialization gain in the HM Attention map module.
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
+ for more details.
+ auxiliary_loss (`bool`, *optional*, defaults to `False`):
+ Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
+ position_embedding_type (`str`, *optional*, defaults to `"sine"`):
+ Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
+ class_cost (`float`, *optional*, defaults to 1):
+ Relative weight of the classification error in the Hungarian matching cost.
+ bbox_cost (`float`, *optional*, defaults to 5):
+ Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
+ giou_cost (`float`, *optional*, defaults to 2):
+ Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
+ mask_loss_coefficient (`float`, *optional*, defaults to 1):
+ Relative weight of the Focal loss in the panoptic segmentation loss.
+ dice_loss_coefficient (`float`, *optional*, defaults to 1):
+ Relative weight of the DICE/F-1 loss in the panoptic segmentation loss.
+ bbox_loss_coefficient (`float`, *optional*, defaults to 5):
+ Relative weight of the L1 bounding box loss in the object detection loss.
+ giou_loss_coefficient (`float`, *optional*, defaults to 2):
+ Relative weight of the generalized IoU loss in the object detection loss.
+ eos_coefficient (`float`, *optional*, defaults to 0.1):
+ Relative classification weight of the 'no-object' class in the object detection loss.
+ num_feature_levels (`int`, *optional*, defaults to 5):
+ The number of input feature levels.
+ encoder_n_points (`int`, *optional*, defaults to 4):
+ The number of sampled keys in each feature level for each attention head in the encoder.
+ decoder_n_points (`int`, *optional*, defaults to 4):
+ The number of sampled keys in each feature level for each attention head in the decoder.
+ two_stage (`bool`, *optional*, defaults to `True`):
+ Whether to apply a two-stage deformable DETR, where the region proposals are also generated by a variant of
+ DETA, which are further fed into the decoder for iterative bounding box refinement.
+ two_stage_num_proposals (`int`, *optional*, defaults to 300):
+ The number of region proposals to be generated, in case `two_stage` is set to `True`.
+ with_box_refine (`bool`, *optional*, defaults to `True`):
+ Whether to apply iterative bounding box refinement, where each decoder layer refines the bounding boxes
+ based on the predictions from the previous layer.
+ focal_alpha (`float`, *optional*, defaults to 0.25):
+ Alpha parameter in the focal loss.
+ assign_first_stage (`bool`, *optional*, defaults to `True`):
+ Whether to assign each prediction i to the highest overlapping ground truth object if the overlap is larger than a threshold 0.7.
+ assign_second_stage (`bool`, *optional*, defaults to `True`):
+ Whether to assign second assignment procedure in the second stage closely follows the first stage assignment procedure.
+ disable_custom_kernels (`bool`, *optional*, defaults to `True`):
+ Disable the use of custom CUDA and CPU kernels. This option is necessary for the ONNX export, as custom
+ kernels are not supported by PyTorch ONNX export.
+
+ Examples:
+
+ ```python
+ >>> from transformers import DetaConfig, DetaModel
+
+ >>> # Initializing a DETA SenseTime/deformable-detr style configuration
+ >>> configuration = DetaConfig()
+
+ >>> # Initializing a model (with random weights) from the SenseTime/deformable-detr style configuration
+ >>> model = DetaModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "deta"
+ attribute_map = {
+ "hidden_size": "d_model",
+ "num_attention_heads": "encoder_attention_heads",
+ }
+
+ def __init__(
+ self,
+ backbone_config=None,
+ backbone=None,
+ use_pretrained_backbone=False,
+ use_timm_backbone=False,
+ backbone_kwargs=None,
+ num_queries=900,
+ max_position_embeddings=2048,
+ encoder_layers=6,
+ encoder_ffn_dim=2048,
+ encoder_attention_heads=8,
+ decoder_layers=6,
+ decoder_ffn_dim=1024,
+ decoder_attention_heads=8,
+ encoder_layerdrop=0.0,
+ is_encoder_decoder=True,
+ activation_function="relu",
+ d_model=256,
+ dropout=0.1,
+ attention_dropout=0.0,
+ activation_dropout=0.0,
+ init_std=0.02,
+ init_xavier_std=1.0,
+ return_intermediate=True,
+ auxiliary_loss=False,
+ position_embedding_type="sine",
+ num_feature_levels=5,
+ encoder_n_points=4,
+ decoder_n_points=4,
+ two_stage=True,
+ two_stage_num_proposals=300,
+ with_box_refine=True,
+ assign_first_stage=True,
+ assign_second_stage=True,
+ class_cost=1,
+ bbox_cost=5,
+ giou_cost=2,
+ mask_loss_coefficient=1,
+ dice_loss_coefficient=1,
+ bbox_loss_coefficient=5,
+ giou_loss_coefficient=2,
+ eos_coefficient=0.1,
+ focal_alpha=0.25,
+ disable_custom_kernels=True,
+ **kwargs,
+ ):
+ if use_pretrained_backbone:
+ raise ValueError("Pretrained backbones are not supported yet.")
+
+ if backbone_config is not None and backbone is not None:
+ raise ValueError("You can't specify both `backbone` and `backbone_config`.")
+
+ if backbone_config is None and backbone is None:
+ logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
+ backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage2", "stage3", "stage4"])
+ else:
+ if isinstance(backbone_config, dict):
+ backbone_model_type = backbone_config.pop("model_type")
+ config_class = CONFIG_MAPPING[backbone_model_type]
+ backbone_config = config_class.from_dict(backbone_config)
+
+ if backbone_kwargs is not None and backbone_kwargs and backbone_config is not None:
+ raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.")
+
+ self.backbone_config = backbone_config
+ self.backbone = backbone
+ self.use_pretrained_backbone = use_pretrained_backbone
+ self.use_timm_backbone = use_timm_backbone
+ self.backbone_kwargs = backbone_kwargs
+ self.num_queries = num_queries
+ self.max_position_embeddings = max_position_embeddings
+ self.d_model = d_model
+ self.encoder_ffn_dim = encoder_ffn_dim
+ self.encoder_layers = encoder_layers
+ self.encoder_attention_heads = encoder_attention_heads
+ self.decoder_ffn_dim = decoder_ffn_dim
+ self.decoder_layers = decoder_layers
+ self.decoder_attention_heads = decoder_attention_heads
+ self.dropout = dropout
+ self.attention_dropout = attention_dropout
+ self.activation_dropout = activation_dropout
+ self.activation_function = activation_function
+ self.init_std = init_std
+ self.init_xavier_std = init_xavier_std
+ self.encoder_layerdrop = encoder_layerdrop
+ self.auxiliary_loss = auxiliary_loss
+ self.position_embedding_type = position_embedding_type
+ # deformable attributes
+ self.num_feature_levels = num_feature_levels
+ self.encoder_n_points = encoder_n_points
+ self.decoder_n_points = decoder_n_points
+ self.two_stage = two_stage
+ self.two_stage_num_proposals = two_stage_num_proposals
+ self.with_box_refine = with_box_refine
+ self.assign_first_stage = assign_first_stage
+ self.assign_second_stage = assign_second_stage
+ if two_stage is True and with_box_refine is False:
+ raise ValueError("If two_stage is True, with_box_refine must be True.")
+ # Hungarian matcher
+ self.class_cost = class_cost
+ self.bbox_cost = bbox_cost
+ self.giou_cost = giou_cost
+ # Loss coefficients
+ self.mask_loss_coefficient = mask_loss_coefficient
+ self.dice_loss_coefficient = dice_loss_coefficient
+ self.bbox_loss_coefficient = bbox_loss_coefficient
+ self.giou_loss_coefficient = giou_loss_coefficient
+ self.eos_coefficient = eos_coefficient
+ self.focal_alpha = focal_alpha
+ self.disable_custom_kernels = disable_custom_kernels
+ super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
+
+ @property
+ def num_attention_heads(self) -> int:
+ return self.encoder_attention_heads
+
+ @property
+ def hidden_size(self) -> int:
+ return self.d_model
+
+ @property
+ def sub_configs(self):
+ return (
+ {"backbone_config": type(self.backbone_config)}
+ if getattr(self, "backbone_config", None) is not None
+ else {}
+ )
+
+
+__all__ = ["DetaConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/image_processing_deta.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/image_processing_deta.py
new file mode 100644
index 0000000000000000000000000000000000000000..434d25a1ab5152b0de5e74463c3fe15eb16f901b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/image_processing_deta.py
@@ -0,0 +1,1228 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for Deformable DETR."""
+
+import pathlib
+from collections.abc import Iterable
+from typing import Any, Callable, Optional, Union
+
+import numpy as np
+
+from ....feature_extraction_utils import BatchFeature
+from ....image_processing_utils import BaseImageProcessor, get_size_dict
+from ....image_transforms import (
+ PaddingMode,
+ center_to_corners_format,
+ corners_to_center_format,
+ pad,
+ rescale,
+ resize,
+ rgb_to_id,
+ to_channel_dimension_format,
+)
+from ....image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ AnnotationFormat,
+ AnnotationType,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ get_image_size,
+ infer_channel_dimension_format,
+ is_batched,
+ is_scaled_image,
+ to_numpy_array,
+ valid_images,
+ validate_annotations,
+ validate_preprocess_arguments,
+)
+from ....utils import (
+ is_flax_available,
+ is_jax_tensor,
+ is_tf_available,
+ is_tf_tensor,
+ is_torch_available,
+ is_torch_tensor,
+ is_torchvision_available,
+ is_vision_available,
+ logging,
+)
+from ....utils.generic import TensorType
+
+
+if is_torch_available():
+ import torch
+
+
+if is_torchvision_available():
+ from torchvision.ops.boxes import batched_nms
+
+if is_vision_available():
+ import PIL
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
+
+
+def get_size_with_aspect_ratio(image_size, size, max_size=None) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size.
+
+ Args:
+ image_size (`tuple[int, int]`):
+ The input image size.
+ size (`int`):
+ The desired output size.
+ max_size (`int`, *optional*):
+ The maximum allowed output size.
+ """
+ height, width = image_size
+ raw_size = None
+ if max_size is not None:
+ min_original_size = float(min((height, width)))
+ max_original_size = float(max((height, width)))
+ if max_original_size / min_original_size * size > max_size:
+ raw_size = max_size * min_original_size / max_original_size
+ size = int(round(raw_size))
+
+ if (height <= width and height == size) or (width <= height and width == size):
+ oh, ow = height, width
+ elif width < height:
+ ow = size
+ if max_size is not None and raw_size is not None:
+ oh = int(raw_size * height / width)
+ else:
+ oh = int(size * height / width)
+ else:
+ oh = size
+ if max_size is not None and raw_size is not None:
+ ow = int(raw_size * width / height)
+ else:
+ ow = int(size * width / height)
+
+ return (oh, ow)
+
+
+def get_resize_output_image_size(
+ input_image: np.ndarray,
+ size: Union[int, tuple[int, int], list[int]],
+ max_size: Optional[int] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size. If the desired output size
+ is a tuple or list, the output image size is returned as is. If the desired output size is an integer, the output
+ image size is computed by keeping the aspect ratio of the input image size.
+
+ Args:
+ input_image (`np.ndarray`):
+ The image to resize.
+ size (`int` or `tuple[int, int]` or `list[int]`):
+ The desired output size.
+ max_size (`int`, *optional*):
+ The maximum allowed output size.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
+ """
+ image_size = get_image_size(input_image, input_data_format)
+ if isinstance(size, (list, tuple)):
+ return size
+
+ return get_size_with_aspect_ratio(image_size, size, max_size)
+
+
+def get_image_size_for_max_height_width(
+ input_image: np.ndarray,
+ max_height: int,
+ max_width: int,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio.
+ Important, even if image_height < max_height and image_width < max_width, the image will be resized
+ to at least one of the edges be equal to max_height or max_width.
+
+ For example:
+ - input_size: (100, 200), max_height: 50, max_width: 50 -> output_size: (25, 50)
+ - input_size: (100, 200), max_height: 200, max_width: 500 -> output_size: (200, 400)
+
+ Args:
+ input_image (`np.ndarray`):
+ The image to resize.
+ max_height (`int`):
+ The maximum allowed height.
+ max_width (`int`):
+ The maximum allowed width.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
+ """
+ image_size = get_image_size(input_image, input_data_format)
+ height, width = image_size
+ height_scale = max_height / height
+ width_scale = max_width / width
+ min_scale = min(height_scale, width_scale)
+ new_height = int(height * min_scale)
+ new_width = int(width * min_scale)
+ return new_height, new_width
+
+
+def get_numpy_to_framework_fn(arr) -> Callable:
+ """
+ Returns a function that converts a numpy array to the framework of the input array.
+
+ Args:
+ arr (`np.ndarray`): The array to convert.
+ """
+ if isinstance(arr, np.ndarray):
+ return np.array
+ if is_tf_available() and is_tf_tensor(arr):
+ import tensorflow as tf
+
+ return tf.convert_to_tensor
+ if is_torch_available() and is_torch_tensor(arr):
+ import torch
+
+ return torch.tensor
+ if is_flax_available() and is_jax_tensor(arr):
+ import jax.numpy as jnp
+
+ return jnp.array
+ raise ValueError(f"Cannot convert arrays of type {type(arr)}")
+
+
+def safe_squeeze(arr: np.ndarray, axis: Optional[int] = None) -> np.ndarray:
+ """
+ Squeezes an array, but only if the axis specified has dim 1.
+ """
+ if axis is None:
+ return arr.squeeze()
+
+ try:
+ return arr.squeeze(axis=axis)
+ except ValueError:
+ return arr
+
+
+def normalize_annotation(annotation: dict, image_size: tuple[int, int]) -> dict:
+ image_height, image_width = image_size
+ norm_annotation = {}
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ boxes = corners_to_center_format(boxes)
+ boxes /= np.asarray([image_width, image_height, image_width, image_height], dtype=np.float32)
+ norm_annotation[key] = boxes
+ else:
+ norm_annotation[key] = value
+ return norm_annotation
+
+
+def max_across_indices(values: Iterable[Any]) -> list[Any]:
+ """
+ Return the maximum value across all indices of an iterable of values.
+ """
+ return [max(values_i) for values_i in zip(*values)]
+
+
+def get_max_height_width(
+ images: list[np.ndarray], input_data_format: Optional[Union[str, ChannelDimension]] = None
+) -> list[int]:
+ """
+ Get the maximum height and width across all images in a batch.
+ """
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(images[0])
+
+ if input_data_format == ChannelDimension.FIRST:
+ _, max_height, max_width = max_across_indices([img.shape for img in images])
+ elif input_data_format == ChannelDimension.LAST:
+ max_height, max_width, _ = max_across_indices([img.shape for img in images])
+ else:
+ raise ValueError(f"Invalid channel dimension format: {input_data_format}")
+ return (max_height, max_width)
+
+
+def make_pixel_mask(
+ image: np.ndarray, output_size: tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None
+) -> np.ndarray:
+ """
+ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+
+ Args:
+ image (`np.ndarray`):
+ Image to make the pixel mask for.
+ output_size (`tuple[int, int]`):
+ Output size of the mask.
+ """
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
+ mask = np.zeros(output_size, dtype=np.int64)
+ mask[:input_height, :input_width] = 1
+ return mask
+
+
+def convert_coco_poly_to_mask(segmentations, height: int, width: int) -> np.ndarray:
+ """
+ Convert a COCO polygon annotation to a mask.
+
+ Args:
+ segmentations (`list[list[float]]`):
+ List of polygons, each polygon represented by a list of x-y coordinates.
+ height (`int`):
+ Height of the mask.
+ width (`int`):
+ Width of the mask.
+ """
+ try:
+ from pycocotools import mask as coco_mask
+ except ImportError:
+ raise ImportError("Pycocotools is not installed in your environment.")
+
+ masks = []
+ for polygons in segmentations:
+ rles = coco_mask.frPyObjects(polygons, height, width)
+ mask = coco_mask.decode(rles)
+ if len(mask.shape) < 3:
+ mask = mask[..., None]
+ mask = np.asarray(mask, dtype=np.uint8)
+ mask = np.any(mask, axis=2)
+ masks.append(mask)
+ if masks:
+ masks = np.stack(masks, axis=0)
+ else:
+ masks = np.zeros((0, height, width), dtype=np.uint8)
+
+ return masks
+
+
+def prepare_coco_detection_annotation(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: Optional[Union[ChannelDimension, str]] = None,
+):
+ """
+ Convert the target in COCO format into the format expected by DETA.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+
+ image_id = target["image_id"]
+ image_id = np.asarray([image_id], dtype=np.int64)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0]
+
+ classes = [obj["category_id"] for obj in annotations]
+ classes = np.asarray(classes, dtype=np.int64)
+
+ # for conversion to coco api
+ area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32)
+ iscrowd = np.asarray([obj.get("iscrowd", 0) for obj in annotations], dtype=np.int64)
+
+ boxes = [obj["bbox"] for obj in annotations]
+ # guard against no boxes via resizing
+ boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {}
+ new_target["image_id"] = image_id
+ new_target["class_labels"] = classes[keep]
+ new_target["boxes"] = boxes[keep]
+ new_target["area"] = area[keep]
+ new_target["iscrowd"] = iscrowd[keep]
+ new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64)
+
+ if annotations and "keypoints" in annotations[0]:
+ keypoints = [obj["keypoints"] for obj in annotations]
+ # Converting the filtered keypoints list to a numpy array
+ keypoints = np.asarray(keypoints, dtype=np.float32)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ if return_segmentation_masks:
+ segmentation_masks = [obj["segmentation"] for obj in annotations]
+ masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width)
+ new_target["masks"] = masks[keep]
+
+ return new_target
+
+
+def masks_to_boxes(masks: np.ndarray) -> np.ndarray:
+ """
+ Compute the bounding boxes around the provided panoptic segmentation masks.
+
+ Args:
+ masks: masks in format `[number_masks, height, width]` where N is the number of masks
+
+ Returns:
+ boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
+ """
+ if masks.size == 0:
+ return np.zeros((0, 4))
+
+ h, w = masks.shape[-2:]
+ y = np.arange(0, h, dtype=np.float32)
+ x = np.arange(0, w, dtype=np.float32)
+ # see https://github.com/pytorch/pytorch/issues/50276
+ y, x = np.meshgrid(y, x, indexing="ij")
+
+ x_mask = masks * np.expand_dims(x, axis=0)
+ x_max = x_mask.reshape(x_mask.shape[0], -1).max(-1)
+ x = np.ma.array(x_mask, mask=~(np.array(masks, dtype=bool)))
+ x_min = x.filled(fill_value=1e8)
+ x_min = x_min.reshape(x_min.shape[0], -1).min(-1)
+
+ y_mask = masks * np.expand_dims(y, axis=0)
+ y_max = y_mask.reshape(x_mask.shape[0], -1).max(-1)
+ y = np.ma.array(y_mask, mask=~(np.array(masks, dtype=bool)))
+ y_min = y.filled(fill_value=1e8)
+ y_min = y_min.reshape(y_min.shape[0], -1).min(-1)
+
+ return np.stack([x_min, y_min, x_max, y_max], 1)
+
+
+def prepare_coco_panoptic_annotation(
+ image: np.ndarray,
+ target: dict,
+ masks_path: Union[str, pathlib.Path],
+ return_masks: bool = True,
+ input_data_format: Union[ChannelDimension, str] = None,
+) -> dict:
+ """
+ Prepare a coco panoptic annotation for DETA.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+ annotation_path = pathlib.Path(masks_path) / target["file_name"]
+
+ new_target = {}
+ new_target["image_id"] = np.asarray([target["image_id"] if "image_id" in target else target["id"]], dtype=np.int64)
+ new_target["size"] = np.asarray([image_height, image_width], dtype=np.int64)
+ new_target["orig_size"] = np.asarray([image_height, image_width], dtype=np.int64)
+
+ if "segments_info" in target:
+ masks = np.asarray(PIL.Image.open(annotation_path), dtype=np.uint32)
+ masks = rgb_to_id(masks)
+
+ ids = np.array([segment_info["id"] for segment_info in target["segments_info"]])
+ masks = masks == ids[:, None, None]
+ masks = masks.astype(np.uint8)
+ if return_masks:
+ new_target["masks"] = masks
+ new_target["boxes"] = masks_to_boxes(masks)
+ new_target["class_labels"] = np.array(
+ [segment_info["category_id"] for segment_info in target["segments_info"]], dtype=np.int64
+ )
+ new_target["iscrowd"] = np.asarray(
+ [segment_info["iscrowd"] for segment_info in target["segments_info"]], dtype=np.int64
+ )
+ new_target["area"] = np.asarray(
+ [segment_info["area"] for segment_info in target["segments_info"]], dtype=np.float32
+ )
+
+ return new_target
+
+
+def resize_annotation(
+ annotation: dict[str, Any],
+ orig_size: tuple[int, int],
+ target_size: tuple[int, int],
+ threshold: float = 0.5,
+ resample: PILImageResampling = PILImageResampling.NEAREST,
+):
+ """
+ Resizes an annotation to a target size.
+
+ Args:
+ annotation (`dict[str, Any]`):
+ The annotation dictionary.
+ orig_size (`tuple[int, int]`):
+ The original size of the input image.
+ target_size (`tuple[int, int]`):
+ The target size of the image, as returned by the preprocessing `resize` step.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The threshold used to binarize the segmentation masks.
+ resample (`PILImageResampling`, defaults to `PILImageResampling.NEAREST`):
+ The resampling filter to use when resizing the masks.
+ """
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(target_size, orig_size))
+ ratio_height, ratio_width = ratios
+
+ new_annotation = {}
+ new_annotation["size"] = target_size
+
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ scaled_boxes = boxes * np.asarray([ratio_width, ratio_height, ratio_width, ratio_height], dtype=np.float32)
+ new_annotation["boxes"] = scaled_boxes
+ elif key == "area":
+ area = value
+ scaled_area = area * (ratio_width * ratio_height)
+ new_annotation["area"] = scaled_area
+ elif key == "masks":
+ masks = value[:, None]
+ masks = np.array([resize(mask, target_size, resample=resample) for mask in masks])
+ masks = masks.astype(np.float32)
+ masks = masks[:, 0] > threshold
+ new_annotation["masks"] = masks
+ elif key == "size":
+ new_annotation["size"] = target_size
+ else:
+ new_annotation[key] = value
+
+ return new_annotation
+
+
+class DetaImageProcessor(BaseImageProcessor):
+ r"""
+ Constructs a Deformable DETR image processor.
+
+ Args:
+ format (`str`, *optional*, defaults to `"coco_detection"`):
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
+ do_resize (`bool`, *optional*, defaults to `True`):
+ Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be
+ overridden by the `do_resize` parameter in the `preprocess` method.
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 800, "longest_edge": 1333}`):
+ Size of the image's `(height, width)` dimensions after resizing. Can be overridden by the `size` parameter
+ in the `preprocess` method. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ do_rescale (`bool`, *optional*, defaults to `True`):
+ Controls whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
+ `do_rescale` parameter in the `preprocess` method.
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
+ `preprocess` method.
+ do_normalize:
+ Controls whether to normalize the image. Can be overridden by the `do_normalize` parameter in the
+ `preprocess` method.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
+ Mean values to use when normalizing the image. Can be a single value or a list of values, one for each
+ channel. Can be overridden by the `image_mean` parameter in the `preprocess` method.
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`):
+ Standard deviation values to use when normalizing the image. Can be a single value or a list of values, one
+ for each channel. Can be overridden by the `image_std` parameter in the `preprocess` method.
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
+ Controls whether to convert the annotations to the format expected by the DETR model. Converts the
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
+ do_pad (`bool`, *optional*, defaults to `True`):
+ Controls whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess`
+ method. If `True`, padding will be applied to the bottom and right of the image with zeros.
+ If `pad_size` is provided, the image will be padded to the specified dimensions.
+ Otherwise, the image will be padded to the maximum height and width of the batch.
+ pad_size (`dict[str, int]`, *optional*):
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
+ height and width in the batch.
+ """
+
+ model_input_names = ["pixel_values", "pixel_mask"]
+
+ def __init__(
+ self,
+ format: Union[str, AnnotationFormat] = AnnotationFormat.COCO_DETECTION,
+ do_resize: bool = True,
+ size: Optional[dict[str, int]] = None,
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
+ do_rescale: bool = True,
+ rescale_factor: Union[int, float] = 1 / 255,
+ do_normalize: bool = True,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ do_convert_annotations: bool = True,
+ do_pad: bool = True,
+ pad_size: Optional[dict[str, int]] = None,
+ **kwargs,
+ ) -> None:
+ if "pad_and_return_pixel_mask" in kwargs:
+ do_pad = kwargs.pop("pad_and_return_pixel_mask")
+
+ size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
+ size = get_size_dict(size, default_to_square=False)
+
+ if do_convert_annotations is None:
+ do_convert_annotations = do_normalize
+
+ super().__init__(**kwargs)
+ self.format = format
+ self.do_resize = do_resize
+ self.size = size
+ self.resample = resample
+ self.do_rescale = do_rescale
+ self.rescale_factor = rescale_factor
+ self.do_normalize = do_normalize
+ self.do_convert_annotations = do_convert_annotations
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
+ self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
+ self.do_pad = do_pad
+ self.pad_size = pad_size
+
+ def prepare_annotation(
+ self,
+ image: np.ndarray,
+ target: dict,
+ format: Optional[AnnotationFormat] = None,
+ return_segmentation_masks: Optional[bool] = None,
+ masks_path: Optional[Union[str, pathlib.Path]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ ) -> dict:
+ """
+ Prepare an annotation for feeding into DETA model.
+ """
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ elif format == AnnotationFormat.COCO_PANOPTIC:
+ return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_panoptic_annotation(
+ image,
+ target,
+ masks_path=masks_path,
+ return_masks=return_segmentation_masks,
+ input_data_format=input_data_format,
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ def resize(
+ self,
+ image: np.ndarray,
+ size: dict[str, int],
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
+ data_format: Optional[ChannelDimension] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`dict[str, int]`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ data_format (`ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred from the input
+ image.
+ """
+ size = get_size_dict(size, default_to_square=False)
+ if "shortest_edge" in size and "longest_edge" in size:
+ new_size = get_resize_output_image_size(
+ image, size["shortest_edge"], size["longest_edge"], input_data_format=input_data_format
+ )
+ elif "height" in size and "width" in size:
+ new_size = (size["height"], size["width"])
+ elif "max_height" in size and "max_width" in size:
+ new_size = get_image_size_for_max_height_width(
+ image, size["max_height"], size["max_width"], input_data_format=input_data_format
+ )
+ else:
+ raise ValueError(
+ "Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got"
+ f" {size.keys()}."
+ )
+ image = resize(
+ image, size=new_size, resample=resample, data_format=data_format, input_data_format=input_data_format
+ )
+ return image
+
+ def resize_annotation(
+ self,
+ annotation,
+ orig_size,
+ size,
+ resample: PILImageResampling = PILImageResampling.NEAREST,
+ ) -> dict:
+ """
+ Resize the annotation to match the resized image. If size is an int, smaller edge of the mask will be matched
+ to this number.
+ """
+ return resize_annotation(annotation, orig_size=orig_size, target_size=size, resample=resample)
+
+ def rescale(
+ self,
+ image: np.ndarray,
+ rescale_factor: float,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ ) -> np.ndarray:
+ """
+ Rescale the image by the given factor. image = image * rescale_factor.
+
+ Args:
+ image (`np.ndarray`):
+ Image to rescale.
+ rescale_factor (`float`):
+ The value to use for rescaling.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ input_data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the input image. If unset, is inferred from the input image. Can be
+ one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ """
+ return rescale(image, rescale_factor, data_format=data_format, input_data_format=input_data_format)
+
+ def normalize_annotation(self, annotation: dict, image_size: tuple[int, int]) -> dict:
+ """
+ Normalize the boxes in the annotation from `[top_left_x, top_left_y, bottom_right_x, bottom_right_y]` to
+ `[center_x, center_y, width, height]` format and from absolute to relative pixel values.
+ """
+ return normalize_annotation(annotation, image_size=image_size)
+
+ def _update_annotation_for_padded_image(
+ self,
+ annotation: dict,
+ input_image_size: tuple[int, int],
+ output_image_size: tuple[int, int],
+ padding,
+ update_bboxes,
+ ) -> dict:
+ """
+ Update the annotation for a padded image.
+ """
+ new_annotation = {}
+ new_annotation["size"] = output_image_size
+
+ for key, value in annotation.items():
+ if key == "masks":
+ masks = value
+ masks = pad(
+ masks,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=0,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ masks = safe_squeeze(masks, 1)
+ new_annotation["masks"] = masks
+ elif key == "boxes" and update_bboxes:
+ boxes = value
+ boxes *= np.asarray(
+ [
+ input_image_size[1] / output_image_size[1],
+ input_image_size[0] / output_image_size[0],
+ input_image_size[1] / output_image_size[1],
+ input_image_size[0] / output_image_size[0],
+ ]
+ )
+ new_annotation["boxes"] = boxes
+ elif key == "size":
+ new_annotation["size"] = output_image_size
+ else:
+ new_annotation[key] = value
+ return new_annotation
+
+ def _pad_image(
+ self,
+ image: np.ndarray,
+ output_size: tuple[int, int],
+ annotation: Optional[dict[str, Any]] = None,
+ constant_values: Union[float, Iterable[float]] = 0,
+ data_format: Optional[ChannelDimension] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ update_bboxes: bool = True,
+ ) -> np.ndarray:
+ """
+ Pad an image with zeros to the given size.
+ """
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
+ output_height, output_width = output_size
+
+ pad_bottom = output_height - input_height
+ pad_right = output_width - input_width
+ padding = ((0, pad_bottom), (0, pad_right))
+ padded_image = pad(
+ image,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=constant_values,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ )
+ if annotation is not None:
+ annotation = self._update_annotation_for_padded_image(
+ annotation, (input_height, input_width), (output_height, output_width), padding, update_bboxes
+ )
+ return padded_image, annotation
+
+ def pad(
+ self,
+ images: list[np.ndarray],
+ annotations: Optional[Union[AnnotationType, list[AnnotationType]]] = None,
+ constant_values: Union[float, Iterable[float]] = 0,
+ return_pixel_mask: bool = True,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ data_format: Optional[ChannelDimension] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ update_bboxes: bool = True,
+ pad_size: Optional[dict[str, int]] = None,
+ ) -> BatchFeature:
+ """
+ Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width
+ in the batch and optionally returns their corresponding pixel mask.
+
+ Args:
+ images (list[`np.ndarray`]):
+ Images to pad.
+ annotations (`AnnotationType` or `list[AnnotationType]`, *optional*):
+ Annotations to transform according to the padding that is applied to the images.
+ constant_values (`float` or `Iterable[float]`, *optional*):
+ The value to use for the padding if `mode` is `"constant"`.
+ return_pixel_mask (`bool`, *optional*, defaults to `True`):
+ Whether to return a pixel mask.
+ return_tensors (`str` or `TensorType`, *optional*):
+ The type of tensors to return. Can be one of:
+ - Unset: Return a list of `np.ndarray`.
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred.
+ update_bboxes (`bool`, *optional*, defaults to `True`):
+ Whether to update the bounding boxes in the annotations to match the padded images. If the
+ bounding boxes have not been converted to relative coordinates and `(centre_x, centre_y, width, height)`
+ format, the bounding boxes will not be updated.
+ pad_size (`dict[str, int]`, *optional*):
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
+ height and width in the batch.
+ """
+ pad_size = pad_size if pad_size is not None else self.pad_size
+ if pad_size is not None:
+ padded_size = (pad_size["height"], pad_size["width"])
+ else:
+ padded_size = get_max_height_width(images, input_data_format=input_data_format)
+
+ annotation_list = annotations if annotations is not None else [None] * len(images)
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotation_list):
+ padded_image, padded_annotation = self._pad_image(
+ image,
+ padded_size,
+ annotation,
+ constant_values=constant_values,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ update_bboxes=update_bboxes,
+ )
+ padded_images.append(padded_image)
+ padded_annotations.append(padded_annotation)
+
+ data = {"pixel_values": padded_images}
+
+ if return_pixel_mask:
+ masks = [
+ make_pixel_mask(image=image, output_size=padded_size, input_data_format=input_data_format)
+ for image in images
+ ]
+ data["pixel_mask"] = masks
+
+ encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
+
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in padded_annotations
+ ]
+
+ return encoded_inputs
+
+ def preprocess(
+ self,
+ images: ImageInput,
+ annotations: Optional[Union[list[dict], list[list[dict]]]] = None,
+ return_segmentation_masks: Optional[bool] = None,
+ masks_path: Optional[Union[str, pathlib.Path]] = None,
+ do_resize: Optional[bool] = None,
+ size: Optional[dict[str, int]] = None,
+ resample=None, # PILImageResampling
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[Union[int, float]] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ do_convert_annotations: Optional[bool] = None,
+ do_pad: Optional[bool] = None,
+ format: Optional[Union[str, AnnotationFormat]] = None,
+ return_tensors: Optional[Union[TensorType, str]] = None,
+ data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ pad_size: Optional[dict[str, int]] = None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+
+ Args:
+ images (`ImageInput`):
+ Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging
+ from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
+ annotations (`list[Dict]` or `list[list[Dict]]`, *optional*):
+ List of annotations associated with the image or batch of images. If annotation is for object
+ detection, the annotations should be a dictionary with the following keys:
+ - "image_id" (`int`): The image id.
+ - "annotations" (`list[Dict]`): List of annotations for an image. Each annotation should be a
+ dictionary. An image can have no annotations, in which case the list should be empty.
+ If annotation is for segmentation, the annotations should be a dictionary with the following keys:
+ - "image_id" (`int`): The image id.
+ - "segments_info" (`list[Dict]`): List of segments for an image. Each segment should be a dictionary.
+ An image can have no segments, in which case the list should be empty.
+ - "file_name" (`str`): The file name of the image.
+ return_segmentation_masks (`bool`, *optional*, defaults to self.return_segmentation_masks):
+ Whether to return segmentation masks.
+ masks_path (`str` or `pathlib.Path`, *optional*):
+ Path to the directory containing the segmentation masks.
+ do_resize (`bool`, *optional*, defaults to self.do_resize):
+ Whether to resize the image.
+ size (`dict[str, int]`, *optional*, defaults to self.size):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling`, *optional*, defaults to self.resample):
+ Resampling filter to use when resizing the image.
+ do_rescale (`bool`, *optional*, defaults to self.do_rescale):
+ Whether to rescale the image.
+ rescale_factor (`float`, *optional*, defaults to self.rescale_factor):
+ Rescale factor to use when rescaling the image.
+ do_normalize (`bool`, *optional*, defaults to self.do_normalize):
+ Whether to normalize the image.
+ image_mean (`float` or `list[float]`, *optional*, defaults to self.image_mean):
+ Mean to use when normalizing the image.
+ image_std (`float` or `list[float]`, *optional*, defaults to self.image_std):
+ Standard deviation to use when normalizing the image.
+ do_convert_annotations (`bool`, *optional*, defaults to self.do_convert_annotations):
+ Whether to convert the annotations to the format expected by the model. Converts the bounding
+ boxes from the format `(top_left_x, top_left_y, width, height)` to `(center_x, center_y, width, height)`
+ and in relative coordinates.
+ do_pad (`bool`, *optional*, defaults to self.do_pad):
+ Whether to pad the image. If `True`, padding will be applied to the bottom and right of
+ the image with zeros. If `pad_size` is provided, the image will be padded to the specified
+ dimensions. Otherwise, the image will be padded to the maximum height and width of the batch.
+ format (`str` or `AnnotationFormat`, *optional*, defaults to self.format):
+ Format of the annotations.
+ return_tensors (`str` or `TensorType`, *optional*, defaults to self.return_tensors):
+ Type of tensors to return. If `None`, will return the list of images.
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
+ The channel dimension format for the output image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - Unset: Use the channel dimension format of the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+ pad_size (`dict[str, int]`, *optional*):
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
+ height and width in the batch.
+ """
+ if "pad_and_return_pixel_mask" in kwargs:
+ logger.warning_once(
+ "The `pad_and_return_pixel_mask` argument is deprecated and will be removed in a future version, "
+ "use `do_pad` instead.",
+ )
+ do_pad = kwargs.pop("pad_and_return_pixel_mask")
+
+ do_resize = self.do_resize if do_resize is None else do_resize
+ size = self.size if size is None else size
+ size = get_size_dict(size=size, default_to_square=False)
+ resample = self.resample if resample is None else resample
+ do_rescale = self.do_rescale if do_rescale is None else do_rescale
+ rescale_factor = self.rescale_factor if rescale_factor is None else rescale_factor
+ do_normalize = self.do_normalize if do_normalize is None else do_normalize
+ image_mean = self.image_mean if image_mean is None else image_mean
+ image_std = self.image_std if image_std is None else image_std
+ do_convert_annotations = (
+ self.do_convert_annotations if do_convert_annotations is None else do_convert_annotations
+ )
+ do_pad = self.do_pad if do_pad is None else do_pad
+ pad_size = self.pad_size if pad_size is None else pad_size
+ format = self.format if format is None else format
+
+ # Here, the pad() method pads to the maximum of (width, height). It does not need to be validated.
+
+ validate_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ )
+
+ if not is_batched(images):
+ images = [images]
+ annotations = [annotations] if annotations is not None else None
+
+ if not valid_images(images):
+ raise ValueError(
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
+ "torch.Tensor, tf.Tensor or jax.ndarray."
+ )
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ if (
+ masks_path is not None
+ and format == AnnotationFormat.COCO_PANOPTIC
+ and not isinstance(masks_path, (pathlib.Path, str))
+ ):
+ raise ValueError(
+ "The path to the directory containing the mask PNG files should be provided as a"
+ f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
+ )
+
+ # All transformations expect numpy arrays
+ images = [to_numpy_array(image) for image in images]
+
+ if do_rescale and is_scaled_image(images[0]):
+ logger.warning_once(
+ "It looks like you are trying to rescale already rescaled images. If the input"
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
+ )
+
+ if input_data_format is None:
+ # We assume that all images have the same channel dimension format.
+ input_data_format = infer_channel_dimension_format(images[0])
+
+ # prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
+ if annotations is not None:
+ prepared_images = []
+ prepared_annotations = []
+ for image, target in zip(images, annotations):
+ target = self.prepare_annotation(
+ image,
+ target,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=input_data_format,
+ )
+ prepared_images.append(image)
+ prepared_annotations.append(target)
+ images = prepared_images
+ annotations = prepared_annotations
+ del prepared_images, prepared_annotations
+
+ # transformations
+ if do_resize:
+ if annotations is not None:
+ resized_images, resized_annotations = [], []
+ for image, target in zip(images, annotations):
+ orig_size = get_image_size(image, input_data_format)
+ resized_image = self.resize(
+ image, size=size, resample=resample, input_data_format=input_data_format
+ )
+ resized_annotation = self.resize_annotation(
+ target, orig_size, get_image_size(resized_image, input_data_format)
+ )
+ resized_images.append(resized_image)
+ resized_annotations.append(resized_annotation)
+ images = resized_images
+ annotations = resized_annotations
+ del resized_images, resized_annotations
+ else:
+ images = [
+ self.resize(image, size=size, resample=resample, input_data_format=input_data_format)
+ for image in images
+ ]
+
+ if do_rescale:
+ images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]
+
+ if do_normalize:
+ images = [
+ self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images
+ ]
+
+ if do_convert_annotations and annotations is not None:
+ annotations = [
+ self.normalize_annotation(annotation, get_image_size(image, input_data_format))
+ for annotation, image in zip(annotations, images)
+ ]
+
+ if do_pad:
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ encoded_inputs = self.pad(
+ images,
+ annotations=annotations,
+ return_pixel_mask=True,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ return_tensors=return_tensors,
+ update_bboxes=do_convert_annotations,
+ pad_size=pad_size,
+ )
+ else:
+ images = [
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
+ for image in images
+ ]
+ encoded_inputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+
+ return encoded_inputs
+
+ def post_process_object_detection(
+ self,
+ outputs,
+ threshold: float = 0.5,
+ target_sizes: Union[TensorType, list[tuple]] = None,
+ nms_threshold: float = 0.7,
+ ):
+ """
+ Converts the output of [`DetaForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`DetrObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*, defaults to 0.5):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ nms_threshold (`float`, *optional*, defaults to 0.7):
+ NMS threshold.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+ batch_size, num_queries, num_labels = out_logits.shape
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = out_logits.sigmoid()
+
+ all_scores = prob.view(batch_size, num_queries * num_labels).to(out_logits.device)
+ all_indexes = torch.arange(num_queries * num_labels)[None].repeat(batch_size, 1).to(out_logits.device)
+ all_boxes = torch.div(all_indexes, out_logits.shape[2], rounding_mode="floor")
+ all_labels = all_indexes % out_logits.shape[2]
+
+ boxes = center_to_corners_format(out_bbox)
+ boxes = torch.gather(boxes, 1, all_boxes.unsqueeze(-1).repeat(1, 1, 4))
+
+ # and from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for b in range(batch_size):
+ box = boxes[b]
+ score = all_scores[b]
+ lbls = all_labels[b]
+
+ pre_topk = score.topk(min(10000, num_queries * num_labels)).indices
+ box = box[pre_topk]
+ score = score[pre_topk]
+ lbls = lbls[pre_topk]
+
+ # apply NMS
+ keep_inds = batched_nms(box, score, lbls, nms_threshold)[:100]
+ score = score[keep_inds]
+ lbls = lbls[keep_inds]
+ box = box[keep_inds]
+
+ results.append(
+ {
+ "scores": score[score > threshold],
+ "labels": lbls[score > threshold],
+ "boxes": box[score > threshold],
+ }
+ )
+
+ return results
+
+
+__all__ = ["DetaImageProcessor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/modeling_deta.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/modeling_deta.py
new file mode 100644
index 0000000000000000000000000000000000000000..a05f82ed072a813713370cbf1fb527a3415bebec
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/deta/modeling_deta.py
@@ -0,0 +1,2816 @@
+# coding=utf-8
+# Copyright 2022 SenseTime and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch DETA model."""
+
+import copy
+import math
+import os
+import warnings
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Optional, Union
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+from torch.autograd import Function
+from torch.autograd.function import once_differentiable
+
+from ....activations import ACT2FN
+from ....file_utils import (
+ ModelOutput,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ is_scipy_available,
+ is_torch_cuda_available,
+ is_vision_available,
+ replace_return_docstrings,
+)
+from ....modeling_attn_mask_utils import _prepare_4d_attention_mask
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_outputs import BaseModelOutput
+from ....modeling_utils import PreTrainedModel
+from ....pytorch_utils import meshgrid
+from ....utils import is_accelerate_available, is_ninja_available, is_torchvision_available, logging, requires_backends
+from ....utils.backbone_utils import load_backbone
+from .configuration_deta import DetaConfig
+
+
+logger = logging.get_logger(__name__)
+
+MultiScaleDeformableAttention = None
+
+
+def load_cuda_kernels():
+ from torch.utils.cpp_extension import load
+
+ global MultiScaleDeformableAttention
+
+ root = Path(__file__).resolve().parent.parent.parent.parent / "kernels" / "deta"
+ src_files = [
+ root / filename
+ for filename in [
+ "vision.cpp",
+ os.path.join("cpu", "ms_deform_attn_cpu.cpp"),
+ os.path.join("cuda", "ms_deform_attn_cuda.cu"),
+ ]
+ ]
+
+ MultiScaleDeformableAttention = load(
+ "MultiScaleDeformableAttention",
+ src_files,
+ with_cuda=True,
+ extra_include_paths=[str(root)],
+ extra_cflags=["-DWITH_CUDA=1"],
+ extra_cuda_cflags=[
+ "-DCUDA_HAS_FP16=1",
+ "-D__CUDA_NO_HALF_OPERATORS__",
+ "-D__CUDA_NO_HALF_CONVERSIONS__",
+ "-D__CUDA_NO_HALF2_OPERATORS__",
+ ],
+ )
+
+
+class MultiScaleDeformableAttentionFunction(Function):
+ @staticmethod
+ def forward(
+ context,
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ im2col_step,
+ ):
+ context.im2col_step = im2col_step
+ output = MultiScaleDeformableAttention.ms_deform_attn_forward(
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ context.im2col_step,
+ )
+ context.save_for_backward(
+ value, value_spatial_shapes, value_level_start_index, sampling_locations, attention_weights
+ )
+ return output
+
+ @staticmethod
+ @once_differentiable
+ def backward(context, grad_output):
+ (
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ ) = context.saved_tensors
+ grad_value, grad_sampling_loc, grad_attn_weight = MultiScaleDeformableAttention.ms_deform_attn_backward(
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ grad_output,
+ context.im2col_step,
+ )
+
+ return grad_value, None, None, grad_sampling_loc, grad_attn_weight, None
+
+
+if is_accelerate_available():
+ from accelerate import PartialState
+ from accelerate.utils import reduce
+
+if is_vision_available():
+ from transformers.image_transforms import center_to_corners_format
+
+if is_torchvision_available():
+ from torchvision.ops.boxes import batched_nms
+
+if is_scipy_available():
+ from scipy.optimize import linear_sum_assignment
+
+logger = logging.get_logger(__name__)
+
+_CONFIG_FOR_DOC = "DetaConfig"
+_CHECKPOINT_FOR_DOC = "jozhang97/deta-swin-large-o365"
+
+
+@dataclass
+class DetaDecoderOutput(ModelOutput):
+ """
+ Base class for outputs of the DetaDecoder. This class adds two attributes to
+ BaseModelOutputWithCrossAttentions, namely:
+ - a stacked tensor of intermediate decoder hidden states (i.e. the output of each decoder layer)
+ - a stacked tensor of intermediate reference points.
+
+ Args:
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the model.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, sequence_length, hidden_size)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
+ plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
+ the self-attention heads.
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` and `config.add_cross_attention=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights of the decoder's cross-attention layer, after the attention softmax,
+ used to compute the weighted average in the cross-attention heads.
+ """
+
+ last_hidden_state: Optional[torch.FloatTensor] = None
+ intermediate_hidden_states: Optional[torch.FloatTensor] = None
+ intermediate_reference_points: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+ cross_attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+@dataclass
+class DetaModelOutput(ModelOutput):
+ """
+ Base class for outputs of the Deformable DETR encoder-decoder model.
+
+ Args:
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points sent through the Transformer decoder.
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, num_queries, hidden_size)`. Hidden-states of the decoder at the output of each layer
+ plus the initial embedding outputs.
+ decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, num_queries,
+ num_queries)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted
+ average in the self-attention heads.
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_queries, num_heads, 4, 4)`.
+ Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
+ weighted average in the cross-attention heads.
+ encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder of the model.
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each
+ layer plus the initial embedding outputs.
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_queries, num_heads, 4, 4)`.
+ Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
+ self-attention heads.
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the first stage.
+ output_proposals (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.two_stage=True`):
+ Logits of proposal bounding boxes coordinates in the gen_encoder_output_proposals.
+ """
+
+ init_reference_points: Optional[torch.FloatTensor] = None
+ last_hidden_state: Optional[torch.FloatTensor] = None
+ intermediate_hidden_states: Optional[torch.FloatTensor] = None
+ intermediate_reference_points: Optional[torch.FloatTensor] = None
+ decoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ decoder_attentions: Optional[tuple[torch.FloatTensor]] = None
+ cross_attentions: Optional[tuple[torch.FloatTensor]] = None
+ encoder_last_hidden_state: Optional[torch.FloatTensor] = None
+ encoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ encoder_attentions: Optional[tuple[torch.FloatTensor]] = None
+ enc_outputs_class: Optional[torch.FloatTensor] = None
+ enc_outputs_coord_logits: Optional[torch.FloatTensor] = None
+ output_proposals: Optional[torch.FloatTensor] = None
+
+
+@dataclass
+class DetaObjectDetectionOutput(ModelOutput):
+ """
+ Output type of [`DetaForObjectDetection`].
+
+ Args:
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
+ scale-invariant IoU loss.
+ loss_dict (`Dict`, *optional*):
+ A dictionary containing the individual losses. Useful for logging.
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
+ Classification logits (including no-object) for all queries.
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
+ possible padding). You can use [`~DetaProcessor.post_process_object_detection`] to retrieve the
+ unnormalized bounding boxes.
+ auxiliary_outputs (`list[Dict]`, *optional*):
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
+ `pred_boxes`) for each decoder layer.
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, num_queries, hidden_size)`. Hidden-states of the decoder at the output of each layer
+ plus the initial embedding outputs.
+ decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, num_queries,
+ num_queries)`. Attentions weights of the decoder, after the attention softmax, used to compute the weighted
+ average in the self-attention heads.
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_queries, num_heads, 4, 4)`.
+ Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
+ weighted average in the cross-attention heads.
+ encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder of the model.
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the encoder at the output of each
+ layer plus the initial embedding outputs.
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_heads, 4,
+ 4)`. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average
+ in the self-attention heads.
+ intermediate_hidden_states (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, hidden_size)`):
+ Stacked intermediate hidden states (output of each layer of the decoder).
+ intermediate_reference_points (`torch.FloatTensor` of shape `(batch_size, config.decoder_layers, num_queries, 4)`):
+ Stacked intermediate reference points (reference points of each layer of the decoder).
+ init_reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Initial reference points sent through the Transformer decoder.
+ enc_outputs_class (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Predicted bounding boxes scores where the top `config.two_stage_num_proposals` scoring bounding boxes are
+ picked as region proposals in the first stage. Output of bounding box binary classification (i.e.
+ foreground and background).
+ enc_outputs_coord_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.with_box_refine=True` and `config.two_stage=True`):
+ Logits of predicted bounding boxes coordinates in the first stage.
+ output_proposals (`torch.FloatTensor` of shape `(batch_size, sequence_length, 4)`, *optional*, returned when `config.two_stage=True`):
+ Logits of proposal bounding boxes coordinates in the gen_encoder_output_proposals.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ loss_dict: Optional[dict] = None
+ logits: Optional[torch.FloatTensor] = None
+ pred_boxes: Optional[torch.FloatTensor] = None
+ auxiliary_outputs: Optional[list[dict]] = None
+ init_reference_points: Optional[torch.FloatTensor] = None
+ last_hidden_state: Optional[torch.FloatTensor] = None
+ intermediate_hidden_states: Optional[torch.FloatTensor] = None
+ intermediate_reference_points: Optional[torch.FloatTensor] = None
+ decoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ decoder_attentions: Optional[tuple[torch.FloatTensor]] = None
+ cross_attentions: Optional[tuple[torch.FloatTensor]] = None
+ encoder_last_hidden_state: Optional[torch.FloatTensor] = None
+ encoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ encoder_attentions: Optional[tuple[torch.FloatTensor]] = None
+ enc_outputs_class: Optional = None
+ enc_outputs_coord_logits: Optional = None
+ output_proposals: Optional[torch.FloatTensor] = None
+
+
+def _get_clones(module, N):
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
+
+
+def inverse_sigmoid(x, eps=1e-5):
+ x = x.clamp(min=0, max=1)
+ x1 = x.clamp(min=eps)
+ x2 = (1 - x).clamp(min=eps)
+ return torch.log(x1 / x2)
+
+
+class DetaFrozenBatchNorm2d(nn.Module):
+ """
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
+
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt, without which any other models than
+ torchvision.models.resnet[18,34,50,101] produce nans.
+ """
+
+ def __init__(self, n):
+ super().__init__()
+ self.register_buffer("weight", torch.ones(n))
+ self.register_buffer("bias", torch.zeros(n))
+ self.register_buffer("running_mean", torch.zeros(n))
+ self.register_buffer("running_var", torch.ones(n))
+
+ def _load_from_state_dict(
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ ):
+ num_batches_tracked_key = prefix + "num_batches_tracked"
+ if num_batches_tracked_key in state_dict:
+ del state_dict[num_batches_tracked_key]
+
+ super()._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
+
+ def forward(self, x):
+ # move reshapes to the beginning
+ # to make it user-friendly
+ weight = self.weight.reshape(1, -1, 1, 1)
+ bias = self.bias.reshape(1, -1, 1, 1)
+ running_var = self.running_var.reshape(1, -1, 1, 1)
+ running_mean = self.running_mean.reshape(1, -1, 1, 1)
+ epsilon = 1e-5
+ scale = weight * (running_var + epsilon).rsqrt()
+ bias = bias - running_mean * scale
+ return x * scale + bias
+
+
+def replace_batch_norm(model):
+ r"""
+ Recursively replace all `torch.nn.BatchNorm2d` with `DetaFrozenBatchNorm2d`.
+
+ Args:
+ model (torch.nn.Module):
+ input model
+ """
+ for name, module in model.named_children():
+ if isinstance(module, nn.BatchNorm2d):
+ new_module = DetaFrozenBatchNorm2d(module.num_features)
+
+ if module.weight.device != torch.device("meta"):
+ new_module.weight.data.copy_(module.weight)
+ new_module.bias.data.copy_(module.bias)
+ new_module.running_mean.data.copy_(module.running_mean)
+ new_module.running_var.data.copy_(module.running_var)
+
+ model._modules[name] = new_module
+
+ if len(list(module.children())) > 0:
+ replace_batch_norm(module)
+
+
+class DetaBackboneWithPositionalEncodings(nn.Module):
+ """
+ Backbone model with positional embeddings.
+
+ nn.BatchNorm2d layers are replaced by DetaFrozenBatchNorm2d as defined above.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ backbone = load_backbone(config)
+ with torch.no_grad():
+ replace_batch_norm(backbone)
+ self.model = backbone
+ self.intermediate_channel_sizes = self.model.channels
+
+ # TODO fix this
+ if config.backbone_config.model_type == "resnet":
+ for name, parameter in self.model.named_parameters():
+ if "stages.1" not in name and "stages.2" not in name and "stages.3" not in name:
+ parameter.requires_grad_(False)
+
+ self.position_embedding = build_position_encoding(config)
+
+ def forward(self, pixel_values: torch.Tensor, pixel_mask: torch.Tensor):
+ """
+ Outputs feature maps of latter stages C_3 through C_5 in ResNet if `config.num_feature_levels > 1`, otherwise
+ outputs feature maps of C_5.
+ """
+ # first, send pixel_values through the backbone to get list of feature maps
+ features = self.model(pixel_values).feature_maps
+
+ # next, create position embeddings
+ out = []
+ pos = []
+ for feature_map in features:
+ # downsample pixel_mask to match shape of corresponding feature_map
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=feature_map.shape[-2:]).to(torch.bool)[0]
+ position_embeddings = self.position_embedding(feature_map, mask).to(feature_map.dtype)
+ out.append((feature_map, mask))
+ pos.append(position_embeddings)
+
+ return out, pos
+
+
+class DetaSinePositionEmbedding(nn.Module):
+ """
+ This is a more standard version of the position embedding, very similar to the one used by the Attention is all you
+ need paper, generalized to work on images.
+ """
+
+ def __init__(self, embedding_dim=64, temperature=10000, normalize=False, scale=None):
+ super().__init__()
+ self.embedding_dim = embedding_dim
+ self.temperature = temperature
+ self.normalize = normalize
+ if scale is not None and normalize is False:
+ raise ValueError("normalize should be True if scale is passed")
+ if scale is None:
+ scale = 2 * math.pi
+ self.scale = scale
+
+ def forward(self, pixel_values, pixel_mask):
+ if pixel_mask is None:
+ raise ValueError("No pixel mask provided")
+ y_embed = pixel_mask.cumsum(1, dtype=torch.float32)
+ x_embed = pixel_mask.cumsum(2, dtype=torch.float32)
+ if self.normalize:
+ eps = 1e-6
+ y_embed = (y_embed - 0.5) / (y_embed[:, -1:, :] + eps) * self.scale
+ x_embed = (x_embed - 0.5) / (x_embed[:, :, -1:] + eps) * self.scale
+
+ dim_t = torch.arange(self.embedding_dim, dtype=torch.int64, device=pixel_values.device).float()
+ dim_t = self.temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / self.embedding_dim)
+
+ pos_x = x_embed[:, :, :, None] / dim_t
+ pos_y = y_embed[:, :, :, None] / dim_t
+ pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3)
+ pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3)
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
+ return pos
+
+
+class DetaLearnedPositionEmbedding(nn.Module):
+ """
+ This module learns positional embeddings up to a fixed maximum size.
+ """
+
+ def __init__(self, embedding_dim=256):
+ super().__init__()
+ self.row_embeddings = nn.Embedding(50, embedding_dim)
+ self.column_embeddings = nn.Embedding(50, embedding_dim)
+
+ def forward(self, pixel_values, pixel_mask=None):
+ height, width = pixel_values.shape[-2:]
+ width_values = torch.arange(width, device=pixel_values.device)
+ height_values = torch.arange(height, device=pixel_values.device)
+ x_emb = self.column_embeddings(width_values)
+ y_emb = self.row_embeddings(height_values)
+ pos = torch.cat([x_emb.unsqueeze(0).repeat(height, 1, 1), y_emb.unsqueeze(1).repeat(1, width, 1)], dim=-1)
+ pos = pos.permute(2, 0, 1)
+ pos = pos.unsqueeze(0)
+ pos = pos.repeat(pixel_values.shape[0], 1, 1, 1)
+ return pos
+
+
+def build_position_encoding(config):
+ n_steps = config.d_model // 2
+ if config.position_embedding_type == "sine":
+ # TODO find a better way of exposing other arguments
+ position_embedding = DetaSinePositionEmbedding(n_steps, normalize=True)
+ elif config.position_embedding_type == "learned":
+ position_embedding = DetaLearnedPositionEmbedding(n_steps)
+ else:
+ raise ValueError(f"Not supported {config.position_embedding_type}")
+
+ return position_embedding
+
+
+def multi_scale_deformable_attention(
+ value: Tensor, value_spatial_shapes: Tensor, sampling_locations: Tensor, attention_weights: Tensor
+) -> Tensor:
+ batch_size, _, num_heads, hidden_dim = value.shape
+ _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape
+ value_list = value.split([height.item() * width.item() for height, width in value_spatial_shapes], dim=1)
+ sampling_grids = 2 * sampling_locations - 1
+ sampling_value_list = []
+ for level_id, (height, width) in enumerate(value_spatial_shapes):
+ # batch_size, height*width, num_heads, hidden_dim
+ # -> batch_size, height*width, num_heads*hidden_dim
+ # -> batch_size, num_heads*hidden_dim, height*width
+ # -> batch_size*num_heads, hidden_dim, height, width
+ value_l_ = (
+ value_list[level_id].flatten(2).transpose(1, 2).reshape(batch_size * num_heads, hidden_dim, height, width)
+ )
+ # batch_size, num_queries, num_heads, num_points, 2
+ # -> batch_size, num_heads, num_queries, num_points, 2
+ # -> batch_size*num_heads, num_queries, num_points, 2
+ sampling_grid_l_ = sampling_grids[:, :, :, level_id].transpose(1, 2).flatten(0, 1)
+ # batch_size*num_heads, hidden_dim, num_queries, num_points
+ sampling_value_l_ = nn.functional.grid_sample(
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
+ )
+ sampling_value_list.append(sampling_value_l_)
+ # (batch_size, num_queries, num_heads, num_levels, num_points)
+ # -> (batch_size, num_heads, num_queries, num_levels, num_points)
+ # -> (batch_size, num_heads, 1, num_queries, num_levels*num_points)
+ attention_weights = attention_weights.transpose(1, 2).reshape(
+ batch_size * num_heads, 1, num_queries, num_levels * num_points
+ )
+ output = (
+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)
+ .sum(-1)
+ .view(batch_size, num_heads * hidden_dim, num_queries)
+ )
+ return output.transpose(1, 2).contiguous()
+
+
+class DetaMultiscaleDeformableAttention(nn.Module):
+ """
+ Multiscale deformable attention as proposed in Deformable DETR.
+ """
+
+ def __init__(self, config: DetaConfig, num_heads: int, n_points: int):
+ super().__init__()
+
+ kernel_loaded = MultiScaleDeformableAttention is not None
+ if is_torch_cuda_available() and is_ninja_available() and not kernel_loaded:
+ try:
+ load_cuda_kernels()
+ except Exception as e:
+ logger.warning(f"Could not load the custom kernel for multi-scale deformable attention: {e}")
+
+ if config.d_model % num_heads != 0:
+ raise ValueError(
+ f"embed_dim (d_model) must be divisible by num_heads, but got {config.d_model} and {num_heads}"
+ )
+ dim_per_head = config.d_model // num_heads
+ # check if dim_per_head is power of 2
+ if not ((dim_per_head & (dim_per_head - 1) == 0) and dim_per_head != 0):
+ warnings.warn(
+ "You'd better set embed_dim (d_model) in DetaMultiscaleDeformableAttention to make the"
+ " dimension of each attention head a power of 2 which is more efficient in the authors' CUDA"
+ " implementation."
+ )
+
+ self.im2col_step = 64
+
+ self.d_model = config.d_model
+ self.n_levels = config.num_feature_levels
+ self.n_heads = num_heads
+ self.n_points = n_points
+
+ self.sampling_offsets = nn.Linear(config.d_model, num_heads * self.n_levels * n_points * 2)
+ self.attention_weights = nn.Linear(config.d_model, num_heads * self.n_levels * n_points)
+ self.value_proj = nn.Linear(config.d_model, config.d_model)
+ self.output_proj = nn.Linear(config.d_model, config.d_model)
+
+ self.disable_custom_kernels = config.disable_custom_kernels
+
+ self._reset_parameters()
+
+ def _reset_parameters(self):
+ nn.init.constant_(self.sampling_offsets.weight.data, 0.0)
+ default_dtype = torch.get_default_dtype()
+ thetas = torch.arange(self.n_heads, dtype=torch.int64).to(default_dtype) * (2.0 * math.pi / self.n_heads)
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (
+ (grid_init / grid_init.abs().max(-1, keepdim=True)[0])
+ .view(self.n_heads, 1, 1, 2)
+ .repeat(1, self.n_levels, self.n_points, 1)
+ )
+ for i in range(self.n_points):
+ grid_init[:, :, i, :] *= i + 1
+ with torch.no_grad():
+ self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1))
+ nn.init.constant_(self.attention_weights.weight.data, 0.0)
+ nn.init.constant_(self.attention_weights.bias.data, 0.0)
+ nn.init.xavier_uniform_(self.value_proj.weight.data)
+ nn.init.constant_(self.value_proj.bias.data, 0.0)
+ nn.init.xavier_uniform_(self.output_proj.weight.data)
+ nn.init.constant_(self.output_proj.bias.data, 0.0)
+
+ def with_pos_embed(self, tensor: torch.Tensor, position_embeddings: Optional[Tensor]):
+ return tensor if position_embeddings is None else tensor + position_embeddings
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ position_embeddings: Optional[torch.Tensor] = None,
+ reference_points=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ output_attentions: bool = False,
+ ):
+ # add position embeddings to the hidden states before projecting to queries and keys
+ if position_embeddings is not None:
+ hidden_states = self.with_pos_embed(hidden_states, position_embeddings)
+
+ batch_size, num_queries, _ = hidden_states.shape
+ batch_size, sequence_length, _ = encoder_hidden_states.shape
+ if (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() != sequence_length:
+ raise ValueError(
+ "Make sure to align the spatial shapes with the sequence length of the encoder hidden states"
+ )
+
+ value = self.value_proj(encoder_hidden_states)
+ if attention_mask is not None:
+ # we invert the attention_mask
+ value = value.masked_fill(~attention_mask[..., None], float(0))
+ value = value.view(batch_size, sequence_length, self.n_heads, self.d_model // self.n_heads)
+ sampling_offsets = self.sampling_offsets(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points, 2
+ )
+ attention_weights = self.attention_weights(hidden_states).view(
+ batch_size, num_queries, self.n_heads, self.n_levels * self.n_points
+ )
+ attention_weights = F.softmax(attention_weights, -1).view(
+ batch_size, num_queries, self.n_heads, self.n_levels, self.n_points
+ )
+ # batch_size, num_queries, n_heads, n_levels, n_points, 2
+ num_coordinates = reference_points.shape[-1]
+ if num_coordinates == 2:
+ offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :]
+ + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
+ )
+ elif num_coordinates == 4:
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :2]
+ + sampling_offsets / self.n_points * reference_points[:, :, None, :, None, 2:] * 0.5
+ )
+ else:
+ raise ValueError(f"Last dim of reference_points must be 2 or 4, but got {reference_points.shape[-1]}")
+
+ if self.disable_custom_kernels:
+ # PyTorch implementation
+ output = multi_scale_deformable_attention(value, spatial_shapes, sampling_locations, attention_weights)
+ else:
+ try:
+ # custom kernel
+ output = MultiScaleDeformableAttentionFunction.apply(
+ value,
+ spatial_shapes,
+ level_start_index,
+ sampling_locations,
+ attention_weights,
+ self.im2col_step,
+ )
+ except Exception:
+ # PyTorch implementation
+ output = multi_scale_deformable_attention(value, spatial_shapes, sampling_locations, attention_weights)
+ output = self.output_proj(output)
+
+ return output, attention_weights
+
+
+class DetaMultiheadAttention(nn.Module):
+ """
+ Multi-headed attention from 'Attention Is All You Need' paper.
+
+ Here, we add position embeddings to the queries and keys (as explained in the Deformable DETR paper).
+ """
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ bias: bool = True,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ if self.head_dim * num_heads != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
+ f" {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, batch_size: int):
+ return tensor.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ def with_pos_embed(self, tensor: torch.Tensor, position_embeddings: Optional[Tensor]):
+ return tensor if position_embeddings is None else tensor + position_embeddings
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_embeddings: Optional[torch.Tensor] = None,
+ output_attentions: bool = False,
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
+ """Input shape: Batch x Time x Channel"""
+
+ batch_size, target_len, embed_dim = hidden_states.size()
+ # add position embeddings to the hidden states before projecting to queries and keys
+ if position_embeddings is not None:
+ hidden_states_original = hidden_states
+ hidden_states = self.with_pos_embed(hidden_states, position_embeddings)
+
+ # get queries, keys and values
+ query_states = self.q_proj(hidden_states) * self.scaling
+ key_states = self._shape(self.k_proj(hidden_states), -1, batch_size)
+ value_states = self._shape(self.v_proj(hidden_states_original), -1, batch_size)
+
+ proj_shape = (batch_size * self.num_heads, -1, self.head_dim)
+ query_states = self._shape(query_states, target_len, batch_size).view(*proj_shape)
+ key_states = key_states.view(*proj_shape)
+ value_states = value_states.view(*proj_shape)
+
+ source_len = key_states.size(1)
+
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
+
+ if attn_weights.size() != (batch_size * self.num_heads, target_len, source_len):
+ raise ValueError(
+ f"Attention weights should be of size {(batch_size * self.num_heads, target_len, source_len)}, but is"
+ f" {attn_weights.size()}"
+ )
+
+ # expand attention_mask
+ if attention_mask is not None:
+ # [batch_size, seq_len] -> [batch_size, 1, target_seq_len, source_seq_len]
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
+
+ if attention_mask is not None:
+ if attention_mask.size() != (batch_size, 1, target_len, source_len):
+ raise ValueError(
+ f"Attention mask should be of size {(batch_size, 1, target_len, source_len)}, but is"
+ f" {attention_mask.size()}"
+ )
+ if attention_mask.dtype == torch.bool:
+ attention_mask = torch.zeros_like(attention_mask, dtype=attn_weights.dtype).masked_fill_(
+ attention_mask, -torch.inf
+ )
+ attn_weights = attn_weights.view(batch_size, self.num_heads, target_len, source_len) + attention_mask
+ attn_weights = attn_weights.view(batch_size * self.num_heads, target_len, source_len)
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ if output_attentions:
+ # this operation is a bit awkward, but it's required to
+ # make sure that attn_weights keeps its gradient.
+ # In order to do so, attn_weights have to reshaped
+ # twice and have to be reused in the following
+ attn_weights_reshaped = attn_weights.view(batch_size, self.num_heads, target_len, source_len)
+ attn_weights = attn_weights_reshaped.view(batch_size * self.num_heads, target_len, source_len)
+ else:
+ attn_weights_reshaped = None
+
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
+
+ attn_output = torch.bmm(attn_probs, value_states)
+
+ if attn_output.size() != (batch_size * self.num_heads, target_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output` should be of size {(batch_size, self.num_heads, target_len, self.head_dim)}, but is"
+ f" {attn_output.size()}"
+ )
+
+ attn_output = attn_output.view(batch_size, self.num_heads, target_len, self.head_dim)
+ attn_output = attn_output.transpose(1, 2)
+ attn_output = attn_output.reshape(batch_size, target_len, embed_dim)
+
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights_reshaped
+
+
+class DetaEncoderLayer(nn.Module):
+ def __init__(self, config: DetaConfig):
+ super().__init__()
+ self.embed_dim = config.d_model
+ self.self_attn = DetaMultiscaleDeformableAttention(
+ config,
+ num_heads=config.encoder_attention_heads,
+ n_points=config.encoder_n_points,
+ )
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ position_embeddings: Optional[torch.Tensor] = None,
+ reference_points=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ output_attentions: bool = False,
+ ):
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Input to the layer.
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
+ Attention mask.
+ position_embeddings (`torch.FloatTensor`, *optional*):
+ Position embeddings, to be added to `hidden_states`.
+ reference_points (`torch.FloatTensor`, *optional*):
+ Reference points.
+ spatial_shapes (`torch.LongTensor`, *optional*):
+ Spatial shapes of the backbone feature maps.
+ level_start_index (`torch.LongTensor`, *optional*):
+ Level start index.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ """
+ residual = hidden_states
+
+ # Apply Multi-scale Deformable Attention Module on the multi-scale feature maps.
+ hidden_states, attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ encoder_hidden_states=hidden_states,
+ encoder_attention_mask=attention_mask,
+ position_embeddings=position_embeddings,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ residual = hidden_states
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ if self.training:
+ if torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any():
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+class DetaDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: DetaConfig):
+ super().__init__()
+ self.embed_dim = config.d_model
+
+ # self-attention
+ self.self_attn = DetaMultiheadAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ )
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+ # cross-attention
+ self.encoder_attn = DetaMultiscaleDeformableAttention(
+ config,
+ num_heads=config.decoder_attention_heads,
+ n_points=config.decoder_n_points,
+ )
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+ # feedforward neural networks
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ position_embeddings: Optional[torch.Tensor] = None,
+ reference_points=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = False,
+ ):
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`):
+ Input to the layer of shape `(batch, seq_len, embed_dim)`.
+ position_embeddings (`torch.FloatTensor`, *optional*):
+ Position embeddings that are added to the queries and keys in the self-attention layer.
+ reference_points (`torch.FloatTensor`, *optional*):
+ Reference points.
+ spatial_shapes (`torch.LongTensor`, *optional*):
+ Spatial shapes.
+ level_start_index (`torch.LongTensor`, *optional*):
+ Level start index.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
+ values.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ """
+ residual = hidden_states
+
+ # Self Attention
+ hidden_states, self_attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ position_embeddings=position_embeddings,
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ second_residual = hidden_states
+
+ # Cross-Attention
+ cross_attn_weights = None
+ hidden_states, cross_attn_weights = self.encoder_attn(
+ hidden_states=hidden_states,
+ attention_mask=encoder_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ position_embeddings=position_embeddings,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = second_residual + hidden_states
+
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights, cross_attn_weights)
+
+ return outputs
+
+
+class DetaPreTrainedModel(PreTrainedModel):
+ config: DetaConfig
+ base_model_prefix = "model"
+ main_input_name = "pixel_values"
+ _no_split_modules = [r"DetaBackboneWithPositionalEncodings", r"DetaEncoderLayer", r"DetaDecoderLayer"]
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ std = self.config.init_std
+
+ if isinstance(module, DetaLearnedPositionEmbedding):
+ nn.init.uniform_(module.row_embeddings.weight)
+ nn.init.uniform_(module.column_embeddings.weight)
+ elif isinstance(module, DetaMultiscaleDeformableAttention):
+ module._reset_parameters()
+ elif isinstance(module, (nn.Linear, nn.Conv2d, nn.BatchNorm2d)):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ if hasattr(module, "reference_points") and not self.config.two_stage:
+ nn.init.xavier_uniform_(module.reference_points.weight.data, gain=1.0)
+ nn.init.constant_(module.reference_points.bias.data, 0.0)
+ if hasattr(module, "level_embed"):
+ nn.init.normal_(module.level_embed)
+
+
+DETA_START_DOCSTRING = r"""
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`DetaConfig`]):
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
+ load the weights associated with the model, only the configuration. Check out the
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+DETA_INPUTS_DOCSTRING = r"""
+ Args:
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Pixel values. Padding will be ignored by default should you provide it.
+
+ Pixel values can be obtained using [`AutoImageProcessor`]. See [`AutoImageProcessor.__call__`] for details.
+
+ pixel_mask (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
+ Mask to avoid performing attention on padding pixel values. Mask values selected in `[0, 1]`:
+
+ - 1 for pixels that are real (i.e. **not masked**),
+ - 0 for pixels that are padding (i.e. **masked**).
+
+ [What are attention masks?](../glossary#attention-mask)
+
+ decoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_queries)`, *optional*):
+ Not used by default. Can be used to mask object queries.
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing the flattened feature map (output of the backbone + projection layer), you
+ can choose to directly pass a flattened representation of an image.
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
+ Optionally, instead of initializing the queries with a tensor of zeros, you can choose to directly pass an
+ embedded representation.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+class DetaEncoder(DetaPreTrainedModel):
+ """
+ Transformer encoder consisting of *config.encoder_layers* deformable attention layers. Each layer is a
+ [`DetaEncoderLayer`].
+
+ The encoder updates the flattened multi-scale feature maps through multiple deformable attention layers.
+
+ Args:
+ config: DetaConfig
+ """
+
+ def __init__(self, config: DetaConfig):
+ super().__init__(config)
+
+ self.dropout = config.dropout
+ self.layers = nn.ModuleList([DetaEncoderLayer(config) for _ in range(config.encoder_layers)])
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @staticmethod
+ def get_reference_points(spatial_shapes, valid_ratios, device):
+ """
+ Get reference points for each feature map. Used in decoder.
+
+ Args:
+ spatial_shapes (`torch.LongTensor` of shape `(num_feature_levels, 2)`):
+ Spatial shapes of each feature map.
+ valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`):
+ Valid ratios of each feature map.
+ device (`torch.device`):
+ Device on which to create the tensors.
+ Returns:
+ `torch.FloatTensor` of shape `(batch_size, num_queries, num_feature_levels, 2)`
+ """
+ reference_points_list = []
+ for level, (height, width) in enumerate(spatial_shapes):
+ ref_y, ref_x = meshgrid(
+ torch.linspace(0.5, height - 0.5, height, dtype=torch.float32, device=device),
+ torch.linspace(0.5, width - 0.5, width, dtype=torch.float32, device=device),
+ indexing="ij",
+ )
+ # TODO: valid_ratios could be useless here. check https://github.com/fundamentalvision/Deformable-DETR/issues/36
+ ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, level, 1] * height)
+ ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, level, 0] * width)
+ ref = torch.stack((ref_x, ref_y), -1)
+ reference_points_list.append(ref)
+ reference_points = torch.cat(reference_points_list, 1)
+ reference_points = reference_points[:, :, None] * valid_ratios[:, None]
+ return reference_points
+
+ def forward(
+ self,
+ inputs_embeds=None,
+ attention_mask=None,
+ position_embeddings=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ valid_ratios=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ ):
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Flattened feature map (output of the backbone + projection layer) that is passed to the encoder.
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding pixel features. Mask values selected in `[0, 1]`:
+ - 1 for pixel features that are real (i.e. **not masked**),
+ - 0 for pixel features that are padding (i.e. **masked**).
+ [What are attention masks?](../glossary#attention-mask)
+ position_embeddings (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Position embeddings that are added to the queries and keys in each self-attention layer.
+ spatial_shapes (`torch.LongTensor` of shape `(num_feature_levels, 2)`):
+ Spatial shapes of each feature map.
+ level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`):
+ Starting index of each feature map.
+ valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`):
+ Ratio of valid area in each feature level.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ hidden_states = inputs_embeds
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ reference_points = self.get_reference_points(spatial_shapes, valid_ratios, device=inputs_embeds.device)
+
+ encoder_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+ for i, encoder_layer in enumerate(self.layers):
+ if output_hidden_states:
+ encoder_states = encoder_states + (hidden_states,)
+ layer_outputs = encoder_layer(
+ hidden_states,
+ attention_mask,
+ position_embeddings=position_embeddings,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_attentions = all_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ encoder_states = encoder_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
+ )
+
+
+class DetaDecoder(DetaPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`DetaDecoderLayer`].
+
+ The decoder updates the query embeddings through multiple self-attention and cross-attention layers.
+
+ Some tweaks for Deformable DETR:
+
+ - `position_embeddings`, `reference_points`, `spatial_shapes` and `valid_ratios` are added to the forward pass.
+ - it also returns a stack of intermediate outputs and reference points from all decoding layers.
+
+ Args:
+ config: DetaConfig
+ """
+
+ def __init__(self, config: DetaConfig):
+ super().__init__(config)
+
+ self.dropout = config.dropout
+ self.layers = nn.ModuleList([DetaDecoderLayer(config) for _ in range(config.decoder_layers)])
+ self.gradient_checkpointing = False
+
+ # hack implementation for iterative bounding box refinement and two-stage Deformable DETR
+ self.bbox_embed = None
+ self.class_embed = None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def forward(
+ self,
+ inputs_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ position_embeddings=None,
+ reference_points=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ valid_ratios=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ ):
+ r"""
+ Args:
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`):
+ The query embeddings that are passed into the decoder.
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding pixel_values of the encoder. Mask values selected
+ in `[0, 1]`:
+ - 1 for pixels that are real (i.e. **not masked**),
+ - 0 for pixels that are padding (i.e. **masked**).
+ position_embeddings (`torch.FloatTensor` of shape `(batch_size, num_queries, hidden_size)`, *optional*):
+ Position embeddings that are added to the queries and keys in each self-attention layer.
+ reference_points (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)` is `as_two_stage` else `(batch_size, num_queries, 2)` or , *optional*):
+ Reference point in range `[0, 1]`, top-left (0,0), bottom-right (1, 1), including padding area.
+ spatial_shapes (`torch.FloatTensor` of shape `(num_feature_levels, 2)`):
+ Spatial shapes of the feature maps.
+ level_start_index (`torch.LongTensor` of shape `(num_feature_levels)`, *optional*):
+ Indexes for the start of each feature level. In range `[0, sequence_length]`.
+ valid_ratios (`torch.FloatTensor` of shape `(batch_size, num_feature_levels, 2)`, *optional*):
+ Ratio of valid area in each feature level.
+
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if inputs_embeds is not None:
+ hidden_states = inputs_embeds
+
+ # decoder layers
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
+ intermediate = ()
+ intermediate_reference_points = ()
+
+ for idx, decoder_layer in enumerate(self.layers):
+ if reference_points.shape[-1] == 4:
+ reference_points_input = (
+ reference_points[:, :, None] * torch.cat([valid_ratios, valid_ratios], -1)[:, None]
+ )
+ else:
+ if reference_points.shape[-1] != 2:
+ raise ValueError("Reference points' last dimension must be of size 2")
+ reference_points_input = reference_points[:, :, None] * valid_ratios[:, None]
+
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ layer_outputs = decoder_layer(
+ hidden_states,
+ position_embeddings=position_embeddings,
+ encoder_hidden_states=encoder_hidden_states,
+ reference_points=reference_points_input,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ encoder_attention_mask=encoder_attention_mask,
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ # hack implementation for iterative bounding box refinement
+ if self.bbox_embed is not None:
+ tmp = self.bbox_embed[idx](hidden_states)
+ if reference_points.shape[-1] == 4:
+ new_reference_points = tmp + inverse_sigmoid(reference_points)
+ new_reference_points = new_reference_points.sigmoid()
+ else:
+ if reference_points.shape[-1] != 2:
+ raise ValueError(
+ f"Reference points' last dimension must be of size 2, but is {reference_points.shape[-1]}"
+ )
+ new_reference_points = tmp
+ new_reference_points[..., :2] = tmp[..., :2] + inverse_sigmoid(reference_points)
+ new_reference_points = new_reference_points.sigmoid()
+ reference_points = new_reference_points.detach()
+
+ intermediate += (hidden_states,)
+ intermediate_reference_points += (reference_points,)
+
+ if output_attentions:
+ all_self_attns += (layer_outputs[1],)
+
+ if encoder_hidden_states is not None:
+ all_cross_attentions += (layer_outputs[2],)
+
+ # Keep batch_size as first dimension
+ intermediate = torch.stack(intermediate, dim=1)
+ intermediate_reference_points = torch.stack(intermediate_reference_points, dim=1)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ hidden_states,
+ intermediate,
+ intermediate_reference_points,
+ all_hidden_states,
+ all_self_attns,
+ all_cross_attentions,
+ ]
+ if v is not None
+ )
+ return DetaDecoderOutput(
+ last_hidden_state=hidden_states,
+ intermediate_hidden_states=intermediate,
+ intermediate_reference_points=intermediate_reference_points,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ The bare DETA Model (consisting of a backbone and encoder-decoder Transformer) outputting raw hidden-states without
+ any specific head on top.
+ """,
+ DETA_START_DOCSTRING,
+)
+class DetaModel(DetaPreTrainedModel):
+ def __init__(self, config: DetaConfig):
+ super().__init__(config)
+
+ if config.two_stage:
+ requires_backends(self, ["torchvision"])
+
+ # Create backbone with positional encoding
+ self.backbone = DetaBackboneWithPositionalEncodings(config)
+ intermediate_channel_sizes = self.backbone.intermediate_channel_sizes
+
+ # Create input projection layers
+ if config.num_feature_levels > 1:
+ num_backbone_outs = len(intermediate_channel_sizes)
+ input_proj_list = []
+ for _ in range(num_backbone_outs):
+ in_channels = intermediate_channel_sizes[_]
+ input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.d_model, kernel_size=1),
+ nn.GroupNorm(32, config.d_model),
+ )
+ )
+ for _ in range(config.num_feature_levels - num_backbone_outs):
+ input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, config.d_model, kernel_size=3, stride=2, padding=1),
+ nn.GroupNorm(32, config.d_model),
+ )
+ )
+ in_channels = config.d_model
+ self.input_proj = nn.ModuleList(input_proj_list)
+ else:
+ self.input_proj = nn.ModuleList(
+ [
+ nn.Sequential(
+ nn.Conv2d(intermediate_channel_sizes[-1], config.d_model, kernel_size=1),
+ nn.GroupNorm(32, config.d_model),
+ )
+ ]
+ )
+
+ if not config.two_stage:
+ self.query_position_embeddings = nn.Embedding(config.num_queries, config.d_model * 2)
+
+ self.encoder = DetaEncoder(config)
+ self.decoder = DetaDecoder(config)
+
+ self.level_embed = nn.Parameter(torch.Tensor(config.num_feature_levels, config.d_model))
+
+ if config.two_stage:
+ self.enc_output = nn.Linear(config.d_model, config.d_model)
+ self.enc_output_norm = nn.LayerNorm(config.d_model)
+ self.pos_trans = nn.Linear(config.d_model * 2, config.d_model * 2)
+ self.pos_trans_norm = nn.LayerNorm(config.d_model * 2)
+ self.pix_trans = nn.Linear(config.d_model, config.d_model)
+ self.pix_trans_norm = nn.LayerNorm(config.d_model)
+ else:
+ self.reference_points = nn.Linear(config.d_model, 2)
+
+ self.assign_first_stage = config.assign_first_stage
+ self.two_stage_num_proposals = config.two_stage_num_proposals
+
+ self.post_init()
+
+ def get_encoder(self):
+ return self.encoder
+
+ def freeze_backbone(self):
+ for name, param in self.backbone.model.named_parameters():
+ param.requires_grad_(False)
+
+ def unfreeze_backbone(self):
+ for name, param in self.backbone.model.named_parameters():
+ param.requires_grad_(True)
+
+ def get_valid_ratio(self, mask, dtype=torch.float32):
+ """Get the valid ratio of all feature maps."""
+
+ _, height, width = mask.shape
+ valid_height = torch.sum(mask[:, :, 0], 1)
+ valid_width = torch.sum(mask[:, 0, :], 1)
+ valid_ratio_height = valid_height.to(dtype) / height
+ valid_ratio_width = valid_width.to(dtype) / width
+ valid_ratio = torch.stack([valid_ratio_width, valid_ratio_height], -1)
+ return valid_ratio
+
+ def get_proposal_pos_embed(self, proposals):
+ """Get the position embedding of the proposals."""
+
+ num_pos_feats = self.config.d_model // 2
+ temperature = 10000
+ scale = 2 * math.pi
+
+ dim_t = torch.arange(num_pos_feats, dtype=torch.int64, device=proposals.device).float()
+ dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_pos_feats)
+ # batch_size, num_queries, 4
+ proposals = proposals.sigmoid() * scale
+ # batch_size, num_queries, 4, 128
+ pos = proposals[:, :, :, None] / dim_t
+ # batch_size, num_queries, 4, 64, 2 -> batch_size, num_queries, 512
+ pos = torch.stack((pos[:, :, :, 0::2].sin(), pos[:, :, :, 1::2].cos()), dim=4).flatten(2)
+ return pos
+
+ def gen_encoder_output_proposals(self, enc_output, padding_mask, spatial_shapes):
+ """Generate the encoder output proposals from encoded enc_output.
+
+ Args:
+ enc_output (Tensor[batch_size, sequence_length, hidden_size]): Output of the encoder.
+ padding_mask (Tensor[batch_size, sequence_length]): Padding mask for `enc_output`.
+ spatial_shapes (Tensor[num_feature_levels, 2]): Spatial shapes of the feature maps.
+
+ Returns:
+ `tuple(torch.FloatTensor)`: A tuple of feature map and bbox prediction.
+ - object_query (Tensor[batch_size, sequence_length, hidden_size]): Object query features. Later used to
+ directly predict a bounding box. (without the need of a decoder)
+ - output_proposals (Tensor[batch_size, sequence_length, 4]): Normalized proposals, after an inverse
+ sigmoid.
+ """
+ batch_size = enc_output.shape[0]
+ proposals = []
+ _cur = 0
+ level_ids = []
+ for level, (height, width) in enumerate(spatial_shapes):
+ mask_flatten_ = padding_mask[:, _cur : (_cur + height * width)].view(batch_size, height, width, 1)
+ valid_height = torch.sum(~mask_flatten_[:, :, 0, 0], 1)
+ valid_width = torch.sum(~mask_flatten_[:, 0, :, 0], 1)
+
+ grid_y, grid_x = meshgrid(
+ torch.linspace(0, height - 1, height, dtype=torch.float32, device=enc_output.device),
+ torch.linspace(0, width - 1, width, dtype=torch.float32, device=enc_output.device),
+ indexing="ij",
+ )
+ grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1)
+
+ scale = torch.cat([valid_width.unsqueeze(-1), valid_height.unsqueeze(-1)], 1).view(batch_size, 1, 1, 2)
+ grid = (grid.unsqueeze(0).expand(batch_size, -1, -1, -1) + 0.5) / scale
+ width_height = torch.ones_like(grid) * 0.05 * (2.0**level)
+ proposal = torch.cat((grid, width_height), -1).view(batch_size, -1, 4)
+ proposals.append(proposal)
+ _cur += height * width
+ level_ids.append(grid.new_ones(height * width, dtype=torch.long) * level)
+ output_proposals = torch.cat(proposals, 1)
+ output_proposals_valid = ((output_proposals > 0.01) & (output_proposals < 0.99)).all(-1, keepdim=True)
+ output_proposals = torch.log(output_proposals / (1 - output_proposals)) # inverse sigmoid
+ output_proposals = output_proposals.masked_fill(padding_mask.unsqueeze(-1), float("inf"))
+ output_proposals = output_proposals.masked_fill(~output_proposals_valid, float("inf"))
+
+ # assign each pixel as an object query
+ object_query = enc_output
+ object_query = object_query.masked_fill(padding_mask.unsqueeze(-1), float(0))
+ object_query = object_query.masked_fill(~output_proposals_valid, float(0))
+ object_query = self.enc_output_norm(self.enc_output(object_query))
+ level_ids = torch.cat(level_ids)
+ return object_query, output_proposals, level_ids
+
+ @add_start_docstrings_to_model_forward(DETA_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=DetaModelOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: Optional[torch.LongTensor] = None,
+ decoder_attention_mask: Optional[torch.FloatTensor] = None,
+ encoder_outputs: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.FloatTensor], DetaModelOutput]:
+ r"""
+ Returns:
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, DetaModel
+ >>> from PIL import Image
+ >>> import requests
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("jozhang97/deta-swin-large-o365")
+ >>> model = DetaModel.from_pretrained("jozhang97/deta-swin-large-o365", two_stage=False)
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+
+ >>> last_hidden_states = outputs.last_hidden_state
+ >>> list(last_hidden_states.shape)
+ [1, 900, 256]
+ ```"""
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ batch_size, num_channels, height, width = pixel_values.shape
+ device = pixel_values.device
+
+ if pixel_mask is None:
+ pixel_mask = torch.ones(((batch_size, height, width)), dtype=torch.long, device=device)
+
+ # Extract multi-scale feature maps of same resolution `config.d_model` (cf Figure 4 in paper)
+ # First, sent pixel_values + pixel_mask through Backbone to obtain the features
+ # which is a list of tuples
+ features, position_embeddings_list = self.backbone(pixel_values, pixel_mask)
+
+ # Then, apply 1x1 convolution to reduce the channel dimension to d_model (256 by default)
+ sources = []
+ masks = []
+ for level, (source, mask) in enumerate(features):
+ sources.append(self.input_proj[level](source))
+ masks.append(mask)
+ if mask is None:
+ raise ValueError("No attention mask was provided")
+
+ # Lowest resolution feature maps are obtained via 3x3 stride 2 convolutions on the final stage
+ if self.config.num_feature_levels > len(sources):
+ _len_sources = len(sources)
+ for level in range(_len_sources, self.config.num_feature_levels):
+ if level == _len_sources:
+ source = self.input_proj[level](features[-1][0])
+ else:
+ source = self.input_proj[level](sources[-1])
+ mask = nn.functional.interpolate(pixel_mask[None].float(), size=source.shape[-2:]).to(torch.bool)[0]
+ pos_l = self.backbone.position_embedding(source, mask).to(source.dtype)
+ sources.append(source)
+ masks.append(mask)
+ position_embeddings_list.append(pos_l)
+
+ # Create queries
+ query_embeds = None
+ if not self.config.two_stage:
+ query_embeds = self.query_position_embeddings.weight
+
+ # Prepare encoder inputs (by flattening)
+ spatial_shapes = [(source.shape[2:]) for source in sources]
+ source_flatten = [source.flatten(2).transpose(1, 2) for source in sources]
+ mask_flatten = [mask.flatten(1) for mask in masks]
+
+ lvl_pos_embed_flatten = []
+ for level, pos_embed in enumerate(position_embeddings_list):
+ pos_embed = pos_embed.flatten(2).transpose(1, 2)
+ lvl_pos_embed = pos_embed + self.level_embed[level].view(1, 1, -1)
+ lvl_pos_embed_flatten.append(lvl_pos_embed)
+
+ source_flatten = torch.cat(source_flatten, 1)
+ mask_flatten = torch.cat(mask_flatten, 1)
+ lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1)
+ spatial_shapes = torch.as_tensor(spatial_shapes, dtype=torch.long, device=source_flatten.device)
+ level_start_index = torch.cat((spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1]))
+ valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1)
+ valid_ratios = valid_ratios.float()
+
+ # Fourth, sent source_flatten + mask_flatten + lvl_pos_embed_flatten (backbone + proj layer output) through encoder
+ # Also provide spatial_shapes, level_start_index and valid_ratios
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ inputs_embeds=source_flatten,
+ attention_mask=mask_flatten,
+ position_embeddings=lvl_pos_embed_flatten,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ valid_ratios=valid_ratios,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
+ encoder_outputs = BaseModelOutput(
+ last_hidden_state=encoder_outputs[0],
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
+ )
+
+ # Fifth, prepare decoder inputs
+ batch_size, _, num_channels = encoder_outputs[0].shape
+ enc_outputs_class = None
+ enc_outputs_coord_logits = None
+ output_proposals = None
+ if self.config.two_stage:
+ object_query_embedding, output_proposals, level_ids = self.gen_encoder_output_proposals(
+ encoder_outputs[0], ~mask_flatten, spatial_shapes
+ )
+
+ # hack implementation for two-stage DETA
+ # apply a detection head to each pixel (A.4 in paper)
+ # linear projection for bounding box binary classification (i.e. foreground and background)
+ enc_outputs_class = self.decoder.class_embed[-1](object_query_embedding)
+ # 3-layer FFN to predict bounding boxes coordinates (bbox regression branch)
+ delta_bbox = self.decoder.bbox_embed[-1](object_query_embedding)
+ enc_outputs_coord_logits = delta_bbox + output_proposals
+
+ # only keep top scoring `config.two_stage_num_proposals` proposals
+ topk = self.two_stage_num_proposals
+ proposal_logit = enc_outputs_class[..., 0]
+
+ if self.assign_first_stage:
+ proposal_boxes = center_to_corners_format(enc_outputs_coord_logits.sigmoid().float()).clamp(0, 1)
+ topk_proposals = []
+ for b in range(batch_size):
+ prop_boxes_b = proposal_boxes[b]
+ prop_logits_b = proposal_logit[b]
+
+ # pre-nms per-level topk
+ pre_nms_topk = 1000
+ pre_nms_inds = []
+ for lvl in range(len(spatial_shapes)):
+ lvl_mask = level_ids == lvl
+ pre_nms_inds.append(torch.topk(prop_logits_b.sigmoid() * lvl_mask, pre_nms_topk)[1])
+ pre_nms_inds = torch.cat(pre_nms_inds)
+
+ # nms on topk indices
+ post_nms_inds = batched_nms(
+ prop_boxes_b[pre_nms_inds], prop_logits_b[pre_nms_inds], level_ids[pre_nms_inds], 0.9
+ )
+ keep_inds = pre_nms_inds[post_nms_inds]
+
+ if len(keep_inds) < self.two_stage_num_proposals:
+ print(
+ f"[WARNING] nms proposals ({len(keep_inds)}) < {self.two_stage_num_proposals}, running"
+ " naive topk"
+ )
+ keep_inds = torch.topk(proposal_logit[b], topk)[1]
+
+ # keep top Q/L indices for L levels
+ q_per_l = topk // len(spatial_shapes)
+ is_level_ordered = (
+ level_ids[keep_inds][None]
+ == torch.arange(len(spatial_shapes), device=level_ids.device)[:, None]
+ )
+ keep_inds_mask = is_level_ordered & (is_level_ordered.cumsum(1) <= q_per_l) # LS
+ keep_inds_mask = keep_inds_mask.any(0) # S
+
+ # pad to Q indices (might let ones filtered from pre-nms sneak by... unlikely because we pick high conf anyways)
+ if keep_inds_mask.sum() < topk:
+ num_to_add = topk - keep_inds_mask.sum()
+ pad_inds = (~keep_inds_mask).nonzero()[:num_to_add]
+ keep_inds_mask[pad_inds] = True
+
+ keep_inds_topk = keep_inds[keep_inds_mask]
+ topk_proposals.append(keep_inds_topk)
+ topk_proposals = torch.stack(topk_proposals)
+ else:
+ topk_proposals = torch.topk(enc_outputs_class[..., 0], topk, dim=1)[1]
+
+ topk_coords_logits = torch.gather(
+ enc_outputs_coord_logits, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4)
+ )
+ topk_coords_logits = topk_coords_logits.detach()
+ reference_points = topk_coords_logits.sigmoid()
+ init_reference_points = reference_points
+ pos_trans_out = self.pos_trans_norm(self.pos_trans(self.get_proposal_pos_embed(topk_coords_logits)))
+ query_embed, target = torch.split(pos_trans_out, num_channels, dim=2)
+
+ topk_feats = torch.stack(
+ [object_query_embedding[b][topk_proposals[b]] for b in range(batch_size)]
+ ).detach()
+ target = target + self.pix_trans_norm(self.pix_trans(topk_feats))
+ else:
+ query_embed, target = torch.split(query_embeds, num_channels, dim=1)
+ query_embed = query_embed.unsqueeze(0).expand(batch_size, -1, -1)
+ target = target.unsqueeze(0).expand(batch_size, -1, -1)
+ reference_points = self.reference_points(query_embed).sigmoid()
+ init_reference_points = reference_points
+
+ decoder_outputs = self.decoder(
+ inputs_embeds=target,
+ position_embeddings=query_embed,
+ encoder_hidden_states=encoder_outputs[0],
+ encoder_attention_mask=mask_flatten,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ valid_ratios=valid_ratios,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ enc_outputs = tuple(value for value in [enc_outputs_class, enc_outputs_coord_logits] if value is not None)
+ tuple_outputs = (init_reference_points,) + decoder_outputs + encoder_outputs + enc_outputs
+
+ return tuple_outputs
+
+ return DetaModelOutput(
+ init_reference_points=init_reference_points,
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ intermediate_hidden_states=decoder_outputs.intermediate_hidden_states,
+ intermediate_reference_points=decoder_outputs.intermediate_reference_points,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_attentions=decoder_outputs.attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ enc_outputs_class=enc_outputs_class,
+ enc_outputs_coord_logits=enc_outputs_coord_logits,
+ output_proposals=output_proposals,
+ )
+
+
+@add_start_docstrings(
+ """
+ DETA Model (consisting of a backbone and encoder-decoder Transformer) with object detection heads on top, for tasks
+ such as COCO detection.
+ """,
+ DETA_START_DOCSTRING,
+)
+class DetaForObjectDetection(DetaPreTrainedModel):
+ # When using clones, all layers > 0 will be clones, but layer 0 *is* required
+ _tied_weights_keys = [r"bbox_embed\.\d+", r"class_embed\.\d+"]
+ # We can't initialize the model on meta device as some weights are modified during the initialization
+ _no_split_modules = None
+
+ def __init__(self, config: DetaConfig):
+ super().__init__(config)
+
+ # Deformable DETR encoder-decoder model
+ self.model = DetaModel(config)
+
+ # Detection heads on top
+ self.class_embed = nn.Linear(config.d_model, config.num_labels)
+ self.bbox_embed = DetaMLPPredictionHead(
+ input_dim=config.d_model, hidden_dim=config.d_model, output_dim=4, num_layers=3
+ )
+
+ prior_prob = 0.01
+ bias_value = -math.log((1 - prior_prob) / prior_prob)
+ self.class_embed.bias.data = torch.ones(config.num_labels) * bias_value
+ nn.init.constant_(self.bbox_embed.layers[-1].weight.data, 0)
+ nn.init.constant_(self.bbox_embed.layers[-1].bias.data, 0)
+
+ # if two-stage, the last class_embed and bbox_embed is for region proposal generation
+ num_pred = (config.decoder_layers + 1) if config.two_stage else config.decoder_layers
+ if config.with_box_refine:
+ self.class_embed = _get_clones(self.class_embed, num_pred)
+ self.bbox_embed = _get_clones(self.bbox_embed, num_pred)
+ nn.init.constant_(self.bbox_embed[0].layers[-1].bias.data[2:], -2.0)
+ # hack implementation for iterative bounding box refinement
+ self.model.decoder.bbox_embed = self.bbox_embed
+ else:
+ nn.init.constant_(self.bbox_embed.layers[-1].bias.data[2:], -2.0)
+ self.class_embed = nn.ModuleList([self.class_embed for _ in range(num_pred)])
+ self.bbox_embed = nn.ModuleList([self.bbox_embed for _ in range(num_pred)])
+ self.model.decoder.bbox_embed = None
+ if config.two_stage:
+ # hack implementation for two-stage
+ self.model.decoder.class_embed = self.class_embed
+ for box_embed in self.bbox_embed:
+ nn.init.constant_(box_embed.layers[-1].bias.data[2:], 0.0)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @torch.jit.unused
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ # this is a workaround to make torchscript happy, as torchscript
+ # doesn't support dictionary with non-homogeneous values, such
+ # as a dict having both a Tensor and a list.
+ aux_loss = [
+ {"logits": logits, "pred_boxes": pred_boxes}
+ for logits, pred_boxes in zip(outputs_class.transpose(0, 1)[:-1], outputs_coord.transpose(0, 1)[:-1])
+ ]
+ return aux_loss
+
+ @add_start_docstrings_to_model_forward(DETA_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=DetaObjectDetectionOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ pixel_mask: Optional[torch.LongTensor] = None,
+ decoder_attention_mask: Optional[torch.FloatTensor] = None,
+ encoder_outputs: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[list[dict]] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.FloatTensor], DetaObjectDetectionOutput]:
+ r"""
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: 'class_labels' and 'boxes' (the class labels and bounding boxes of an image in the batch
+ respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding boxes
+ in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image, 4)`.
+
+ Returns:
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, DetaForObjectDetection
+ >>> from PIL import Image
+ >>> import requests
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("jozhang97/deta-swin-large")
+ >>> model = DetaForObjectDetection.from_pretrained("jozhang97/deta-swin-large")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
+ >>> target_sizes = torch.tensor([image.size[::-1]])
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.5, target_sizes=target_sizes)[
+ ... 0
+ ... ]
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
+ ... box = [round(i, 2) for i in box.tolist()]
+ ... print(
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
+ ... f"{round(score.item(), 3)} at location {box}"
+ ... )
+ Detected cat with confidence 0.802 at location [9.87, 54.36, 316.93, 473.44]
+ Detected cat with confidence 0.795 at location [346.62, 24.35, 639.62, 373.2]
+ Detected remote with confidence 0.725 at location [40.41, 73.36, 175.77, 117.29]
+ Detected remote with confidence 0.638 at location [333.34, 76.81, 370.22, 187.94]
+ Detected couch with confidence 0.584 at location [0.03, 0.99, 640.02, 474.93]
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # First, sent images through DETR base model to obtain encoder + decoder outputs
+ outputs = self.model(
+ pixel_values,
+ pixel_mask=pixel_mask,
+ decoder_attention_mask=decoder_attention_mask,
+ encoder_outputs=encoder_outputs,
+ inputs_embeds=inputs_embeds,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs.intermediate_hidden_states if return_dict else outputs[2]
+ init_reference = outputs.init_reference_points if return_dict else outputs[0]
+ inter_references = outputs.intermediate_reference_points if return_dict else outputs[3]
+
+ # class logits + predicted bounding boxes
+ outputs_classes = []
+ outputs_coords = []
+
+ for level in range(hidden_states.shape[1]):
+ if level == 0:
+ reference = init_reference
+ else:
+ reference = inter_references[:, level - 1]
+ reference = inverse_sigmoid(reference)
+ outputs_class = self.class_embed[level](hidden_states[:, level])
+ delta_bbox = self.bbox_embed[level](hidden_states[:, level])
+ if reference.shape[-1] == 4:
+ outputs_coord_logits = delta_bbox + reference
+ elif reference.shape[-1] == 2:
+ delta_bbox[..., :2] += reference
+ outputs_coord_logits = delta_bbox
+ else:
+ raise ValueError(f"reference.shape[-1] should be 4 or 2, but got {reference.shape[-1]}")
+ outputs_coord = outputs_coord_logits.sigmoid()
+ outputs_classes.append(outputs_class)
+ outputs_coords.append(outputs_coord)
+ # Keep batch_size as first dimension
+ outputs_class = torch.stack(outputs_classes, dim=1)
+ outputs_coord = torch.stack(outputs_coords, dim=1)
+
+ logits = outputs_class[:, -1]
+ pred_boxes = outputs_coord[:, -1]
+
+ loss, loss_dict, auxiliary_outputs = None, None, None
+ if labels is not None:
+ # First: create the matcher
+ matcher = DetaHungarianMatcher(
+ class_cost=self.config.class_cost, bbox_cost=self.config.bbox_cost, giou_cost=self.config.giou_cost
+ )
+ # Second: create the criterion
+ losses = ["labels", "boxes", "cardinality"]
+ criterion = DetaLoss(
+ matcher=matcher,
+ num_classes=self.config.num_labels,
+ focal_alpha=self.config.focal_alpha,
+ losses=losses,
+ num_queries=self.config.num_queries,
+ assign_first_stage=self.config.assign_first_stage,
+ assign_second_stage=self.config.assign_second_stage,
+ )
+ criterion.to(logits.device)
+ # Third: compute the losses, based on outputs and labels
+ outputs_loss = {}
+ outputs_loss["logits"] = logits
+ outputs_loss["pred_boxes"] = pred_boxes
+ outputs_loss["init_reference"] = init_reference
+ if self.config.auxiliary_loss:
+ auxiliary_outputs = self._set_aux_loss(outputs_class, outputs_coord)
+ outputs_loss["auxiliary_outputs"] = auxiliary_outputs
+ if self.config.two_stage:
+ enc_outputs_coord = outputs.enc_outputs_coord_logits.sigmoid()
+ outputs_loss["enc_outputs"] = {
+ "logits": outputs.enc_outputs_class,
+ "pred_boxes": enc_outputs_coord,
+ "anchors": outputs.output_proposals.sigmoid(),
+ }
+
+ loss_dict = criterion(outputs_loss, labels)
+ # Fourth: compute total loss, as a weighted sum of the various losses
+ weight_dict = {"loss_ce": 1, "loss_bbox": self.config.bbox_loss_coefficient}
+ weight_dict["loss_giou"] = self.config.giou_loss_coefficient
+ if self.config.auxiliary_loss:
+ aux_weight_dict = {}
+ for i in range(self.config.decoder_layers - 1):
+ aux_weight_dict.update({k + f"_{i}": v for k, v in weight_dict.items()})
+ aux_weight_dict.update({k + "_enc": v for k, v in weight_dict.items()})
+ weight_dict.update(aux_weight_dict)
+ loss = sum(loss_dict[k] * weight_dict[k] for k in loss_dict if k in weight_dict)
+
+ if not return_dict:
+ if auxiliary_outputs is not None:
+ output = (logits, pred_boxes) + auxiliary_outputs + outputs
+ else:
+ output = (logits, pred_boxes) + outputs
+ tuple_outputs = ((loss, loss_dict) + output) if loss is not None else output
+
+ return tuple_outputs
+
+ dict_outputs = DetaObjectDetectionOutput(
+ loss=loss,
+ loss_dict=loss_dict,
+ logits=logits,
+ pred_boxes=pred_boxes,
+ auxiliary_outputs=auxiliary_outputs,
+ last_hidden_state=outputs.last_hidden_state,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ intermediate_hidden_states=outputs.intermediate_hidden_states,
+ intermediate_reference_points=outputs.intermediate_reference_points,
+ init_reference_points=outputs.init_reference_points,
+ enc_outputs_class=outputs.enc_outputs_class,
+ enc_outputs_coord_logits=outputs.enc_outputs_coord_logits,
+ output_proposals=outputs.output_proposals,
+ )
+
+ return dict_outputs
+
+
+def dice_loss(inputs, targets, num_boxes):
+ """
+ Compute the DICE loss, similar to generalized IOU for masks
+
+ Args:
+ inputs: A float tensor of arbitrary shape.
+ The predictions for each example.
+ targets: A float tensor with the same shape as inputs. Stores the binary
+ classification label for each element in inputs (0 for the negative class and 1 for the positive
+ class).
+ """
+ inputs = inputs.sigmoid()
+ inputs = inputs.flatten(1)
+ numerator = 2 * (inputs * targets).sum(1)
+ denominator = inputs.sum(-1) + targets.sum(-1)
+ loss = 1 - (numerator + 1) / (denominator + 1)
+ return loss.sum() / num_boxes
+
+
+def sigmoid_focal_loss(inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2):
+ """
+ Loss used in RetinaNet for dense detection: https://huggingface.co/papers/1708.02002.
+
+ Args:
+ inputs (`torch.FloatTensor` of arbitrary shape):
+ The predictions for each example.
+ targets (`torch.FloatTensor` with the same shape as `inputs`)
+ A tensor storing the binary classification label for each element in the `inputs` (0 for the negative class
+ and 1 for the positive class).
+ alpha (`float`, *optional*, defaults to `0.25`):
+ Optional weighting factor in the range (0,1) to balance positive vs. negative examples.
+ gamma (`int`, *optional*, defaults to `2`):
+ Exponent of the modulating factor (1 - p_t) to balance easy vs hard examples.
+
+ Returns:
+ Loss tensor
+ """
+ prob = inputs.sigmoid()
+ ce_loss = nn.functional.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
+ # add modulating factor
+ p_t = prob * targets + (1 - prob) * (1 - targets)
+ loss = ce_loss * ((1 - p_t) ** gamma)
+
+ if alpha >= 0:
+ alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
+ loss = alpha_t * loss
+
+ return loss.mean(1).sum() / num_boxes
+
+
+class DetaLoss(nn.Module):
+ """
+ This class computes the losses for `DetaForObjectDetection`. The process happens in two steps: 1) we compute
+ hungarian assignment between ground truth boxes and the outputs of the model 2) we supervise each pair of matched
+ ground-truth / prediction (supervised class and box).
+
+ Args:
+ matcher (`DetaHungarianMatcher`):
+ Module able to compute a matching between targets and proposals.
+ num_classes (`int`):
+ Number of object categories, omitting the special no-object category.
+ focal_alpha (`float`):
+ Alpha parameter in focal loss.
+ losses (`list[str]`):
+ List of all the losses to be applied. See `get_loss` for a list of all available losses.
+ """
+
+ def __init__(
+ self,
+ matcher,
+ num_classes,
+ focal_alpha,
+ losses,
+ num_queries,
+ assign_first_stage=False,
+ assign_second_stage=False,
+ ):
+ super().__init__()
+ self.matcher = matcher
+ self.num_classes = num_classes
+ self.focal_alpha = focal_alpha
+ self.losses = losses
+ self.assign_first_stage = assign_first_stage
+ self.assign_second_stage = assign_second_stage
+
+ if self.assign_first_stage:
+ self.stg1_assigner = DetaStage1Assigner()
+ if self.assign_second_stage:
+ self.stg2_assigner = DetaStage2Assigner(num_queries)
+
+ def loss_labels(self, outputs, targets, indices, num_boxes):
+ """
+ Classification loss (Binary focal loss) targets dicts must contain the key "class_labels" containing a tensor
+ of dim [nb_target_boxes]
+ """
+ if "logits" not in outputs:
+ raise KeyError("No logits were found in the outputs")
+ source_logits = outputs["logits"]
+
+ idx = self._get_source_permutation_idx(indices)
+ target_classes_o = torch.cat([t["class_labels"][J] for t, (_, J) in zip(targets, indices)])
+ target_classes = torch.full(
+ source_logits.shape[:2], self.num_classes, dtype=torch.int64, device=source_logits.device
+ )
+ target_classes[idx] = target_classes_o
+
+ target_classes_onehot = torch.zeros(
+ [source_logits.shape[0], source_logits.shape[1], source_logits.shape[2] + 1],
+ dtype=source_logits.dtype,
+ layout=source_logits.layout,
+ device=source_logits.device,
+ )
+ target_classes_onehot.scatter_(2, target_classes.unsqueeze(-1), 1)
+
+ target_classes_onehot = target_classes_onehot[:, :, :-1]
+ loss_ce = (
+ sigmoid_focal_loss(source_logits, target_classes_onehot, num_boxes, alpha=self.focal_alpha, gamma=2)
+ * source_logits.shape[1]
+ )
+ losses = {"loss_ce": loss_ce}
+
+ return losses
+
+ @torch.no_grad()
+ def loss_cardinality(self, outputs, targets, indices, num_boxes):
+ """
+ Compute the cardinality error, i.e. the absolute error in the number of predicted non-empty boxes.
+
+ This is not really a loss, it is intended for logging purposes only. It doesn't propagate gradients.
+ """
+ logits = outputs["logits"]
+ device = logits.device
+ target_lengths = torch.as_tensor([len(v["class_labels"]) for v in targets], device=device)
+ # Count the number of predictions that are NOT "no-object" (which is the last class)
+ card_pred = (logits.argmax(-1) != logits.shape[-1] - 1).sum(1)
+ card_err = nn.functional.l1_loss(card_pred.float(), target_lengths.float())
+ losses = {"cardinality_error": card_err}
+ return losses
+
+ def loss_boxes(self, outputs, targets, indices, num_boxes):
+ """
+ Compute the losses related to the bounding boxes, the L1 regression loss and the GIoU loss.
+
+ Targets dicts must contain the key "boxes" containing a tensor of dim [nb_target_boxes, 4]. The target boxes
+ are expected in format (center_x, center_y, w, h), normalized by the image size.
+ """
+ if "pred_boxes" not in outputs:
+ raise KeyError("No predicted boxes found in outputs")
+ idx = self._get_source_permutation_idx(indices)
+ source_boxes = outputs["pred_boxes"][idx]
+ target_boxes = torch.cat([t["boxes"][i] for t, (_, i) in zip(targets, indices)], dim=0)
+
+ loss_bbox = nn.functional.l1_loss(source_boxes, target_boxes, reduction="none")
+
+ losses = {}
+ losses["loss_bbox"] = loss_bbox.sum() / num_boxes
+
+ loss_giou = 1 - torch.diag(
+ generalized_box_iou(center_to_corners_format(source_boxes), center_to_corners_format(target_boxes))
+ )
+ losses["loss_giou"] = loss_giou.sum() / num_boxes
+ return losses
+
+ def _get_source_permutation_idx(self, indices):
+ # permute predictions following indices
+ batch_idx = torch.cat([torch.full_like(source, i) for i, (source, _) in enumerate(indices)])
+ source_idx = torch.cat([source for (source, _) in indices])
+ return batch_idx, source_idx
+
+ def _get_target_permutation_idx(self, indices):
+ # permute targets following indices
+ batch_idx = torch.cat([torch.full_like(target, i) for i, (_, target) in enumerate(indices)])
+ target_idx = torch.cat([target for (_, target) in indices])
+ return batch_idx, target_idx
+
+ def get_loss(self, loss, outputs, targets, indices, num_boxes):
+ loss_map = {
+ "labels": self.loss_labels,
+ "cardinality": self.loss_cardinality,
+ "boxes": self.loss_boxes,
+ }
+ if loss not in loss_map:
+ raise ValueError(f"Loss {loss} not supported")
+ return loss_map[loss](outputs, targets, indices, num_boxes)
+
+ def forward(self, outputs, targets):
+ """
+ This performs the loss computation.
+
+ Args:
+ outputs (`dict`, *optional*):
+ Dictionary of tensors, see the output specification of the model for the format.
+ targets (`list[dict]`, *optional*):
+ List of dicts, such that `len(targets) == batch_size`. The expected keys in each dict depends on the
+ losses applied, see each loss' doc.
+ """
+ outputs_without_aux = {k: v for k, v in outputs.items() if k not in ("auxiliary_outputs", "enc_outputs")}
+
+ # Retrieve the matching between the outputs of the last layer and the targets
+ if self.assign_second_stage:
+ indices = self.stg2_assigner(outputs_without_aux, targets)
+ else:
+ indices = self.matcher(outputs_without_aux, targets)
+
+ # Compute the average number of target boxes across all nodes, for normalization purposes
+ num_boxes = sum(len(t["class_labels"]) for t in targets)
+ num_boxes = torch.as_tensor([num_boxes], dtype=torch.float, device=next(iter(outputs.values())).device)
+ # Check that we have initialized the distributed state
+ world_size = 1
+ if is_accelerate_available():
+ if PartialState._shared_state != {}:
+ num_boxes = reduce(num_boxes)
+ world_size = PartialState().num_processes
+ num_boxes = torch.clamp(num_boxes / world_size, min=1).item()
+
+ # Compute all the requested losses
+ losses = {}
+ for loss in self.losses:
+ losses.update(self.get_loss(loss, outputs, targets, indices, num_boxes))
+
+ # In case of auxiliary losses, we repeat this process with the output of each intermediate layer.
+ if "auxiliary_outputs" in outputs:
+ for i, auxiliary_outputs in enumerate(outputs["auxiliary_outputs"]):
+ if not self.assign_second_stage:
+ indices = self.matcher(auxiliary_outputs, targets)
+ for loss in self.losses:
+ l_dict = self.get_loss(loss, auxiliary_outputs, targets, indices, num_boxes)
+ l_dict = {k + f"_{i}": v for k, v in l_dict.items()}
+ losses.update(l_dict)
+
+ if "enc_outputs" in outputs:
+ enc_outputs = outputs["enc_outputs"]
+ bin_targets = copy.deepcopy(targets)
+ for bt in bin_targets:
+ bt["class_labels"] = torch.zeros_like(bt["class_labels"])
+ if self.assign_first_stage:
+ indices = self.stg1_assigner(enc_outputs, bin_targets)
+ else:
+ indices = self.matcher(enc_outputs, bin_targets)
+ for loss in self.losses:
+ l_dict = self.get_loss(loss, enc_outputs, bin_targets, indices, num_boxes)
+ l_dict = {k + "_enc": v for k, v in l_dict.items()}
+ losses.update(l_dict)
+
+ return losses
+
+
+class DetaMLPPredictionHead(nn.Module):
+ """
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
+ height and width of a bounding box w.r.t. an image.
+
+ Copied from https://github.com/facebookresearch/detr/blob/master/models/detr.py
+
+ """
+
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ return x
+
+
+class DetaHungarianMatcher(nn.Module):
+ """
+ This class computes an assignment between the targets and the predictions of the network.
+
+ For efficiency reasons, the targets don't include the no_object. Because of this, in general, there are more
+ predictions than targets. In this case, we do a 1-to-1 matching of the best predictions, while the others are
+ un-matched (and thus treated as non-objects).
+
+ Args:
+ class_cost:
+ The relative weight of the classification error in the matching cost.
+ bbox_cost:
+ The relative weight of the L1 error of the bounding box coordinates in the matching cost.
+ giou_cost:
+ The relative weight of the giou loss of the bounding box in the matching cost.
+ """
+
+ def __init__(self, class_cost: float = 1, bbox_cost: float = 1, giou_cost: float = 1):
+ super().__init__()
+ requires_backends(self, ["scipy"])
+
+ self.class_cost = class_cost
+ self.bbox_cost = bbox_cost
+ self.giou_cost = giou_cost
+ if class_cost == 0 and bbox_cost == 0 and giou_cost == 0:
+ raise ValueError("All costs of the Matcher can't be 0")
+
+ @torch.no_grad()
+ def forward(self, outputs, targets):
+ """
+ Args:
+ outputs (`dict`):
+ A dictionary that contains at least these entries:
+ * "logits": Tensor of dim [batch_size, num_queries, num_classes] with the classification logits
+ * "pred_boxes": Tensor of dim [batch_size, num_queries, 4] with the predicted box coordinates.
+ targets (`list[dict]`):
+ A list of targets (len(targets) = batch_size), where each target is a dict containing:
+ * "class_labels": Tensor of dim [num_target_boxes] (where num_target_boxes is the number of
+ ground-truth
+ objects in the target) containing the class labels
+ * "boxes": Tensor of dim [num_target_boxes, 4] containing the target box coordinates.
+
+ Returns:
+ `list[Tuple]`: A list of size `batch_size`, containing tuples of (index_i, index_j) where:
+ - index_i is the indices of the selected predictions (in order)
+ - index_j is the indices of the corresponding selected targets (in order)
+ For each batch element, it holds: len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
+ """
+ batch_size, num_queries = outputs["logits"].shape[:2]
+
+ # We flatten to compute the cost matrices in a batch
+ out_prob = outputs["logits"].flatten(0, 1).sigmoid() # [batch_size * num_queries, num_classes]
+ out_bbox = outputs["pred_boxes"].flatten(0, 1) # [batch_size * num_queries, 4]
+
+ # Also concat the target labels and boxes
+ target_ids = torch.cat([v["class_labels"] for v in targets])
+ target_bbox = torch.cat([v["boxes"] for v in targets])
+
+ # Compute the classification cost.
+ alpha = 0.25
+ gamma = 2.0
+ neg_cost_class = (1 - alpha) * (out_prob**gamma) * (-(1 - out_prob + 1e-8).log())
+ pos_cost_class = alpha * ((1 - out_prob) ** gamma) * (-(out_prob + 1e-8).log())
+ class_cost = pos_cost_class[:, target_ids] - neg_cost_class[:, target_ids]
+
+ # Compute the L1 cost between boxes
+ bbox_cost = torch.cdist(out_bbox, target_bbox, p=1)
+
+ # Compute the giou cost between boxes
+ giou_cost = -generalized_box_iou(center_to_corners_format(out_bbox), center_to_corners_format(target_bbox))
+
+ # Final cost matrix
+ cost_matrix = self.bbox_cost * bbox_cost + self.class_cost * class_cost + self.giou_cost * giou_cost
+ cost_matrix = cost_matrix.view(batch_size, num_queries, -1).cpu()
+
+ sizes = [len(v["boxes"]) for v in targets]
+ indices = [linear_sum_assignment(c[i]) for i, c in enumerate(cost_matrix.split(sizes, -1))]
+ return [(torch.as_tensor(i, dtype=torch.int64), torch.as_tensor(j, dtype=torch.int64)) for i, j in indices]
+
+
+def _upcast(t: Tensor) -> Tensor:
+ # Protects from numerical overflows in multiplications by upcasting to the equivalent higher type
+ if t.is_floating_point():
+ return t if t.dtype in (torch.float32, torch.float64) else t.float()
+ else:
+ return t if t.dtype in (torch.int32, torch.int64) else t.int()
+
+
+def box_area(boxes: Tensor) -> Tensor:
+ """
+ Computes the area of a set of bounding boxes, which are specified by its (x1, y1, x2, y2) coordinates.
+
+ Args:
+ boxes (`torch.FloatTensor` of shape `(number_of_boxes, 4)`):
+ Boxes for which the area will be computed. They are expected to be in (x1, y1, x2, y2) format with `0 <= x1
+ < x2` and `0 <= y1 < y2`.
+
+ Returns:
+ `torch.FloatTensor`: a tensor containing the area for each box.
+ """
+ boxes = _upcast(boxes)
+ return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
+
+
+def box_iou(boxes1, boxes2):
+ area1 = box_area(boxes1)
+ area2 = box_area(boxes2)
+
+ left_top = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
+ right_bottom = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
+
+ width_height = (right_bottom - left_top).clamp(min=0) # [N,M,2]
+ inter = width_height[:, :, 0] * width_height[:, :, 1] # [N,M]
+
+ union = area1[:, None] + area2 - inter
+
+ iou = inter / union
+ return iou, union
+
+
+def generalized_box_iou(boxes1, boxes2):
+ """
+ Generalized IoU from https://giou.stanford.edu/. The boxes should be in [x0, y0, x1, y1] (corner) format.
+
+ Returns:
+ `torch.FloatTensor`: a [N, M] pairwise matrix, where N = len(boxes1) and M = len(boxes2)
+ """
+ # degenerate boxes gives inf / nan results
+ # so do an early check
+ if not (boxes1[:, 2:] >= boxes1[:, :2]).all():
+ raise ValueError(f"boxes1 must be in [x0, y0, x1, y1] (corner) format, but got {boxes1}")
+ if not (boxes2[:, 2:] >= boxes2[:, :2]).all():
+ raise ValueError(f"boxes2 must be in [x0, y0, x1, y1] (corner) format, but got {boxes2}")
+ iou, union = box_iou(boxes1, boxes2)
+
+ top_left = torch.min(boxes1[:, None, :2], boxes2[:, :2])
+ bottom_right = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
+
+ width_height = (bottom_right - top_left).clamp(min=0) # [N,M,2]
+ area = width_height[:, :, 0] * width_height[:, :, 1]
+
+ return iou - (area - union) / area
+
+
+# from https://github.com/facebookresearch/detectron2/blob/cbbc1ce26473cb2a5cc8f58e8ada9ae14cb41052/detectron2/layers/wrappers.py#L100
+def nonzero_tuple(x):
+ """
+ A 'as_tuple=True' version of torch.nonzero to support torchscript. because of
+ https://github.com/pytorch/pytorch/issues/38718
+ """
+ if torch.jit.is_scripting():
+ if x.dim() == 0:
+ return x.unsqueeze(0).nonzero().unbind(1)
+ return x.nonzero().unbind(1)
+ else:
+ return x.nonzero(as_tuple=True)
+
+
+# from https://github.com/facebookresearch/detectron2/blob/9921a2caa585d4fa66c4b534b6fab6e74d89b582/detectron2/modeling/matcher.py#L9
+class DetaMatcher:
+ """
+ This class assigns to each predicted "element" (e.g., a box) a ground-truth element. Each predicted element will
+ have exactly zero or one matches; each ground-truth element may be matched to zero or more predicted elements.
+
+ The matching is determined by the MxN match_quality_matrix, that characterizes how well each (ground-truth,
+ prediction)-pair match each other. For example, if the elements are boxes, this matrix may contain box
+ intersection-over-union overlap values.
+
+ The matcher returns (a) a vector of length N containing the index of the ground-truth element m in [0, M) that
+ matches to prediction n in [0, N). (b) a vector of length N containing the labels for each prediction.
+ """
+
+ def __init__(self, thresholds: list[float], labels: list[int], allow_low_quality_matches: bool = False):
+ """
+ Args:
+ thresholds (`list[float]`):
+ A list of thresholds used to stratify predictions into levels.
+ labels (`list[int`):
+ A list of values to label predictions belonging at each level. A label can be one of {-1, 0, 1}
+ signifying {ignore, negative class, positive class}, respectively.
+ allow_low_quality_matches (`bool`, *optional*, defaults to `False`):
+ If `True`, produce additional matches for predictions with maximum match quality lower than
+ high_threshold. See `set_low_quality_matches_` for more details.
+
+ For example,
+ thresholds = [0.3, 0.5] labels = [0, -1, 1] All predictions with iou < 0.3 will be marked with 0 and
+ thus will be considered as false positives while training. All predictions with 0.3 <= iou < 0.5 will
+ be marked with -1 and thus will be ignored. All predictions with 0.5 <= iou will be marked with 1 and
+ thus will be considered as true positives.
+ """
+ # Add -inf and +inf to first and last position in thresholds
+ thresholds = thresholds[:]
+ if thresholds[0] < 0:
+ raise ValueError("Thresholds should be positive")
+ thresholds.insert(0, -float("inf"))
+ thresholds.append(float("inf"))
+ # Currently torchscript does not support all + generator
+ if not all(low <= high for (low, high) in zip(thresholds[:-1], thresholds[1:])):
+ raise ValueError("Thresholds should be sorted.")
+ if not all(l in [-1, 0, 1] for l in labels):
+ raise ValueError("All labels should be either -1, 0 or 1")
+ if len(labels) != len(thresholds) - 1:
+ raise ValueError("Number of labels should be equal to number of thresholds - 1")
+ self.thresholds = thresholds
+ self.labels = labels
+ self.allow_low_quality_matches = allow_low_quality_matches
+
+ def __call__(self, match_quality_matrix):
+ """
+ Args:
+ match_quality_matrix (Tensor[float]): an MxN tensor, containing the
+ pairwise quality between M ground-truth elements and N predicted elements. All elements must be >= 0
+ (due to the us of `torch.nonzero` for selecting indices in `set_low_quality_matches_`).
+
+ Returns:
+ matches (Tensor[int64]): a vector of length N, where matches[i] is a matched
+ ground-truth index in [0, M)
+ match_labels (Tensor[int8]): a vector of length N, where pred_labels[i] indicates
+ whether a prediction is a true or false positive or ignored
+ """
+ assert match_quality_matrix.dim() == 2
+ if match_quality_matrix.numel() == 0:
+ default_matches = match_quality_matrix.new_full((match_quality_matrix.size(1),), 0, dtype=torch.int64)
+ # When no gt boxes exist, we define IOU = 0 and therefore set labels
+ # to `self.labels[0]`, which usually defaults to background class 0
+ # To choose to ignore instead, can make labels=[-1,0,-1,1] + set appropriate thresholds
+ default_match_labels = match_quality_matrix.new_full(
+ (match_quality_matrix.size(1),), self.labels[0], dtype=torch.int8
+ )
+ return default_matches, default_match_labels
+
+ assert torch.all(match_quality_matrix >= 0)
+
+ # match_quality_matrix is M (gt) x N (predicted)
+ # Max over gt elements (dim 0) to find best gt candidate for each prediction
+ matched_vals, matches = match_quality_matrix.max(dim=0)
+
+ match_labels = matches.new_full(matches.size(), 1, dtype=torch.int8)
+
+ for l, low, high in zip(self.labels, self.thresholds[:-1], self.thresholds[1:]):
+ low_high = (matched_vals >= low) & (matched_vals < high)
+ match_labels[low_high] = l
+
+ if self.allow_low_quality_matches:
+ self.set_low_quality_matches_(match_labels, match_quality_matrix)
+
+ return matches, match_labels
+
+ def set_low_quality_matches_(self, match_labels, match_quality_matrix):
+ """
+ Produce additional matches for predictions that have only low-quality matches. Specifically, for each
+ ground-truth G find the set of predictions that have maximum overlap with it (including ties); for each
+ prediction in that set, if it is unmatched, then match it to the ground-truth G.
+
+ This function implements the RPN assignment case (i) in Sec. 3.1.2 of :paper:`Faster R-CNN`.
+ """
+ # For each gt, find the prediction with which it has highest quality
+ highest_quality_foreach_gt, _ = match_quality_matrix.max(dim=1)
+ # Find the highest quality match available, even if it is low, including ties.
+ # Note that the matches qualities must be positive due to the use of
+ # `torch.nonzero`.
+ _, pred_inds_with_highest_quality = nonzero_tuple(match_quality_matrix == highest_quality_foreach_gt[:, None])
+ # If an anchor was labeled positive only due to a low-quality match
+ # with gt_A, but it has larger overlap with gt_B, it's matched index will still be gt_B.
+ # This follows the implementation in Detectron, and is found to have no significant impact.
+ match_labels[pred_inds_with_highest_quality] = 1
+
+
+# from https://github.com/facebookresearch/detectron2/blob/cbbc1ce26473cb2a5cc8f58e8ada9ae14cb41052/detectron2/modeling/sampling.py#L9
+def subsample_labels(labels: torch.Tensor, num_samples: int, positive_fraction: float, bg_label: int):
+ """
+ Return `num_samples` (or fewer, if not enough found) random samples from `labels` which is a mixture of positives &
+ negatives. It will try to return as many positives as possible without exceeding `positive_fraction * num_samples`,
+ and then try to fill the remaining slots with negatives.
+
+ Args:
+ labels (Tensor): (N, ) label vector with values:
+ * -1: ignore
+ * bg_label: background ("negative") class
+ * otherwise: one or more foreground ("positive") classes
+ num_samples (int): The total number of labels with value >= 0 to return.
+ Values that are not sampled will be filled with -1 (ignore).
+ positive_fraction (float): The number of subsampled labels with values > 0
+ is `min(num_positives, int(positive_fraction * num_samples))`. The number of negatives sampled is
+ `min(num_negatives, num_samples - num_positives_sampled)`. In order words, if there are not enough
+ positives, the sample is filled with negatives. If there are also not enough negatives, then as many
+ elements are sampled as is possible.
+ bg_label (int): label index of background ("negative") class.
+
+ Returns:
+ pos_idx, neg_idx (Tensor):
+ 1D vector of indices. The total length of both is `num_samples` or fewer.
+ """
+ positive = nonzero_tuple((labels != -1) & (labels != bg_label))[0]
+ negative = nonzero_tuple(labels == bg_label)[0]
+
+ num_pos = int(num_samples * positive_fraction)
+ # protect against not enough positive examples
+ num_pos = min(positive.numel(), num_pos)
+ num_neg = num_samples - num_pos
+ # protect against not enough negative examples
+ num_neg = min(negative.numel(), num_neg)
+
+ # randomly select positive and negative examples
+ perm1 = torch.randperm(positive.numel(), device=positive.device)[:num_pos]
+ perm2 = torch.randperm(negative.numel(), device=negative.device)[:num_neg]
+
+ pos_idx = positive[perm1]
+ neg_idx = negative[perm2]
+ return pos_idx, neg_idx
+
+
+def sample_topk_per_gt(pr_inds, gt_inds, iou, k):
+ if len(gt_inds) == 0:
+ return pr_inds, gt_inds
+ # find topk matches for each gt
+ gt_inds2, counts = gt_inds.unique(return_counts=True)
+ scores, pr_inds2 = iou[gt_inds2].topk(k, dim=1)
+ gt_inds2 = gt_inds2[:, None].repeat(1, k)
+
+ # filter to as many matches that gt has
+ pr_inds3 = torch.cat([pr[:c] for c, pr in zip(counts, pr_inds2)])
+ gt_inds3 = torch.cat([gt[:c] for c, gt in zip(counts, gt_inds2)])
+ return pr_inds3, gt_inds3
+
+
+# modified from https://github.com/facebookresearch/detectron2/blob/cbbc1ce26473cb2a5cc8f58e8ada9ae14cb41052/detectron2/modeling/roi_heads/roi_heads.py#L123
+class DetaStage2Assigner(nn.Module):
+ def __init__(self, num_queries, max_k=4):
+ super().__init__()
+ self.positive_fraction = 0.25
+ self.bg_label = 400 # number > 91 to filter out later
+ self.batch_size_per_image = num_queries
+ self.proposal_matcher = DetaMatcher(thresholds=[0.6], labels=[0, 1], allow_low_quality_matches=True)
+ self.k = max_k
+
+ def _sample_proposals(self, matched_idxs: torch.Tensor, matched_labels: torch.Tensor, gt_classes: torch.Tensor):
+ """
+ Based on the matching between N proposals and M groundtruth, sample the proposals and set their classification
+ labels.
+
+ Args:
+ matched_idxs (Tensor): a vector of length N, each is the best-matched
+ gt index in [0, M) for each proposal.
+ matched_labels (Tensor): a vector of length N, the matcher's label
+ (one of cfg.MODEL.ROI_HEADS.IOU_LABELS) for each proposal.
+ gt_classes (Tensor): a vector of length M.
+
+ Returns:
+ Tensor: a vector of indices of sampled proposals. Each is in [0, N). Tensor: a vector of the same length,
+ the classification label for
+ each sampled proposal. Each sample is labeled as either a category in [0, num_classes) or the
+ background (num_classes).
+ """
+ has_gt = gt_classes.numel() > 0
+ # Get the corresponding GT for each proposal
+ if has_gt:
+ gt_classes = gt_classes[matched_idxs]
+ # Label unmatched proposals (0 label from matcher) as background (label=num_classes)
+ gt_classes[matched_labels == 0] = self.bg_label
+ # Label ignore proposals (-1 label)
+ gt_classes[matched_labels == -1] = -1
+ else:
+ gt_classes = torch.zeros_like(matched_idxs) + self.bg_label
+
+ sampled_fg_idxs, sampled_bg_idxs = subsample_labels(
+ gt_classes, self.batch_size_per_image, self.positive_fraction, self.bg_label
+ )
+
+ sampled_idxs = torch.cat([sampled_fg_idxs, sampled_bg_idxs], dim=0)
+ return sampled_idxs, gt_classes[sampled_idxs]
+
+ def forward(self, outputs, targets, return_cost_matrix=False):
+ # COCO categories are from 1 to 90. They set num_classes=91 and apply sigmoid.
+
+ bs = len(targets)
+ indices = []
+ ious = []
+ for b in range(bs):
+ iou, _ = box_iou(
+ center_to_corners_format(targets[b]["boxes"]),
+ center_to_corners_format(outputs["init_reference"][b].detach()),
+ )
+ matched_idxs, matched_labels = self.proposal_matcher(
+ iou
+ ) # proposal_id -> highest_iou_gt_id, proposal_id -> [1 if iou > 0.6, 0 ow]
+ (
+ sampled_idxs,
+ sampled_gt_classes,
+ ) = self._sample_proposals( # list of sampled proposal_ids, sampled_id -> [0, num_classes)+[bg_label]
+ matched_idxs, matched_labels, targets[b]["class_labels"]
+ )
+ pos_pr_inds = sampled_idxs[sampled_gt_classes != self.bg_label]
+ pos_gt_inds = matched_idxs[pos_pr_inds]
+ pos_pr_inds, pos_gt_inds = self.postprocess_indices(pos_pr_inds, pos_gt_inds, iou)
+ indices.append((pos_pr_inds, pos_gt_inds))
+ ious.append(iou)
+ if return_cost_matrix:
+ return indices, ious
+ return indices
+
+ def postprocess_indices(self, pr_inds, gt_inds, iou):
+ return sample_topk_per_gt(pr_inds, gt_inds, iou, self.k)
+
+
+# modified from https://github.com/facebookresearch/detectron2/blob/cbbc1ce26473cb2a5cc8f58e8ada9ae14cb41052/detectron2/modeling/proposal_generator/rpn.py#L181
+class DetaStage1Assigner(nn.Module):
+ def __init__(self, t_low=0.3, t_high=0.7, max_k=4):
+ super().__init__()
+ self.positive_fraction = 0.5
+ self.batch_size_per_image = 256
+ self.k = max_k
+ self.t_low = t_low
+ self.t_high = t_high
+ self.anchor_matcher = DetaMatcher(
+ thresholds=[t_low, t_high], labels=[0, -1, 1], allow_low_quality_matches=True
+ )
+
+ def _subsample_labels(self, label):
+ """
+ Randomly sample a subset of positive and negative examples, and overwrite the label vector to the ignore value
+ (-1) for all elements that are not included in the sample.
+
+ Args:
+ labels (Tensor): a vector of -1, 0, 1. Will be modified in-place and returned.
+ """
+ pos_idx, neg_idx = subsample_labels(label, self.batch_size_per_image, self.positive_fraction, 0)
+ # Fill with the ignore label (-1), then set positive and negative labels
+ label.fill_(-1)
+ label.scatter_(0, pos_idx, 1)
+ label.scatter_(0, neg_idx, 0)
+ return label
+
+ def forward(self, outputs, targets):
+ bs = len(targets)
+ indices = []
+ for b in range(bs):
+ anchors = outputs["anchors"][b]
+ if len(targets[b]["boxes"]) == 0:
+ indices.append(
+ (
+ torch.tensor([], dtype=torch.long, device=anchors.device),
+ torch.tensor([], dtype=torch.long, device=anchors.device),
+ )
+ )
+ continue
+ iou, _ = box_iou(
+ center_to_corners_format(targets[b]["boxes"]),
+ center_to_corners_format(anchors),
+ )
+ matched_idxs, matched_labels = self.anchor_matcher(
+ iou
+ ) # proposal_id -> highest_iou_gt_id, proposal_id -> [1 if iou > 0.7, 0 if iou < 0.3, -1 ow]
+ matched_labels = self._subsample_labels(matched_labels)
+
+ all_pr_inds = torch.arange(len(anchors), device=matched_labels.device)
+ pos_pr_inds = all_pr_inds[matched_labels == 1]
+ pos_gt_inds = matched_idxs[pos_pr_inds]
+ pos_pr_inds, pos_gt_inds = self.postprocess_indices(pos_pr_inds, pos_gt_inds, iou)
+ pos_pr_inds, pos_gt_inds = pos_pr_inds.to(anchors.device), pos_gt_inds.to(anchors.device)
+ indices.append((pos_pr_inds, pos_gt_inds))
+ return indices
+
+ def postprocess_indices(self, pr_inds, gt_inds, iou):
+ return sample_topk_per_gt(pr_inds, gt_inds, iou, self.k)
+
+
+__all__ = ["DetaForObjectDetection", "DetaModel", "DetaPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..db3d0a634051c713aee33b48f2962647ac48d0eb
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_efficientformer import *
+ from .image_processing_efficientformer import *
+ from .modeling_efficientformer import *
+ from .modeling_tf_efficientformer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2246fd2943d94c638c6e2eaa293019846e624b1b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/configuration_efficientformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/configuration_efficientformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be3e3722ec175e2e9bfead83fa42add7a1cb9179
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/configuration_efficientformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/image_processing_efficientformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/image_processing_efficientformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fe2b5905a5a657f1b43846217e24888adbbdc1c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/image_processing_efficientformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/modeling_efficientformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/modeling_efficientformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..367a7802311539f778f0415b116274bb7c5c9411
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/modeling_efficientformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/modeling_tf_efficientformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/modeling_tf_efficientformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e4e403296e6ddb9cb4d8c09772d8b8bf3ec329b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/__pycache__/modeling_tf_efficientformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/configuration_efficientformer.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/configuration_efficientformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..9aaee649ba047e5967f132eb0b3527dce5855d11
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/configuration_efficientformer.py
@@ -0,0 +1,170 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""EfficientFormer model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class EfficientFormerConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of an [`EfficientFormerModel`]. It is used to
+ instantiate an EfficientFormer model according to the specified arguments, defining the model architecture.
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the EfficientFormer
+ [snap-research/efficientformer-l1](https://huggingface.co/snap-research/efficientformer-l1) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ depths (`List(int)`, *optional*, defaults to `[3, 2, 6, 4]`)
+ Depth of each stage.
+ hidden_sizes (`List(int)`, *optional*, defaults to `[48, 96, 224, 448]`)
+ Dimensionality of each stage.
+ downsamples (`List(bool)`, *optional*, defaults to `[True, True, True, True]`)
+ Whether or not to downsample inputs between two stages.
+ dim (`int`, *optional*, defaults to 448):
+ Number of channels in Meta3D layers
+ key_dim (`int`, *optional*, defaults to 32):
+ The size of the key in meta3D block.
+ attention_ratio (`int`, *optional*, defaults to 4):
+ Ratio of the dimension of the query and value to the dimension of the key in MSHA block
+ resolution (`int`, *optional*, defaults to 7)
+ Size of each patch
+ num_hidden_layers (`int`, *optional*, defaults to 5):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 8):
+ Number of attention heads for each attention layer in the 3D MetaBlock.
+ mlp_expansion_ratio (`int`, *optional*, defaults to 4):
+ Ratio of size of the hidden dimensionality of an MLP to the dimensionality of its input.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings and encoder.
+ patch_size (`int`, *optional*, defaults to 16):
+ The size (resolution) of each patch.
+ num_channels (`int`, *optional*, defaults to 3):
+ The number of input channels.
+ pool_size (`int`, *optional*, defaults to 3):
+ Kernel size of pooling layers.
+ downsample_patch_size (`int`, *optional*, defaults to 3):
+ The size of patches in downsampling layers.
+ downsample_stride (`int`, *optional*, defaults to 2):
+ The stride of convolution kernels in downsampling layers.
+ downsample_pad (`int`, *optional*, defaults to 1):
+ Padding in downsampling layers.
+ drop_path_rate (`int`, *optional*, defaults to 0):
+ Rate at which to increase dropout probability in DropPath.
+ num_meta3d_blocks (`int`, *optional*, defaults to 1):
+ The number of 3D MetaBlocks in the last stage.
+ distillation (`bool`, *optional*, defaults to `True`):
+ Whether to add a distillation head.
+ use_layer_scale (`bool`, *optional*, defaults to `True`):
+ Whether to scale outputs from token mixers.
+ layer_scale_init_value (`float`, *optional*, defaults to 1e-5):
+ Factor by which outputs from token mixers are scaled.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ image_size (`int`, *optional*, defaults to `224`):
+ The size (resolution) of each image.
+
+ Example:
+
+ ```python
+ >>> from transformers import EfficientFormerConfig, EfficientFormerModel
+
+ >>> # Initializing a EfficientFormer efficientformer-l1 style configuration
+ >>> configuration = EfficientFormerConfig()
+
+ >>> # Initializing a EfficientFormerModel (with random weights) from the efficientformer-l3 style configuration
+ >>> model = EfficientFormerModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "efficientformer"
+
+ def __init__(
+ self,
+ depths: list[int] = [3, 2, 6, 4],
+ hidden_sizes: list[int] = [48, 96, 224, 448],
+ downsamples: list[bool] = [True, True, True, True],
+ dim: int = 448,
+ key_dim: int = 32,
+ attention_ratio: int = 4,
+ resolution: int = 7,
+ num_hidden_layers: int = 5,
+ num_attention_heads: int = 8,
+ mlp_expansion_ratio: int = 4,
+ hidden_dropout_prob: float = 0.0,
+ patch_size: int = 16,
+ num_channels: int = 3,
+ pool_size: int = 3,
+ downsample_patch_size: int = 3,
+ downsample_stride: int = 2,
+ downsample_pad: int = 1,
+ drop_path_rate: float = 0.0,
+ num_meta3d_blocks: int = 1,
+ distillation: bool = True,
+ use_layer_scale: bool = True,
+ layer_scale_init_value: float = 1e-5,
+ hidden_act: str = "gelu",
+ initializer_range: float = 0.02,
+ layer_norm_eps: float = 1e-12,
+ image_size: int = 224,
+ batch_norm_eps: float = 1e-05,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.hidden_sizes = hidden_sizes
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.depths = depths
+ self.mlp_expansion_ratio = mlp_expansion_ratio
+ self.downsamples = downsamples
+ self.dim = dim
+ self.key_dim = key_dim
+ self.attention_ratio = attention_ratio
+ self.resolution = resolution
+ self.pool_size = pool_size
+ self.downsample_patch_size = downsample_patch_size
+ self.downsample_stride = downsample_stride
+ self.downsample_pad = downsample_pad
+ self.drop_path_rate = drop_path_rate
+ self.num_meta3d_blocks = num_meta3d_blocks
+ self.distillation = distillation
+ self.use_layer_scale = use_layer_scale
+ self.layer_scale_init_value = layer_scale_init_value
+ self.image_size = image_size
+ self.batch_norm_eps = batch_norm_eps
+
+
+__all__ = [
+ "EfficientFormerConfig",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/image_processing_efficientformer.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/image_processing_efficientformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..39267aa2e6cd07dc184092b6c8ef4d5ed76d922a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/image_processing_efficientformer.py
@@ -0,0 +1,324 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for EfficientFormer."""
+
+from typing import Optional, Union
+
+import numpy as np
+
+from ....image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
+from ....image_transforms import (
+ get_resize_output_image_size,
+ resize,
+ to_channel_dimension_format,
+)
+from ....image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ infer_channel_dimension_format,
+ is_batched,
+ is_scaled_image,
+ to_numpy_array,
+ valid_images,
+ validate_kwargs,
+ validate_preprocess_arguments,
+)
+from ....utils import TensorType, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class EfficientFormerImageProcessor(BaseImageProcessor):
+ r"""
+ Constructs a EfficientFormer image processor.
+
+ Args:
+ do_resize (`bool`, *optional*, defaults to `True`):
+ Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
+ size["width"])`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
+ size (`dict`, *optional*, defaults to `{"height": 224, "width": 224}`):
+ Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
+ method.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
+ `preprocess` method.
+ do_center_crop (`bool`, *optional*, defaults to `True`):
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
+ `preprocess` method.
+ crop_size (`dict[str, int]` *optional*, defaults to 224):
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
+ method.
+ do_rescale (`bool`, *optional*, defaults to `True`):
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
+ parameter in the `preprocess` method.
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
+ `preprocess` method.
+ do_normalize:
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
+ method.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
+ """
+
+ model_input_names = ["pixel_values"]
+
+ def __init__(
+ self,
+ do_resize: bool = True,
+ size: Optional[dict[str, int]] = None,
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
+ do_center_crop: bool = True,
+ do_rescale: bool = True,
+ rescale_factor: Union[int, float] = 1 / 255,
+ crop_size: Optional[dict[str, int]] = None,
+ do_normalize: bool = True,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ size = size if size is not None else {"height": 224, "width": 224}
+ size = get_size_dict(size)
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
+
+ self.do_resize = do_resize
+ self.do_rescale = do_rescale
+ self.do_normalize = do_normalize
+ self.do_center_crop = do_center_crop
+ self.crop_size = crop_size
+ self.size = size
+ self.resample = resample
+ self.rescale_factor = rescale_factor
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
+ self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
+ self._valid_processor_keys = [
+ "images",
+ "do_resize",
+ "size",
+ "resample",
+ "do_center_crop",
+ "crop_size",
+ "do_rescale",
+ "rescale_factor",
+ "do_normalize",
+ "image_mean",
+ "image_std",
+ "return_tensors",
+ "data_format",
+ "input_data_format",
+ ]
+
+ def resize(
+ self,
+ image: np.ndarray,
+ size: dict[str, int],
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Resize an image to `(size["height"], size["width"])`.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`dict[str, int]`):
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
+ resample:
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
+ data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred.
+
+ Returns:
+ `np.ndarray`: The resized image.
+ """
+ size = get_size_dict(size)
+
+ if "shortest_edge" in size:
+ size = get_resize_output_image_size(
+ image, size=size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
+ )
+ # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
+ elif "height" in size and "width" in size:
+ size = (size["height"], size["width"])
+ else:
+ raise ValueError(f"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}")
+ return resize(
+ image, size=size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs
+ )
+
+ def preprocess(
+ self,
+ images: ImageInput,
+ do_resize: Optional[bool] = None,
+ size: Optional[dict[str, int]] = None,
+ resample: PILImageResampling = None,
+ do_center_crop: Optional[bool] = None,
+ crop_size: Optional[int] = None,
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or batch of images.
+
+ Args:
+ images (`ImageInput`):
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
+ Whether to resize the image.
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
+ Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
+ resizing.
+ resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
+ `PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
+ an effect if `do_resize` is set to `True`.
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
+ Whether to center crop the image.
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
+ Whether to rescale the image values between [0 - 1].
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
+ Whether to normalize the image.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
+ Image mean to use if `do_normalize` is set to `True`.
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
+ Image standard deviation to use if `do_normalize` is set to `True`.
+ return_tensors (`str` or `TensorType`, *optional*):
+ The type of tensors to return. Can be one of:
+ - Unset: Return a list of `np.ndarray`.
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
+ The channel dimension format for the output image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - Unset: Use the channel dimension format of the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+ """
+ do_resize = do_resize if do_resize is not None else self.do_resize
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
+ crop_size = crop_size if crop_size is not None else self.crop_size
+ crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
+ resample = resample if resample is not None else self.resample
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
+ image_mean = image_mean if image_mean is not None else self.image_mean
+ image_std = image_std if image_std is not None else self.image_std
+
+ size = size if size is not None else self.size
+ size_dict = get_size_dict(size)
+
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
+
+ if not is_batched(images):
+ images = [images]
+
+ if not valid_images(images):
+ raise ValueError(
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
+ "torch.Tensor, tf.Tensor or jax.ndarray."
+ )
+ validate_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_center_crop=do_center_crop,
+ crop_size=crop_size,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ )
+ # All transformations expect numpy arrays.
+ images = [to_numpy_array(image) for image in images]
+
+ if do_rescale and is_scaled_image(images[0]):
+ logger.warning_once(
+ "It looks like you are trying to rescale already rescaled images. If the input"
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
+ )
+
+ if input_data_format is None:
+ # We assume that all images have the same channel dimension format.
+ input_data_format = infer_channel_dimension_format(images[0])
+
+ if do_resize:
+ images = [
+ self.resize(image=image, size=size_dict, resample=resample, input_data_format=input_data_format)
+ for image in images
+ ]
+
+ if do_center_crop:
+ images = [
+ self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) for image in images
+ ]
+
+ if do_rescale:
+ images = [
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
+ for image in images
+ ]
+
+ if do_normalize:
+ images = [
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
+ for image in images
+ ]
+
+ images = [
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
+ ]
+
+ data = {"pixel_values": images}
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+
+__all__ = ["EfficientFormerImageProcessor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/modeling_efficientformer.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/modeling_efficientformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d75e45dbc85b5d69a31dfe434288f0e46175868
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/modeling_efficientformer.py
@@ -0,0 +1,807 @@
+# coding=utf-8
+# Copyright 2022 Snapchat Research and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch EfficientFormer model."""
+
+import itertools
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
+from ....modeling_utils import PreTrainedModel
+from ....utils import (
+ ModelOutput,
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+)
+from .configuration_efficientformer import EfficientFormerConfig
+
+
+logger = logging.get_logger(__name__)
+
+# General docstring
+_CONFIG_FOR_DOC = "EfficientFormerConfig"
+
+# Base docstring
+_CHECKPOINT_FOR_DOC = "snap-research/efficientformer-l1-300"
+_EXPECTED_OUTPUT_SHAPE = [1, 49, 448]
+
+# Image classification docstring
+_IMAGE_CLASS_CHECKPOINT = "snap-research/efficientformer-l1-300"
+_IMAGE_CLASS_EXPECTED_OUTPUT = "Egyptian cat"
+
+
+class EfficientFormerPatchEmbeddings(nn.Module):
+ """
+ This class performs downsampling between two stages. For the input tensor with the shape [batch_size, num_channels,
+ height, width] it produces output tensor with the shape [batch_size, num_channels, height/stride, width/stride]
+ """
+
+ def __init__(self, config: EfficientFormerConfig, num_channels: int, embed_dim: int, apply_norm: bool = True):
+ super().__init__()
+ self.num_channels = num_channels
+
+ self.projection = nn.Conv2d(
+ num_channels,
+ embed_dim,
+ kernel_size=config.downsample_patch_size,
+ stride=config.downsample_stride,
+ padding=config.downsample_pad,
+ )
+ self.norm = nn.BatchNorm2d(embed_dim, eps=config.batch_norm_eps) if apply_norm else nn.Identity()
+
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+
+ embeddings = self.projection(pixel_values)
+ embeddings = self.norm(embeddings)
+
+ return embeddings
+
+
+class EfficientFormerSelfAttention(nn.Module):
+ def __init__(self, dim: int, key_dim: int, num_heads: int, attention_ratio: int, resolution: int):
+ super().__init__()
+
+ self.num_heads = num_heads
+ self.key_dim = key_dim
+ self.attention_ratio = attention_ratio
+ self.scale = key_dim**-0.5
+ self.total_key_dim = key_dim * num_heads
+ self.expanded_key_dim = int(attention_ratio * key_dim)
+ self.total_expanded_key_dim = int(self.expanded_key_dim * num_heads)
+ hidden_size = self.total_expanded_key_dim + self.total_key_dim * 2
+ self.qkv = nn.Linear(dim, hidden_size)
+ self.projection = nn.Linear(self.total_expanded_key_dim, dim)
+ points = list(itertools.product(range(resolution), range(resolution)))
+ num_points = len(points)
+ attention_offsets = {}
+ idxs = []
+ for point_1 in points:
+ for point_2 in points:
+ offset = (abs(point_1[0] - point_2[0]), abs(point_1[1] - point_2[1]))
+ if offset not in attention_offsets:
+ attention_offsets[offset] = len(attention_offsets)
+ idxs.append(attention_offsets[offset])
+ self.attention_biases = torch.nn.Parameter(torch.zeros(num_heads, len(attention_offsets)))
+ self.register_buffer("attention_bias_idxs", torch.LongTensor(idxs).view(num_points, num_points))
+
+ @torch.no_grad()
+ def train(self, mode=True):
+ super().train(mode)
+ if mode and hasattr(self, "ab"):
+ del self.ab
+ else:
+ self.ab = self.attention_biases[:, self.attention_bias_idxs]
+
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> tuple[torch.Tensor]:
+ batch_size, sequence_length, num_channels = hidden_states.shape
+ qkv = self.qkv(hidden_states)
+ query_layer, key_layer, value_layer = qkv.reshape(batch_size, sequence_length, self.num_heads, -1).split(
+ [self.key_dim, self.key_dim, self.expanded_key_dim], dim=3
+ )
+ query_layer = query_layer.permute(0, 2, 1, 3)
+ key_layer = key_layer.permute(0, 2, 1, 3)
+ value_layer = value_layer.permute(0, 2, 1, 3)
+
+ # set `model.to(torch_device)` won't change `self.ab.device`, if there is no follow-up `train` or `eval` call.
+ # Let's do it manually here, so users won't have to do this everytime.
+ if not self.training:
+ self.ab = self.ab.to(self.attention_biases.device)
+ attention_probs = (torch.matmul(query_layer, key_layer.transpose(-2, -1))) * self.scale + (
+ self.attention_biases[:, self.attention_bias_idxs] if self.training else self.ab
+ )
+
+ attention_probs = attention_probs.softmax(dim=-1)
+
+ context_layer = torch.matmul(attention_probs, value_layer).transpose(1, 2)
+ context_layer = context_layer.reshape(batch_size, sequence_length, self.total_expanded_key_dim)
+ context_layer = self.projection(context_layer)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+class EfficientFormerConvStem(nn.Module):
+ def __init__(self, config: EfficientFormerConfig, out_channels: int):
+ super().__init__()
+
+ self.convolution1 = nn.Conv2d(config.num_channels, out_channels // 2, kernel_size=3, stride=2, padding=1)
+ self.batchnorm_before = nn.BatchNorm2d(out_channels // 2, eps=config.batch_norm_eps)
+
+ self.convolution2 = nn.Conv2d(out_channels // 2, out_channels, kernel_size=3, stride=2, padding=1)
+ self.batchnorm_after = nn.BatchNorm2d(out_channels, eps=config.batch_norm_eps)
+
+ self.activation = nn.ReLU()
+
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
+ features = self.batchnorm_before(self.convolution1(pixel_values))
+ features = self.activation(features)
+ features = self.batchnorm_after(self.convolution2(features))
+ features = self.activation(features)
+
+ return features
+
+
+class EfficientFormerPooling(nn.Module):
+ def __init__(self, pool_size: int):
+ super().__init__()
+ self.pool = nn.AvgPool2d(pool_size, stride=1, padding=pool_size // 2, count_include_pad=False)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ output = self.pool(hidden_states) - hidden_states
+ return output
+
+
+class EfficientFormerDenseMlp(nn.Module):
+ def __init__(
+ self,
+ config: EfficientFormerConfig,
+ in_features: int,
+ hidden_features: Optional[int] = None,
+ out_features: Optional[int] = None,
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+
+ self.linear_in = nn.Linear(in_features, hidden_features)
+ self.activation = ACT2FN[config.hidden_act]
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.linear_out = nn.Linear(hidden_features, out_features)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.linear_in(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.linear_out(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ return hidden_states
+
+
+class EfficientFormerConvMlp(nn.Module):
+ def __init__(
+ self,
+ config: EfficientFormerConfig,
+ in_features: int,
+ hidden_features: Optional[int] = None,
+ out_features: Optional[int] = None,
+ drop: float = 0.0,
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+
+ self.convolution1 = nn.Conv2d(in_features, hidden_features, 1)
+ self.activation = ACT2FN[config.hidden_act]
+ self.convolution2 = nn.Conv2d(hidden_features, out_features, 1)
+ self.dropout = nn.Dropout(drop)
+
+ self.batchnorm_before = nn.BatchNorm2d(hidden_features, eps=config.batch_norm_eps)
+ self.batchnorm_after = nn.BatchNorm2d(out_features, eps=config.batch_norm_eps)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.convolution1(hidden_state)
+ hidden_state = self.batchnorm_before(hidden_state)
+
+ hidden_state = self.activation(hidden_state)
+ hidden_state = self.dropout(hidden_state)
+ hidden_state = self.convolution2(hidden_state)
+
+ hidden_state = self.batchnorm_after(hidden_state)
+ hidden_state = self.dropout(hidden_state)
+
+ return hidden_state
+
+
+def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
+ """
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
+
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
+ argument.
+ """
+ if drop_prob == 0.0 or not training:
+ return input
+ keep_prob = 1 - drop_prob
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
+ random_tensor.floor_() # binarize
+ output = input.div(keep_prob) * random_tensor
+ return output
+
+
+class EfficientFormerDropPath(nn.Module):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
+
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ return drop_path(hidden_states, self.drop_prob, self.training)
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+class EfficientFormerFlat(nn.Module):
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor]:
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+ return hidden_states
+
+
+class EfficientFormerMeta3D(nn.Module):
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0):
+ super().__init__()
+
+ self.token_mixer = EfficientFormerSelfAttention(
+ dim=config.dim,
+ key_dim=config.key_dim,
+ num_heads=config.num_attention_heads,
+ attention_ratio=config.attention_ratio,
+ resolution=config.resolution,
+ )
+
+ self.layernorm1 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
+ self.layernorm2 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
+
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
+ self.mlp = EfficientFormerDenseMlp(config, in_features=dim, hidden_features=mlp_hidden_dim)
+
+ self.drop_path = EfficientFormerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.use_layer_scale = config.use_layer_scale
+ if config.use_layer_scale:
+ self.layer_scale_1 = nn.Parameter(config.layer_scale_init_value * torch.ones(dim), requires_grad=True)
+ self.layer_scale_2 = nn.Parameter(config.layer_scale_init_value * torch.ones(dim), requires_grad=True)
+
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> tuple[torch.Tensor]:
+ self_attention_outputs = self.token_mixer(self.layernorm1(hidden_states), output_attentions)
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ if self.use_layer_scale:
+ layer_output = hidden_states + self.drop_path(
+ self.layer_scale_1.unsqueeze(0).unsqueeze(0) * attention_output
+ )
+ layer_output = layer_output + self.drop_path(
+ self.layer_scale_2.unsqueeze(0).unsqueeze(0) * self.mlp(self.layernorm2(layer_output))
+ )
+ else:
+ layer_output = hidden_states + self.drop_path(attention_output)
+ layer_output = layer_output + self.drop_path(self.mlp(self.layernorm2(layer_output)))
+
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+
+class EfficientFormerMeta3DLayers(nn.Module):
+ def __init__(self, config: EfficientFormerConfig):
+ super().__init__()
+ drop_paths = [
+ config.drop_path_rate * (block_idx + sum(config.depths[:-1]))
+ for block_idx in range(config.num_meta3d_blocks)
+ ]
+ self.blocks = nn.ModuleList(
+ [EfficientFormerMeta3D(config, config.hidden_sizes[-1], drop_path=drop_path) for drop_path in drop_paths]
+ )
+
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> tuple[torch.Tensor]:
+ all_attention_outputs = () if output_attentions else None
+
+ for layer_module in self.blocks:
+ if isinstance(hidden_states, tuple):
+ hidden_states = hidden_states[0]
+
+ hidden_states = layer_module(hidden_states, output_attentions)
+
+ if output_attentions:
+ all_attention_outputs = all_attention_outputs + (hidden_states[1],)
+
+ if output_attentions:
+ outputs = (hidden_states[0],) + all_attention_outputs
+ return outputs
+
+ return hidden_states
+
+
+class EfficientFormerMeta4D(nn.Module):
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0):
+ super().__init__()
+ pool_size = config.pool_size if config.pool_size is not None else 3
+ self.token_mixer = EfficientFormerPooling(pool_size=pool_size)
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
+ self.mlp = EfficientFormerConvMlp(
+ config, in_features=dim, hidden_features=mlp_hidden_dim, drop=config.hidden_dropout_prob
+ )
+
+ self.drop_path = EfficientFormerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.use_layer_scale = config.use_layer_scale
+ if config.use_layer_scale:
+ self.layer_scale_1 = nn.Parameter(config.layer_scale_init_value * torch.ones(dim), requires_grad=True)
+ self.layer_scale_2 = nn.Parameter(config.layer_scale_init_value * torch.ones(dim), requires_grad=True)
+
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor]:
+ outputs = self.token_mixer(hidden_states)
+
+ if self.use_layer_scale:
+ layer_output = hidden_states + self.drop_path(self.layer_scale_1.unsqueeze(-1).unsqueeze(-1) * outputs)
+
+ layer_output = layer_output + self.drop_path(
+ self.layer_scale_2.unsqueeze(-1).unsqueeze(-1) * self.mlp(layer_output)
+ )
+ else:
+ layer_output = hidden_states + self.drop_path(outputs)
+ layer_output = layer_output + self.drop_path(self.mlp(layer_output))
+
+ return layer_output
+
+
+class EfficientFormerMeta4DLayers(nn.Module):
+ def __init__(self, config: EfficientFormerConfig, stage_idx: int):
+ super().__init__()
+ num_layers = (
+ config.depths[stage_idx] if stage_idx != -1 else config.depths[stage_idx] - config.num_meta3d_blocks
+ )
+ drop_paths = [
+ config.drop_path_rate * (block_idx + sum(config.depths[:stage_idx])) for block_idx in range(num_layers)
+ ]
+
+ self.blocks = nn.ModuleList(
+ [
+ EfficientFormerMeta4D(config, config.hidden_sizes[stage_idx], drop_path=drop_path)
+ for drop_path in drop_paths
+ ]
+ )
+
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor]:
+ for layer_module in self.blocks:
+ hidden_states = layer_module(hidden_states)
+ return hidden_states
+
+
+class EfficientFormerIntermediateStage(nn.Module):
+ def __init__(self, config: EfficientFormerConfig, index: int):
+ super().__init__()
+ self.meta4D_layers = EfficientFormerMeta4DLayers(config, index)
+
+ def forward(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor]:
+ hidden_states = self.meta4D_layers(hidden_states)
+ return hidden_states
+
+
+class EfficientFormerLastStage(nn.Module):
+ def __init__(self, config: EfficientFormerConfig):
+ super().__init__()
+ self.meta4D_layers = EfficientFormerMeta4DLayers(config, -1)
+ self.flat = EfficientFormerFlat()
+ self.meta3D_layers = EfficientFormerMeta3DLayers(config)
+
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> tuple[torch.Tensor]:
+ hidden_states = self.meta4D_layers(hidden_states)
+ hidden_states = self.flat(hidden_states)
+ hidden_states = self.meta3D_layers(hidden_states, output_attentions)
+
+ return hidden_states
+
+
+class EfficientFormerEncoder(nn.Module):
+ def __init__(self, config: EfficientFormerConfig):
+ super().__init__()
+ self.config = config
+ num_intermediate_stages = len(config.depths) - 1
+ downsamples = [
+ config.downsamples[i] or config.hidden_sizes[i] != config.hidden_sizes[i + 1]
+ for i in range(num_intermediate_stages)
+ ]
+ intermediate_stages = []
+
+ for i in range(num_intermediate_stages):
+ intermediate_stages.append(EfficientFormerIntermediateStage(config, i))
+ if downsamples[i]:
+ intermediate_stages.append(
+ EfficientFormerPatchEmbeddings(config, config.hidden_sizes[i], config.hidden_sizes[i + 1])
+ )
+
+ self.intermediate_stages = nn.ModuleList(intermediate_stages)
+ self.last_stage = EfficientFormerLastStage(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_hidden_states: bool = False,
+ output_attentions: bool = False,
+ return_dict: bool = True,
+ ) -> BaseModelOutput:
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ for layer_module in self.intermediate_stages:
+ hidden_states = layer_module(hidden_states)
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_output = self.last_stage(hidden_states, output_attentions=output_attentions)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + layer_output[1:]
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (layer_output[0],)
+
+ if not return_dict:
+ return tuple(v for v in [layer_output[0], all_hidden_states, all_self_attentions] if v is not None)
+
+ return BaseModelOutput(
+ last_hidden_state=layer_output[0],
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class EfficientFormerPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: EfficientFormerConfig
+ base_model_prefix = "efficientformer"
+ main_input_name = "pixel_values"
+ supports_gradient_checkpointing = False
+
+ def _init_weights(self, module: nn.Module):
+ """Initialize the weights"""
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+EFFICIENTFORMER_START_DOCSTRING = r"""
+ This model is a PyTorch [nn.Module](https://pytorch.org/docs/stable/nn.html#nn.Module) subclass. Use it as a
+ regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
+
+ Parameters:
+ config ([`EfficientFormerConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+EFFICIENTFORMER_INPUTS_DOCSTRING = r"""
+ Args:
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Pixel values. Pixel values can be obtained using [`ViTImageProcessor`]. See
+ [`ViTImageProcessor.preprocess`] for details.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare EfficientFormer Model transformer outputting raw hidden-states without any specific head on top.",
+ EFFICIENTFORMER_START_DOCSTRING,
+)
+class EfficientFormerModel(EfficientFormerPreTrainedModel):
+ def __init__(self, config: EfficientFormerConfig):
+ super().__init__(config)
+ self.config = config
+ _no_split_modules = ["EfficientFormerMeta4D"]
+
+ self.patch_embed = EfficientFormerConvStem(config, config.hidden_sizes[0])
+ self.encoder = EfficientFormerEncoder(config)
+ self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=BaseModelOutputWithPooling,
+ config_class=_CONFIG_FOR_DOC,
+ modality="vision",
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
+ )
+ def forward(
+ self,
+ pixel_values: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, BaseModelOutput]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ embedding_output = self.patch_embed(pixel_values)
+ encoder_outputs = self.encoder(
+ embedding_output, output_attentions=output_attentions, output_hidden_states=output_hidden_states
+ )
+
+ sequence_output = encoder_outputs[0]
+ sequence_output = self.layernorm(sequence_output)
+
+ if not return_dict:
+ head_outputs = (sequence_output,)
+ return head_outputs + encoder_outputs[1:]
+
+ return BaseModelOutput(
+ last_hidden_state=sequence_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ EfficientFormer Model transformer with an image classification head on top (a linear layer on top of the final
+ hidden state of the [CLS] token) e.g. for ImageNet.
+ """,
+ EFFICIENTFORMER_START_DOCSTRING,
+)
+class EfficientFormerForImageClassification(EfficientFormerPreTrainedModel):
+ def __init__(self, config: EfficientFormerConfig):
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.efficientformer = EfficientFormerModel(config)
+
+ # Classifier head
+ self.classifier = (
+ nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
+ output_type=ImageClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
+ )
+ def forward(
+ self,
+ pixel_values: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, ImageClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.efficientformer(
+ pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.classifier(sequence_output.mean(-2))
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return ImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@dataclass
+class EfficientFormerForImageClassificationWithTeacherOutput(ModelOutput):
+ """
+ Output type of [`EfficientFormerForImageClassificationWithTeacher`].
+
+ Args:
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Prediction scores as the average of the cls_logits and distillation logits.
+ cls_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
+ class token).
+ distillation_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
+ distillation token).
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
+ plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
+ the self-attention heads.
+ """
+
+ logits: Optional[torch.FloatTensor] = None
+ cls_logits: Optional[torch.FloatTensor] = None
+ distillation_logits: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+@add_start_docstrings(
+ """
+ EfficientFormer Model transformer with image classification heads on top (a linear layer on top of the final hidden
+ state of the [CLS] token and a linear layer on top of the final hidden state of the distillation token) e.g. for
+ ImageNet.
+
+
+
+ This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
+ supported.
+
+
+ """,
+ EFFICIENTFORMER_START_DOCSTRING,
+)
+class EfficientFormerForImageClassificationWithTeacher(EfficientFormerPreTrainedModel):
+ def __init__(self, config: EfficientFormerConfig):
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.efficientformer = EfficientFormerModel(config)
+
+ # Classifier head
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
+ # Distillation head
+ self.distillation_classifier = (
+ nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
+ output_type=EfficientFormerForImageClassificationWithTeacherOutput,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
+ )
+ def forward(
+ self,
+ pixel_values: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, EfficientFormerForImageClassificationWithTeacherOutput]:
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ outputs = self.efficientformer(
+ pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ cls_logits = self.classifier(sequence_output.mean(-2))
+ distillation_logits = self.distillation_classifier(sequence_output.mean(-2))
+
+ # during inference, return the average of both classifier predictions
+ logits = (cls_logits + distillation_logits) / 2
+
+ if not return_dict:
+ output = (logits, cls_logits, distillation_logits) + outputs[1:]
+ return output
+
+ return EfficientFormerForImageClassificationWithTeacherOutput(
+ logits=logits,
+ cls_logits=cls_logits,
+ distillation_logits=distillation_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "EfficientFormerForImageClassification",
+ "EfficientFormerForImageClassificationWithTeacher",
+ "EfficientFormerModel",
+ "EfficientFormerPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/modeling_tf_efficientformer.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/modeling_tf_efficientformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..643097e79c3eab47b62f7e7c4781b2b276418176
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/efficientformer/modeling_tf_efficientformer.py
@@ -0,0 +1,1198 @@
+# coding=utf-8
+# Copyright 2023 Snapchat Research and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""TensorFlow EfficientFormer model."""
+
+import itertools
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import tensorflow as tf
+
+from ....activations_tf import ACT2FN
+from ....modeling_tf_outputs import (
+ TFBaseModelOutput,
+ TFBaseModelOutputWithPooling,
+ TFImageClassifierOutput,
+)
+from ....modeling_tf_utils import (
+ TFPreTrainedModel,
+ TFSequenceClassificationLoss,
+ get_initializer,
+ keras,
+ keras_serializable,
+ unpack_inputs,
+)
+from ....tf_utils import shape_list, stable_softmax
+from ....utils import (
+ ModelOutput,
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+)
+from .configuration_efficientformer import EfficientFormerConfig
+
+
+logger = logging.get_logger(__name__)
+
+# General docstring
+_CONFIG_FOR_DOC = "EfficientFormerConfig"
+
+# Base docstring
+_CHECKPOINT_FOR_DOC = "snap-research/efficientformer-l1-300"
+_EXPECTED_OUTPUT_SHAPE = [1, 49, 448]
+
+# Image classification docstring
+_IMAGE_CLASS_CHECKPOINT = "snap-research/efficientformer-l1-300"
+_IMAGE_CLASS_EXPECTED_OUTPUT = "LABEL_281"
+
+
+class TFEfficientFormerPatchEmbeddings(keras.layers.Layer):
+ """
+ This class performs downsampling between two stages. For the input tensor with the shape [batch_size, num_channels,
+ height, width] it produces output tensor with the shape [batch_size, num_channels, height/stride, width/stride]
+ """
+
+ def __init__(
+ self, config: EfficientFormerConfig, num_channels: int, embed_dim: int, apply_norm: bool = True, **kwargs
+ ) -> None:
+ super().__init__(**kwargs)
+ self.num_channels = num_channels
+
+ self.padding = keras.layers.ZeroPadding2D(padding=config.downsample_pad)
+ self.projection = keras.layers.Conv2D(
+ filters=embed_dim,
+ kernel_size=config.downsample_patch_size,
+ strides=config.downsample_stride,
+ padding="valid",
+ name="projection",
+ )
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
+ self.norm = (
+ keras.layers.BatchNormalization(axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="norm")
+ if apply_norm
+ else tf.identity
+ )
+ self.embed_dim = embed_dim
+
+ def call(self, pixel_values: tf.Tensor, training: bool = False) -> tf.Tensor:
+ tf.debugging.assert_shapes(
+ [(pixel_values, (..., None, None, self.num_channels))],
+ message="Make sure that the channel dimension of the pixel values match with the one set in the configuration.",
+ )
+ embeddings = self.projection(self.padding(pixel_values))
+ embeddings = self.norm(embeddings, training=training)
+ return embeddings
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "projection", None) is not None:
+ with tf.name_scope(self.projection.name):
+ self.projection.build([None, None, None, self.num_channels])
+ if getattr(self, "norm", None) is not None:
+ if hasattr(self.norm, "name"):
+ with tf.name_scope(self.norm.name):
+ self.norm.build([None, None, None, self.embed_dim])
+
+
+class TFEfficientFormerSelfAttention(keras.layers.Layer):
+ def __init__(
+ self,
+ dim: int,
+ key_dim: int,
+ num_heads: int,
+ attention_ratio: int,
+ resolution: int,
+ config: EfficientFormerConfig,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.num_heads = num_heads
+ self.key_dim = key_dim
+ self.attention_ratio = attention_ratio
+ self.scale = key_dim**-0.5
+ self.total_key_dim = key_dim * num_heads
+ self.expanded_key_dim = int(attention_ratio * key_dim)
+ self.total_expanded_key_dim = int(self.expanded_key_dim * num_heads)
+ hidden_size = self.total_expanded_key_dim + self.total_key_dim * 2
+
+ self.qkv = keras.layers.Dense(
+ units=hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="qkv"
+ )
+ self.projection = keras.layers.Dense(
+ units=dim, kernel_initializer=get_initializer(config.initializer_range), name="projection"
+ )
+ self.resolution = resolution
+ self.dim = dim
+
+ def build(self, input_shape: tf.TensorShape) -> None:
+ points = list(itertools.product(range(self.resolution), range(self.resolution)))
+ num_points = len(points)
+ attention_offsets = {}
+
+ idxs = []
+
+ for point_1 in points:
+ for point_2 in points:
+ offset = (abs(point_1[0] - point_2[0]), abs(point_1[1] - point_2[1]))
+ if offset not in attention_offsets:
+ attention_offsets[offset] = len(attention_offsets)
+ idxs.append(attention_offsets[offset])
+
+ self.attention_biases = self.add_weight(
+ shape=(self.num_heads, len(attention_offsets)),
+ initializer=keras.initializers.zeros(),
+ trainable=True,
+ name="attention_biases",
+ )
+ self.attention_bias_idxs = self.add_weight(
+ shape=(num_points, num_points),
+ trainable=False,
+ dtype=tf.int32,
+ name="attention_bias_idxs",
+ )
+
+ self.attention_bias_idxs.assign(tf.reshape(tf.cast(idxs, dtype=tf.int32), (num_points, num_points)))
+
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "qkv", None) is not None:
+ with tf.name_scope(self.qkv.name):
+ self.qkv.build([None, None, self.dim])
+ if getattr(self, "projection", None) is not None:
+ with tf.name_scope(self.projection.name):
+ self.projection.build([None, None, self.total_expanded_key_dim])
+
+ def call(
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
+ ) -> tuple[tf.Tensor]:
+ batch_size, sequence_length, *_ = shape_list(hidden_states)
+ qkv = self.qkv(inputs=hidden_states)
+
+ query_layer, key_layer, value_layer = tf.split(
+ tf.reshape(tensor=qkv, shape=(batch_size, sequence_length, self.num_heads, -1)),
+ num_or_size_splits=[self.key_dim, self.key_dim, self.expanded_key_dim],
+ axis=3,
+ )
+
+ query_layer = tf.transpose(query_layer, perm=[0, 2, 1, 3])
+ key_layer = tf.transpose(key_layer, perm=[0, 2, 1, 3])
+ value_layer = tf.transpose(value_layer, perm=[0, 2, 1, 3])
+
+ attention_probs = tf.matmul(query_layer, tf.transpose(key_layer, perm=[0, 1, 3, 2]))
+ scale = tf.cast(self.scale, dtype=attention_probs.dtype)
+ attention_probs = tf.multiply(attention_probs, scale)
+
+ attention_biases = tf.gather(params=self.attention_biases, indices=self.attention_bias_idxs, axis=1)
+ attention_probs = attention_probs + attention_biases
+ attention_probs = stable_softmax(logits=attention_probs, axis=-1)
+
+ context_layer = tf.matmul(attention_probs, value_layer)
+ context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
+
+ context_layer = tf.reshape(
+ tensor=context_layer, shape=(batch_size, sequence_length, self.total_expanded_key_dim)
+ )
+ context_layer = self.projection(context_layer)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+class TFEfficientFormerConvStem(keras.layers.Layer):
+ def __init__(self, config: EfficientFormerConfig, out_channels: int, **kwargs):
+ super().__init__(**kwargs)
+
+ self.padding = keras.layers.ZeroPadding2D(padding=1)
+ self.convolution1 = keras.layers.Conv2D(
+ filters=out_channels // 2, kernel_size=3, strides=2, padding="valid", name="convolution1"
+ )
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
+ self.batchnorm_before = keras.layers.BatchNormalization(
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_before"
+ )
+
+ self.convolution2 = keras.layers.Conv2D(
+ filters=out_channels,
+ kernel_size=3,
+ strides=2,
+ padding="valid",
+ name="convolution2",
+ )
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
+ self.batchnorm_after = keras.layers.BatchNormalization(
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_after"
+ )
+
+ self.activation = keras.layers.Activation(activation=keras.activations.relu, name="activation")
+ self.out_channels = out_channels
+ self.config = config
+
+ def call(self, pixel_values: tf.Tensor, training: bool = False) -> tf.Tensor:
+ features = self.batchnorm_before(self.convolution1(self.padding(pixel_values)), training=training)
+ features = self.activation(features)
+ features = self.batchnorm_after(self.convolution2(self.padding(features)), training=training)
+ features = self.activation(features)
+ return features
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "convolution1", None) is not None:
+ with tf.name_scope(self.convolution1.name):
+ self.convolution1.build([None, None, None, self.config.num_channels])
+ if getattr(self, "batchnorm_before", None) is not None:
+ with tf.name_scope(self.batchnorm_before.name):
+ self.batchnorm_before.build([None, None, None, self.out_channels // 2])
+ if getattr(self, "convolution2", None) is not None:
+ with tf.name_scope(self.convolution2.name):
+ self.convolution2.build([None, None, None, self.out_channels // 2])
+ if getattr(self, "batchnorm_after", None) is not None:
+ with tf.name_scope(self.batchnorm_after.name):
+ self.batchnorm_after.build([None, None, None, self.out_channels])
+ if getattr(self, "activation", None) is not None:
+ with tf.name_scope(self.activation.name):
+ self.activation.build(None)
+
+
+class TFEfficientFormerPooling(keras.layers.Layer):
+ def __init__(self, pool_size: int, **kwargs):
+ super().__init__(**kwargs)
+ self.pool = keras.layers.AveragePooling2D(pool_size=pool_size, strides=1, padding="same")
+
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
+ output = self.pool(hidden_states)
+ output = output - hidden_states
+ return output
+
+
+class TFEfficientFormerDenseMlp(keras.layers.Layer):
+ def __init__(
+ self,
+ config: EfficientFormerConfig,
+ in_features: int,
+ hidden_features: Optional[int] = None,
+ out_features: Optional[int] = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+
+ self.linear_in = keras.layers.Dense(
+ units=hidden_features, kernel_initializer=get_initializer(config.initializer_range), name="linear_in"
+ )
+ self.activation = ACT2FN[config.hidden_act]
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
+
+ self.linear_out = keras.layers.Dense(
+ units=out_features, kernel_initializer=get_initializer(config.initializer_range), name="linear_out"
+ )
+ self.hidden_features = hidden_features
+ self.in_features = in_features
+
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tf.Tensor:
+ hidden_states = self.linear_in(inputs=hidden_states)
+ hidden_states = self.activation(hidden_states)
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
+ hidden_states = self.linear_out(inputs=hidden_states)
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
+
+ return hidden_states
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "linear_in", None) is not None:
+ with tf.name_scope(self.linear_in.name):
+ self.linear_in.build([None, None, self.in_features])
+ if getattr(self, "linear_out", None) is not None:
+ with tf.name_scope(self.linear_out.name):
+ self.linear_out.build([None, None, self.hidden_features])
+
+
+class TFEfficientFormerConvMlp(keras.layers.Layer):
+ def __init__(
+ self,
+ config: EfficientFormerConfig,
+ in_features: int,
+ hidden_features: Optional[int] = None,
+ out_features: Optional[int] = None,
+ drop: float = 0.0,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+
+ self.convolution1 = keras.layers.Conv2D(
+ filters=hidden_features,
+ kernel_size=1,
+ name="convolution1",
+ padding="valid",
+ )
+
+ self.activation = ACT2FN[config.hidden_act]
+
+ self.convolution2 = keras.layers.Conv2D(
+ filters=out_features,
+ kernel_size=1,
+ name="convolution2",
+ padding="valid",
+ )
+
+ self.dropout = keras.layers.Dropout(rate=drop)
+
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
+ self.batchnorm_before = keras.layers.BatchNormalization(
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_before"
+ )
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
+ self.batchnorm_after = keras.layers.BatchNormalization(
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_after"
+ )
+ self.hidden_features = hidden_features
+ self.in_features = in_features
+ self.out_features = out_features
+
+ def call(self, hidden_state: tf.Tensor, training: bool = False) -> tf.Tensor:
+ hidden_state = self.convolution1(hidden_state)
+ hidden_state = self.batchnorm_before(hidden_state, training=training)
+ hidden_state = self.activation(hidden_state)
+ hidden_state = self.dropout(hidden_state, training=training)
+ hidden_state = self.convolution2(hidden_state)
+ hidden_state = self.batchnorm_after(hidden_state, training=training)
+ hidden_state = self.dropout(hidden_state, training=training)
+ return hidden_state
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "convolution1", None) is not None:
+ with tf.name_scope(self.convolution1.name):
+ self.convolution1.build([None, None, None, self.in_features])
+ if getattr(self, "convolution2", None) is not None:
+ with tf.name_scope(self.convolution2.name):
+ self.convolution2.build([None, None, None, self.hidden_features])
+ if getattr(self, "batchnorm_before", None) is not None:
+ with tf.name_scope(self.batchnorm_before.name):
+ self.batchnorm_before.build([None, None, None, self.hidden_features])
+ if getattr(self, "batchnorm_after", None) is not None:
+ with tf.name_scope(self.batchnorm_after.name):
+ self.batchnorm_after.build([None, None, None, self.out_features])
+
+
+# Copied from transformers.models.convnext.modeling_tf_convnext.TFConvNextDropPath with ConvNext->EfficientFormer
+class TFEfficientFormerDropPath(keras.layers.Layer):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
+ References:
+ (1) github.com:rwightman/pytorch-image-models
+ """
+
+ def __init__(self, drop_path: float, **kwargs):
+ super().__init__(**kwargs)
+ self.drop_path = drop_path
+
+ def call(self, x: tf.Tensor, training=None):
+ if training:
+ keep_prob = 1 - self.drop_path
+ shape = (tf.shape(x)[0],) + (1,) * (len(tf.shape(x)) - 1)
+ random_tensor = keep_prob + tf.random.uniform(shape, 0, 1)
+ random_tensor = tf.floor(random_tensor)
+ return (x / keep_prob) * random_tensor
+ return x
+
+
+class TFEfficientFormerFlat(keras.layers.Layer):
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ def call(self, hidden_states: tf.Tensor) -> tuple[tf.Tensor]:
+ batch_size, _, _, in_channels = shape_list(hidden_states)
+ hidden_states = tf.reshape(hidden_states, shape=[batch_size, -1, in_channels])
+ return hidden_states
+
+
+class TFEfficientFormerMeta3D(keras.layers.Layer):
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0, **kwargs):
+ super().__init__(**kwargs)
+
+ self.token_mixer = TFEfficientFormerSelfAttention(
+ dim=config.dim,
+ key_dim=config.key_dim,
+ num_heads=config.num_attention_heads,
+ attention_ratio=config.attention_ratio,
+ resolution=config.resolution,
+ name="token_mixer",
+ config=config,
+ )
+ self.dim = dim
+ self.config = config
+
+ self.layernorm1 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm1")
+ self.layernorm2 = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm2")
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
+ self.mlp = TFEfficientFormerDenseMlp(config, in_features=dim, hidden_features=mlp_hidden_dim, name="mlp")
+
+ # Using `layers.Activation` instead of `tf.identity` to better control `training' behavior.
+ self.drop_path = (
+ TFEfficientFormerDropPath(drop_path)
+ if drop_path > 0.0
+ else keras.layers.Activation("linear", name="drop_path")
+ )
+ self.config = config
+
+ def build(self, input_shape=None):
+ self.layer_scale_1 = None
+ self.layer_scale_2 = None
+
+ if self.config.use_layer_scale:
+ self.layer_scale_1 = self.add_weight(
+ shape=(self.dim,),
+ initializer=keras.initializers.Constant(value=self.config.layer_scale_init_value),
+ trainable=True,
+ name="layer_scale_1",
+ )
+ self.layer_scale_2 = self.add_weight(
+ shape=(self.dim,),
+ initializer=keras.initializers.Constant(value=self.config.layer_scale_init_value),
+ trainable=True,
+ name="layer_scale_2",
+ )
+
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "token_mixer", None) is not None:
+ with tf.name_scope(self.token_mixer.name):
+ self.token_mixer.build(None)
+ if getattr(self, "layernorm1", None) is not None:
+ with tf.name_scope(self.layernorm1.name):
+ self.layernorm1.build([None, None, self.dim])
+ if getattr(self, "layernorm2", None) is not None:
+ with tf.name_scope(self.layernorm2.name):
+ self.layernorm2.build([None, None, self.dim])
+ if getattr(self, "mlp", None) is not None:
+ with tf.name_scope(self.mlp.name):
+ self.mlp.build(None)
+ if getattr(self, "drop_path", None) is not None:
+ with tf.name_scope(self.drop_path.name):
+ self.drop_path.build(None)
+
+ def call(
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
+ ) -> tuple[tf.Tensor]:
+ self_attention_outputs = self.token_mixer(
+ hidden_states=self.layernorm1(hidden_states, training=training),
+ output_attentions=output_attentions,
+ training=training,
+ )
+
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ if self.config.use_layer_scale:
+ layer_output = hidden_states + self.drop_path(
+ tf.expand_dims(tf.expand_dims(self.layer_scale_1, 0), 0) * attention_output,
+ training=training,
+ )
+ layer_output = layer_output + self.drop_path(
+ tf.expand_dims(tf.expand_dims(self.layer_scale_2, 0), 0)
+ * self.mlp(hidden_states=self.layernorm2(inputs=layer_output, training=training), training=training),
+ training=training,
+ )
+ else:
+ layer_output = hidden_states + self.drop_path(attention_output, training=training)
+ layer_output = layer_output + self.drop_path(
+ self.mlp(hidden_states=self.layernorm2(inputs=layer_output, training=training), training=training),
+ training=training,
+ )
+
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+
+class TFEfficientFormerMeta3DLayers(keras.layers.Layer):
+ def __init__(self, config: EfficientFormerConfig, **kwargs):
+ super().__init__(**kwargs)
+ drop_paths = [
+ config.drop_path_rate * (block_idx + sum(config.depths[:-1]))
+ for block_idx in range(config.num_meta3d_blocks)
+ ]
+ self.blocks = [
+ TFEfficientFormerMeta3D(config, config.hidden_sizes[-1], drop_path=drop_path, name=f"blocks.{i}")
+ for i, drop_path in enumerate(drop_paths)
+ ]
+
+ def call(
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
+ ) -> tuple[tf.Tensor]:
+ all_attention_outputs = () if output_attentions else None
+
+ for i, layer_module in enumerate(self.blocks):
+ if isinstance(hidden_states, tuple):
+ hidden_states = hidden_states[0]
+
+ hidden_states = layer_module(
+ hidden_states=hidden_states, output_attentions=output_attentions, training=training
+ )
+ if output_attentions:
+ all_attention_outputs = all_attention_outputs + (hidden_states[1],)
+
+ if output_attentions:
+ outputs = (hidden_states[0],) + all_attention_outputs
+ return outputs
+
+ return hidden_states
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "blocks", None) is not None:
+ for layer in self.blocks:
+ with tf.name_scope(layer.name):
+ layer.build(None)
+
+
+class TFEfficientFormerMeta4D(keras.layers.Layer):
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0, **kwargs):
+ super().__init__(**kwargs)
+ pool_size = config.pool_size if config.pool_size is not None else 3
+ self.token_mixer = TFEfficientFormerPooling(pool_size=pool_size, name="token_mixer")
+ self.dim = dim
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
+ self.mlp = TFEfficientFormerConvMlp(
+ config=config, in_features=dim, hidden_features=mlp_hidden_dim, drop=config.hidden_dropout_prob, name="mlp"
+ )
+
+ self.drop_path = (
+ TFEfficientFormerDropPath(drop_path, name="drop_path")
+ if drop_path > 0.0
+ else keras.layers.Activation("linear", name="drop_path")
+ )
+ self.config = config
+
+ def build(self, input_shape=None):
+ self.layer_scale_1 = None
+ self.layer_scale_2 = None
+
+ if self.config.use_layer_scale:
+ self.layer_scale_1 = self.add_weight(
+ shape=(self.dim),
+ initializer=keras.initializers.Constant(value=self.config.layer_scale_init_value),
+ trainable=True,
+ name="layer_scale_1",
+ )
+ self.layer_scale_2 = self.add_weight(
+ shape=(self.dim),
+ initializer=keras.initializers.Constant(value=self.config.layer_scale_init_value),
+ trainable=True,
+ name="layer_scale_2",
+ )
+
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "token_mixer", None) is not None:
+ with tf.name_scope(self.token_mixer.name):
+ self.token_mixer.build(None)
+ if getattr(self, "mlp", None) is not None:
+ with tf.name_scope(self.mlp.name):
+ self.mlp.build(None)
+ if getattr(self, "drop_path", None) is not None:
+ with tf.name_scope(self.drop_path.name):
+ self.drop_path.build(None)
+
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tuple[tf.Tensor]:
+ outputs = self.token_mixer(hidden_states)
+
+ if self.config.use_layer_scale:
+ layer_output = hidden_states + self.drop_path(
+ tf.expand_dims(tf.expand_dims(self.layer_scale_1, 0), 0) * outputs,
+ training=training,
+ )
+
+ layer_output = layer_output + self.drop_path(
+ tf.expand_dims(tf.expand_dims(self.layer_scale_2, 0), 0)
+ * self.mlp(hidden_state=layer_output, training=training),
+ training=training,
+ )
+
+ else:
+ layer_output = hidden_states + self.drop_path(outputs, training=training)
+ layer_output = layer_output + self.drop_path(
+ self.mlp(hidden_state=layer_output, training=training), training=training
+ )
+
+ return layer_output
+
+
+class TFEfficientFormerMeta4DLayers(keras.layers.Layer):
+ def __init__(self, config: EfficientFormerConfig, stage_idx: int, **kwargs):
+ super().__init__(**kwargs)
+ num_layers = (
+ config.depths[stage_idx] if stage_idx != -1 else config.depths[stage_idx] - config.num_meta3d_blocks
+ )
+ drop_paths = [
+ config.drop_path_rate * (block_idx + sum(config.depths[:stage_idx])) for block_idx in range(num_layers)
+ ]
+
+ self.blocks = [
+ TFEfficientFormerMeta4D(
+ config=config, dim=config.hidden_sizes[stage_idx], drop_path=drop_paths[i], name=f"blocks.{i}"
+ )
+ for i in range(len(drop_paths))
+ ]
+
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tuple[tf.Tensor]:
+ for layer_module in self.blocks:
+ hidden_states = layer_module(hidden_states=hidden_states, training=training)
+ return hidden_states
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "blocks", None) is not None:
+ for layer in self.blocks:
+ with tf.name_scope(layer.name):
+ layer.build(None)
+
+
+class TFEfficientFormerIntermediateStage(keras.layers.Layer):
+ def __init__(self, config: EfficientFormerConfig, index: int, **kwargs):
+ super().__init__(**kwargs)
+ self.meta4D_layers = TFEfficientFormerMeta4DLayers(config=config, stage_idx=index, name="meta4D_layers")
+
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tuple[tf.Tensor]:
+ hidden_states = self.meta4D_layers(hidden_states=hidden_states, training=training)
+ return hidden_states
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "meta4D_layers", None) is not None:
+ with tf.name_scope(self.meta4D_layers.name):
+ self.meta4D_layers.build(None)
+
+
+class TFEfficientFormerLastStage(keras.layers.Layer):
+ def __init__(self, config: EfficientFormerConfig, **kwargs):
+ super().__init__(**kwargs)
+ self.meta4D_layers = TFEfficientFormerMeta4DLayers(config=config, stage_idx=-1, name="meta4D_layers")
+ self.flat = TFEfficientFormerFlat(name="flat")
+ self.meta3D_layers = TFEfficientFormerMeta3DLayers(config, name="meta3D_layers")
+
+ def call(
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
+ ) -> tuple[tf.Tensor]:
+ hidden_states = self.meta4D_layers(hidden_states=hidden_states, training=training)
+ hidden_states = self.flat(hidden_states=hidden_states)
+ hidden_states = self.meta3D_layers(
+ hidden_states=hidden_states, output_attentions=output_attentions, training=training
+ )
+
+ return hidden_states
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "meta4D_layers", None) is not None:
+ with tf.name_scope(self.meta4D_layers.name):
+ self.meta4D_layers.build(None)
+ if getattr(self, "flat", None) is not None:
+ with tf.name_scope(self.flat.name):
+ self.flat.build(None)
+ if getattr(self, "meta3D_layers", None) is not None:
+ with tf.name_scope(self.meta3D_layers.name):
+ self.meta3D_layers.build(None)
+
+
+class TFEfficientFormerEncoder(keras.layers.Layer):
+ def __init__(self, config: EfficientFormerConfig, **kwargs):
+ super().__init__(**kwargs)
+
+ self.config = config
+ num_intermediate_stages = len(config.depths) - 1
+ downsamples = [
+ config.downsamples[i] or config.hidden_sizes[i] != config.hidden_sizes[i + 1]
+ for i in range(num_intermediate_stages)
+ ]
+
+ intermediate_stages = []
+ layer_count = -1
+ for i in range(num_intermediate_stages):
+ layer_count += 1
+ intermediate_stages.append(
+ TFEfficientFormerIntermediateStage(config, i, name=f"intermediate_stages.{layer_count}")
+ )
+ if downsamples[i]:
+ layer_count += 1
+ intermediate_stages.append(
+ TFEfficientFormerPatchEmbeddings(
+ config,
+ config.hidden_sizes[i],
+ config.hidden_sizes[i + 1],
+ name=f"intermediate_stages.{layer_count}",
+ )
+ )
+ self.intermediate_stages = intermediate_stages
+ self.last_stage = TFEfficientFormerLastStage(config, name="last_stage")
+
+ def call(
+ self,
+ hidden_states: tf.Tensor,
+ output_hidden_states: bool,
+ output_attentions: bool,
+ return_dict: bool,
+ training: bool = False,
+ ) -> TFBaseModelOutput:
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ for layer_module in self.intermediate_stages:
+ hidden_states = layer_module(hidden_states, training=training)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_output = self.last_stage(hidden_states, output_attentions=output_attentions, training=training)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + layer_output[1:]
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (layer_output[0],)
+
+ if not return_dict:
+ return tuple(v for v in [layer_output[0], all_hidden_states, all_self_attentions] if v is not None)
+
+ return TFBaseModelOutput(
+ last_hidden_state=layer_output[0],
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "last_stage", None) is not None:
+ with tf.name_scope(self.last_stage.name):
+ self.last_stage.build(None)
+ for layer in self.intermediate_stages:
+ with tf.name_scope(layer.name):
+ layer.build(None)
+
+
+@keras_serializable
+class TFEfficientFormerMainLayer(keras.layers.Layer):
+ config_class = EfficientFormerConfig
+
+ def __init__(self, config: EfficientFormerConfig, **kwargs) -> None:
+ super().__init__(**kwargs)
+ self.config = config
+
+ self.patch_embed = TFEfficientFormerConvStem(config, config.hidden_sizes[0], name="patch_embed")
+ self.encoder = TFEfficientFormerEncoder(config, name="encoder")
+ self.layernorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm")
+
+ @unpack_inputs
+ def call(
+ self,
+ pixel_values: Optional[tf.Tensor] = None,
+ output_attentions: Optional[tf.Tensor] = None,
+ output_hidden_states: Optional[tf.Tensor] = None,
+ return_dict: Optional[bool] = None,
+ training: bool = False,
+ ) -> Union[TFBaseModelOutput, tuple[tf.Tensor, ...]]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ # When running on CPU, keras.layers.Conv2D and keras.layers.AveragePool2D do not
+ # support channels first NCHW format. A number of blocks contain both.
+ # So change the input format from (batch_size, num_channels, height, width) to
+ # (batch_size, height, width, num_channels) here.
+ # shape = (batch_size, in_height, in_width, in_channels=num_channels)
+ pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
+ embedding_output = self.patch_embed(pixel_values, training=training)
+
+ encoder_outputs = self.encoder(
+ hidden_states=embedding_output,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ sequence_output = encoder_outputs[0]
+ sequence_output = self.layernorm(sequence_output, training=training)
+
+ # Change the hidden states from (batch_size, height, width, num_channels) to
+ # (batch_size, num_channels, height, width).
+ # The hidden states are in (batch_size, height, width, num_channels)
+ # shape after all stages except the MB3D blocks.
+ if output_hidden_states:
+ hidden_states = tuple(tf.transpose(h, perm=(0, 3, 1, 2)) for h in encoder_outputs[1][:-1]) + (
+ encoder_outputs[1][-1],
+ )
+
+ if not return_dict:
+ head_outputs = (sequence_output,)
+ return head_outputs + encoder_outputs[1:]
+
+ return TFBaseModelOutput(
+ last_hidden_state=sequence_output,
+ hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "patch_embed", None) is not None:
+ with tf.name_scope(self.patch_embed.name):
+ self.patch_embed.build(None)
+ if getattr(self, "encoder", None) is not None:
+ with tf.name_scope(self.encoder.name):
+ self.encoder.build(None)
+ if getattr(self, "layernorm", None) is not None:
+ with tf.name_scope(self.layernorm.name):
+ self.layernorm.build([None, None, self.config.hidden_sizes[-1]])
+
+
+class TFEfficientFormerPreTrainedModel(TFPreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config_class = EfficientFormerConfig
+ base_model_prefix = "efficientformer"
+ main_input_name = "pixel_values"
+
+
+EFFICIENTFORMER_START_DOCSTRING = r"""
+ This model is a TensorFlow
+ [keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer). Use it as a regular
+ TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and behavior.
+
+
+ Parameters:
+ config ([`EfficientFormerConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+EFFICIENTFORMER_INPUTS_DOCSTRING = r"""
+ Args:
+ pixel_values ((`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
+ [`EfficientFormerImageProcessor.__call__`] for details.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare EfficientFormer Model transformer outputting raw hidden-states without any specific head on top.",
+ EFFICIENTFORMER_START_DOCSTRING,
+)
+class TFEfficientFormerModel(TFEfficientFormerPreTrainedModel):
+ def __init__(self, config: EfficientFormerConfig, **kwargs) -> None:
+ super().__init__(config, **kwargs)
+
+ self.efficientformer = TFEfficientFormerMainLayer(config, name="efficientformer")
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFBaseModelOutputWithPooling,
+ config_class=_CONFIG_FOR_DOC,
+ modality="vision",
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
+ )
+ def call(
+ self,
+ pixel_values: Optional[tf.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ training: bool = False,
+ ) -> Union[tuple, TFBaseModelOutput]:
+ outputs = self.efficientformer(
+ pixel_values=pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ return outputs
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "efficientformer", None) is not None:
+ with tf.name_scope(self.efficientformer.name):
+ self.efficientformer.build(None)
+
+
+@add_start_docstrings(
+ """
+ EfficientFormer Model transformer with an image classification head on top of pooled last hidden state, e.g. for
+ ImageNet.
+ """,
+ EFFICIENTFORMER_START_DOCSTRING,
+)
+class TFEfficientFormerForImageClassification(TFEfficientFormerPreTrainedModel, TFSequenceClassificationLoss):
+ def __init__(self, config: EfficientFormerConfig):
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.efficientformer = TFEfficientFormerMainLayer(config, name="efficientformer")
+
+ # Classifier head
+ self.classifier = (
+ keras.layers.Dense(config.num_labels, name="classifier")
+ if config.num_labels > 0
+ else keras.layers.Activation("linear", name="classifier")
+ )
+ self.config = config
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
+ output_type=TFImageClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
+ )
+ def call(
+ self,
+ pixel_values: Optional[tf.Tensor] = None,
+ labels: Optional[tf.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ training: bool = False,
+ ) -> Union[tf.Tensor, TFImageClassifierOutput]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.efficientformer(
+ pixel_values=pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.classifier(tf.reduce_mean(sequence_output, axis=-2))
+
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFImageClassifierOutput(
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "efficientformer", None) is not None:
+ with tf.name_scope(self.efficientformer.name):
+ self.efficientformer.build(None)
+ if getattr(self, "classifier", None) is not None:
+ if hasattr(self.classifier, "name"):
+ with tf.name_scope(self.classifier.name):
+ self.classifier.build([None, None, self.config.hidden_sizes[-1]])
+
+
+@dataclass
+class TFEfficientFormerForImageClassificationWithTeacherOutput(ModelOutput):
+ """
+ Args:
+ Output type of [`EfficientFormerForImageClassificationWithTeacher`].
+ logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
+ Prediction scores as the average of the cls_logits and distillation logits.
+ cls_logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
+ Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
+ class token).
+ distillation_logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
+ Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
+ distillation token).
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when
+ `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus
+ the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when
+ `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
+ the self-attention heads.
+ """
+
+ logits: Optional[tf.Tensor] = None
+ cls_logits: Optional[tf.Tensor] = None
+ distillation_logits: Optional[tf.Tensor] = None
+ hidden_states: Optional[tuple[tf.Tensor]] = None
+ attentions: Optional[tuple[tf.Tensor]] = None
+
+
+@add_start_docstrings(
+ """
+ EfficientFormer Model transformer with image classification heads on top (a linear layer on top of the final hidden
+ state and a linear layer on top of the final hidden state of the distillation token) e.g. for ImageNet.
+
+ .. warning::
+ This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
+ supported.
+ """,
+ EFFICIENTFORMER_START_DOCSTRING,
+)
+class TFEfficientFormerForImageClassificationWithTeacher(TFEfficientFormerPreTrainedModel):
+ def __init__(self, config: EfficientFormerConfig) -> None:
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.efficientformer = TFEfficientFormerMainLayer(config, name="efficientformer")
+
+ # Classifier heads
+ self.classifier = (
+ keras.layers.Dense(config.num_labels, name="classifier")
+ if config.num_labels > 0
+ else keras.layers.Activation("linear", name="classifier")
+ )
+ self.distillation_classifier = (
+ keras.layers.Dense(config.num_labels, name="distillation_classifier")
+ if config.num_labels > 0
+ else keras.layers.Activation("linear", name="distillation_classifier")
+ )
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
+ output_type=TFEfficientFormerForImageClassificationWithTeacherOutput,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
+ )
+ def call(
+ self,
+ pixel_values: Optional[tf.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ training: bool = False,
+ ) -> Union[tuple, TFEfficientFormerForImageClassificationWithTeacherOutput]:
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if training:
+ raise Exception(
+ "This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet supported."
+ )
+
+ outputs = self.efficientformer(
+ pixel_values=pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ sequence_output = outputs[0]
+
+ cls_logits = self.classifier(tf.reduce_mean(sequence_output, axis=-2))
+ distillation_logits = self.distillation_classifier(tf.reduce_mean(sequence_output, axis=-2))
+ logits = (cls_logits + distillation_logits) / 2
+
+ if not return_dict:
+ output = (logits, cls_logits, distillation_logits) + outputs[1:]
+ return output
+
+ return TFEfficientFormerForImageClassificationWithTeacherOutput(
+ logits=logits,
+ cls_logits=cls_logits,
+ distillation_logits=distillation_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "efficientformer", None) is not None:
+ with tf.name_scope(self.efficientformer.name):
+ self.efficientformer.build(None)
+ if getattr(self, "classifier", None) is not None:
+ if hasattr(self.classifier, "name"):
+ with tf.name_scope(self.classifier.name):
+ self.classifier.build([None, None, self.config.hidden_sizes[-1]])
+ if getattr(self, "distillation_classifier", None) is not None:
+ if hasattr(self.distillation_classifier, "name"):
+ with tf.name_scope(self.distillation_classifier.name):
+ self.distillation_classifier.build([None, None, self.config.hidden_sizes[-1]])
+
+
+__all__ = [
+ "TFEfficientFormerForImageClassification",
+ "TFEfficientFormerForImageClassificationWithTeacher",
+ "TFEfficientFormerModel",
+ "TFEfficientFormerPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2beb8f463ff10af33ea980599ea4d5fc05888acb
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2023 The HuggingFace and Baidu Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_ernie_m import *
+ from .modeling_ernie_m import *
+ from .tokenization_ernie_m import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e21735ddc8fbadd8e569642d25affe16d1d1dc3c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/configuration_ernie_m.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/configuration_ernie_m.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0cb551b74684b720797f5aee587f59af7c99c9a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/configuration_ernie_m.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/modeling_ernie_m.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/modeling_ernie_m.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94dbf2b5bf0c3ffef5d3e5708370e7f5f1416448
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/modeling_ernie_m.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/tokenization_ernie_m.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/tokenization_ernie_m.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c9431bfb510a67e2917b55e4f05617904b1da080
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/__pycache__/tokenization_ernie_m.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/configuration_ernie_m.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/configuration_ernie_m.py
new file mode 100644
index 0000000000000000000000000000000000000000..839b17b11bf7248136668d8c325f03e10a64cd96
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/configuration_ernie_m.py
@@ -0,0 +1,112 @@
+# coding=utf-8
+# Copyright 2023 Xuan Ouyang, Shuohuan Wang, Chao Pang, Yu Sun, Hao Tian, Hua Wu, Haifeng Wang and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""ErnieM model configuration"""
+# Adapted from original paddlenlp repository.(https://github.com/PaddlePaddle/PaddleNLP/blob/develop/paddlenlp/transformers/ernie_m/configuration.py)
+
+from __future__ import annotations
+
+from ....configuration_utils import PretrainedConfig
+
+
+class ErnieMConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`ErnieMModel`]. It is used to instantiate a
+ Ernie-M model according to the specified arguments, defining the model architecture. Instantiating a configuration
+ with the defaults will yield a similar configuration to that of the `Ernie-M`
+ [susnato/ernie-m-base_pytorch](https://huggingface.co/susnato/ernie-m-base_pytorch) architecture.
+
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 250002):
+ Vocabulary size of `inputs_ids` in [`ErnieMModel`]. Also is the vocab size of token embedding matrix.
+ Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling
+ [`ErnieMModel`].
+ hidden_size (`int`, *optional*, defaults to 768):
+ Dimensionality of the embedding layer, encoder layers and pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 3072):
+ Dimensionality of the feed-forward (ff) layer in the encoder. Input tensors to feed-forward layers are
+ firstly projected from hidden_size to intermediate_size, and then projected back to hidden_size. Typically
+ intermediate_size is larger than hidden_size.
+ hidden_act (`str`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function in the feed-forward layer. `"gelu"`, `"relu"` and any other torch
+ supported activation functions are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings and encoder.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability used in `MultiHeadAttention` in all encoder layers to drop some attention target.
+ max_position_embeddings (`int`, *optional*, defaults to 514):
+ The maximum value of the dimensionality of position encoding, which dictates the maximum supported length
+ of an input sequence.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the normal initializer for initializing all weight matrices. The index of padding
+ token in the token vocabulary.
+ pad_token_id (`int`, *optional*, defaults to 1):
+ Padding token id.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
+ The epsilon used by the layer normalization layers.
+ classifier_dropout (`float`, *optional*):
+ The dropout ratio for the classification head.
+ act_dropout (`float`, *optional*, defaults to 0.0):
+ This dropout probability is used in `ErnieMEncoderLayer` after activation.
+
+ A normal_initializer initializes weight matrices as normal distributions. See
+ `ErnieMPretrainedModel._init_weights()` for how weights are initialized in `ErnieMModel`.
+ """
+
+ model_type = "ernie_m"
+ attribute_map: dict[str, str] = {"dropout": "classifier_dropout", "num_classes": "num_labels"}
+
+ def __init__(
+ self,
+ vocab_size: int = 250002,
+ hidden_size: int = 768,
+ num_hidden_layers: int = 12,
+ num_attention_heads: int = 12,
+ intermediate_size: int = 3072,
+ hidden_act: str = "gelu",
+ hidden_dropout_prob: float = 0.1,
+ attention_probs_dropout_prob: float = 0.1,
+ max_position_embeddings: int = 514,
+ initializer_range: float = 0.02,
+ pad_token_id: int = 1,
+ layer_norm_eps: float = 1e-05,
+ classifier_dropout=None,
+ act_dropout=0.0,
+ **kwargs,
+ ):
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.max_position_embeddings = max_position_embeddings
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.classifier_dropout = classifier_dropout
+ self.act_dropout = act_dropout
+
+
+__all__ = ["ErnieMConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/modeling_ernie_m.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/modeling_ernie_m.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2c939b255b510d86642d6c44b383cf52e5080c6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/modeling_ernie_m.py
@@ -0,0 +1,1061 @@
+# coding=utf-8
+# Copyright 2023 Xuan Ouyang, Shuohuan Wang, Chao Pang, Yu Sun, Hao Tian, Hua Wu, Haifeng Wang The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch ErnieM model."""
+
+import math
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn, tensor
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ....modeling_utils import PreTrainedModel
+from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
+from ....utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
+from ....utils.deprecation import deprecate_kwarg
+from .configuration_ernie_m import ErnieMConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "susnato/ernie-m-base_pytorch"
+_CONFIG_FOR_DOC = "ErnieMConfig"
+_TOKENIZER_FOR_DOC = "ErnieMTokenizer"
+
+
+# Adapted from paddlenlp.transformers.ernie_m.modeling.ErnieEmbeddings
+class ErnieMEmbeddings(nn.Module):
+ """Construct the embeddings from word and position embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=config.pad_token_id
+ )
+ self.layer_norm = nn.LayerNorm(normalized_shape=config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
+ self.padding_idx = config.pad_token_id
+
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.LongTensor] = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ if position_ids is None:
+ input_shape = inputs_embeds.size()[:-1]
+ ones = torch.ones(input_shape, dtype=torch.int64, device=inputs_embeds.device)
+ seq_length = torch.cumsum(ones, dim=1)
+ position_ids = seq_length - ones
+
+ if past_key_values_length > 0:
+ position_ids = position_ids + past_key_values_length
+ # to mimic paddlenlp implementation
+ position_ids += 2
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = inputs_embeds + position_embeddings
+ embeddings = self.layer_norm(embeddings)
+ embeddings = self.dropout(embeddings)
+
+ return embeddings
+
+
+class ErnieMSelfAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.q_proj = nn.Linear(config.hidden_size, self.all_head_size)
+ self.k_proj = nn.Linear(config.hidden_size, self.all_head_size)
+ self.v_proj = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.position_embedding_type = position_embedding_type or getattr(
+ config, "position_embedding_type", "absolute"
+ )
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ self.max_position_embeddings = config.max_position_embeddings
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
+
+ self.is_decoder = config.is_decoder
+
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
+ x = x.view(new_x_shape)
+ return x.permute(0, 2, 1, 3)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ mixed_query_layer = self.q_proj(hidden_states)
+
+ # If this is instantiated as a cross-attention module, the keys
+ # and values come from an encoder; the attention mask needs to be
+ # such that the encoder's padding tokens are not attended to.
+ is_cross_attention = encoder_hidden_states is not None
+
+ if is_cross_attention and past_key_values is not None:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values[0]
+ value_layer = past_key_values[1]
+ attention_mask = encoder_attention_mask
+ elif is_cross_attention:
+ key_layer = self.transpose_for_scores(self.k_proj(encoder_hidden_states))
+ value_layer = self.transpose_for_scores(self.v_proj(encoder_hidden_states))
+ attention_mask = encoder_attention_mask
+ elif past_key_values is not None:
+ key_layer = self.transpose_for_scores(self.k_proj(hidden_states))
+ value_layer = self.transpose_for_scores(self.v_proj(hidden_states))
+ key_layer = torch.cat([past_key_values[0], key_layer], dim=2)
+ value_layer = torch.cat([past_key_values[1], value_layer], dim=2)
+ else:
+ key_layer = self.transpose_for_scores(self.k_proj(hidden_states))
+ value_layer = self.transpose_for_scores(self.v_proj(hidden_states))
+
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ use_cache = past_key_values is not None
+ if self.is_decoder:
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
+ # Further calls to cross_attention layer can then reuse all cross-attention
+ # key/value_states (first "if" case)
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
+ past_key_values = (key_layer, value_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
+ if use_cache:
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
+ -1, 1
+ )
+ else:
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
+ distance = position_ids_l - position_ids_r
+
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
+
+ if self.position_embedding_type == "relative_key":
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores
+ elif self.position_embedding_type == "relative_key_query":
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in ErnieMModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = attention_probs * head_mask
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ if self.is_decoder:
+ outputs = outputs + (past_key_values,)
+ return outputs
+
+
+class ErnieMAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None):
+ super().__init__()
+ self.self_attn = ErnieMSelfAttention(config, position_embedding_type=position_embedding_type)
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.self_attn.num_attention_heads, self.self_attn.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.self_attn.q_proj = prune_linear_layer(self.self_attn.q_proj, index)
+ self.self_attn.k_proj = prune_linear_layer(self.self_attn.k_proj, index)
+ self.self_attn.v_proj = prune_linear_layer(self.self_attn.v_proj, index)
+ self.out_proj = prune_linear_layer(self.out_proj, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self_attn.num_attention_heads = self.self_attn.num_attention_heads - len(heads)
+ self.self_attn.all_head_size = self.self_attn.attention_head_size * self.self_attn.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ self_outputs = self.self_attn(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values,
+ output_attentions,
+ )
+ attention_output = self.out_proj(self_outputs[0])
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+class ErnieMEncoderLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ # to mimic paddlenlp implementation
+ dropout = 0.1 if config.hidden_dropout_prob is None else config.hidden_dropout_prob
+ act_dropout = config.hidden_dropout_prob if config.act_dropout is None else config.act_dropout
+
+ self.self_attn = ErnieMAttention(config)
+ self.linear1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.dropout = nn.Dropout(act_dropout)
+ self.linear2 = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout1 = nn.Dropout(dropout)
+ self.dropout2 = nn.Dropout(dropout)
+ if isinstance(config.hidden_act, str):
+ self.activation = ACT2FN[config.hidden_act]
+ else:
+ self.activation = config.hidden_act
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ output_attentions: Optional[bool] = True,
+ ):
+ residual = hidden_states
+ if output_attentions:
+ hidden_states, attention_opt_weights = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ )
+
+ else:
+ hidden_states = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ )
+ hidden_states = residual + self.dropout1(hidden_states)
+ hidden_states = self.norm1(hidden_states)
+ residual = hidden_states
+
+ hidden_states = self.linear1(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.linear2(hidden_states)
+ hidden_states = residual + self.dropout2(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+
+ if output_attentions:
+ return hidden_states, attention_opt_weights
+ else:
+ return hidden_states
+
+
+class ErnieMEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layers = nn.ModuleList([ErnieMEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+
+ def forward(
+ self,
+ input_embeds: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ output_attentions: Optional[bool] = False,
+ output_hidden_states: Optional[bool] = False,
+ return_dict: Optional[bool] = True,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
+ hidden_states = () if output_hidden_states else None
+ attentions = () if output_attentions else None
+
+ output = input_embeds
+ if output_hidden_states:
+ hidden_states = hidden_states + (output,)
+ for i, layer in enumerate(self.layers):
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+
+ output, opt_attn_weights = layer(
+ hidden_states=output,
+ attention_mask=attention_mask,
+ head_mask=layer_head_mask,
+ past_key_values=past_key_values[i] if past_key_values is not None else None,
+ )
+
+ if output_hidden_states:
+ hidden_states = hidden_states + (output,)
+ if output_attentions:
+ attentions = attentions + (opt_attn_weights,)
+
+ last_hidden_state = output
+ if not return_dict:
+ return tuple(v for v in [last_hidden_state, hidden_states, attentions] if v is not None)
+
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=last_hidden_state, hidden_states=hidden_states, attentions=attentions
+ )
+
+
+class ErnieMPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+class ErnieMPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: ErnieMConfig
+ base_model_prefix = "ernie_m"
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+ERNIE_M_START_DOCSTRING = r"""
+
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
+ behavior.
+
+ Parameters:
+ config ([`ErnieMConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+ERNIE_M_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`ErnieMTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare ErnieM Model transformer outputting raw hidden-states without any specific head on top.",
+ ERNIE_M_START_DOCSTRING,
+)
+class ErnieMModel(ErnieMPreTrainedModel):
+ def __init__(self, config, add_pooling_layer=True):
+ super().__init__(config)
+ self.initializer_range = config.initializer_range
+ self.embeddings = ErnieMEmbeddings(config)
+ self.encoder = ErnieMEncoder(config)
+ self.pooler = ErnieMPooler(config) if add_pooling_layer else None
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layers[layer].self_attn.prune_heads(heads)
+
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ processor_class=_TOKENIZER_FOR_DOC,
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=BaseModelOutputWithPastAndCrossAttentions,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[tensor] = None,
+ position_ids: Optional[tensor] = None,
+ attention_mask: Optional[tensor] = None,
+ head_mask: Optional[tensor] = None,
+ inputs_embeds: Optional[tensor] = None,
+ past_key_values: Optional[tuple[tuple[tensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.FloatTensor], BaseModelOutputWithPoolingAndCrossAttentions]:
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time.")
+
+ # init the default bool value
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ past_key_values_length = 0
+ if past_key_values is not None:
+ past_key_values_length = past_key_values.get_seq_length()
+
+ # Adapted from paddlenlp.transformers.ernie_m.ErnieMModel
+ if attention_mask is None:
+ attention_mask = (input_ids == self.config.pad_token_id).to(torch.float32)
+ attention_mask *= torch.finfo(attention_mask.dtype).min
+ if past_key_values is not None:
+ batch_size = past_key_values[0][0].shape[0]
+ past_mask = torch.zeros([batch_size, 1, 1, past_key_values_length], dtype=attention_mask.dtype)
+ attention_mask = torch.concat([past_mask, attention_mask], dim=-1)
+ # For 2D attention_mask from tokenizer
+ elif attention_mask.ndim == 2:
+ attention_mask = attention_mask.to(torch.float32)
+ attention_mask = 1.0 - attention_mask
+ attention_mask *= torch.finfo(attention_mask.dtype).min
+
+ extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(1)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ sequence_output = encoder_outputs[0]
+ pooler_output = self.pooler(sequence_output) if self.pooler is not None else None
+ return (sequence_output, pooler_output) + encoder_outputs[1:]
+
+ sequence_output = encoder_outputs["last_hidden_state"]
+ pooler_output = self.pooler(sequence_output) if self.pooler is not None else None
+ hidden_states = None if not output_hidden_states else encoder_outputs["hidden_states"]
+ attentions = None if not output_attentions else encoder_outputs["attentions"]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooler_output,
+ hidden_states=hidden_states,
+ attentions=attentions,
+ )
+
+
+@add_start_docstrings(
+ """ErnieM Model transformer with a sequence classification/regression head on top (a linear layer on top of
+ the pooled output) e.g. for GLUE tasks.""",
+ ERNIE_M_START_DOCSTRING,
+)
+class ErnieMForSequenceClassification(ErnieMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.ernie_m = ErnieMModel(config)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ processor_class=_TOKENIZER_FOR_DOC,
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=SequenceClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ past_key_values: Optional[list[torch.Tensor]] = None,
+ use_cache: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ return_dict: Optional[bool] = True,
+ labels: Optional[torch.Tensor] = None,
+ ) -> Union[tuple[torch.FloatTensor], SequenceClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.ernie_m(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ past_key_values=past_key_values,
+ output_hidden_states=output_hidden_states,
+ output_attentions=output_attentions,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """ErnieM Model with a multiple choice classification head on top (a linear layer on top of
+ the pooled output and a softmax) e.g. for RocStories/SWAG tasks.""",
+ ERNIE_M_START_DOCSTRING,
+)
+class ErnieMForMultipleChoice(ErnieMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.ernie_m = ErnieMModel(config)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=MultipleChoiceModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = True,
+ ) -> Union[tuple[torch.FloatTensor], MultipleChoiceModelOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.ernie_m(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """ErnieM Model with a token classification head on top (a linear layer on top of
+ the hidden-states output) e.g. for Named-Entity-Recognition (NER) tasks.""",
+ ERNIE_M_START_DOCSTRING,
+)
+class ErnieMForTokenClassification(ErnieMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.ernie_m = ErnieMModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ processor_class=_TOKENIZER_FOR_DOC,
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TokenClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ past_key_values: Optional[list[torch.Tensor]] = None,
+ output_hidden_states: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ return_dict: Optional[bool] = True,
+ labels: Optional[torch.Tensor] = None,
+ ) -> Union[tuple[torch.FloatTensor], TokenClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.ernie_m(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """ErnieM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).""",
+ ERNIE_M_START_DOCSTRING,
+)
+class ErnieMForQuestionAnswering(ErnieMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.ernie_m = ErnieMModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ processor_class=_TOKENIZER_FOR_DOC,
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=QuestionAnsweringModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ start_positions: Optional[torch.Tensor] = None,
+ end_positions: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = True,
+ ) -> Union[tuple[torch.FloatTensor], QuestionAnsweringModelOutput]:
+ r"""
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.ernie_m(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[2:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """ErnieMForInformationExtraction is a Ernie-M Model with two linear layer on top of the hidden-states output to
+ compute `start_prob` and `end_prob`, designed for Universal Information Extraction.""",
+ ERNIE_M_START_DOCSTRING,
+)
+class ErnieMForInformationExtraction(ErnieMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.ernie_m = ErnieMModel(config)
+ self.linear_start = nn.Linear(config.hidden_size, 1)
+ self.linear_end = nn.Linear(config.hidden_size, 1)
+ self.sigmoid = nn.Sigmoid()
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(ERNIE_M_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ start_positions: Optional[torch.Tensor] = None,
+ end_positions: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = True,
+ ) -> Union[tuple[torch.FloatTensor], QuestionAnsweringModelOutput]:
+ r"""
+ start_positions (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for position (index) for computing the start_positions loss. Position outside of the sequence are
+ not taken into account for computing the loss.
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) for computing the end_positions loss. Position outside of the sequence are not
+ taken into account for computing the loss.
+ """
+
+ result = self.ernie_m(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ if return_dict:
+ sequence_output = result.last_hidden_state
+ elif not return_dict:
+ sequence_output = result[0]
+
+ start_logits = self.linear_start(sequence_output)
+ start_logits = start_logits.squeeze(-1)
+ end_logits = self.linear_end(sequence_output)
+ end_logits = end_logits.squeeze(-1)
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = BCEWithLogitsLoss()
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ return tuple(
+ i
+ for i in [total_loss, start_logits, end_logits, result.hidden_states, result.attentions]
+ if i is not None
+ )
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=result.hidden_states,
+ attentions=result.attentions,
+ )
+
+
+__all__ = [
+ "ErnieMForMultipleChoice",
+ "ErnieMForQuestionAnswering",
+ "ErnieMForSequenceClassification",
+ "ErnieMForTokenClassification",
+ "ErnieMModel",
+ "ErnieMPreTrainedModel",
+ "ErnieMForInformationExtraction",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/tokenization_ernie_m.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/tokenization_ernie_m.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c33abd043e6d170485e6d01298788d461275aa6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/ernie_m/tokenization_ernie_m.py
@@ -0,0 +1,409 @@
+# coding=utf-8
+# Copyright 2023 Xuan Ouyang, Shuohuan Wang, Chao Pang, Yu Sun, Hao Tian, Hua Wu, Haifeng Wang and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for Ernie-M."""
+
+import os
+import unicodedata
+from typing import Any, Optional
+
+import sentencepiece as spm
+
+from ....tokenization_utils import PreTrainedTokenizer
+from ....utils import logging
+from ....utils.import_utils import requires
+
+
+logger = logging.get_logger(__name__)
+
+SPIECE_UNDERLINE = "▁"
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "sentencepiece_model_ckpt": "sentencepiece.bpe.model"}
+
+RESOURCE_FILES_NAMES = {
+ "sentencepiece_model_file": "sentencepiece.bpe.model",
+ "vocab_file": "vocab.txt",
+}
+
+
+# Adapted from paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer
+@requires(backends=("sentencepiece",))
+class ErnieMTokenizer(PreTrainedTokenizer):
+ r"""
+ Constructs a Ernie-M tokenizer. It uses the `sentencepiece` tools to cut the words to sub-words.
+
+ Args:
+ sentencepiece_model_file (`str`):
+ The file path of sentencepiece model.
+ vocab_file (`str`, *optional*):
+ The file path of the vocabulary.
+ do_lower_case (`str`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
+ A special token representing the `unknown (out-of-vocabulary)` token. An unknown token is set to be
+ `unk_token` inorder to be converted to an ID.
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
+ A special token separating two different sentences in the same input.
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
+ A special token used to make arrays of tokens the same size for batching purposes.
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
+ A special token used for sequence classification. It is the last token of the sequence when built with
+ special tokens.
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
+ A special token representing a masked token. This is the token used in the masked language modeling task
+ which the model tries to predict the original unmasked ones.
+ """
+
+ # Ernie-M model doesn't have token_type embedding.
+ model_input_names: list[str] = ["input_ids"]
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ resource_files_names = RESOURCE_FILES_NAMES
+
+ def __init__(
+ self,
+ sentencepiece_model_ckpt,
+ vocab_file=None,
+ do_lower_case=False,
+ encoding="utf8",
+ unk_token="[UNK]",
+ sep_token="[SEP]",
+ pad_token="[PAD]",
+ cls_token="[CLS]",
+ mask_token="[MASK]",
+ sp_model_kwargs: Optional[dict[str, Any]] = None,
+ **kwargs,
+ ) -> None:
+ # Mask token behave like a normal word, i.e. include the space before it and
+ # is included in the raw text, there should be a match in a non-normalized sentence.
+
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
+
+ self.do_lower_case = do_lower_case
+ self.sentencepiece_model_ckpt = sentencepiece_model_ckpt
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.Load(sentencepiece_model_ckpt)
+
+ # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
+ if vocab_file is not None:
+ self.vocab = self.load_vocab(filepath=vocab_file)
+ else:
+ self.vocab = {self.sp_model.id_to_piece(id): id for id in range(self.sp_model.get_piece_size())}
+ self.reverse_vocab = {v: k for k, v in self.vocab.items()}
+
+ super().__init__(
+ do_lower_case=do_lower_case,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ vocab_file=vocab_file,
+ encoding=encoding,
+ sp_model_kwargs=self.sp_model_kwargs,
+ **kwargs,
+ )
+
+ def get_offset_mapping(self, text):
+ if text is None:
+ return None
+
+ split_tokens = self.tokenize(text)
+ normalized_text, char_mapping = "", []
+
+ for i, ch in enumerate(text):
+ if ch in self.SP_CHAR_MAPPING:
+ ch = self.SP_CHAR_MAPPING.get(ch)
+ else:
+ ch = unicodedata.normalize("NFKC", ch)
+ if self.is_whitespace(ch):
+ continue
+ normalized_text += ch
+ char_mapping.extend([i] * len(ch))
+
+ text, token_mapping, offset = normalized_text, [], 0
+
+ if self.do_lower_case:
+ text = text.lower()
+
+ for token in split_tokens:
+ if token[:1] == "▁":
+ token = token[1:]
+ start = text[offset:].index(token) + offset
+ end = start + len(token)
+
+ token_mapping.append((char_mapping[start], char_mapping[end - 1] + 1))
+ offset = end
+ return token_mapping
+
+ @property
+ def vocab_size(self):
+ return len(self.vocab)
+
+ def get_vocab(self):
+ return dict(self.vocab, **self.added_tokens_encoder)
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state["sp_model"] = None
+ return state
+
+ def __setstate__(self, d):
+ self.__dict__ = d
+
+ # for backward compatibility
+ if not hasattr(self, "sp_model_kwargs"):
+ self.sp_model_kwargs = {}
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.Load(self.sentencepiece_model_ckpt)
+
+ def clean_text(self, text):
+ """Performs invalid character removal and whitespace cleanup on text."""
+ return "".join(self.SP_CHAR_MAPPING.get(c, c) for c in text)
+
+ def _tokenize(self, text, enable_sampling=False, nbest_size=64, alpha=0.1):
+ """Tokenize a string."""
+
+ if self.sp_model_kwargs.get("enable_sampling") is True:
+ enable_sampling = True
+ if self.sp_model_kwargs.get("alpha") is not None:
+ alpha = self.sp_model_kwargs.get("alpha")
+ if self.sp_model_kwargs.get("nbest_size") is not None:
+ nbest_size = self.sp_model_kwargs.get("nbest_size")
+
+ if not enable_sampling:
+ pieces = self.sp_model.EncodeAsPieces(text)
+ else:
+ pieces = self.sp_model.SampleEncodeAsPieces(text, nbest_size, alpha)
+ new_pieces = []
+ for pi, piece in enumerate(pieces):
+ if piece == SPIECE_UNDERLINE:
+ if not pieces[pi + 1].startswith(SPIECE_UNDERLINE) and pi != 0:
+ new_pieces.append(SPIECE_UNDERLINE)
+ continue
+ else:
+ continue
+ lst_i = 0
+ for i, chunk in enumerate(piece):
+ if chunk == SPIECE_UNDERLINE:
+ continue
+ if self.is_ch_char(chunk) or self.is_punct(chunk):
+ if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
+ new_pieces.append(piece[lst_i:i])
+ new_pieces.append(chunk)
+ lst_i = i + 1
+ elif chunk.isdigit() and i > 0 and not piece[i - 1].isdigit():
+ if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
+ new_pieces.append(piece[lst_i:i])
+ lst_i = i
+ elif not chunk.isdigit() and i > 0 and piece[i - 1].isdigit():
+ if i > lst_i and piece[lst_i:i] != SPIECE_UNDERLINE:
+ new_pieces.append(piece[lst_i:i])
+ lst_i = i
+ if len(piece) > lst_i:
+ new_pieces.append(piece[lst_i:])
+ return new_pieces
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (strings for sub-words) in a single string."""
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
+ return out_string
+
+ def convert_ids_to_string(self, ids):
+ """
+ Converts a sequence of tokens (strings for sub-words) in a single string.
+ """
+ tokens = self.convert_ids_to_tokens(ids)
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
+ return out_string
+
+ # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
+ def _convert_token_to_id(self, token):
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
+
+ # to mimic paddlenlp.transformers.ernie_m.tokenizer.ErnieMTokenizer functioning
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.reverse_vocab.get(index, self.unk_token)
+
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
+ r"""
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An ErnieM sequence has the following format:
+
+ - single sequence: `[CLS] X [SEP]`
+ - pair of sequences: `[CLS] A [SEP] [SEP] B [SEP]`
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ Returns:
+ `list[int]`: List of input_id with the appropriate special tokens.
+ """
+ if token_ids_1 is None:
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
+ _cls = [self.cls_token_id]
+ _sep = [self.sep_token_id]
+ return _cls + token_ids_0 + _sep + _sep + token_ids_1 + _sep
+
+ def build_offset_mapping_with_special_tokens(self, offset_mapping_0, offset_mapping_1=None):
+ r"""
+ Build offset map from a pair of offset map by concatenating and adding offsets of special tokens. An Ernie-M
+ offset_mapping has the following format:
+
+ - single sequence: `(0,0) X (0,0)`
+ - pair of sequences: `(0,0) A (0,0) (0,0) B (0,0)`
+
+ Args:
+ offset_mapping_ids_0 (`list[tuple]`):
+ List of char offsets to which the special tokens will be added.
+ offset_mapping_ids_1 (`list[tuple]`, *optional*):
+ Optional second list of wordpiece offsets for offset mapping pairs.
+ Returns:
+ `list[tuple]`: List of wordpiece offsets with the appropriate offsets of special tokens.
+ """
+ if offset_mapping_1 is None:
+ return [(0, 0)] + offset_mapping_0 + [(0, 0)]
+
+ return [(0, 0)] + offset_mapping_0 + [(0, 0), (0, 0)] + offset_mapping_1 + [(0, 0)]
+
+ def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False):
+ r"""
+ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `encode` method.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of ids of the first sequence.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`str`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+ Returns:
+ `list[int]`:
+ The list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ if token_ids_1 is not None:
+ raise ValueError(
+ "You should not supply a second sequence if the provided sequence of "
+ "ids is already formatted with special tokens for the model."
+ )
+ return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_0]
+
+ if token_ids_1 is not None:
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
+ return [1] + ([0] * len(token_ids_0)) + [1]
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Create the token type IDs corresponding to the sequences passed. [What are token type
+ IDs?](../glossary#token-type-ids) Should be overridden in a subclass if the model has a special way of
+ building: those.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ The first tokenized sequence.
+ token_ids_1 (`list[int]`, *optional*):
+ The second tokenized sequence.
+ Returns:
+ `list[int]`: The token type ids.
+ """
+ # called when `add_special_tokens` is True, so align with `build_inputs_with_special_tokens` method
+ if token_ids_1 is None:
+ # [CLS] X [SEP]
+ return (len(token_ids_0) + 2) * [0]
+
+ # [CLS] A [SEP] [SEP] B [SEP]
+ return [0] * (len(token_ids_0) + 1) + [1] * (len(token_ids_1) + 3)
+
+ def is_ch_char(self, char):
+ """
+ is_ch_char
+ """
+ if "\u4e00" <= char <= "\u9fff":
+ return True
+ return False
+
+ def is_alpha(self, char):
+ """
+ is_alpha
+ """
+ if ("a" <= char <= "z") or ("A" <= char <= "Z"):
+ return True
+ return False
+
+ def is_punct(self, char):
+ """
+ is_punct
+ """
+ if char in ",;:.?!~,;:。?!《》【】":
+ return True
+ return False
+
+ def is_whitespace(self, char):
+ """
+ is whitespace
+ """
+ if char == " " or char == "\t" or char == "\n" or char == "\r":
+ return True
+ if len(char) == 1:
+ cat = unicodedata.category(char)
+ if cat == "Zs":
+ return True
+ return False
+
+ def load_vocab(self, filepath):
+ token_to_idx = {}
+ with open(filepath, "r", encoding="utf-8") as f:
+ for index, line in enumerate(f):
+ token = line.rstrip("\n")
+ token_to_idx[token] = int(index)
+
+ return token_to_idx
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ index = 0
+ if os.path.isdir(save_directory):
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ else:
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
+ with open(vocab_file, "w", encoding="utf-8") as writer:
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
+ " Please check that the vocabulary is not corrupted!"
+ )
+ index = token_index
+ writer.write(token + "\n")
+ index += 1
+
+ tokenizer_model_file = os.path.join(save_directory, "sentencepiece.bpe.model")
+ with open(tokenizer_model_file, "wb") as fi:
+ content_spiece_model = self.sp_model.serialized_model_proto()
+ fi.write(content_spiece_model)
+
+ return (vocab_file,)
+
+
+__all__ = ["ErnieMTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c23b58f35012f1ddc00e2275c484810287de6f8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_gptsan_japanese import *
+ from .modeling_gptsan_japanese import *
+ from .tokenization_gptsan_japanese import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab7a08c46afd097149b82b049ee6669f9fe45d04
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/configuration_gptsan_japanese.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/configuration_gptsan_japanese.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e055d4686a46983498f5b5e94c10dd354898de3a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/configuration_gptsan_japanese.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/modeling_gptsan_japanese.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/modeling_gptsan_japanese.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8279d6de32b741a4ce341547fa2abd9fab65afdf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/modeling_gptsan_japanese.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/tokenization_gptsan_japanese.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/tokenization_gptsan_japanese.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4467f110e54897946cc576a729782046847ac1f6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/__pycache__/tokenization_gptsan_japanese.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/configuration_gptsan_japanese.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/configuration_gptsan_japanese.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7d1e23e080eddc5cce28e72c551d123bec09de6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/configuration_gptsan_japanese.py
@@ -0,0 +1,157 @@
+# coding=utf-8
+# Copyright 2023, HuggingFace Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""GPTSAN-japanese model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class GPTSanJapaneseConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`GPTSanJapaneseModel`]. It is used to instantiate
+ a GPTSANJapanese model according to the specified arguments, defining the model architecture. Instantiating a
+ configuration with the defaults will yield a similar configuration to that of the GPTSANJapanese
+ [Tanrei/GPTSAN-japanese](https://huggingface.co/Tanrei/GPTSAN-japanese) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Arguments:
+ vocab_size (`int`, *optional*, defaults to 36000):
+ Vocabulary size of the GPTSANJapanese model. Defines the number of different tokens that can be represented
+ by the `inputs_ids` passed when calling [`GPTSanJapaneseModel`].
+ max_position_embeddings (`int`, *optional*, defaults to 1280):
+ The maximum sequence length that this model might ever be used with. Defaults set this to 1280.
+ d_model (`int`, *optional*, defaults to 1024):
+ Size of the encoder layers and the pooler layer.
+ d_ff (`int`, *optional*, defaults to 8192):
+ Size of the intermediate feed forward layer in each `SwitchTransformersBlock`.
+ d_ext (`int`, *optional*, defaults to 4096):
+ Size of the intermediate feed forward layer in each Extra-layers.
+ d_spout (`int`, *optional*, defaults to 128):
+ Size of the `spout` vector.
+ num_switch_layers (`int`, *optional*, defaults to 10):
+ Number of layers in the Switch Transformer layer.
+ num_ext_layers (`int`, *optional*, defaults to 0):
+ Number of layers in the Extra-layers.
+ num_heads (`int`, *optional*, defaults to 16):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ num_experts (`int`, *optional*, defaults to 16):
+ Number of experts for each SwitchTransformer layer.
+ expert_capacity (`int`, *optional*, defaults to 128):
+ Number of tokens that can be stored in each expert. If set to 1, the model will behave like a regular
+ Transformer.
+ dropout_rate (`float`, *optional*, defaults to 0.0):
+ The ratio for all dropout layers.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
+ The epsilon used by the layer normalization layers.
+ router_bias (`bool`, *optional*, defaults to `False`):
+ Whether to add a bias to the router.
+ router_jitter_noise (`float`, *optional*, defaults to 0.0):
+ Amount of noise to add to the router. Set it to 0.0 during prediction or set small value (usually 1e-2)
+ during training.
+ router_dtype (`str`, *optional*, default to `"float32"`):
+ The `dtype` used for the routers. It is preferable to keep the `dtype` to `"float32"` as specified in the
+ *selective precision* discussion in [the paper](https://huggingface.co/papers/2101.03961).
+ router_ignore_padding_tokens (`bool`, *optional*, defaults to `False`):
+ Whether to ignore padding tokens when routing.
+ output_hidden_states (`bool`, *optional*, default to `False`):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ output_attentions (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the attentions tensors of all attention layers.
+ initializer_factor (`float`, *optional*, defaults to 0.002):
+ A factor for initializing all weight matrices.
+ output_router_logits (`bool`, *optional*, default to `False`):
+ Whether or not to return the router logits of all experts.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models)
+ """
+
+ model_type = "gptsan-japanese"
+ keys_to_ignore_at_inference = [
+ "past_key_values",
+ ]
+ attribute_map = {
+ "hidden_size": "d_model",
+ "num_attention_heads": "num_heads",
+ "num_hidden_layers": "num_layers",
+ }
+
+ def __init__(
+ self,
+ vocab_size=36000,
+ max_position_embeddings=1280,
+ d_model=1024,
+ d_ff=8192,
+ d_ext=4096,
+ d_spout=128,
+ num_switch_layers=10,
+ num_ext_layers=0,
+ num_heads=16,
+ num_experts=16,
+ expert_capacity=128,
+ dropout_rate=0.0,
+ layer_norm_epsilon=1e-5,
+ router_bias=False,
+ router_jitter_noise=0.0,
+ router_dtype="float32",
+ router_ignore_padding_tokens=False,
+ output_hidden_states=False,
+ output_attentions=False,
+ initializer_factor=0.002,
+ output_router_logits=False,
+ use_cache=True,
+ separator_token_id=35998,
+ pad_token_id=35995,
+ eos_token_id=35999,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.max_position_embeddings = max_position_embeddings
+ self.d_model = d_model
+ self.d_ff = d_ff
+ self.d_ext = d_ext
+ self.d_spout = d_spout
+ self.num_switch_layers = num_switch_layers
+ self.num_ext_layers = num_ext_layers
+ self.num_layers = num_switch_layers + num_ext_layers
+ self.num_heads = num_heads
+ self.num_experts = num_experts
+ self.expert_capacity = expert_capacity
+ self.dropout_rate = dropout_rate
+ self.layer_norm_epsilon = layer_norm_epsilon
+ self.router_bias = router_bias
+ self.router_jitter_noise = router_jitter_noise
+ self.router_dtype = router_dtype
+ self.router_ignore_padding_tokens = router_ignore_padding_tokens
+ self.output_hidden_states = output_hidden_states
+ self.output_attentions = output_attentions
+ self.initializer_factor = initializer_factor
+ self.output_router_logits = output_router_logits
+ self.use_cache = use_cache
+
+ super().__init__(
+ separator_token_id=separator_token_id,
+ pad_token_id=pad_token_id,
+ eos_token_id=eos_token_id,
+ **kwargs,
+ )
+
+
+__all__ = ["GPTSanJapaneseConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/modeling_gptsan_japanese.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/modeling_gptsan_japanese.py
new file mode 100644
index 0000000000000000000000000000000000000000..aeae3f2a2f7c8c3d1df0603a9f54c7f2c8acc17f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/modeling_gptsan_japanese.py
@@ -0,0 +1,1330 @@
+# coding=utf-8
+# Copyright 2023 Toshiyuki Sakamoto(tanreinama) and HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch GPTSANJapanese model."""
+
+from typing import Optional, Union
+
+import torch
+import torch.nn as nn
+
+from ....activations import ACT2FN
+from ....modeling_outputs import MoECausalLMOutputWithPast, MoEModelOutputWithPastAndCrossAttentions
+from ....modeling_utils import PreTrainedModel
+from ....utils import (
+ DUMMY_INPUTS,
+ DUMMY_MASK,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ is_torch_fx_proxy,
+ logging,
+)
+from ....utils.deprecation import deprecate_kwarg
+from .configuration_gptsan_japanese import GPTSanJapaneseConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CONFIG_FOR_DOC = "GPTSanJapaneseConfig"
+_CHECKPOINT_FOR_DOC = "Tanrei/GPTSAN-japanese"
+
+####################################################
+# This dict contains ids and associated url
+# for the pretrained weights provided with the models
+####################################################
+
+
+def router_z_loss_func(router_logits: torch.Tensor) -> float:
+ r"""
+ Compute the router z-loss implemented in PyTorch.
+
+ The router z-loss was introduced in [Designing Effective Sparse Expert Models](https://huggingface.co/papers/2202.08906).
+ It encourages router logits to remain small in an effort to improve stability.
+
+ Args:
+ router_logits (`float`):
+ Input logits of shape [batch_size, sequence_length, num_experts]
+
+ Returns:
+ Scalar router z-loss.
+ """
+ num_groups, tokens_per_group, _ = router_logits.shape
+ log_z = torch.logsumexp(router_logits, dim=-1)
+ z_loss = log_z**2
+ return torch.sum(z_loss) / (num_groups * tokens_per_group)
+
+
+def load_balancing_loss_func(router_probs: torch.Tensor, expert_indices: torch.Tensor) -> float:
+ r"""
+ Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
+
+ See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
+ function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
+ experts is too unbalanced.
+
+ Args:
+ router_probs (`torch.Tensor`):
+ Probability assigned to each expert per token. Shape: [batch_size, seqeunce_length, num_experts].
+ expert_indices (`torch.Tensor`):
+ Indices tensor of shape [batch_size, seqeunce_length] identifying the selected expert for a given token.
+
+ Returns:
+ The auxiliary loss.
+ """
+ num_experts = router_probs.shape[-1]
+
+ # cast the expert indices to int64, otherwise one-hot encoding will fail
+ if expert_indices.dtype != torch.int64:
+ expert_indices = expert_indices.to(torch.int64)
+
+ if len(expert_indices.shape) == 2:
+ expert_indices = expert_indices.unsqueeze(2)
+
+ expert_mask = torch.nn.functional.one_hot(expert_indices, num_experts)
+
+ # For a given token, determine if it was routed to a given expert.
+ expert_mask = torch.max(expert_mask, axis=-2).values
+
+ # cast to float32 otherwise mean will fail
+ expert_mask = expert_mask.to(torch.float32)
+ tokens_per_group_and_expert = torch.mean(expert_mask, axis=-2)
+
+ router_prob_per_group_and_expert = torch.mean(router_probs, axis=-2)
+ return torch.mean(tokens_per_group_and_expert * router_prob_per_group_and_expert) * (num_experts**2)
+
+
+class GPTSanJapaneseDenseActDense(nn.Module):
+ """
+ FFN Layer for Switch Transformer and Extra layers
+
+ GPTSAN can mix Switch Transformer layers and normal Transformer layers This class is used as Expert in Switch
+ Transformer layers and as FFN in regular Transformer layers. RELU is used in the Switch Transformer layer, and
+ Swish is used in the normal Transformer layer, so there is a choice of which is used in the argument.
+
+ """
+
+ def __init__(self, config: GPTSanJapaneseConfig, ext_layer=False):
+ super().__init__()
+ d_inter = config.d_ext if ext_layer else config.d_ff
+ self.wi = nn.Linear(config.d_model, d_inter, bias=ext_layer)
+ self.wo = nn.Linear(d_inter, config.d_model, bias=ext_layer)
+ self.dropout = nn.Identity() if ext_layer else nn.Dropout(config.dropout_rate)
+ self.act = ACT2FN["swish" if ext_layer else "relu"]
+
+ def forward(self, hidden_states):
+ r"""
+ Args:
+ hidden_states (`torch.Tensor`) :
+ [num_groups, tokens_per_group, hidden_dim] inputs to send to experts.
+ Returns:
+ torch.Tensor[num_groups, tokens_per_group, hidden_dim]
+
+ """
+ hidden_states = self.wi(hidden_states)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.wo(hidden_states)
+ return hidden_states
+
+
+class GPTSanJapaneseTop1Router(nn.Module):
+ """
+ Router using tokens choose top-1 experts assignment.
+
+ This router uses the same mechanism as in Switch Transformer (https://huggingface.co/papers/2101.03961) and V-MoE
+ (https://huggingface.co/papers/2106.05974): tokens choose their top experts. Items are sorted by router_probs and then
+ routed to their choice of expert until the expert's expert_capacity is reached. **There is no guarantee that each
+ token is processed by an expert**, or that each expert receives at least one token.
+
+ """
+
+ def __init__(self, config: GPTSanJapaneseConfig):
+ super().__init__()
+ self.num_experts = config.num_experts
+ self.expert_capacity = config.expert_capacity
+ self.classifier = nn.Linear(config.hidden_size, self.num_experts, bias=config.router_bias)
+ self.jitter_noise = config.router_jitter_noise
+ self.ignore_padding_tokens = config.router_ignore_padding_tokens
+ self.dtype = getattr(torch, config.router_dtype)
+
+ def _compute_router_probabilities(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ r"""
+ Computes router probabilities from input hidden states.
+
+ Args:
+ hidden_states (`torch.Tensor`):
+ (batch_size, sequence_length, hidden_dim) from which router probabilities are computed.
+ Returns:
+ router_probabilities (`torch.Tensor`):
+ Tensor of shape (batch_size, sequence_length, num_experts) corresponding to the probabilities for each
+ token and expert. Used for routing tokens to experts.
+ router_logits (`torch.Tensor`):
+ Logits tensor of shape (batch_size, sequence_length, num_experts) corresponding to raw router logits.
+ This is used later for computing router z-loss.
+ """
+ # float32 is used to ensure stability. See the discussion of "selective precision" in
+ # https://huggingface.co/papers/2101.03961.
+ # We also store the previous dtype to cast back the output to the previous dtype
+ self.input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(self.dtype)
+
+ if self.training and self.jitter_noise > 0:
+ # Multiply the token inputs by the uniform distribution - adding some noise
+ hidden_states *= torch.empty_like(hidden_states).uniform_(1.0 - self.jitter_noise, 1.0 + self.jitter_noise)
+
+ # Shape: [num_groups, tokens_per_group, num_experts]
+ self._cast_classifier()
+ router_logits = self.classifier(hidden_states)
+
+ # Apply Softmax and cast back to the original `dtype`
+ router_probabilities = nn.functional.softmax(router_logits, dim=-1, dtype=self.dtype).to(self.input_dtype)
+ return router_probabilities, router_logits
+
+ def _cast_classifier(self):
+ r"""
+ `bitsandbytes` `Linear8bitLt` layers does not support manual casting Therefore we need to check if they are an
+ instance of the `Linear8bitLt` class by checking special attributes.
+ """
+ if not (hasattr(self.classifier, "SCB") or hasattr(self.classifier, "CB")):
+ self.classifier = self.classifier.to(self.dtype)
+
+ def forward(self, hidden_states: torch.Tensor) -> tuple:
+ r"""
+ Generic forward function for every Router class. Each Router expects to have the same input hidden states
+ (`hidden_states`) corresponding to the hidden states for each token, the `expert_capacity` corresponding to the
+ number of tokens the Router will send to each expert, some Routers can send up to few tokens to each expert.
+
+ Each Router works as the following: it expects the hidden states for each token, gets the `router_probs` and
+ `router_logits` from the `router_weights`. This will assign for each token, the raw probability to be assigned
+ to an expert. Then each Router class will have to define its own `_compute_routing_instructions`.
+
+ Args:
+ hidden_states (`torch.Tensor`) :
+ [num_groups, tokens_per_group, hidden_dim] inputs to send to experts.
+ Returns:
+ tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`] Tuple containing the expert index, the router probs
+ and the router logits. The router probabilities and logits are required to compute the loss.
+ """
+ router_probs, router_logits = self._compute_router_probabilities(hidden_states)
+
+ expert_index = torch.argmax(router_probs, dim=-1)
+ expert_index = torch.nn.functional.one_hot(expert_index, num_classes=self.num_experts)
+
+ # Mask tokens outside expert capacity. Sum over each sequence
+ token_priority = torch.cumsum(expert_index, dim=-2)
+ # mask if the token routed to to the expert will overflow
+ expert_capacity_mask = token_priority <= self.expert_capacity
+ expert_index = expert_index * expert_capacity_mask
+
+ router_probs = torch.max(router_probs, dim=-1).values.unsqueeze(-1)
+ return expert_index, router_probs, router_logits
+
+
+class GPTSanJapaneseSparseMLP(nn.Module):
+ r"""
+ Implementation of the Switch Transformers Sparse MLP module.
+ """
+
+ def __init__(self, config: GPTSanJapaneseConfig, expert_class: nn.Module = GPTSanJapaneseDenseActDense):
+ super().__init__()
+ # Step 1: Get the correct router according to its class
+ self.router = GPTSanJapaneseTop1Router(config)
+
+ # Step 2: Get the experts
+ self.experts = nn.ModuleDict()
+ for idx in range(config.num_experts):
+ self.experts[f"expert_{idx}"] = expert_class(config)
+
+ def forward(self, hidden_states):
+ r"""
+ Hold on, this will be slightly tricky to understand In the correct order, a MoE layer does the following:
+
+ 1- Gets the `router_mask` from the router. The shape of the mask is `(batch_size, sequence_length, num_expert)`
+ and corresponds to the argmax of the `router_probs`. The probabilities are needed in the computation of the
+ hidden states : they are broadcasted to the hidden states values (can be interpreted as a scaling factor).
+
+ 2- Dispatch the tokens to its associated experts. We do a classic for loop over the experts and assign for each
+ expert the corresponding hidden states.
+
+ """
+ # Step 1: Get the router_mask from the router as well as the probabilities
+ router_mask, router_probs, router_logits = self.router(hidden_states)
+ expert_index = torch.argmax(router_mask, dim=-1)
+
+ # The routers introduced might not always map all the tokens, to a router, which means that some hidden states
+ # can be unchanged from one layer to another. That is why the hidden states are cloned before updating only the selected ones.
+
+ next_states = hidden_states.clone()
+ for idx, expert in enumerate(self.experts.values()):
+ token_indices = router_mask[:, :, idx].bool()
+ next_states[token_indices] = expert(hidden_states[token_indices]).to(next_states.dtype)
+
+ hidden_states = router_probs * next_states
+ return hidden_states, (router_logits, expert_index)
+
+
+class GPTSanJapaneseLayerSparseFF(nn.Module):
+ r"""
+ Switch Transformers Feed Forward layer module. This is a wrapper around the Mixture of Experts module.
+
+ Parameters:
+ config : ([`GPTSanJapaneseConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+ """
+
+ def __init__(self, config: GPTSanJapaneseConfig):
+ super().__init__()
+ self.mlp = GPTSanJapaneseSparseMLP(config)
+ self.soft_bypass_mlp = nn.Linear(config.d_model, config.d_model, bias=False)
+ self.norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
+
+ def forward(self, hidden_states, output_router_logits):
+ r"""
+ Args:
+ hidden_states (`torch.Tensor`) :
+ [num_groups, tokens_per_group, hidden_dim] inputs to send to experts.
+ output_router_logits (`bool`) :
+ output experts router output.
+ Returns:
+ torch.Tensor[num_groups, tokens_per_group, hidden_dim]
+
+ """
+ forwarded_states, router_tuple = self.mlp(hidden_states)
+ forwarded_states += torch.tanh(self.soft_bypass_mlp(hidden_states))
+ output = hidden_states + self.norm(forwarded_states)
+
+ if output_router_logits and router_tuple is not None:
+ return output, router_tuple
+ else:
+ return output
+
+
+class GPTSanJapaneseLayerDenseFF(nn.Module):
+ r"""
+ Extra Transformers Feed Forward layer module.
+
+ Parameters:
+ config : ([`GPTSanJapaneseConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+ """
+
+ def __init__(self, config: GPTSanJapaneseConfig):
+ super().__init__()
+ # Check if it is a sparse layer, if not then it is a dense layer
+ self.mlp = GPTSanJapaneseDenseActDense(config, ext_layer=True)
+ self.norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
+
+ def forward(self, hidden_states):
+ r"""
+ Args:
+ hidden_states (`torch.Tensor`) :
+ [num_groups, tokens_per_group, hidden_dim] inputs to send to experts.
+ Returns:
+ torch.Tensor[num_groups, tokens_per_group, hidden_dim]
+
+ """
+ forwarded_states = self.mlp(hidden_states)
+ output = hidden_states + self.norm(forwarded_states)
+ return output
+
+
+class GPTSanJapaneseAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool = False,
+ bias: bool = True,
+ is_causal: bool = False,
+ config: Optional[GPTSanJapaneseConfig] = None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ self.config = config
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.is_causal = is_causal
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: Optional[torch.Tensor] = None,
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ layer_head_mask: Optional[torch.Tensor] = None,
+ output_attentions: bool = False,
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+
+ bsz, tgt_len, _ = hidden_states.size()
+
+ # get query proj
+ query_states = self.q_proj(hidden_states) * self.scaling
+ # get key, value proj
+ # `past_key_values[0].shape[2] == key_value_states.shape[1]`
+ # is checking that the `sequence_length` of the `past_key_values` is the same as
+ # the provided `key_value_states` to support prefix tuning
+ if (
+ is_cross_attention
+ and past_key_values is not None
+ and past_key_values[0].shape[2] == key_value_states.shape[1]
+ ):
+ # reuse k,v, cross_attentions
+ key_states = past_key_values[0]
+ value_states = past_key_values[1]
+ elif is_cross_attention:
+ # cross_attentions
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
+ elif past_key_values is not None:
+ # reuse k, v, self_attention
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
+ key_states = torch.cat([past_key_values[0], key_states], dim=2)
+ value_states = torch.cat([past_key_values[1], value_states], dim=2)
+ else:
+ # self_attention
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
+
+ if self.is_decoder:
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
+ # Further calls to cross_attention layer can then reuse all cross-attention
+ # key/value_states (first "if" case)
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
+ past_key_values = (key_states, value_states)
+
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
+ key_states = key_states.reshape(*proj_shape)
+ value_states = value_states.reshape(*proj_shape)
+
+ src_len = key_states.size(1)
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
+
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
+ raise ValueError(
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
+ f" {attn_weights.size()}"
+ )
+
+ if attention_mask is not None:
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
+ raise ValueError(
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
+ )
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ if layer_head_mask is not None:
+ if layer_head_mask.size() != (self.num_heads,):
+ raise ValueError(
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
+ f" {layer_head_mask.size()}"
+ )
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ if output_attentions:
+ # this operation is a bit awkward, but it's required to
+ # make sure that attn_weights keeps its gradient.
+ # In order to do so, attn_weights have to be reshaped
+ # twice and have to be reused in the following
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
+ else:
+ attn_weights_reshaped = None
+
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
+
+ attn_output = torch.bmm(attn_probs, value_states)
+
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
+ f" {attn_output.size()}"
+ )
+
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
+ attn_output = attn_output.transpose(1, 2)
+
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
+ # partitioned across GPUs when using tensor-parallelism.
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
+
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights_reshaped, past_key_values
+
+
+class GPTSanJapaneseLayerSelfAttention(nn.Module):
+ """
+ Self Attention and Normalization Unit
+ """
+
+ def __init__(self, config, has_relative_attention_bias=False):
+ super().__init__()
+ self.self_attn = GPTSanJapaneseAttention(
+ embed_dim=config.d_model,
+ num_heads=config.num_heads,
+ is_decoder=True,
+ bias=has_relative_attention_bias,
+ )
+ self.norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_epsilon)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: Optional[tuple[torch.FloatTensor]],
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = False,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[Union[torch.Tensor, tuple[torch.Tensor]], ...]:
+ r"""
+ Self-attention and normalize block.
+
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ if the model is configured as a decoder.
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up
+ decoding. If `past_key_values` are used, the user can optionally input only the last
+ `decoder_input_ids` (those that don't have their past key value states given to this model) of shape
+ `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ head_mask (`numpy.ndarray` of shape `({0})`, `optional):
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ Returns:
+ tuple[torch.Tensor[num_groups, tokens_per_group, hidden_dim],...]
+ """
+ # Self Attention
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
+ self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
+ atten_out = self.self_attn(
+ hidden_states=hidden_states,
+ past_key_values=self_attn_past_key_value,
+ attention_mask=(1 - attention_mask) * torch.finfo(hidden_states.dtype).min,
+ layer_head_mask=head_mask,
+ output_attentions=output_attentions,
+ )
+ if output_attentions:
+ attn_weights = (atten_out[1],)
+ else:
+ attn_weights = ()
+
+ attention_output = atten_out[0]
+
+ hidden = hidden_states + self.norm(attention_output)
+
+ if use_cache:
+ outputs = (hidden, atten_out[2]) # hidden, present, (attentions)
+ else:
+ outputs = (hidden,) # hidden, (attentions)
+
+ return outputs + attn_weights
+
+
+class GPTSanJapaneseBlock(nn.Module):
+ """
+ Self Attention and FFN Unit
+ """
+
+ def __init__(self, config, ext_layer=False):
+ super().__init__()
+ self.self_attn = GPTSanJapaneseLayerSelfAttention(config)
+ self.feed_forward = GPTSanJapaneseLayerDenseFF(config) if ext_layer else GPTSanJapaneseLayerSparseFF(config)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: Optional[tuple[torch.FloatTensor]],
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = False,
+ output_attentions: Optional[bool] = False,
+ output_router_tuple: Optional[bool] = False,
+ ) -> tuple[Union[torch.Tensor, tuple[torch.Tensor]], ...]:
+ r"""
+ GPTSAN transformer block.
+
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ if the model is configured as a decoder.
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up
+ decoding. If `past_key_values` are used, the user can optionally input only the last
+ `decoder_input_ids` (those that don't have their past key value states given to this model) of shape
+ `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ head_mask (`numpy.ndarray` of shape `({0})`, `optional):
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ output_attentions (`bool`) :
+ output attention probabirities.
+ output_router_tuple:
+ output experts router logits and expert id.
+ Returns:
+ tuple[torch.Tensor[num_groups, tokens_per_group, hidden_dim],...]
+ """
+ atten_out = self.self_attn(
+ hidden_states=hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ )
+ attention_output = atten_out[0]
+
+ if isinstance(self.feed_forward, GPTSanJapaneseLayerSparseFF):
+ sparse_out = self.feed_forward(attention_output, output_router_tuple)
+ if output_router_tuple:
+ hidden, router_tuple = sparse_out
+ else:
+ hidden = sparse_out
+ else:
+ hidden = self.feed_forward(attention_output)
+
+ outputs = (hidden,) + atten_out[1:]
+
+ if isinstance(self.feed_forward, GPTSanJapaneseLayerSparseFF) and output_router_tuple:
+ outputs += (router_tuple,)
+
+ return outputs
+
+
+class GPTSanJapanesePreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: GPTSanJapaneseConfig
+ base_model_prefix = "gptsan_japanese"
+ supports_gradient_checkpointing = False
+ _no_split_modules = ["GPTSanJapaneseBlock"]
+ _skip_keys_device_placement = "past_key_values"
+
+ @property
+ def dummy_inputs(self):
+ input_ids = torch.tensor(DUMMY_INPUTS)
+ input_mask = torch.tensor(DUMMY_MASK)
+ dummy_inputs = {
+ "input_ids": input_ids,
+ "attention_mask": input_mask,
+ }
+ return dummy_inputs
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ factor = self.config.initializer_factor # Used for testing weights initialization
+ if isinstance(module, nn.LayerNorm):
+ module.weight.data.fill_(factor * 1.0)
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
+ if hasattr(module, "bias") and module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=factor * 1.0)
+ elif isinstance(module, GPTSanJapaneseModel):
+ # Mesh TensorFlow embeddings initialization
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
+ module.embed_tokens.weight.data.normal_(mean=0.0, std=factor * 1.0)
+ module.position_embeddings.weight.data.normal_(mean=0.0, std=factor * 1.0)
+ if hasattr(module, "extra_position_embeddings") and module.extra_position_embeddings is not None:
+ module.extra_position_embeddings.weight.data.normal_(mean=0.0, std=factor * 1.0)
+ elif isinstance(module, (GPTSanJapaneseModel, GPTSanJapaneseForConditionalGeneration)):
+ # Mesh TensorFlow embeddings initialization
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L1624
+ module.final_logits_bias.data.normal_(mean=0.0, std=factor * 1.0)
+ if hasattr(module, "lm_head") and not self.config.tie_word_embeddings:
+ module.lm_head.weight.data.normal_(mean=0.0, std=factor * 1.0)
+ elif isinstance(module, GPTSanJapaneseDenseActDense):
+ # Mesh TensorFlow FF initialization
+ # See https://github.com/tensorflow/mesh/blob/master/mesh_tensorflow/transformer/transformer_layers.py#L56
+ # and https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/layers.py#L89
+ module.wi.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_model) ** -0.5))
+ if hasattr(module.wi, "bias") and module.wi.bias is not None:
+ module.wi.bias.data.zero_()
+ module.wo.weight.data.normal_(mean=0.0, std=factor * ((self.config.d_ff) ** -0.5))
+ if hasattr(module.wo, "bias") and module.wo.bias is not None:
+ module.wo.bias.data.zero_()
+ elif isinstance(module, GPTSanJapaneseAttention):
+ # Multi-headed attention
+ d_model = self.config.d_model
+ key_value_proj_dim = self.config.d_model
+ n_heads = self.config.num_heads
+ module.k_proj.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
+ module.v_proj.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
+ module.q_proj.weight.data.normal_(mean=0.0, std=factor * ((d_model * key_value_proj_dim) ** -0.5))
+ module.out_proj.weight.data.normal_(mean=0.0, std=factor * ((n_heads * key_value_proj_dim) ** -0.5))
+ elif isinstance(module, GPTSanJapaneseSparseMLP):
+ # Mesh TensorFlow attention initialization to avoid scaling before softmax
+ # See https://github.com/tensorflow/mesh/blob/fa19d69eafc9a482aff0b59ddd96b025c0cb207d/mesh_tensorflow/transformer/attention.py#L136
+ d_model = self.config.d_model
+ key_value_proj_dim = self.config.d_model
+ n_heads = self.config.num_heads
+ module.router.classifier.weight.data.normal_(mean=0.0, std=factor * 1)
+ for idx in range(self.config.num_experts):
+ module.experts[f"expert_{idx}"].wi.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
+ module.experts[f"expert_{idx}"].wo.weight.data.normal_(mean=0.0, std=factor * (d_model**-0.5))
+
+ def _shift_right(self, input_ids):
+ decoder_start_token_id = self.config.decoder_start_token_id
+ pad_token_id = self.config.pad_token_id
+
+ if decoder_start_token_id is None:
+ raise ValueError(
+ "self.model.config.decoder_start_token_id has to be defined. In T5 it is usually set to the pad_token_id. "
+ "See T5 docs for more information."
+ )
+
+ # shift inputs to the right
+ if is_torch_fx_proxy(input_ids):
+ # Item assignment is not supported natively for proxies.
+ shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), decoder_start_token_id)
+ shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1)
+ else:
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
+ shifted_input_ids[..., 0] = decoder_start_token_id
+
+ if pad_token_id is None:
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
+ # replace possible -100 values in labels by `pad_token_id`
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
+
+ return shifted_input_ids
+
+
+GPTSAN_JAPANESE_START_DOCSTRING = r"""
+
+ The [GPTSAN-japanese](https://github.com/tanreinama/GPTSAN) model was proposed in General-purpose Swich transformer
+ based Japanese language model
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`GPTSanJapaneseConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+GPTSAN_JAPANESE_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. GPTSAN-japanese is a model that generates sentence
+ continuations or predicts tokens at mask positions. Special tokens required for inputs to the model are
+ automatically appended.
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ token_type_ids (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ An input that masks the Prefix part in the Prefix-LM input. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **prefix** input,
+ - 0 for tokens that are **not-prefix** input.
+ spout (`torch.Tensor` of shape `(batch_size, config.d_spout)`):
+ This vector is transformed through an 8-layer FFN and can be used instead of `past_key_values`.
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
+ input (see `past_key_values`). This is useful if you want more control over how to convert
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+ router_logits (`tuple(torch.FloatTensor)`, *optional*, returned when `output_router_logits=True` is passed or when `config.add_router_probs=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
+ Router logits of the decoder model, useful to compute the auxiliary loss for Mixture of Experts models.
+"""
+
+
+@add_start_docstrings(
+ "The bare GPTSAN-japanese Model transformer outputting raw hidden-states without any specific head on top.",
+ GPTSAN_JAPANESE_START_DOCSTRING,
+)
+class GPTSanJapaneseModel(GPTSanJapanesePreTrainedModel):
+ def __init__(self, config: GPTSanJapaneseConfig):
+ super().__init__(config)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.d_model)
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model)
+ self.last_project = nn.Linear(config.d_model, config.d_model, bias=True)
+ self.act = ACT2FN["swish"]
+
+ self.blocks = torch.nn.ModuleList([])
+ for _ in range(config.num_switch_layers):
+ self.blocks.append(GPTSanJapaneseBlock(config))
+ for _ in range(config.num_ext_layers):
+ self.blocks.append(GPTSanJapaneseBlock(config, ext_layer=True))
+
+ if config.num_ext_layers > 0:
+ self.extra_position_embeddings = nn.Embedding(config.max_position_embeddings, config.d_model)
+
+ if config.d_spout:
+ spouts = []
+ for _ in range(8):
+ spouts.append(nn.Linear(config.d_spout, config.d_spout, bias=False))
+ spouts.append(nn.Tanh())
+ spouts.append(nn.Linear(config.d_spout, config.num_layers * 2 * config.d_model, bias=False))
+ self.spout = nn.Sequential(*spouts)
+
+ self.post_init()
+
+ def set_input_embeddings(self, new_embeddings):
+ self.embed_tokens = new_embeddings
+
+ @add_start_docstrings_to_model_forward(GPTSAN_JAPANESE_INPUTS_DOCSTRING)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.FloatTensor] = None,
+ spout: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = False,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ output_router_logits: Optional[bool] = None,
+ num_precontext: Optional[torch.LongTensor] = None,
+ ) -> Union[MoEModelOutputWithPastAndCrossAttentions, tuple[torch.FloatTensor]]:
+ r"""
+ num_precontext (`torch.LongTensor` of shape `(batch_size,1)`):
+ length of `hybrid` input tokens in the input. Tokens up to this length refer to both front and back like
+ BERT, tokens after that refer only to front like GPT. see also:
+ https://github.com/tanreinama/GPTSAN/blob/main/report/model.md
+
+ Returns:
+ `MoEModelOutputWithPastAndCrossAttentions` or `tuple` if `return_dict` returns
+ MoEModelOutputWithPastAndCrossAttentions instead of tuple
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ device = self.position_embeddings.weight.device
+ if input_ids is None:
+ input_ids = torch.zeros([1, 1]).int().to(device) # dummy for input_ids was None
+ if inputs_embeds is not None:
+ raise NotImplementedError(
+ "GPTSanJapaneseModel does not use `inputs_embeds`. Make sure to pass in `input_ids` instead."
+ )
+ num_pasts_contexts = 0
+ num_batch = input_ids.shape[0]
+ pasts_or_spout_value = None
+ if past_key_values is not None:
+ num_pasts_contexts = past_key_values.get_seq_length()
+ elif self.config.d_spout and spout is not None:
+ # `spout` is a special input vector specific to GPTSAN
+ # This controls the output by projecting embedded information such as the class of sentences during learning.
+ # It should passed instead of the first past_key_values.
+ # See the original GPTSAN repository for details
+ num_pasts_contexts += 1
+
+ # If there is an attention_mask, increase first one for spout
+ if self.config.d_spout and spout is not None and attention_mask is not None:
+ attention_mask_with_spout = torch.ones(num_batch, attention_mask.shape[1] + 1, device=device)
+ attention_mask_with_spout[:, 1:] -= 1 - attention_mask # 1st token should be spout
+ attention_mask = attention_mask_with_spout # update attention_mask
+
+ if num_precontext is not None:
+ # `num_precontext` is the number of tokens that refer to each other in prefix-lm
+ # created per batch, so dimension of num_precontext should be [batch, 1]
+ if not (
+ len(num_precontext.shape) == 2 and num_precontext.shape[1] == 1
+ ): # num_precontext Should be [batch,1]
+ raise ValueError("num_precontext should be [batch, 1] size.")
+ num_precontext = torch.reshape(num_precontext, [-1])
+ else:
+ num_precontext = torch.zeros([num_batch]).int().to(device)
+
+ num_input_contexts = input_ids.shape[1]
+ num_output_contexts = num_input_contexts + num_pasts_contexts
+
+ hidden_states = self.embed_tokens(input_ids)
+
+ if past_key_values is not None:
+ pasts_or_spout_value = past_key_values
+ elif self.config.d_spout and spout is not None:
+ # Make vector from `spout` of GPTSAN to the same shape as past_key_values
+ pasts_or_spout_value = self.spout(spout) # projecting `spout` vector
+ pasts_or_spout_value = torch.reshape(
+ pasts_or_spout_value,
+ [
+ num_batch,
+ self.config.num_layers,
+ 2,
+ self.config.num_heads,
+ num_pasts_contexts,
+ self.config.d_model // self.config.num_heads,
+ ],
+ )
+ pasts_or_spout_value = torch.split(pasts_or_spout_value, [1] * self.config.num_layers, dim=1)
+ # make same shape as past_key_values
+ pasts_or_spout_value = tuple(
+ tuple(b.squeeze(1) for b in torch.split(a.squeeze(1), [1, 1], dim=1)) for a in pasts_or_spout_value
+ )
+ else:
+ pasts_or_spout_value = [None] * self.config.num_layers
+
+ # Token position considering spout and pasts
+ token_position = torch.arange(num_input_contexts).to(device) + num_pasts_contexts
+
+ if attention_mask is None:
+ attention_mask = torch.ones(num_batch, num_input_contexts, device=device)
+
+ # positions for get position_embeddings
+ gather_position = (
+ (
+ torch.zeros((num_batch, self.config.d_model, num_input_contexts)).to(device)
+ + token_position.unsqueeze(0)
+ )
+ .transpose(1, 2)
+ .long()
+ )
+ # When padding with padding_side="left", zeros line up on the left side of attention_mask, so position_embeddings is shifted accordingly
+ gather_position -= (1 - attention_mask).argmin(dim=-1).unsqueeze(1).unsqueeze(2)
+ gather_position = torch.clip(gather_position, num_pasts_contexts, self.config.max_position_embeddings - 1)
+
+ # attention_mask is applied per batch
+ for i in range(num_batch):
+ hidden_states[i] += torch.gather(self.position_embeddings.weight, dim=0, index=gather_position[i])
+
+ # Create a mask to be used when making the prefix Input length of Prefix-LM variable
+ causal_mask = (
+ torch.tril(torch.ones((num_output_contexts, num_output_contexts), dtype=torch.uint8))
+ .view(1, 1, num_output_contexts, num_output_contexts)
+ .to(device)
+ )
+ prefix_lm_mask = causal_mask[:, :, -num_input_contexts:, :]
+ if token_type_ids is not None:
+ token_type_ids = token_type_ids.unsqueeze(1).unsqueeze(2)
+ prefix_lm_mask = ((prefix_lm_mask + token_type_ids) > 0).float()
+ # Merge prefix_lm_mask and attention_mask
+ extended_attention_mask = prefix_lm_mask * attention_mask.unsqueeze(1).unsqueeze(2)
+
+ # Prepare head mask if needed
+ if head_mask is not None:
+ head_mask = self.get_head_mask(
+ head_mask, self.config.num_switch_layers + self.config.num_ext_layers
+ ) # n_layer x batch x n_heads x N x N
+
+ # outputs
+ present_key_value_states = () if self.config.use_cache or use_cache else None
+ all_hidden_states = () if self.config.output_hidden_states or output_hidden_states else None
+ all_attentions = () if self.config.output_attentions or output_attentions else None
+ all_router_probs = () if self.config.output_router_logits or output_router_logits else None
+
+ for layer, past in enumerate(pasts_or_spout_value):
+ if layer == self.config.num_switch_layers:
+ if self.config.num_ext_layers > 0:
+ # extra_position_embeddings are extra position embeddings that are only created when extending the model with code from the original GPTSAN repository. Not used in the default model.
+ # However, it is created when you create an additional layer and partially train only that location.
+ # Therefore, convert_gptsan_tf_checkpoint_to_pytorch.py is used when converting and loading models created in the original GPTSAN repository.
+ for i in range(num_batch):
+ hidden_states[i] += torch.gather(
+ self.extra_position_embeddings.weight, dim=0, index=gather_position[i]
+ )
+
+ output_router_tuple = (
+ self.config.output_router_logits or output_router_logits
+ ) and layer < self.config.num_switch_layers
+ block_output = self.blocks[layer](
+ hidden_states=hidden_states,
+ past_key_values=past,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ use_cache=self.config.use_cache or use_cache,
+ output_attentions=self.config.output_attentions or output_attentions,
+ output_router_tuple=output_router_tuple,
+ )
+
+ outpos = 0
+ hidden_states = block_output[outpos]
+ if self.config.output_hidden_states or output_hidden_states:
+ all_hidden_states += (hidden_states,)
+ if self.config.use_cache or use_cache:
+ outpos += 1
+ present = block_output[outpos]
+ present_key_value_states += (present,)
+ if self.config.output_attentions or output_attentions:
+ outpos += 1
+ attention_probs = block_output[outpos]
+ all_attentions += (attention_probs,)
+ if output_router_tuple:
+ outpos += 1
+ router_tuple = block_output[outpos]
+ all_router_probs.append(router_tuple[0])
+
+ hidden_states = self.last_project(hidden_states)
+ hidden_states = self.act(hidden_states)
+
+ if self.config.output_hidden_states or output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ hidden_states,
+ present_key_value_states,
+ all_hidden_states,
+ all_attentions,
+ all_router_probs,
+ ]
+ if v is not None
+ )
+
+ return MoEModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=present_key_value_states,
+ hidden_states=all_hidden_states,
+ attentions=all_attentions,
+ router_probs=all_router_probs,
+ )
+
+
+@add_start_docstrings(
+ "The bare GPTSAN-japanese Model with a language modeling head.",
+ GPTSAN_JAPANESE_START_DOCSTRING,
+)
+class GPTSanJapaneseForConditionalGeneration(GPTSanJapanesePreTrainedModel):
+ _tied_weights_keys = ["lm_head.weight"]
+
+ def __init__(self, config: GPTSanJapaneseConfig):
+ super().__init__(config)
+ self.model = GPTSanJapaneseModel(config)
+ self.register_buffer("final_logits_bias", torch.zeros([1, config.vocab_size]))
+ self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
+ if not self.config.torchscript:
+ self.lm_head.weight = self.model.embed_tokens.weight
+
+ @add_start_docstrings_to_model_forward(GPTSAN_JAPANESE_INPUTS_DOCSTRING)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.FloatTensor] = None,
+ spout: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = False,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ output_router_logits: Optional[bool] = None,
+ labels: Optional[torch.LongTensor] = None,
+ ) -> Union[tuple[torch.FloatTensor], MoECausalLMOutputWithPast]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
+ labels in `[0, ..., config.vocab_size]`
+
+ Returns:
+ `MoECausalLMOutputWithPast` or `tuple` if `return_dict` returns MoECausalLMOutputWithPast instead of tuple
+
+ Example:
+
+ Text Generation with regular LM Model
+ ```python
+ >>> from transformers import AutoModel, AutoTokenizer, trainer_utils
+
+ >>> device = "cuda"
+ >>> model = AutoModel.from_pretrained("Tanrei/GPTSAN-japanese").to(device)
+ >>> tokenizer = AutoTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
+ >>> x_token = tokenizer("織田信長は、", return_tensors="pt")
+ >>> trainer_utils.set_seed(30)
+ >>> input_ids = x_token.input_ids.to(device)
+ >>> gen_token = model.generate(input_ids, max_new_tokens=50)
+ >>> tokenizer.decode(gen_token[0])
+ "織田信長は、政治・軍事の中枢まで掌握した政治家であり、日本史上類を見ない驚異的な軍事侵攻を続け..."
+ ```
+
+ Text Generation with Prefix-LM Model
+ ```python
+ >>> from transformers import AutoModel, AutoTokenizer, trainer_utils
+
+ >>> device = "cuda"
+ >>> model = AutoModel.from_pretrained("Tanrei/GPTSAN-japanese").to(device)
+ >>> tokenizer = AutoTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
+ >>> x_token = tokenizer("", prefix_text="織田信長は、", return_tensors="pt")
+ >>> trainer_utils.set_seed(30)
+ >>> input_ids = x_token.input_ids.to(device)
+ >>> token_type_ids = x_token.token_type_ids.to(device)
+ >>> gen_token = model.generate(input_ids, token_type_ids=token_type_ids, max_new_tokens=50)
+ >>> tokenizer.decode(gen_token[0])
+ "織田信長は、政治・外交で数々の戦果を上げるが、1568年からは、いわゆる本能寺の変で細川晴元に暗殺される..."
+ ```
+
+ Simultaneously Text Generation And Masked Language Model
+ ```python
+ >>> from transformers import AutoModel, AutoTokenizer, trainer_utils
+
+ >>> device = "cuda"
+ >>> model = AutoModel.from_pretrained("Tanrei/GPTSAN-japanese").to(device)
+ >>> tokenizer = AutoTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
+ >>> masked_sentence = "武田信玄は、<|inputmask|>時代ファンならぜひ押さえ<|inputmask|>きたい名将の一人。"
+ >>> x_token = tokenizer("", prefix_text=masked_sentence, return_tensors="pt")
+ >>> trainer_utils.set_seed(30)
+ >>> input_ids = x_token.input_ids.to(device)
+ >>> token_type_ids = x_token.token_type_ids.to(device)
+ >>> out_lm_token = model.generate(input_ids, token_type_ids=token_type_ids, max_new_tokens=50)
+ >>> out_mlm_token = model(input_ids, token_type_ids=token_type_ids).logits.argmax(axis=-1)
+ >>> tokenizer.decode(out_mlm_token[0])
+ "武田信玄は、戦国時代ファンならぜひ押さえておきたい名将の一人。"
+
+ >>> tokenizer.decode(out_lm_token[0][input_ids.shape[1] :])
+ "武田氏の三代に渡った武田家のひとり\n甲斐市に住む、日本史上最大の戦国大名。..."
+ ```"""
+ SEG_TOKEN = self.config.separator_token_id
+ use_cache = use_cache or self.config.use_cache
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ model_return_dict = True
+ num_precontext = None
+ if input_ids is not None:
+ num_batch = input_ids.shape[0]
+ num_precontext = torch.zeros([num_batch]).int().to(input_ids.device)
+ where_separators = torch.where(input_ids == SEG_TOKEN)
+ num_precontext[where_separators[0]] += where_separators[1]
+ num_precontext = num_precontext.unsqueeze(1)
+
+ outputs = self.model(
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ spout,
+ past_key_values,
+ head_mask,
+ use_cache,
+ inputs_embeds,
+ decoder_inputs_embeds,
+ output_attentions,
+ output_hidden_states,
+ model_return_dict,
+ output_router_logits,
+ num_precontext,
+ )
+
+ lm_logits = self.lm_head(outputs[0])
+ if lm_logits.shape[-1] == self.final_logits_bias.shape[-1]:
+ lm_logits = lm_logits + self.final_logits_bias
+
+ loss = None
+ z_loss = None
+ router_probs = None
+ aux_loss = None
+ if labels is not None:
+ # move labels to correct device to enable model parallelism
+ labels = labels.to(lm_logits.device)
+
+ loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
+
+ if output_router_logits:
+ # Compute the router loss (z_loss + auxiliary loss) for each router in the encoder and decoder
+ router_logits, expert_indexes = self._unpack_router_logits(outputs.router_probs)
+ z_loss = router_z_loss_func(router_logits)
+ router_probs = nn.Softmax(dim=-1)(router_logits)
+ aux_loss = load_balancing_loss_func(router_probs, expert_indexes)
+
+ loss = loss_fct(lm_logits.view(-1, lm_logits.size(-1)), labels.view(-1))
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ loss,
+ lm_logits,
+ outputs.past_key_values,
+ outputs.hidden_states,
+ outputs.router_probs,
+ z_loss,
+ aux_loss,
+ ]
+ if v is not None
+ )
+
+ return MoECausalLMOutputWithPast(
+ loss=loss,
+ logits=lm_logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ router_logits=outputs.router_probs,
+ z_loss=z_loss,
+ aux_loss=aux_loss,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids: torch.LongTensor,
+ attention_mask: torch.FloatTensor,
+ token_type_ids: Optional[torch.FloatTensor] = None,
+ spout: Optional[Union[list, torch.FloatTensor]] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ **kwargs,
+ ):
+ if isinstance(spout, list):
+ spout = torch.tensor(spout).float()
+ if input_ids is not None:
+ spout = spout.to(input_ids.device)
+ if past_key_values is not None:
+ return {
+ "input_ids": input_ids[:, -1:] if input_ids is not None else None,
+ "attention_mask": attention_mask,
+ "token_type_ids": token_type_ids[:, -1:] if token_type_ids is not None else None,
+ "spout": spout,
+ "past_key_values": past_key_values,
+ }
+ return {
+ "input_ids": input_ids,
+ "attention_mask": attention_mask,
+ "token_type_ids": token_type_ids,
+ "spout": spout,
+ "past_key_values": None,
+ }
+
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
+ return self._shift_right(labels)
+
+ def resize_token_embeddings(
+ self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None, mean_resizing: bool = True
+ ) -> nn.Embedding:
+ new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
+ self._resize_final_logits_bias(new_embeddings.weight.shape[0])
+ return new_embeddings
+
+ def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
+ old_num_tokens = self.final_logits_bias.shape[-1]
+ if new_num_tokens <= old_num_tokens:
+ new_bias = self.final_logits_bias[:, :new_num_tokens]
+ else:
+ extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
+ new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
+ self.register_buffer("final_logits_bias", new_bias)
+
+ def get_input_embeddings(self):
+ return self.model.get_input_embeddings()
+
+ def set_input_embeddings(self, new_embeddings):
+ self.model.set_input_embeddings(new_embeddings)
+
+ def _unpack_router_logits(self, router_outputs):
+ total_router_logits = []
+ total_expert_indexes = []
+ for router_output in router_outputs:
+ if len(router_output[0].shape) > 1:
+ router_logits, expert_indexes = router_output
+ total_router_logits.append(router_logits)
+ total_expert_indexes.append(expert_indexes)
+ return torch.cat(total_router_logits, dim=1), torch.cat(total_expert_indexes, dim=1)
+
+
+__all__ = ["GPTSanJapaneseForConditionalGeneration", "GPTSanJapaneseModel", "GPTSanJapanesePreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/tokenization_gptsan_japanese.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/tokenization_gptsan_japanese.py
new file mode 100644
index 0000000000000000000000000000000000000000..c67b27f64fa16c8b0c69f2cb0c31f7d4d5688437
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/gptsan_japanese/tokenization_gptsan_japanese.py
@@ -0,0 +1,518 @@
+# coding=utf-8
+# Copyright 2023 HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for GPTSANJapanese."""
+
+import collections
+import json
+import os
+import re
+import sys
+from typing import Optional, Union
+
+import numpy as np
+
+from ....tokenization_utils import PreTrainedTokenizer
+from ....tokenization_utils_base import (
+ BatchEncoding,
+ PreTokenizedInput,
+ PreTokenizedInputPair,
+ TextInput,
+ TextInputPair,
+ TruncationStrategy,
+)
+from ....utils import PaddingStrategy, logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "emoji_file": "emoji.json"}
+
+
+def load_vocab_and_emoji(vocab_file, emoji_file):
+ """Loads a vocabulary file and emoji file into a dictionary."""
+ with open(emoji_file, "r", encoding="utf-8") as f:
+ emoji = json.loads(f.read())
+
+ vocab = collections.OrderedDict()
+ raw_vocab = collections.OrderedDict()
+ ids_to_tokens = collections.OrderedDict()
+ with open(vocab_file, "r", encoding="utf-8") as f:
+ token = f.readlines()
+ token = [[t.rstrip("\n")] if (t == ",\n" or "," not in t) else t.rstrip("\n").split(",") for t in token]
+ for idx, b in enumerate(token):
+ ids_to_tokens[idx] = b
+ raw_vocab[",".join(b)] = idx
+ for wd in b:
+ vocab[wd] = idx
+
+ return vocab, raw_vocab, ids_to_tokens, emoji
+
+
+class GPTSanJapaneseTokenizer(PreTrainedTokenizer):
+ """
+ This tokenizer is based on GPTNeoXJapaneseTokenizer and has the following modifications
+ - Decoding byte0~byte255 tokens correctly
+ - Added bagofword token handling
+ - Return token_type_ids for Prefix-LM model
+ The bagofword token represents a repetition of the previous token and is converted to 3 consecutive tokens when
+ decoding In addition, the original Japanese special Sub-Word-Encoding has been released in this repository
+ (https://github.com/tanreinama/Japanese-BPEEncoder_V2). The token_type_ids is a mask indicating the prefix input
+ position of the Prefix-LM model. To specify a prefix position, specify a prefix input for prefix_text, or specify a
+ sentence of the prefix part and the part after it as a text pair of batch input.
+
+ Example:
+
+ ```python
+ >>> from transformers import GPTSanJapaneseTokenizer
+
+ >>> tokenizer = GPTSanJapaneseTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
+ >>> # You can confirm both 慶応 and 慶應 are encoded to 17750
+ >>> tokenizer("吾輩は猫である🐯。実は慶応(慶應)大学出身")["input_ids"]
+ [35993, 35998, 34347, 31459, 30647, 31448, 25, 30659, 35729, 35676, 32417, 30647, 17750, 35589, 17750, 35590, 321, 1281]
+
+ >>> # Both 慶応 and 慶應 are decoded to 慶応
+ >>> tokenizer.decode(tokenizer("吾輩は猫である🐯。実は慶応(慶應)大学出身")["input_ids"])
+ '吾輩は猫である🐯。実は慶応(慶応)大学出身'
+ ```
+
+ Example for Prefix-LM:
+
+ ```python
+ >>> from transformers import GPTSanJapaneseTokenizer
+
+ >>> tokenizer = GPTSanJapaneseTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
+ >>> tokenizer("実は慶応(慶應)大学出身", prefix_text="吾輩は猫である🐯。")["input_ids"]
+ [35993, 34347, 31459, 30647, 31448, 25, 30659, 35729, 35676, 35998, 32417, 30647, 17750, 35589, 17750, 35590, 321, 1281]
+
+ >>> # Mask for Prefix-LM inputs
+ >>> tokenizer("実は慶応(慶應)大学出身", prefix_text="吾輩は猫である🐯。")["token_type_ids"]
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
+ ```
+
+ Example for batch encode:
+
+ ```python
+ >>> from transformers import GPTSanJapaneseTokenizer
+
+ >>> tokenizer = GPTSanJapaneseTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
+ >>> tokenizer([["武田信玄", "は、"], ["織田信長", "の配下の、"]], padding=True)["input_ids"]
+ [[35993, 35998, 8640, 25948, 35993, 35998, 30647, 35675, 35999, 35999], [35993, 35998, 10382, 9868, 35993, 35998, 30646, 9459, 30646, 35675]]
+
+ >>> # Mask for Prefix-LM inputs
+ >>> tokenizer([["武田信玄", "は、"], ["織田信長", "の配下の、"]], padding=True)["token_type_ids"]
+ [[1, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
+
+ >>> # Mask for padding
+ >>> tokenizer([["武田信玄", "は、"], ["織田信長", "の配下の、"]], padding=True)["attention_mask"]
+ [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
+ ```
+
+ Args:
+ vocab_file (`str`):
+ File containing the vocabulary.
+ emoji_file (`str`):
+ File containing the emoji.
+ unk_token (`str`, *optional*, defaults to `"<|nottoken|>"`):
+ The token used for unknown character
+ pad_token (`str`, *optional*, defaults to `"<|separator|>"`):
+ The token used for padding
+ bos_token (`str`, *optional*, defaults to `"<|startoftext|>"`):
+ The beginning of sequence token.
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
+ The end of sequence token.
+ sep_token (`str`, *optional*, defaults to `"<|segmenter|>"`):
+ A special token to separate token to prefix part and general input part.
+ do_clean_text (`bool`, *optional*, defaults to `False`):
+ Whether or not to clean text for URL, EMAIL, TEL, Japanese DATE and Japanese PRICE.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask", "token_type_ids"]
+
+ def __init__(
+ self,
+ vocab_file,
+ emoji_file,
+ unk_token="<|nottoken|>",
+ pad_token="<|separator|>",
+ bos_token="<|startoftext|>",
+ eos_token="<|endoftext|>",
+ sep_token="<|segmenter|>",
+ do_clean_text=False,
+ **kwargs,
+ ):
+ if not os.path.isfile(vocab_file):
+ raise ValueError(
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
+ " model use `tokenizer = GPTSanJapaneseTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
+ )
+ if not os.path.isfile(emoji_file):
+ raise ValueError(
+ f"Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google"
+ " pretrained model use `tokenizer = GPTSanJapaneseTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
+ )
+ self.do_clean_text = do_clean_text
+ self.vocab, self.raw_vocab, self.ids_to_tokens, self.emoji = load_vocab_and_emoji(vocab_file, emoji_file)
+ self.subword_tokenizer = SubWordJapaneseTokenizer(
+ vocab=self.vocab, ids_to_tokens=self.ids_to_tokens, emoji=self.emoji
+ )
+
+ super().__init__(
+ unk_token=unk_token,
+ pad_token=pad_token,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ do_clean_text=do_clean_text,
+ **kwargs,
+ )
+
+ @property
+ def vocab_size(self):
+ # self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab
+ return len(self.raw_vocab)
+
+ def get_vocab(self):
+ return dict(self.raw_vocab, **self.added_tokens_encoder)
+
+ def _tokenize(self, text):
+ return self.subword_tokenizer.tokenize(text, clean=self.do_clean_text)
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.subword_tokenizer.convert_id_to_token(index)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ words = []
+ byte_tokens = []
+ for word in tokens:
+ if word[:6] == "<|byte" and word[-2:] == "|>":
+ byte_tokens.append(int(word[6:-2]))
+ else:
+ if len(byte_tokens) > 0:
+ words.append(bytearray(byte_tokens).decode("utf-8", errors="replace"))
+ byte_tokens = []
+ if word[:7] == "<|emoji" and word[-2:] == "|>":
+ words.append(self.emoji["emoji_inv"][word])
+ elif word == "":
+ words.append(" ")
+ elif word == "
":
+ words.append("\n")
+ elif word == "":
+ words.append("\t")
+ elif word == "":
+ words.append("▀")
+ elif word == "":
+ words.append("ǀ")
+ elif word == "":
+ words.append("‖")
+ elif word == "<|bagoftoken|>":
+ if len(words) > 0:
+ words.append(words[-1])
+ words.append(words[-1])
+ words.append(words[-1])
+ elif word.startswith("<|") and word.endswith("|>"):
+ words.append("")
+ else:
+ words.append(word)
+ if len(byte_tokens) > 0:
+ words.append(bytearray(byte_tokens).decode("utf-8", errors="replace"))
+ text = "".join(words)
+ return text
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ index = 0
+ if os.path.isdir(save_directory):
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ emoji_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"]
+ )
+ else:
+ vocab_file = (
+ (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ emoji_file = (
+ (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"]
+ )
+ with open(vocab_file, "w", encoding="utf-8") as writer:
+ for token_index, token in self.ids_to_tokens.items():
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
+ " Please check that the vocabulary is not corrupted!"
+ )
+ index = token_index
+ writer.write(",".join(token) + "\n")
+ index += 1
+ with open(emoji_file, "w", encoding="utf-8") as writer:
+ json.dump(self.emoji, writer)
+ return vocab_file, emoji_file
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ # docstyle-ignore
+ """
+ The tokenizer returns token_type_ids as separators between the Prefix part and the rest.
+ token_type_ids is 1 for the Prefix part and 0 for the rest of the token.
+
+ Example:
+ ```python
+ >>> from transformers import GPTSanJapaneseTokenizer
+
+ >>> tokenizer = GPTSanJapaneseTokenizer.from_pretrained("Tanrei/GPTSAN-japanese")
+ >>> x_token = tokenizer("アイウエ")
+ >>> # input_ids: | SOT | SEG | ア | イ | ウ | エ |
+ >>> # token_type_ids: | 1 | 0 | 0 | 0 | 0 | 0 |
+
+ >>> x_token = tokenizer("", prefix_text="アイウエ")
+ >>> # input_ids: | SOT | ア | イ | ウ | エ | SEG |
+ >>> # token_type_ids: | 1 | 1 | 1 | 1 | 1 | 0 |
+
+ >>> x_token = tokenizer("ウエ", prefix_text="アイ")
+ >>> # input_ids: | SOT | ア | イ | SEG | ウ | エ |
+ >>> # token_type_ids: | 1 | 1 | 1 | 0 | 0 | 0 |
+ ```"""
+ prefix_len = 0
+ if self.sep_token in self.vocab:
+ segid = self.vocab[self.sep_token]
+ if segid in token_ids_0:
+ prefix_len = token_ids_0.index(segid)
+ if token_ids_1 is None:
+ total_len = len(token_ids_0)
+ else:
+ total_len = len(token_ids_0 + token_ids_1)
+ return prefix_len * [1] + (total_len - prefix_len) * [0]
+
+ def prepare_for_tokenization(self, text, prefix_text=None, add_sep_token=None, **kwargs):
+ # GPTSAN inserts extra SEP tokens in Prefix-LM in addition to SOT for text generation.
+ # SOT at the beginning of the text, and SEP at the separator between the Prefix part and the rest.
+ if add_sep_token is None:
+ add_sep_token = self.sep_token not in text # If insert un-prefix position explicitly
+ prepared = self.bos_token if self.bos_token in self.vocab else ""
+ prepared += prefix_text if prefix_text is not None else ""
+ if add_sep_token:
+ prepared += self.sep_token if self.sep_token in self.vocab else ""
+ prepared += text
+ return (prepared, kwargs)
+
+ def _batch_encode_plus(
+ self,
+ batch_text_or_text_pairs: Union[
+ list[TextInput], list[TextInputPair], list[PreTokenizedInput], list[PreTokenizedInputPair]
+ ],
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: Optional[int] = None,
+ stride: int = 0,
+ is_split_into_words: bool = False,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[str] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ # This tokenizer converts input text pairs into Prefix input and subsequent input
+ if isinstance(batch_text_or_text_pairs[0], tuple) or isinstance(tuple(batch_text_or_text_pairs[0]), list):
+ # As a single text with an explicit un-prefix position
+ batch_prefix_texts = []
+ for pref, txt in batch_text_or_text_pairs:
+ batch_prefix_texts.append(pref + self.sep_token + txt)
+ batch_text_or_text_pairs = batch_prefix_texts
+
+ return super()._batch_encode_plus(
+ batch_text_or_text_pairs,
+ add_special_tokens,
+ padding_strategy,
+ truncation_strategy,
+ max_length,
+ stride,
+ is_split_into_words,
+ pad_to_multiple_of,
+ return_tensors,
+ return_token_type_ids,
+ return_attention_mask,
+ return_overflowing_tokens,
+ return_special_tokens_mask,
+ return_offsets_mapping,
+ return_length,
+ verbose,
+ **kwargs,
+ )
+
+
+class SubWordJapaneseTokenizer:
+ """
+ This tokenizer is based on GPTNeoXJapaneseTokenizer and has the following modifications
+ - Decoding byte0~byte255 tokens correctly
+ - Added bagofword token handling
+
+ https://github.com/tanreinama/Japanese-BPEEncoder_V2 This tokenizer class is under MIT License according to the
+ original repository.
+
+ MIT License
+
+ Copyright (c) 2020 tanreinama
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of
+ the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
+ THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ SOFTWARE.
+ """
+
+ def __init__(self, vocab, ids_to_tokens, emoji):
+ self.vocab = vocab # same as swe
+ self.ids_to_tokens = ids_to_tokens # same as bpe
+ self.emoji = emoji
+ self.maxlen = np.max([len(w) for w in self.vocab])
+ self.content_repatter1 = re.compile(r"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)")
+ self.content_repatter2 = re.compile(r"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*")
+ self.content_repatter3 = re.compile(r"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}")
+ self.content_repatter4 = re.compile(
+ r"([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"
+ )
+ self.content_repatter5 = re.compile(
+ r"(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*"
+ )
+ # The original version of this regex displays catastrophic backtracking behaviour. We avoid this using
+ # possessive quantifiers in Py >= 3.11. In versions below this, we avoid the vulnerability using a slightly
+ # different regex that should generally have the same behaviour in most non-pathological cases.
+ if sys.version_info >= (3, 11):
+ self.content_repatter6 = re.compile(
+ r"(?:\d,\d{3}|[\d億])*+"
+ r"(?:\d,\d{3}|[\d万])*+"
+ r"(?:\d,\d{3}|[\d千])*+"
+ r"(?:千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+"
+ r"(?:\(税込\)|\(税抜\)|\+tax)*"
+ )
+ else:
+ self.content_repatter6 = re.compile(
+ r"(?:\d,\d{3}|[\d億万千])*"
+ r"(?:千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+"
+ r"(?:\(税込\)|\(税抜\)|\+tax)*"
+ )
+ keisen = "─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿"
+ blocks = "▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟"
+ self.content_trans1 = str.maketrans(dict.fromkeys(keisen + blocks, ""))
+
+ def __len__(self):
+ return len(self.ids_to_tokens)
+
+ def clean_text(self, content):
+ content = self.content_repatter1.sub("", content)
+ content = self.content_repatter2.sub("", content)
+ content = self.content_repatter3.sub("", content)
+ content = self.content_repatter4.sub("", content)
+ content = self.content_repatter5.sub("", content)
+ content = self.content_repatter6.sub("", content)
+ content = content.translate(self.content_trans1)
+ while "" in content:
+ content = content.replace("", "")
+ return content
+
+ def tokenize(self, text, clean=False):
+ text = text.replace(" ", "")
+ text = text.replace(" ", "")
+ text = text.replace("\r\n", "
")
+ text = text.replace("\n", "
")
+ text = text.replace("\r", "
")
+ text = text.replace("\t", "")
+ text = text.replace("—", "ー")
+ text = text.replace("−", "ー")
+ for k, v in self.emoji["emoji"].items():
+ if k in text:
+ text = text.replace(k, v)
+ if clean:
+ text = self.clean_text(text)
+
+ def check_simbol(x):
+ e = x.encode()
+ if len(x) == 1 and len(e) == 2:
+ c = (int(e[0]) << 8) + int(e[1])
+ if (
+ (c >= 0xC2A1 and c <= 0xC2BF)
+ or (c >= 0xC780 and c <= 0xC783)
+ or (c >= 0xCAB9 and c <= 0xCBBF)
+ or (c >= 0xCC80 and c <= 0xCDA2)
+ ):
+ return True
+ return False
+
+ def checku2e(x):
+ e = x.encode()
+ if len(x) == 1 and len(e) == 3:
+ c = (int(e[0]) << 16) + (int(e[1]) << 8) + int(e[2])
+ if c >= 0xE28080 and c <= 0xE2B07F:
+ return True
+ return False
+
+ pos = 0
+ result = []
+ while pos < len(text):
+ end = min(len(text), pos + self.maxlen + 1) if text[pos] == "<" else pos + 3
+ candidates = [] # (token_id, token, pos)
+ for e in range(end, pos, -1):
+ wd = text[pos:e]
+ if wd in self.vocab:
+ if wd[0] == "<" and len(wd) > 2:
+ candidates = [(self.vocab[wd], wd, e)]
+ break
+ else:
+ candidates.append((self.vocab[wd], wd, e))
+ if len(candidates) > 0:
+ # the smallest token_id is adopted
+ _, wd, e = sorted(candidates, key=lambda x: x[0])[0]
+ result.append(wd)
+ pos = e
+ else:
+ end = pos + 1
+ wd = text[pos:end]
+ if check_simbol(wd):
+ result.append("")
+ elif checku2e(wd):
+ result.append("")
+ else:
+ for i in wd.encode("utf-8"):
+ result.append("<|byte%d|>" % i)
+ pos = end
+ return result
+
+ def convert_id_to_token(self, index):
+ return self.ids_to_tokens[index][0]
+
+
+__all__ = ["GPTSanJapaneseTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a4b3eb1be2b4e69dcad1540abdd91f412de0ca2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_graphormer import *
+ from .modeling_graphormer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..47dc4e30ddd519944b7e7173a7771cbfad3f20fd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/collating_graphormer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/collating_graphormer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1886d2a011ddd0dfd3f0f2e3ce47b033571c9a76
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/collating_graphormer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/configuration_graphormer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/configuration_graphormer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb25704140d4f243556df365a4a3ef7f00b1f130
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/configuration_graphormer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/modeling_graphormer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/modeling_graphormer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bab60baa8a418a66ff766d195b68238d448423de
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/__pycache__/modeling_graphormer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/algos_graphormer.pyx b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/algos_graphormer.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..a0fafbdee53b55efb9596036817b03be0d006992
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/algos_graphormer.pyx
@@ -0,0 +1,107 @@
+# Copyright (c) Microsoft Corporation and HuggingFace
+# Licensed under the MIT License.
+
+import cython
+
+cimport numpy
+from cython.parallel cimport parallel, prange
+
+import numpy as np
+
+
+# Reduce this number if matrices are too big for large graphs
+UNREACHABLE_NODE_DISTANCE = 510
+
+def floyd_warshall(adjacency_matrix):
+ """
+ Applies the Floyd-Warshall algorithm to the adjacency matrix, to compute the
+ shortest paths distance between all nodes, up to UNREACHABLE_NODE_DISTANCE.
+ """
+ (nrows, ncols) = adjacency_matrix.shape
+ assert nrows == ncols
+ cdef unsigned int n = nrows
+
+ adj_mat_copy = adjacency_matrix.astype(np.int32, order='C', casting='safe', copy=True)
+ assert adj_mat_copy.flags['C_CONTIGUOUS']
+ cdef numpy.ndarray[numpy.int32_t, ndim=2, mode='c'] M = adj_mat_copy
+ cdef numpy.ndarray[numpy.int32_t, ndim=2, mode='c'] path = -1 * np.ones([n, n], dtype=np.int32)
+
+ cdef unsigned int i, j, k
+ cdef numpy.int32_t M_ij, M_ik, cost_ikkj
+ cdef numpy.int32_t* M_ptr = &M[0,0]
+ cdef numpy.int32_t* M_i_ptr
+ cdef numpy.int32_t* M_k_ptr
+
+ # set unreachable nodes distance to UNREACHABLE_NODE_DISTANCE
+ for i in range(n):
+ for j in range(n):
+ if i == j:
+ M[i][j] = 0
+ elif M[i][j] == 0:
+ M[i][j] = UNREACHABLE_NODE_DISTANCE
+
+ # floyed algo
+ for k in range(n):
+ M_k_ptr = M_ptr + n*k
+ for i in range(n):
+ M_i_ptr = M_ptr + n*i
+ M_ik = M_i_ptr[k]
+ for j in range(n):
+ cost_ikkj = M_ik + M_k_ptr[j]
+ M_ij = M_i_ptr[j]
+ if M_ij > cost_ikkj:
+ M_i_ptr[j] = cost_ikkj
+ path[i][j] = k
+
+ # set unreachable path to UNREACHABLE_NODE_DISTANCE
+ for i in range(n):
+ for j in range(n):
+ if M[i][j] >= UNREACHABLE_NODE_DISTANCE:
+ path[i][j] = UNREACHABLE_NODE_DISTANCE
+ M[i][j] = UNREACHABLE_NODE_DISTANCE
+
+ return M, path
+
+
+def get_all_edges(path, i, j):
+ """
+ Recursive function to compute all possible paths between two nodes from the graph adjacency matrix.
+ """
+ cdef int k = path[i][j]
+ if k == -1:
+ return []
+ else:
+ return get_all_edges(path, i, k) + [k] + get_all_edges(path, k, j)
+
+
+def gen_edge_input(max_dist, path, edge_feat):
+ """
+ Generates the full edge feature and adjacency matrix.
+ Shape: num_nodes * num_nodes * max_distance_between_nodes * num_edge_features
+ Dim 1 is the input node, dim 2 the output node of the edge, dim 3 the depth of the edge, dim 4 the feature
+ """
+ (nrows, ncols) = path.shape
+ assert nrows == ncols
+ cdef unsigned int n = nrows
+ cdef unsigned int max_dist_copy = max_dist
+
+ path_copy = path.astype(long, order='C', casting='safe', copy=True)
+ edge_feat_copy = edge_feat.astype(long, order='C', casting='safe', copy=True)
+ assert path_copy.flags['C_CONTIGUOUS']
+ assert edge_feat_copy.flags['C_CONTIGUOUS']
+
+ cdef numpy.ndarray[numpy.int32_t, ndim=4, mode='c'] edge_fea_all = -1 * np.ones([n, n, max_dist_copy, edge_feat.shape[-1]], dtype=np.int32)
+ cdef unsigned int i, j, k, num_path, cur
+
+ for i in range(n):
+ for j in range(n):
+ if i == j:
+ continue
+ if path_copy[i][j] == UNREACHABLE_NODE_DISTANCE:
+ continue
+ path = [i] + get_all_edges(path_copy, i, j) + [j]
+ num_path = len(path) - 1
+ for k in range(num_path):
+ edge_fea_all[i, j, k, :] = edge_feat_copy[path[k], path[k+1], :]
+
+ return edge_fea_all
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/collating_graphormer.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/collating_graphormer.py
new file mode 100644
index 0000000000000000000000000000000000000000..19bcaac3f572c75fa247936eac5852e2d8d418ce
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/collating_graphormer.py
@@ -0,0 +1,135 @@
+# Copyright (c) Microsoft Corporation and HuggingFace
+# Licensed under the MIT License.
+
+from collections.abc import Mapping
+from typing import Any
+
+import numpy as np
+import torch
+
+from ....utils import is_cython_available, requires_backends
+
+
+if is_cython_available():
+ import pyximport
+
+ pyximport.install(setup_args={"include_dirs": np.get_include()})
+ from . import algos_graphormer # noqa E402
+
+
+def convert_to_single_emb(x, offset: int = 512):
+ feature_num = x.shape[1] if len(x.shape) > 1 else 1
+ feature_offset = 1 + np.arange(0, feature_num * offset, offset, dtype=np.int64)
+ x = x + feature_offset
+ return x
+
+
+def preprocess_item(item, keep_features=True):
+ requires_backends(preprocess_item, ["cython"])
+
+ if keep_features and "edge_attr" in item: # edge_attr
+ edge_attr = np.asarray(item["edge_attr"], dtype=np.int64)
+ else:
+ edge_attr = np.ones((len(item["edge_index"][0]), 1), dtype=np.int64) # same embedding for all
+
+ if keep_features and "node_feat" in item: # input_nodes
+ node_feature = np.asarray(item["node_feat"], dtype=np.int64)
+ else:
+ node_feature = np.ones((item["num_nodes"], 1), dtype=np.int64) # same embedding for all
+
+ edge_index = np.asarray(item["edge_index"], dtype=np.int64)
+
+ input_nodes = convert_to_single_emb(node_feature) + 1
+ num_nodes = item["num_nodes"]
+
+ if len(edge_attr.shape) == 1:
+ edge_attr = edge_attr[:, None]
+ attn_edge_type = np.zeros([num_nodes, num_nodes, edge_attr.shape[-1]], dtype=np.int64)
+ attn_edge_type[edge_index[0], edge_index[1]] = convert_to_single_emb(edge_attr) + 1
+
+ # node adj matrix [num_nodes, num_nodes] bool
+ adj = np.zeros([num_nodes, num_nodes], dtype=bool)
+ adj[edge_index[0], edge_index[1]] = True
+
+ shortest_path_result, path = algos_graphormer.floyd_warshall(adj)
+ max_dist = np.amax(shortest_path_result)
+
+ input_edges = algos_graphormer.gen_edge_input(max_dist, path, attn_edge_type)
+ attn_bias = np.zeros([num_nodes + 1, num_nodes + 1], dtype=np.single) # with graph token
+
+ # combine
+ item["input_nodes"] = input_nodes + 1 # we shift all indices by one for padding
+ item["attn_bias"] = attn_bias
+ item["attn_edge_type"] = attn_edge_type
+ item["spatial_pos"] = shortest_path_result.astype(np.int64) + 1 # we shift all indices by one for padding
+ item["in_degree"] = np.sum(adj, axis=1).reshape(-1) + 1 # we shift all indices by one for padding
+ item["out_degree"] = item["in_degree"] # for undirected graph
+ item["input_edges"] = input_edges + 1 # we shift all indices by one for padding
+ if "labels" not in item:
+ item["labels"] = item["y"]
+
+ return item
+
+
+class GraphormerDataCollator:
+ def __init__(self, spatial_pos_max=20, on_the_fly_processing=False):
+ if not is_cython_available():
+ raise ImportError("Graphormer preprocessing needs Cython (pyximport)")
+
+ self.spatial_pos_max = spatial_pos_max
+ self.on_the_fly_processing = on_the_fly_processing
+
+ def __call__(self, features: list[dict]) -> dict[str, Any]:
+ if self.on_the_fly_processing:
+ features = [preprocess_item(i) for i in features]
+
+ if not isinstance(features[0], Mapping):
+ features = [vars(f) for f in features]
+ batch = {}
+
+ max_node_num = max(len(i["input_nodes"]) for i in features)
+ node_feat_size = len(features[0]["input_nodes"][0])
+ edge_feat_size = len(features[0]["attn_edge_type"][0][0])
+ max_dist = max(len(i["input_edges"][0][0]) for i in features)
+ edge_input_size = len(features[0]["input_edges"][0][0][0])
+ batch_size = len(features)
+
+ batch["attn_bias"] = torch.zeros(batch_size, max_node_num + 1, max_node_num + 1, dtype=torch.float)
+ batch["attn_edge_type"] = torch.zeros(batch_size, max_node_num, max_node_num, edge_feat_size, dtype=torch.long)
+ batch["spatial_pos"] = torch.zeros(batch_size, max_node_num, max_node_num, dtype=torch.long)
+ batch["in_degree"] = torch.zeros(batch_size, max_node_num, dtype=torch.long)
+ batch["input_nodes"] = torch.zeros(batch_size, max_node_num, node_feat_size, dtype=torch.long)
+ batch["input_edges"] = torch.zeros(
+ batch_size, max_node_num, max_node_num, max_dist, edge_input_size, dtype=torch.long
+ )
+
+ for ix, f in enumerate(features):
+ for k in ["attn_bias", "attn_edge_type", "spatial_pos", "in_degree", "input_nodes", "input_edges"]:
+ f[k] = torch.tensor(f[k])
+
+ if len(f["attn_bias"][1:, 1:][f["spatial_pos"] >= self.spatial_pos_max]) > 0:
+ f["attn_bias"][1:, 1:][f["spatial_pos"] >= self.spatial_pos_max] = float("-inf")
+
+ batch["attn_bias"][ix, : f["attn_bias"].shape[0], : f["attn_bias"].shape[1]] = f["attn_bias"]
+ batch["attn_edge_type"][ix, : f["attn_edge_type"].shape[0], : f["attn_edge_type"].shape[1], :] = f[
+ "attn_edge_type"
+ ]
+ batch["spatial_pos"][ix, : f["spatial_pos"].shape[0], : f["spatial_pos"].shape[1]] = f["spatial_pos"]
+ batch["in_degree"][ix, : f["in_degree"].shape[0]] = f["in_degree"]
+ batch["input_nodes"][ix, : f["input_nodes"].shape[0], :] = f["input_nodes"]
+ batch["input_edges"][
+ ix, : f["input_edges"].shape[0], : f["input_edges"].shape[1], : f["input_edges"].shape[2], :
+ ] = f["input_edges"]
+
+ batch["out_degree"] = batch["in_degree"]
+
+ sample = features[0]["labels"]
+ if len(sample) == 1: # one task
+ if isinstance(sample[0], float): # regression
+ batch["labels"] = torch.from_numpy(np.concatenate([i["labels"] for i in features]))
+ else: # binary classification
+ batch["labels"] = torch.from_numpy(np.concatenate([i["labels"] for i in features]))
+ else: # multi task classification, left to float to keep the NaNs
+ batch["labels"] = torch.from_numpy(np.stack([i["labels"] for i in features], axis=0))
+
+ return batch
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/configuration_graphormer.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/configuration_graphormer.py
new file mode 100644
index 0000000000000000000000000000000000000000..81c13c6a802b3128d4f88b23f59ac31e8484e901
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/configuration_graphormer.py
@@ -0,0 +1,220 @@
+# coding=utf-8
+# Copyright 2022 Microsoft, clefourrier and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Graphormer model configuration"""
+
+from typing import Optional
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class GraphormerConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`~GraphormerModel`]. It is used to instantiate an
+ Graphormer model according to the specified arguments, defining the model architecture. Instantiating a
+ configuration with the defaults will yield a similar configuration to that of the Graphormer
+ [graphormer-base-pcqm4mv1](https://huggingface.co/graphormer-base-pcqm4mv1) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ num_classes (`int`, *optional*, defaults to 1):
+ Number of target classes or labels, set to n for binary classification of n tasks.
+ num_atoms (`int`, *optional*, defaults to 512*9):
+ Number of node types in the graphs.
+ num_edges (`int`, *optional*, defaults to 512*3):
+ Number of edges types in the graph.
+ num_in_degree (`int`, *optional*, defaults to 512):
+ Number of in degrees types in the input graphs.
+ num_out_degree (`int`, *optional*, defaults to 512):
+ Number of out degrees types in the input graphs.
+ num_edge_dis (`int`, *optional*, defaults to 128):
+ Number of edge dis in the input graphs.
+ multi_hop_max_dist (`int`, *optional*, defaults to 20):
+ Maximum distance of multi hop edges between two nodes.
+ spatial_pos_max (`int`, *optional*, defaults to 1024):
+ Maximum distance between nodes in the graph attention bias matrices, used during preprocessing and
+ collation.
+ edge_type (`str`, *optional*, defaults to multihop):
+ Type of edge relation chosen.
+ max_nodes (`int`, *optional*, defaults to 512):
+ Maximum number of nodes which can be parsed for the input graphs.
+ share_input_output_embed (`bool`, *optional*, defaults to `False`):
+ Shares the embedding layer between encoder and decoder - careful, True is not implemented.
+ num_layers (`int`, *optional*, defaults to 12):
+ Number of layers.
+ embedding_dim (`int`, *optional*, defaults to 768):
+ Dimension of the embedding layer in encoder.
+ ffn_embedding_dim (`int`, *optional*, defaults to 768):
+ Dimension of the "intermediate" (often named feed-forward) layer in encoder.
+ num_attention_heads (`int`, *optional*, defaults to 32):
+ Number of attention heads in the encoder.
+ self_attention (`bool`, *optional*, defaults to `True`):
+ Model is self attentive (False not implemented).
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for the attention weights.
+ activation_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for the activation of the linear transformer layer.
+ layerdrop (`float`, *optional*, defaults to 0.0):
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
+ for more details.
+ bias (`bool`, *optional*, defaults to `True`):
+ Uses bias in the attention module - unsupported at the moment.
+ embed_scale(`float`, *optional*, defaults to None):
+ Scaling factor for the node embeddings.
+ num_trans_layers_to_freeze (`int`, *optional*, defaults to 0):
+ Number of transformer layers to freeze.
+ encoder_normalize_before (`bool`, *optional*, defaults to `False`):
+ Normalize features before encoding the graph.
+ pre_layernorm (`bool`, *optional*, defaults to `False`):
+ Apply layernorm before self attention and the feed forward network. Without this, post layernorm will be
+ used.
+ apply_graphormer_init (`bool`, *optional*, defaults to `False`):
+ Apply a custom graphormer initialisation to the model before training.
+ freeze_embeddings (`bool`, *optional*, defaults to `False`):
+ Freeze the embedding layer, or train it along the model.
+ encoder_normalize_before (`bool`, *optional*, defaults to `False`):
+ Apply the layer norm before each encoder block.
+ q_noise (`float`, *optional*, defaults to 0.0):
+ Amount of quantization noise (see "Training with Quantization Noise for Extreme Model Compression"). (For
+ more detail, see fairseq's documentation on quant_noise).
+ qn_block_size (`int`, *optional*, defaults to 8):
+ Size of the blocks for subsequent quantization with iPQ (see q_noise).
+ kdim (`int`, *optional*, defaults to None):
+ Dimension of the key in the attention, if different from the other values.
+ vdim (`int`, *optional*, defaults to None):
+ Dimension of the value in the attention, if different from the other values.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models).
+ traceable (`bool`, *optional*, defaults to `False`):
+ Changes return value of the encoder's inner_state to stacked tensors.
+
+ Example:
+ ```python
+ >>> from transformers import GraphormerForGraphClassification, GraphormerConfig
+
+ >>> # Initializing a Graphormer graphormer-base-pcqm4mv2 style configuration
+ >>> configuration = GraphormerConfig()
+
+ >>> # Initializing a model from the graphormer-base-pcqm4mv1 style configuration
+ >>> model = GraphormerForGraphClassification(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```
+ """
+
+ model_type = "graphormer"
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ def __init__(
+ self,
+ num_classes: int = 1,
+ num_atoms: int = 512 * 9,
+ num_edges: int = 512 * 3,
+ num_in_degree: int = 512,
+ num_out_degree: int = 512,
+ num_spatial: int = 512,
+ num_edge_dis: int = 128,
+ multi_hop_max_dist: int = 5, # sometimes is 20
+ spatial_pos_max: int = 1024,
+ edge_type: str = "multi_hop",
+ max_nodes: int = 512,
+ share_input_output_embed: bool = False,
+ num_hidden_layers: int = 12,
+ embedding_dim: int = 768,
+ ffn_embedding_dim: int = 768,
+ num_attention_heads: int = 32,
+ dropout: float = 0.1,
+ attention_dropout: float = 0.1,
+ activation_dropout: float = 0.1,
+ layerdrop: float = 0.0,
+ encoder_normalize_before: bool = False,
+ pre_layernorm: bool = False,
+ apply_graphormer_init: bool = False,
+ activation_fn: str = "gelu",
+ embed_scale: Optional[float] = None,
+ freeze_embeddings: bool = False,
+ num_trans_layers_to_freeze: int = 0,
+ traceable: bool = False,
+ q_noise: float = 0.0,
+ qn_block_size: int = 8,
+ kdim: Optional[int] = None,
+ vdim: Optional[int] = None,
+ bias: bool = True,
+ self_attention: bool = True,
+ pad_token_id=0,
+ bos_token_id=1,
+ eos_token_id=2,
+ **kwargs,
+ ):
+ self.num_classes = num_classes
+ self.num_atoms = num_atoms
+ self.num_in_degree = num_in_degree
+ self.num_out_degree = num_out_degree
+ self.num_edges = num_edges
+ self.num_spatial = num_spatial
+ self.num_edge_dis = num_edge_dis
+ self.edge_type = edge_type
+ self.multi_hop_max_dist = multi_hop_max_dist
+ self.spatial_pos_max = spatial_pos_max
+ self.max_nodes = max_nodes
+ self.num_hidden_layers = num_hidden_layers
+ self.embedding_dim = embedding_dim
+ self.hidden_size = embedding_dim
+ self.ffn_embedding_dim = ffn_embedding_dim
+ self.num_attention_heads = num_attention_heads
+ self.dropout = dropout
+ self.attention_dropout = attention_dropout
+ self.activation_dropout = activation_dropout
+ self.layerdrop = layerdrop
+ self.encoder_normalize_before = encoder_normalize_before
+ self.pre_layernorm = pre_layernorm
+ self.apply_graphormer_init = apply_graphormer_init
+ self.activation_fn = activation_fn
+ self.embed_scale = embed_scale
+ self.freeze_embeddings = freeze_embeddings
+ self.num_trans_layers_to_freeze = num_trans_layers_to_freeze
+ self.share_input_output_embed = share_input_output_embed
+ self.traceable = traceable
+ self.q_noise = q_noise
+ self.qn_block_size = qn_block_size
+
+ # These parameters are here for future extensions
+ # atm, the model only supports self attention
+ self.kdim = kdim
+ self.vdim = vdim
+ self.self_attention = self_attention
+ self.bias = bias
+
+ super().__init__(
+ pad_token_id=pad_token_id,
+ bos_token_id=bos_token_id,
+ eos_token_id=eos_token_id,
+ **kwargs,
+ )
+
+
+__all__ = ["GraphormerConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/modeling_graphormer.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/modeling_graphormer.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3e8ea742c8dabd4bd13e34ea84fa60547fc0645
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/graphormer/modeling_graphormer.py
@@ -0,0 +1,912 @@
+# coding=utf-8
+# Copyright 2022 Microsoft, clefourrier The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Graphormer model."""
+
+import math
+from collections.abc import Iterable, Iterator
+from typing import Optional, Union
+
+import torch
+import torch.nn as nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_outputs import (
+ BaseModelOutputWithNoAttention,
+ SequenceClassifierOutput,
+)
+from ....modeling_utils import PreTrainedModel
+from ....utils import logging
+from .configuration_graphormer import GraphormerConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "graphormer-base-pcqm4mv1"
+_CONFIG_FOR_DOC = "GraphormerConfig"
+
+
+def quant_noise(module: nn.Module, p: float, block_size: int):
+ """
+ From:
+ https://github.com/facebookresearch/fairseq/blob/dd0079bde7f678b0cd0715cbd0ae68d661b7226d/fairseq/modules/quant_noise.py
+
+ Wraps modules and applies quantization noise to the weights for subsequent quantization with Iterative Product
+ Quantization as described in "Training with Quantization Noise for Extreme Model Compression"
+
+ Args:
+ - module: nn.Module
+ - p: amount of Quantization Noise
+ - block_size: size of the blocks for subsequent quantization with iPQ
+
+ Remarks:
+ - Module weights must have the right sizes wrt the block size
+ - Only Linear, Embedding and Conv2d modules are supported for the moment
+ - For more detail on how to quantize by blocks with convolutional weights, see "And the Bit Goes Down:
+ Revisiting the Quantization of Neural Networks"
+ - We implement the simplest form of noise here as stated in the paper which consists in randomly dropping
+ blocks
+ """
+
+ # if no quantization noise, don't register hook
+ if p <= 0:
+ return module
+
+ # supported modules
+ if not isinstance(module, (nn.Linear, nn.Embedding, nn.Conv2d)):
+ raise NotImplementedError("Module unsupported for quant_noise.")
+
+ # test whether module.weight has the right sizes wrt block_size
+ is_conv = module.weight.ndim == 4
+
+ # 2D matrix
+ if not is_conv:
+ if module.weight.size(1) % block_size != 0:
+ raise AssertionError("Input features must be a multiple of block sizes")
+
+ # 4D matrix
+ else:
+ # 1x1 convolutions
+ if module.kernel_size == (1, 1):
+ if module.in_channels % block_size != 0:
+ raise AssertionError("Input channels must be a multiple of block sizes")
+ # regular convolutions
+ else:
+ k = module.kernel_size[0] * module.kernel_size[1]
+ if k % block_size != 0:
+ raise AssertionError("Kernel size must be a multiple of block size")
+
+ def _forward_pre_hook(mod, input):
+ # no noise for evaluation
+ if mod.training:
+ if not is_conv:
+ # gather weight and sizes
+ weight = mod.weight
+ in_features = weight.size(1)
+ out_features = weight.size(0)
+
+ # split weight matrix into blocks and randomly drop selected blocks
+ mask = torch.zeros(in_features // block_size * out_features, device=weight.device)
+ mask.bernoulli_(p)
+ mask = mask.repeat_interleave(block_size, -1).view(-1, in_features)
+
+ else:
+ # gather weight and sizes
+ weight = mod.weight
+ in_channels = mod.in_channels
+ out_channels = mod.out_channels
+
+ # split weight matrix into blocks and randomly drop selected blocks
+ if mod.kernel_size == (1, 1):
+ mask = torch.zeros(
+ int(in_channels // block_size * out_channels),
+ device=weight.device,
+ )
+ mask.bernoulli_(p)
+ mask = mask.repeat_interleave(block_size, -1).view(-1, in_channels)
+ else:
+ mask = torch.zeros(weight.size(0), weight.size(1), device=weight.device)
+ mask.bernoulli_(p)
+ mask = mask.unsqueeze(2).unsqueeze(3).repeat(1, 1, mod.kernel_size[0], mod.kernel_size[1])
+
+ # scale weights and apply mask
+ mask = mask.to(torch.bool) # x.bool() is not currently supported in TorchScript
+ s = 1 / (1 - p)
+ mod.weight.data = s * weight.masked_fill(mask, 0)
+
+ module.register_forward_pre_hook(_forward_pre_hook)
+ return module
+
+
+class LayerDropModuleList(nn.ModuleList):
+ """
+ From:
+ https://github.com/facebookresearch/fairseq/blob/dd0079bde7f678b0cd0715cbd0ae68d661b7226d/fairseq/modules/layer_drop.py
+ A LayerDrop implementation based on [`torch.nn.ModuleList`]. LayerDrop as described in
+ https://huggingface.co/papers/1909.11556.
+
+ We refresh the choice of which layers to drop every time we iterate over the LayerDropModuleList instance. During
+ evaluation we always iterate over all layers.
+
+ Usage:
+
+ ```python
+ layers = LayerDropList(p=0.5, modules=[layer1, layer2, layer3])
+ for layer in layers: # this might iterate over layers 1 and 3
+ x = layer(x)
+ for layer in layers: # this might iterate over all layers
+ x = layer(x)
+ for layer in layers: # this might not iterate over any layers
+ x = layer(x)
+ ```
+
+ Args:
+ p (float): probability of dropping out each layer
+ modules (iterable, optional): an iterable of modules to add
+ """
+
+ def __init__(self, p: float, modules: Optional[Iterable[nn.Module]] = None):
+ super().__init__(modules)
+ self.p = p
+
+ def __iter__(self) -> Iterator[nn.Module]:
+ dropout_probs = torch.empty(len(self)).uniform_()
+ for i, m in enumerate(super().__iter__()):
+ if not self.training or (dropout_probs[i] > self.p):
+ yield m
+
+
+class GraphormerGraphNodeFeature(nn.Module):
+ """
+ Compute node features for each node in the graph.
+ """
+
+ def __init__(self, config: GraphormerConfig):
+ super().__init__()
+ self.num_heads = config.num_attention_heads
+ self.num_atoms = config.num_atoms
+
+ self.atom_encoder = nn.Embedding(config.num_atoms + 1, config.hidden_size, padding_idx=config.pad_token_id)
+ self.in_degree_encoder = nn.Embedding(
+ config.num_in_degree, config.hidden_size, padding_idx=config.pad_token_id
+ )
+ self.out_degree_encoder = nn.Embedding(
+ config.num_out_degree, config.hidden_size, padding_idx=config.pad_token_id
+ )
+
+ self.graph_token = nn.Embedding(1, config.hidden_size)
+
+ def forward(
+ self,
+ input_nodes: torch.LongTensor,
+ in_degree: torch.LongTensor,
+ out_degree: torch.LongTensor,
+ ) -> torch.Tensor:
+ n_graph, n_node = input_nodes.size()[:2]
+
+ node_feature = ( # node feature + graph token
+ self.atom_encoder(input_nodes).sum(dim=-2) # [n_graph, n_node, n_hidden]
+ + self.in_degree_encoder(in_degree)
+ + self.out_degree_encoder(out_degree)
+ )
+
+ graph_token_feature = self.graph_token.weight.unsqueeze(0).repeat(n_graph, 1, 1)
+
+ graph_node_feature = torch.cat([graph_token_feature, node_feature], dim=1)
+
+ return graph_node_feature
+
+
+class GraphormerGraphAttnBias(nn.Module):
+ """
+ Compute attention bias for each head.
+ """
+
+ def __init__(self, config: GraphormerConfig):
+ super().__init__()
+ self.num_heads = config.num_attention_heads
+ self.multi_hop_max_dist = config.multi_hop_max_dist
+
+ # We do not change edge feature embedding learning, as edge embeddings are represented as a combination of the original features
+ # + shortest path
+ self.edge_encoder = nn.Embedding(config.num_edges + 1, config.num_attention_heads, padding_idx=0)
+
+ self.edge_type = config.edge_type
+ if self.edge_type == "multi_hop":
+ self.edge_dis_encoder = nn.Embedding(
+ config.num_edge_dis * config.num_attention_heads * config.num_attention_heads,
+ 1,
+ )
+
+ self.spatial_pos_encoder = nn.Embedding(config.num_spatial, config.num_attention_heads, padding_idx=0)
+
+ self.graph_token_virtual_distance = nn.Embedding(1, config.num_attention_heads)
+
+ def forward(
+ self,
+ input_nodes: torch.LongTensor,
+ attn_bias: torch.Tensor,
+ spatial_pos: torch.LongTensor,
+ input_edges: torch.LongTensor,
+ attn_edge_type: torch.LongTensor,
+ ) -> torch.Tensor:
+ n_graph, n_node = input_nodes.size()[:2]
+ graph_attn_bias = attn_bias.clone()
+ graph_attn_bias = graph_attn_bias.unsqueeze(1).repeat(
+ 1, self.num_heads, 1, 1
+ ) # [n_graph, n_head, n_node+1, n_node+1]
+
+ # spatial pos
+ # [n_graph, n_node, n_node, n_head] -> [n_graph, n_head, n_node, n_node]
+ spatial_pos_bias = self.spatial_pos_encoder(spatial_pos).permute(0, 3, 1, 2)
+ graph_attn_bias[:, :, 1:, 1:] = graph_attn_bias[:, :, 1:, 1:] + spatial_pos_bias
+
+ # reset spatial pos here
+ t = self.graph_token_virtual_distance.weight.view(1, self.num_heads, 1)
+ graph_attn_bias[:, :, 1:, 0] = graph_attn_bias[:, :, 1:, 0] + t
+ graph_attn_bias[:, :, 0, :] = graph_attn_bias[:, :, 0, :] + t
+
+ # edge feature
+ if self.edge_type == "multi_hop":
+ spatial_pos_ = spatial_pos.clone()
+
+ spatial_pos_[spatial_pos_ == 0] = 1 # set pad to 1
+ # set 1 to 1, input_nodes > 1 to input_nodes - 1
+ spatial_pos_ = torch.where(spatial_pos_ > 1, spatial_pos_ - 1, spatial_pos_)
+ if self.multi_hop_max_dist > 0:
+ spatial_pos_ = spatial_pos_.clamp(0, self.multi_hop_max_dist)
+ input_edges = input_edges[:, :, :, : self.multi_hop_max_dist, :]
+ # [n_graph, n_node, n_node, max_dist, n_head]
+
+ input_edges = self.edge_encoder(input_edges).mean(-2)
+ max_dist = input_edges.size(-2)
+ edge_input_flat = input_edges.permute(3, 0, 1, 2, 4).reshape(max_dist, -1, self.num_heads)
+ edge_input_flat = torch.bmm(
+ edge_input_flat,
+ self.edge_dis_encoder.weight.reshape(-1, self.num_heads, self.num_heads)[:max_dist, :, :],
+ )
+ input_edges = edge_input_flat.reshape(max_dist, n_graph, n_node, n_node, self.num_heads).permute(
+ 1, 2, 3, 0, 4
+ )
+ input_edges = (input_edges.sum(-2) / (spatial_pos_.float().unsqueeze(-1))).permute(0, 3, 1, 2)
+ else:
+ # [n_graph, n_node, n_node, n_head] -> [n_graph, n_head, n_node, n_node]
+ input_edges = self.edge_encoder(attn_edge_type).mean(-2).permute(0, 3, 1, 2)
+
+ graph_attn_bias[:, :, 1:, 1:] = graph_attn_bias[:, :, 1:, 1:] + input_edges
+ graph_attn_bias = graph_attn_bias + attn_bias.unsqueeze(1) # reset
+
+ return graph_attn_bias
+
+
+class GraphormerMultiheadAttention(nn.Module):
+ """Multi-headed attention.
+
+ See "Attention Is All You Need" for more details.
+ """
+
+ def __init__(self, config: GraphormerConfig):
+ super().__init__()
+ self.embedding_dim = config.embedding_dim
+ self.kdim = config.kdim if config.kdim is not None else config.embedding_dim
+ self.vdim = config.vdim if config.vdim is not None else config.embedding_dim
+ self.qkv_same_dim = self.kdim == config.embedding_dim and self.vdim == config.embedding_dim
+
+ self.num_heads = config.num_attention_heads
+ self.attention_dropout_module = torch.nn.Dropout(p=config.attention_dropout, inplace=False)
+
+ self.head_dim = config.embedding_dim // config.num_attention_heads
+ if not (self.head_dim * config.num_attention_heads == self.embedding_dim):
+ raise AssertionError("The embedding_dim must be divisible by num_heads.")
+ self.scaling = self.head_dim**-0.5
+
+ self.self_attention = True # config.self_attention
+ if not (self.self_attention):
+ raise NotImplementedError("The Graphormer model only supports self attention for now.")
+ if self.self_attention and not self.qkv_same_dim:
+ raise AssertionError("Self-attention requires query, key and value to be of the same size.")
+
+ self.k_proj = quant_noise(
+ nn.Linear(self.kdim, config.embedding_dim, bias=config.bias),
+ config.q_noise,
+ config.qn_block_size,
+ )
+ self.v_proj = quant_noise(
+ nn.Linear(self.vdim, config.embedding_dim, bias=config.bias),
+ config.q_noise,
+ config.qn_block_size,
+ )
+ self.q_proj = quant_noise(
+ nn.Linear(config.embedding_dim, config.embedding_dim, bias=config.bias),
+ config.q_noise,
+ config.qn_block_size,
+ )
+
+ self.out_proj = quant_noise(
+ nn.Linear(config.embedding_dim, config.embedding_dim, bias=config.bias),
+ config.q_noise,
+ config.qn_block_size,
+ )
+
+ self.onnx_trace = False
+
+ def reset_parameters(self):
+ if self.qkv_same_dim:
+ # Empirically observed the convergence to be much better with
+ # the scaled initialization
+ nn.init.xavier_uniform_(self.k_proj.weight, gain=1 / math.sqrt(2))
+ nn.init.xavier_uniform_(self.v_proj.weight, gain=1 / math.sqrt(2))
+ nn.init.xavier_uniform_(self.q_proj.weight, gain=1 / math.sqrt(2))
+ else:
+ nn.init.xavier_uniform_(self.k_proj.weight)
+ nn.init.xavier_uniform_(self.v_proj.weight)
+ nn.init.xavier_uniform_(self.q_proj.weight)
+
+ nn.init.xavier_uniform_(self.out_proj.weight)
+ if self.out_proj.bias is not None:
+ nn.init.constant_(self.out_proj.bias, 0.0)
+
+ def forward(
+ self,
+ query: torch.LongTensor,
+ key: Optional[torch.Tensor],
+ value: Optional[torch.Tensor],
+ attn_bias: Optional[torch.Tensor],
+ key_padding_mask: Optional[torch.Tensor] = None,
+ need_weights: bool = True,
+ attn_mask: Optional[torch.Tensor] = None,
+ before_softmax: bool = False,
+ need_head_weights: bool = False,
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
+ """
+ Args:
+ key_padding_mask (Bytetorch.Tensor, optional): mask to exclude
+ keys that are pads, of shape `(batch, src_len)`, where padding elements are indicated by 1s.
+ need_weights (bool, optional): return the attention weights,
+ averaged over heads (default: False).
+ attn_mask (Bytetorch.Tensor, optional): typically used to
+ implement causal attention, where the mask prevents the attention from looking forward in time
+ (default: None).
+ before_softmax (bool, optional): return the raw attention
+ weights and values before the attention softmax.
+ need_head_weights (bool, optional): return the attention
+ weights for each head. Implies *need_weights*. Default: return the average attention weights over all
+ heads.
+ """
+ if need_head_weights:
+ need_weights = True
+
+ tgt_len, bsz, embedding_dim = query.size()
+ src_len = tgt_len
+ if not (embedding_dim == self.embedding_dim):
+ raise AssertionError(
+ f"The query embedding dimension {embedding_dim} is not equal to the expected embedding_dim"
+ f" {self.embedding_dim}."
+ )
+ if not (list(query.size()) == [tgt_len, bsz, embedding_dim]):
+ raise AssertionError("Query size incorrect in Graphormer, compared to model dimensions.")
+
+ if key is not None:
+ src_len, key_bsz, _ = key.size()
+ if not torch.jit.is_scripting():
+ if (key_bsz != bsz) or (value is None) or not (src_len, bsz == value.shape[:2]):
+ raise AssertionError(
+ "The batch shape does not match the key or value shapes provided to the attention."
+ )
+
+ q = self.q_proj(query)
+ k = self.k_proj(query)
+ v = self.v_proj(query)
+
+ q *= self.scaling
+
+ q = q.contiguous().view(tgt_len, bsz * self.num_heads, self.head_dim).transpose(0, 1)
+ if k is not None:
+ k = k.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
+ if v is not None:
+ v = v.contiguous().view(-1, bsz * self.num_heads, self.head_dim).transpose(0, 1)
+
+ if (k is None) or not (k.size(1) == src_len):
+ raise AssertionError("The shape of the key generated in the attention is incorrect")
+
+ # This is part of a workaround to get around fork/join parallelism
+ # not supporting Optional types.
+ if key_padding_mask is not None and key_padding_mask.dim() == 0:
+ key_padding_mask = None
+
+ if key_padding_mask is not None:
+ if key_padding_mask.size(0) != bsz or key_padding_mask.size(1) != src_len:
+ raise AssertionError(
+ "The shape of the generated padding mask for the key does not match expected dimensions."
+ )
+ attn_weights = torch.bmm(q, k.transpose(1, 2))
+ attn_weights = self.apply_sparse_mask(attn_weights, tgt_len, src_len, bsz)
+
+ if list(attn_weights.size()) != [bsz * self.num_heads, tgt_len, src_len]:
+ raise AssertionError("The attention weights generated do not match the expected dimensions.")
+
+ if attn_bias is not None:
+ attn_weights += attn_bias.view(bsz * self.num_heads, tgt_len, src_len)
+
+ if attn_mask is not None:
+ attn_mask = attn_mask.unsqueeze(0)
+ attn_weights += attn_mask
+
+ if key_padding_mask is not None:
+ # don't attend to padding symbols
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ attn_weights = attn_weights.masked_fill(
+ key_padding_mask.unsqueeze(1).unsqueeze(2).to(torch.bool), float("-inf")
+ )
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ if before_softmax:
+ return attn_weights, v
+
+ attn_weights_float = torch.nn.functional.softmax(attn_weights, dim=-1)
+ attn_weights = attn_weights_float.type_as(attn_weights)
+ attn_probs = self.attention_dropout_module(attn_weights)
+
+ if v is None:
+ raise AssertionError("No value generated")
+ attn = torch.bmm(attn_probs, v)
+ if list(attn.size()) != [bsz * self.num_heads, tgt_len, self.head_dim]:
+ raise AssertionError("The attention generated do not match the expected dimensions.")
+
+ attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, embedding_dim)
+ attn: torch.Tensor = self.out_proj(attn)
+
+ attn_weights = None
+ if need_weights:
+ attn_weights = attn_weights_float.contiguous().view(bsz, self.num_heads, tgt_len, src_len).transpose(1, 0)
+ if not need_head_weights:
+ # average attention weights over heads
+ attn_weights = attn_weights.mean(dim=0)
+
+ return attn, attn_weights
+
+ def apply_sparse_mask(self, attn_weights: torch.Tensor, tgt_len: int, src_len: int, bsz: int) -> torch.Tensor:
+ return attn_weights
+
+
+class GraphormerGraphEncoderLayer(nn.Module):
+ def __init__(self, config: GraphormerConfig) -> None:
+ super().__init__()
+
+ # Initialize parameters
+ self.embedding_dim = config.embedding_dim
+ self.num_attention_heads = config.num_attention_heads
+ self.q_noise = config.q_noise
+ self.qn_block_size = config.qn_block_size
+ self.pre_layernorm = config.pre_layernorm
+
+ self.dropout_module = torch.nn.Dropout(p=config.dropout, inplace=False)
+
+ self.activation_dropout_module = torch.nn.Dropout(p=config.activation_dropout, inplace=False)
+
+ # Initialize blocks
+ self.activation_fn = ACT2FN[config.activation_fn]
+ self.self_attn = GraphormerMultiheadAttention(config)
+
+ # layer norm associated with the self attention layer
+ self.self_attn_layer_norm = nn.LayerNorm(self.embedding_dim)
+
+ self.fc1 = self.build_fc(
+ self.embedding_dim,
+ config.ffn_embedding_dim,
+ q_noise=config.q_noise,
+ qn_block_size=config.qn_block_size,
+ )
+ self.fc2 = self.build_fc(
+ config.ffn_embedding_dim,
+ self.embedding_dim,
+ q_noise=config.q_noise,
+ qn_block_size=config.qn_block_size,
+ )
+
+ # layer norm associated with the position wise feed-forward NN
+ self.final_layer_norm = nn.LayerNorm(self.embedding_dim)
+
+ def build_fc(
+ self, input_dim: int, output_dim: int, q_noise: float, qn_block_size: int
+ ) -> Union[nn.Module, nn.Linear, nn.Embedding, nn.Conv2d]:
+ return quant_noise(nn.Linear(input_dim, output_dim), q_noise, qn_block_size)
+
+ def forward(
+ self,
+ input_nodes: torch.Tensor,
+ self_attn_bias: Optional[torch.Tensor] = None,
+ self_attn_mask: Optional[torch.Tensor] = None,
+ self_attn_padding_mask: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
+ """
+ nn.LayerNorm is applied either before or after the self-attention/ffn modules similar to the original
+ Transformer implementation.
+ """
+ residual = input_nodes
+ if self.pre_layernorm:
+ input_nodes = self.self_attn_layer_norm(input_nodes)
+
+ input_nodes, attn = self.self_attn(
+ query=input_nodes,
+ key=input_nodes,
+ value=input_nodes,
+ attn_bias=self_attn_bias,
+ key_padding_mask=self_attn_padding_mask,
+ need_weights=False,
+ attn_mask=self_attn_mask,
+ )
+ input_nodes = self.dropout_module(input_nodes)
+ input_nodes = residual + input_nodes
+ if not self.pre_layernorm:
+ input_nodes = self.self_attn_layer_norm(input_nodes)
+
+ residual = input_nodes
+ if self.pre_layernorm:
+ input_nodes = self.final_layer_norm(input_nodes)
+ input_nodes = self.activation_fn(self.fc1(input_nodes))
+ input_nodes = self.activation_dropout_module(input_nodes)
+ input_nodes = self.fc2(input_nodes)
+ input_nodes = self.dropout_module(input_nodes)
+ input_nodes = residual + input_nodes
+ if not self.pre_layernorm:
+ input_nodes = self.final_layer_norm(input_nodes)
+
+ return input_nodes, attn
+
+
+class GraphormerGraphEncoder(nn.Module):
+ def __init__(self, config: GraphormerConfig):
+ super().__init__()
+
+ self.dropout_module = torch.nn.Dropout(p=config.dropout, inplace=False)
+ self.layerdrop = config.layerdrop
+ self.embedding_dim = config.embedding_dim
+ self.apply_graphormer_init = config.apply_graphormer_init
+ self.traceable = config.traceable
+
+ self.graph_node_feature = GraphormerGraphNodeFeature(config)
+ self.graph_attn_bias = GraphormerGraphAttnBias(config)
+
+ self.embed_scale = config.embed_scale
+
+ if config.q_noise > 0:
+ self.quant_noise = quant_noise(
+ nn.Linear(self.embedding_dim, self.embedding_dim, bias=False),
+ config.q_noise,
+ config.qn_block_size,
+ )
+ else:
+ self.quant_noise = None
+
+ if config.encoder_normalize_before:
+ self.emb_layer_norm = nn.LayerNorm(self.embedding_dim)
+ else:
+ self.emb_layer_norm = None
+
+ if config.pre_layernorm:
+ self.final_layer_norm = nn.LayerNorm(self.embedding_dim)
+
+ if self.layerdrop > 0.0:
+ self.layers = LayerDropModuleList(p=self.layerdrop)
+ else:
+ self.layers = nn.ModuleList([])
+ self.layers.extend([GraphormerGraphEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+
+ # Apply initialization of model params after building the model
+ if config.freeze_embeddings:
+ raise NotImplementedError("Freezing embeddings is not implemented yet.")
+
+ for layer in range(config.num_trans_layers_to_freeze):
+ m = self.layers[layer]
+ if m is not None:
+ for p in m.parameters():
+ p.requires_grad = False
+
+ def forward(
+ self,
+ input_nodes: torch.LongTensor,
+ input_edges: torch.LongTensor,
+ attn_bias: torch.Tensor,
+ in_degree: torch.LongTensor,
+ out_degree: torch.LongTensor,
+ spatial_pos: torch.LongTensor,
+ attn_edge_type: torch.LongTensor,
+ perturb=None,
+ last_state_only: bool = False,
+ token_embeddings: Optional[torch.Tensor] = None,
+ attn_mask: Optional[torch.Tensor] = None,
+ ) -> tuple[Union[torch.Tensor, list[torch.LongTensor]], torch.Tensor]:
+ # compute padding mask. This is needed for multi-head attention
+ data_x = input_nodes
+ n_graph, n_node = data_x.size()[:2]
+ padding_mask = (data_x[:, :, 0]).eq(0)
+ padding_mask_cls = torch.zeros(n_graph, 1, device=padding_mask.device, dtype=padding_mask.dtype)
+ padding_mask = torch.cat((padding_mask_cls, padding_mask), dim=1)
+
+ attn_bias = self.graph_attn_bias(input_nodes, attn_bias, spatial_pos, input_edges, attn_edge_type)
+
+ if token_embeddings is not None:
+ input_nodes = token_embeddings
+ else:
+ input_nodes = self.graph_node_feature(input_nodes, in_degree, out_degree)
+
+ if perturb is not None:
+ input_nodes[:, 1:, :] += perturb
+
+ if self.embed_scale is not None:
+ input_nodes = input_nodes * self.embed_scale
+
+ if self.quant_noise is not None:
+ input_nodes = self.quant_noise(input_nodes)
+
+ if self.emb_layer_norm is not None:
+ input_nodes = self.emb_layer_norm(input_nodes)
+
+ input_nodes = self.dropout_module(input_nodes)
+
+ input_nodes = input_nodes.transpose(0, 1)
+
+ inner_states = []
+ if not last_state_only:
+ inner_states.append(input_nodes)
+
+ for layer in self.layers:
+ input_nodes, _ = layer(
+ input_nodes,
+ self_attn_padding_mask=padding_mask,
+ self_attn_mask=attn_mask,
+ self_attn_bias=attn_bias,
+ )
+ if not last_state_only:
+ inner_states.append(input_nodes)
+
+ graph_rep = input_nodes[0, :, :]
+
+ if last_state_only:
+ inner_states = [input_nodes]
+
+ if self.traceable:
+ return torch.stack(inner_states), graph_rep
+ else:
+ return inner_states, graph_rep
+
+
+class GraphormerDecoderHead(nn.Module):
+ def __init__(self, embedding_dim: int, num_classes: int):
+ super().__init__()
+ """num_classes should be 1 for regression, or the number of classes for classification"""
+ self.lm_output_learned_bias = nn.Parameter(torch.zeros(1))
+ self.classifier = nn.Linear(embedding_dim, num_classes, bias=False)
+ self.num_classes = num_classes
+
+ def forward(self, input_nodes: torch.Tensor, **unused) -> torch.Tensor:
+ input_nodes = self.classifier(input_nodes)
+ input_nodes = input_nodes + self.lm_output_learned_bias
+ return input_nodes
+
+
+class GraphormerPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: GraphormerConfig
+ base_model_prefix = "graphormer"
+ main_input_name_nodes = "input_nodes"
+ main_input_name_edges = "input_edges"
+
+ def normal_(self, data: torch.Tensor):
+ # with FSDP, module params will be on CUDA, so we cast them back to CPU
+ # so that the RNG is consistent with and without FSDP
+ data.copy_(data.cpu().normal_(mean=0.0, std=0.02).to(data.device))
+
+ def init_graphormer_params(self, module: Union[nn.Linear, nn.Embedding, GraphormerMultiheadAttention]):
+ """
+ Initialize the weights specific to the Graphormer Model.
+ """
+ if isinstance(module, nn.Linear):
+ self.normal_(module.weight.data)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ if isinstance(module, nn.Embedding):
+ self.normal_(module.weight.data)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ if isinstance(module, GraphormerMultiheadAttention):
+ self.normal_(module.q_proj.weight.data)
+ self.normal_(module.k_proj.weight.data)
+ self.normal_(module.v_proj.weight.data)
+
+ def _init_weights(
+ self,
+ module: Union[
+ nn.Linear, nn.Conv2d, nn.Embedding, nn.LayerNorm, GraphormerMultiheadAttention, GraphormerGraphEncoder
+ ],
+ ):
+ """
+ Initialize the weights
+ """
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ # We might be missing part of the Linear init, dependent on the layer num
+ module.weight.data.normal_(mean=0.0, std=0.02)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=0.02)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, GraphormerMultiheadAttention):
+ module.q_proj.weight.data.normal_(mean=0.0, std=0.02)
+ module.k_proj.weight.data.normal_(mean=0.0, std=0.02)
+ module.v_proj.weight.data.normal_(mean=0.0, std=0.02)
+ module.reset_parameters()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ elif isinstance(module, GraphormerGraphEncoder):
+ if module.apply_graphormer_init:
+ module.apply(self.init_graphormer_params)
+
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+class GraphormerModel(GraphormerPreTrainedModel):
+ """The Graphormer model is a graph-encoder model.
+
+ It goes from a graph to its representation. If you want to use the model for a downstream classification task, use
+ GraphormerForGraphClassification instead. For any other downstream task, feel free to add a new class, or combine
+ this model with a downstream model of your choice, following the example in GraphormerForGraphClassification.
+ """
+
+ def __init__(self, config: GraphormerConfig):
+ super().__init__(config)
+ self.max_nodes = config.max_nodes
+
+ self.graph_encoder = GraphormerGraphEncoder(config)
+
+ self.share_input_output_embed = config.share_input_output_embed
+ self.lm_output_learned_bias = None
+
+ # Remove head is set to true during fine-tuning
+ self.load_softmax = not getattr(config, "remove_head", False)
+
+ self.lm_head_transform_weight = nn.Linear(config.embedding_dim, config.embedding_dim)
+ self.activation_fn = ACT2FN[config.activation_fn]
+ self.layer_norm = nn.LayerNorm(config.embedding_dim)
+
+ self.post_init()
+
+ def reset_output_layer_parameters(self):
+ self.lm_output_learned_bias = nn.Parameter(torch.zeros(1))
+
+ def forward(
+ self,
+ input_nodes: torch.LongTensor,
+ input_edges: torch.LongTensor,
+ attn_bias: torch.Tensor,
+ in_degree: torch.LongTensor,
+ out_degree: torch.LongTensor,
+ spatial_pos: torch.LongTensor,
+ attn_edge_type: torch.LongTensor,
+ perturb: Optional[torch.FloatTensor] = None,
+ masked_tokens: None = None,
+ return_dict: Optional[bool] = None,
+ **unused,
+ ) -> Union[tuple[torch.LongTensor], BaseModelOutputWithNoAttention]:
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ inner_states, graph_rep = self.graph_encoder(
+ input_nodes, input_edges, attn_bias, in_degree, out_degree, spatial_pos, attn_edge_type, perturb=perturb
+ )
+
+ # last inner state, then revert Batch and Graph len
+ input_nodes = inner_states[-1].transpose(0, 1)
+
+ # project masked tokens only
+ if masked_tokens is not None:
+ raise NotImplementedError
+
+ input_nodes = self.layer_norm(self.activation_fn(self.lm_head_transform_weight(input_nodes)))
+
+ # project back to size of vocabulary
+ if self.share_input_output_embed and hasattr(self.graph_encoder.embed_tokens, "weight"):
+ input_nodes = torch.nn.functional.linear(input_nodes, self.graph_encoder.embed_tokens.weight)
+
+ if not return_dict:
+ return tuple(x for x in [input_nodes, inner_states] if x is not None)
+ return BaseModelOutputWithNoAttention(last_hidden_state=input_nodes, hidden_states=inner_states)
+
+ def max_nodes(self):
+ """Maximum output length supported by the encoder."""
+ return self.max_nodes
+
+
+class GraphormerForGraphClassification(GraphormerPreTrainedModel):
+ """
+ This model can be used for graph-level classification or regression tasks.
+
+ It can be trained on
+ - regression (by setting config.num_classes to 1); there should be one float-type label per graph
+ - one task classification (by setting config.num_classes to the number of classes); there should be one integer
+ label per graph
+ - binary multi-task classification (by setting config.num_classes to the number of labels); there should be a list
+ of integer labels for each graph.
+ """
+
+ def __init__(self, config: GraphormerConfig):
+ super().__init__(config)
+ self.encoder = GraphormerModel(config)
+ self.embedding_dim = config.embedding_dim
+ self.num_classes = config.num_classes
+ self.classifier = GraphormerDecoderHead(self.embedding_dim, self.num_classes)
+ self.is_encoder_decoder = True
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def forward(
+ self,
+ input_nodes: torch.LongTensor,
+ input_edges: torch.LongTensor,
+ attn_bias: torch.Tensor,
+ in_degree: torch.LongTensor,
+ out_degree: torch.LongTensor,
+ spatial_pos: torch.LongTensor,
+ attn_edge_type: torch.LongTensor,
+ labels: Optional[torch.LongTensor] = None,
+ return_dict: Optional[bool] = None,
+ **unused,
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ encoder_outputs = self.encoder(
+ input_nodes,
+ input_edges,
+ attn_bias,
+ in_degree,
+ out_degree,
+ spatial_pos,
+ attn_edge_type,
+ return_dict=True,
+ )
+ outputs, hidden_states = encoder_outputs["last_hidden_state"], encoder_outputs["hidden_states"]
+
+ head_outputs = self.classifier(outputs)
+ logits = head_outputs[:, 0, :].contiguous()
+
+ loss = None
+ if labels is not None:
+ mask = ~torch.isnan(labels)
+
+ if self.num_classes == 1: # regression
+ loss_fct = MSELoss()
+ loss = loss_fct(logits[mask].squeeze(), labels[mask].squeeze().float())
+ elif self.num_classes > 1 and len(labels.shape) == 1: # One task classification
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits[mask].view(-1, self.num_classes), labels[mask].view(-1))
+ else: # Binary multi-task classification
+ loss_fct = BCEWithLogitsLoss(reduction="sum")
+ loss = loss_fct(logits[mask], labels[mask])
+
+ if not return_dict:
+ return tuple(x for x in [loss, logits, hidden_states] if x is not None)
+ return SequenceClassifierOutput(loss=loss, logits=logits, hidden_states=hidden_states, attentions=None)
+
+
+__all__ = ["GraphormerForGraphClassification", "GraphormerModel", "GraphormerPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..826bdbddc1f182de43a795ab0d78ad4009507c14
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_jukebox import *
+ from .modeling_jukebox import *
+ from .tokenization_jukebox import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fe0c0fd9b310bc20d96649901960d7785b19986
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/configuration_jukebox.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/configuration_jukebox.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe62f489db8bc5187c8e607b1d600d8e5f77de40
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/configuration_jukebox.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/modeling_jukebox.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/modeling_jukebox.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..afd2b07226b7d1245e3aa5d8fa72470a9b65aba3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/modeling_jukebox.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e34e68efc66ec17a490296794d607971e0f36524145a0236f1a2246cb24eec2c
+size 140843
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/tokenization_jukebox.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/tokenization_jukebox.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..780f27986b76dbc87ad1417c4cacf2219c9e4068
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/__pycache__/tokenization_jukebox.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/configuration_jukebox.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/configuration_jukebox.py
new file mode 100644
index 0000000000000000000000000000000000000000..9bb2e3da54aa232bf934a7922f731796a7146937
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/configuration_jukebox.py
@@ -0,0 +1,613 @@
+# coding=utf-8
+# Copyright 2022 The OpenAI Team Authors and HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Jukebox configuration"""
+
+import os
+from typing import Union
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+_LARGE_ATTENTION = [
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "cross_attention",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "cross_attention",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "cross_attention",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "cross_attention",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "cross_attention",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "cross_attention",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "block_attn",
+ "transpose_block_attn",
+ "prev_block_attn",
+ "cross_attention",
+]
+_RawColumnPreviousRowAttention = ["block_attn", "transpose_block_attn", "prev_block_attn"]
+_FullDenseAttention = ["dense_attention"]
+_PrimePrimeDenseAttention = ["prime_attn", "prime_attn", "dense_attn"]
+
+
+def full_dense_attention(layer):
+ return _FullDenseAttention[0]
+
+
+def raw_column_previous_row_attention(layer):
+ return _RawColumnPreviousRowAttention[layer % 3]
+
+
+def large_separated_enc_dec_w_lyrics(layer):
+ return _LARGE_ATTENTION[layer % 79]
+
+
+def enc_dec_with_lyrics(layer):
+ if layer % 16 == 15:
+ return _PrimePrimeDenseAttention[layer % 3]
+ return _RawColumnPreviousRowAttention[layer % 3]
+
+
+ATTENTION_PATTERNS = {
+ "full_dense_attention": full_dense_attention,
+ "raw_column_previous_row_attention": raw_column_previous_row_attention, # Alternate row, column and previous row attn
+ "large_separated_enc_dec_w_lyrics": large_separated_enc_dec_w_lyrics, # Used by large separated_enc_dec model with lyrics
+ "enc_dec_with_lyrics": enc_dec_with_lyrics, # Used by encoder_decoder model with lyrics
+}
+
+
+class JukeboxPriorConfig(PretrainedConfig):
+ """
+ This is the configuration class to store the configuration of a [`JukeboxPrior`]. It is used to instantiate a
+ `JukeboxPrior` according to the specified arguments, defining the model architecture. Instantiating a
+ configuration with the defaults will yield a similar configuration to that of the top level prior from the
+ [openai/jukebox-1b-lyrics](https://huggingface.co/openai/jukebox
+ -1b-lyrics) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+
+ Args:
+ act_fn (`str`, *optional*, defaults to `"quick_gelu"`):
+ Activation function.
+ alignment_head (`int`, *optional*, defaults to 2):
+ Head that is responsible of the alignment between lyrics and music. Only used to compute the lyric to audio
+ alignment
+ alignment_layer (`int`, *optional*, defaults to 68):
+ Index of the layer that is responsible of the alignment between lyrics and music. Only used to compute the
+ lyric to audio alignment
+ attention_multiplier (`float`, *optional*, defaults to 0.25):
+ Multiplier coefficient used to define the hidden dimension of the attention layers. 0.25 means that
+ 0.25*width of the model will be used.
+ attention_pattern (`str`, *optional*, defaults to `"enc_dec_with_lyrics"`):
+ Which attention pattern to use for the decoder/
+ attn_dropout (`int`, *optional*, defaults to 0):
+ Dropout probability for the post-attention layer dropout in the decoder.
+ attn_res_scale (`bool`, *optional*, defaults to `False`):
+ Whether or not to scale the residuals in the attention conditioner block.
+ blocks (`int`, *optional*, defaults to 64):
+ Number of blocks used in the `block_attn`. A sequence of length seq_len is factored as `[blocks, seq_len //
+ blocks]` in the `JukeboxAttention` layer.
+ conv_res_scale (`int`, *optional*):
+ Whether or not to scale the residuals in the conditioner block. Since the top level prior does not have a
+ conditioner, the default value is to None and should not be modified.
+ num_layers (`int`, *optional*, defaults to 72):
+ Number of layers of the transformer architecture.
+ emb_dropout (`int`, *optional*, defaults to 0):
+ Embedding dropout used in the lyric decoder.
+ encoder_config (`JukeboxPriorConfig`, *optional*) :
+ Configuration of the encoder which models the prior on the lyrics.
+ encoder_loss_fraction (`float`, *optional*, defaults to 0.4):
+ Multiplication factor used in front of the lyric encoder loss.
+ hidden_size (`int`, *optional*, defaults to 2048):
+ Hidden dimension of the attention layers.
+ init_scale (`float`, *optional*, defaults to 0.2):
+ Initialization scales for the prior modules.
+ is_encoder_decoder (`bool`, *optional*, defaults to `True`):
+ Whether or not the prior is an encoder-decoder model. In case it is not, and `nb_relevant_lyric_tokens` is
+ greater than 0, the `encoder` args should be specified for the lyric encoding.
+ mask (`bool`, *optional*, defaults to `False`):
+ Whether or not to mask the previous positions in the attention.
+ max_duration (`int`, *optional*, defaults to 600):
+ Maximum supported duration of the generated song in seconds.
+ max_nb_genres (`int`, *optional*, defaults to 1):
+ Maximum number of genres that can be used to condition the model.
+ merged_decoder (`bool`, *optional*, defaults to `True`):
+ Whether or not the decoder and the encoder inputs are merged. This is used for the separated
+ encoder-decoder architecture
+ metadata_conditioning (`bool`, *optional*, defaults to `True)`:
+ Whether or not to condition on the artist and genre metadata.
+ metadata_dims (`List[int]`, *optional*, defaults to `[604, 7898]`):
+ Number of genres and the number of artists that were used to train the embedding layers of the prior
+ models.
+ min_duration (`int`, *optional*, defaults to 0):
+ Minimum duration of the generated audio on which the model was trained.
+ mlp_multiplier (`float`, *optional*, defaults to 1.0):
+ Multiplier coefficient used to define the hidden dimension of the MLP layers. 0.25 means that 0.25*width of
+ the model will be used.
+ music_vocab_size (`int`, *optional*, defaults to 2048):
+ Number of different music tokens. Should be similar to the `JukeboxVQVAEConfig.nb_discrete_codes`.
+ n_ctx (`int`, *optional*, defaults to 6144):
+ Number of context tokens for each prior. The context tokens are the music tokens that are attended to when
+ generating music tokens.
+ n_heads (`int`, *optional*, defaults to 2):
+ Number of attention heads.
+ nb_relevant_lyric_tokens (`int`, *optional*, defaults to 384):
+ Number of lyric tokens that are used when sampling a single window of length `n_ctx`
+ res_conv_depth (`int`, *optional*, defaults to 3):
+ Depth of the `JukeboxDecoderConvBock` used to upsample the previously sampled audio in the
+ `JukeboxMusicTokenConditioner`.
+ res_conv_width (`int`, *optional*, defaults to 128):
+ Width of the `JukeboxDecoderConvBock` used to upsample the previously sampled audio in the
+ `JukeboxMusicTokenConditioner`.
+ res_convolution_multiplier (`int`, *optional*, defaults to 1):
+ Multiplier used to scale the `hidden_dim` of the `JukeboxResConv1DBlock`.
+ res_dilation_cycle (`int`, *optional*):
+ Dilation cycle used to define the `JukeboxMusicTokenConditioner`. Usually similar to the ones used in the
+ corresponding level of the VQVAE. The first prior does not use it as it is not conditioned on upper level
+ tokens.
+ res_dilation_growth_rate (`int`, *optional*, defaults to 1):
+ Dilation grow rate used between each convolutionnal block of the `JukeboxMusicTokenConditioner`
+ res_downs_t (`List[int]`, *optional*, defaults to `[3, 2, 2]`):
+ Downsampling rates used in the audio conditioning network
+ res_strides_t (`List[int]`, *optional*, defaults to `[2, 2, 2]`):
+ Striding used in the audio conditioning network
+ resid_dropout (`int`, *optional*, defaults to 0):
+ Residual dropout used in the attention pattern.
+ sampling_rate (`int`, *optional*, defaults to 44100):
+ Sampling rate used for training.
+ spread (`int`, *optional*):
+ Spread used in the `summary_spread_attention` pattern
+ timing_dims (`int`, *optional*, defaults to 64):
+ Dimension of the timing embedding.
+ zero_out (`bool`, *optional*, defaults to `False`):
+ Whether or not to zero out convolution weights when initializing.
+ """
+
+ model_type = "jukebox_prior"
+ attribute_map = {
+ "max_position_embeddings": "n_positions",
+ "num_attention_heads": "n_head",
+ }
+
+ def __init__(
+ self,
+ act_fn="quick_gelu",
+ level=0,
+ alignment_head=2,
+ alignment_layer=68,
+ attention_multiplier=0.25,
+ attention_pattern="enc_dec_with_lyrics",
+ attn_dropout=0,
+ attn_res_scale=False,
+ blocks=64,
+ conv_res_scale=None,
+ num_layers=72,
+ emb_dropout=0,
+ encoder_config=None,
+ encoder_loss_fraction=0.4,
+ hidden_size=2048,
+ init_scale=0.2,
+ is_encoder_decoder=True,
+ lyric_vocab_size=80,
+ mask=False,
+ max_duration=600,
+ max_nb_genres=1,
+ merged_decoder=True,
+ metadata_conditioning=True,
+ metadata_dims=[604, 7898],
+ min_duration=0,
+ mlp_multiplier=1.0,
+ music_vocab_size=2048,
+ n_ctx=6144,
+ n_heads=2,
+ nb_relevant_lyric_tokens=384,
+ res_conv_depth=3,
+ res_conv_width=128,
+ res_convolution_multiplier=1,
+ res_dilation_cycle=None,
+ res_dilation_growth_rate=1,
+ res_downs_t=[3, 2, 2],
+ res_strides_t=[2, 2, 2],
+ resid_dropout=0,
+ sampling_rate=44100,
+ spread=None,
+ timing_dims=64,
+ zero_out=False,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.act_fn = act_fn
+ self.alignment_head = alignment_head
+ self.alignment_layer = alignment_layer
+ self.attention_multiplier = attention_multiplier
+ self.attention_pattern = attention_pattern
+ self.attn_dropout = attn_dropout
+ self.attn_res_scale = attn_res_scale
+ self.blocks = blocks
+ self.conv_res_scale = conv_res_scale
+ self.num_layers = num_layers
+ self.emb_dropout = emb_dropout
+ self.music_vocab_size = music_vocab_size
+ if encoder_config is not None:
+ self.encoder_config = JukeboxPriorConfig(**encoder_config)
+ else:
+ self.encoder_config = None
+ self.encoder_loss_fraction = encoder_loss_fraction
+ self.init_scale = init_scale
+ self.is_encoder_decoder = is_encoder_decoder
+ self.lyric_vocab_size = lyric_vocab_size
+ self.level = level
+ self.mask = mask
+ self.max_duration = max_duration
+ self.max_nb_genres = max_nb_genres
+ self.merged_decoder = merged_decoder
+ self.metadata_conditioning = metadata_conditioning
+ self.metadata_dims = metadata_dims
+ self.min_duration = min_duration
+ self.mlp_multiplier = mlp_multiplier
+ self.n_ctx = n_ctx
+ self.n_heads = n_heads
+ self.nb_relevant_lyric_tokens = nb_relevant_lyric_tokens
+ self.res_conv_depth = res_conv_depth
+ self.res_conv_width = res_conv_width
+ self.res_convolution_multiplier = res_convolution_multiplier
+ self.res_dilation_cycle = res_dilation_cycle
+ self.res_dilation_growth_rate = res_dilation_growth_rate
+ self.res_downs_t = res_downs_t
+ self.res_strides_t = res_strides_t
+ self.resid_dropout = resid_dropout
+ self.sampling_rate = sampling_rate
+ self.spread = spread
+ self.timing_dims = timing_dims
+ self.hidden_size = hidden_size
+ self.zero_out = zero_out
+
+ @classmethod
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], level=0, **kwargs):
+ cls._set_token_in_kwargs(kwargs)
+
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
+
+ # get the prior config dict if we are loading from JukeboxConfig
+ if config_dict.get("model_type") == "jukebox":
+ config_dict = config_dict[f"prior_{level}"]
+
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
+ logger.warning(
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
+ )
+
+ return cls.from_dict(config_dict, **kwargs)
+
+
+class JukeboxVQVAEConfig(PretrainedConfig):
+ """
+ This is the configuration class to store the configuration of a [`JukeboxVQVAE`]. It is used to instantiate a
+ `JukeboxVQVAE` according to the specified arguments, defining the model architecture. Instantiating a configuration
+ with the defaults will yield a similar configuration to that of the VQVAE from
+ [openai/jukebox-1b-lyrics](https://huggingface.co/openai/jukebox-1b-lyrics) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ act_fn (`str`, *optional*, defaults to `"relu"`):
+ Activation function of the model.
+ nb_discrete_codes (`int`, *optional*, defaults to 2048):
+ Number of codes of the VQVAE.
+ commit (`float`, *optional*, defaults to 0.02):
+ Commit loss multiplier.
+ conv_input_shape (`int`, *optional*, defaults to 1):
+ Number of audio channels.
+ conv_res_scale (`bool`, *optional*, defaults to `False`):
+ Whether or not to scale the residuals of the `JukeboxResConv1DBlock`.
+ embed_dim (`int`, *optional*, defaults to 64):
+ Embedding dimension of the codebook vectors.
+ hop_fraction (`List[int]`, *optional*, defaults to `[0.125, 0.5, 0.5]`):
+ Fraction of non-intersecting window used when continuing the sampling process.
+ levels (`int`, *optional*, defaults to 3):
+ Number of hierarchical levels that used in the VQVAE.
+ lmu (`float`, *optional*, defaults to 0.99):
+ Used in the codebook update, exponential moving average coefficient. For more detail refer to Appendix A.1
+ of the original [VQVAE paper](https://huggingface.co/papers/1711.00937v2.pdf)
+ multipliers (`List[int]`, *optional*, defaults to `[2, 1, 1]`):
+ Depth and width multipliers used for each level. Used on the `res_conv_width` and `res_conv_depth`
+ res_conv_depth (`int`, *optional*, defaults to 4):
+ Depth of the encoder and decoder block. If no `multipliers` are used, this is the same for each level.
+ res_conv_width (`int`, *optional*, defaults to 32):
+ Width of the encoder and decoder block. If no `multipliers` are used, this is the same for each level.
+ res_convolution_multiplier (`int`, *optional*, defaults to 1):
+ Scaling factor of the hidden dimension used in the `JukeboxResConv1DBlock`.
+ res_dilation_cycle (`int`, *optional*):
+ Dilation cycle value used in the `JukeboxResnet`. If an int is used, each new Conv1 block will have a depth
+ reduced by a power of `res_dilation_cycle`.
+ res_dilation_growth_rate (`int`, *optional*, defaults to 3):
+ Resnet dilation growth rate used in the VQVAE (dilation_growth_rate ** depth)
+ res_downs_t (`List[int]`, *optional*, defaults to `[3, 2, 2]`):
+ Downsampling rate for each level of the hierarchical VQ-VAE.
+ res_strides_t (`List[int]`, *optional*, defaults to `[2, 2, 2]`):
+ Stride used for each level of the hierarchical VQ-VAE.
+ sample_length (`int`, *optional*, defaults to 1058304):
+ Provides the max input shape of the VQVAE. Is used to compute the input shape of each level.
+ init_scale (`float`, *optional*, defaults to 0.2):
+ Initialization scale.
+ zero_out (`bool`, *optional*, defaults to `False`):
+ Whether or not to zero out convolution weights when initializing.
+ """
+
+ model_type = "jukebox_vqvae"
+
+ def __init__(
+ self,
+ act_fn="relu",
+ nb_discrete_codes=2048,
+ commit=0.02,
+ conv_input_shape=1,
+ conv_res_scale=False,
+ embed_dim=64,
+ hop_fraction=[0.125, 0.5, 0.5],
+ levels=3,
+ lmu=0.99,
+ multipliers=[2, 1, 1],
+ res_conv_depth=4,
+ res_conv_width=32,
+ res_convolution_multiplier=1,
+ res_dilation_cycle=None,
+ res_dilation_growth_rate=3,
+ res_downs_t=[3, 2, 2],
+ res_strides_t=[2, 2, 2],
+ sample_length=1058304,
+ init_scale=0.2,
+ zero_out=False,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.hop_fraction = hop_fraction
+ self.conv_input_shape = conv_input_shape
+ self.sample_length = sample_length
+
+ # VQVAE parameters (all used)
+ self.levels = levels
+ self.embed_dim = embed_dim
+ self.nb_discrete_codes = nb_discrete_codes
+ self.res_conv_width = res_conv_width
+ self.res_conv_depth = res_conv_depth
+ self.res_convolution_multiplier = res_convolution_multiplier
+ self.res_dilation_growth_rate = res_dilation_growth_rate
+ self.res_dilation_cycle = res_dilation_cycle
+ self.multipliers = multipliers
+ self.res_downs_t = res_downs_t
+ self.res_strides_t = res_strides_t
+ self.lmu = lmu
+ self.commit = commit
+ self.conv_res_scale = conv_res_scale
+ self.act_fn = act_fn
+ self.init_scale = init_scale
+ self.zero_out = zero_out
+
+ @classmethod
+ def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], **kwargs):
+ cls._set_token_in_kwargs(kwargs)
+
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
+
+ # get the text config dict if we are loading from CLIPConfig
+ if config_dict.get("model_type") == "jukebox":
+ config_dict = config_dict["vqvae_config"]
+
+ if "model_type" in config_dict and hasattr(cls, "model_type") and config_dict["model_type"] != cls.model_type:
+ logger.warning(
+ f"You are using a model of type {config_dict['model_type']} to instantiate a model of type "
+ f"{cls.model_type}. This is not supported for all configurations of models and can yield errors."
+ )
+
+ return cls.from_dict(config_dict, **kwargs)
+
+
+class JukeboxConfig(PretrainedConfig):
+ """
+ This is the configuration class to store the configuration of a [`JukeboxModel`].
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information. Instantiating a configuration with the defaults will
+ yield a similar configuration to that of
+ [openai/jukebox-1b-lyrics](https://huggingface.co/openai/jukebox-1b-lyrics) architecture.
+
+
+ The downsampling and stride are used to determine downsampling of the input sequence. For example, downsampling =
+ (5,3), and strides = (2, 2) will downsample the audio by 2^5 = 32 to get the first level of codes, and 2**8 = 256
+ to get the second level codes. This is mostly true for training the top level prior and the upsamplers.
+
+ Args:
+ vqvae_config (`JukeboxVQVAEConfig`, *optional*):
+ Configuration for the `JukeboxVQVAE` model.
+ prior_config_list (`List[JukeboxPriorConfig]`, *optional*):
+ List of the configs for each of the `JukeboxPrior` of the model. The original architecture uses 3 priors.
+ nb_priors (`int`, *optional*, defaults to 3):
+ Number of prior models that will sequentially sample tokens. Each prior is conditional auto regressive
+ (decoder) model, apart from the top prior, which can include a lyric encoder. The available models were
+ trained using a top prior and 2 upsampler priors.
+ sampling_rate (`int`, *optional*, defaults to 44100):
+ Sampling rate of the raw audio.
+ timing_dims (`int`, *optional*, defaults to 64):
+ Dimensions of the JukeboxRangeEmbedding layer which is equivalent to traditional positional embedding
+ layer. The timing embedding layer converts the absolute and relative position in the currently sampled
+ audio to a tensor of length `timing_dims` that will be added to the music tokens.
+ min_duration (`int`, *optional*, defaults to 0):
+ Minimum duration of the audios to generate
+ max_duration (`float`, *optional*, defaults to 600.0):
+ Maximum duration of the audios to generate
+ max_nb_genres (`int`, *optional*, defaults to 5):
+ Maximum number of genres that can be used to condition a single sample.
+ metadata_conditioning (`bool`, *optional*, defaults to `True`):
+ Whether or not to use metadata conditioning, corresponding to the artist, the genre and the min/maximum
+ duration.
+
+ Example:
+
+ ```python
+ >>> from transformers import JukeboxModel, JukeboxConfig
+
+ >>> # Initializing a Jukebox configuration
+ >>> configuration = JukeboxConfig()
+
+ >>> # Initializing a model from the configuration
+ >>> model = JukeboxModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```
+ """
+
+ model_type = "jukebox"
+
+ def __init__(
+ self,
+ vqvae_config=None,
+ prior_config_list=None,
+ nb_priors=3,
+ sampling_rate=44100,
+ timing_dims=64,
+ min_duration=0,
+ max_duration=600.0,
+ max_nb_genres=5,
+ metadata_conditioning=True,
+ **kwargs,
+ ):
+ if vqvae_config is None:
+ vqvae_config = {}
+ logger.info("vqvae_config is None. initializing the JukeboxVQVAE with default values.")
+
+ self.vqvae_config = JukeboxVQVAEConfig(**vqvae_config)
+ if prior_config_list is not None:
+ self.prior_configs = [JukeboxPriorConfig(**prior_config) for prior_config in prior_config_list]
+ else:
+ self.prior_configs = []
+ for prior_idx in range(nb_priors):
+ prior_config = kwargs.pop(f"prior_{prior_idx}", None)
+ if prior_config is None:
+ prior_config = {}
+ logger.info(
+ f"prior_{prior_idx}'s config is None. Initializing the JukeboxPriorConfig list with default"
+ " values."
+ )
+ self.prior_configs.append(JukeboxPriorConfig(**prior_config))
+
+ self.hop_fraction = self.vqvae_config.hop_fraction
+
+ self.nb_priors = nb_priors
+
+ # Metadata conditioning
+ self.max_nb_genres = max_nb_genres
+ self.sampling_rate = sampling_rate
+ self.timing_dims = timing_dims
+ self.min_duration = min_duration
+ self.max_duration = max_duration
+ self.metadata_conditioning = metadata_conditioning
+
+ super().__init__(**kwargs)
+
+ @classmethod
+ def from_configs(cls, prior_configs: list[JukeboxPriorConfig], vqvae_config: JukeboxVQVAEConfig, **kwargs):
+ r"""
+ Instantiate a [`JukeboxConfig`] (or a derived class) from clip text model configuration and clip vision model
+ configuration.
+
+ Returns:
+ [`JukeboxConfig`]: An instance of a configuration object
+ """
+ prior_config_list = [config.to_dict() for config in prior_configs]
+ return cls(prior_config_list=prior_config_list, vqvae_config_dict=vqvae_config.to_dict(), **kwargs)
+
+ def to_dict(self):
+ # Override the default to_dict to apply to_dict to the list of prior configs.
+ result = super().to_dict()
+ result["prior_config_list"] = [config.to_dict() for config in result.pop("prior_configs")]
+ return result
+
+
+__all__ = ["JukeboxConfig", "JukeboxPriorConfig", "JukeboxVQVAEConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/modeling_jukebox.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/modeling_jukebox.py
new file mode 100644
index 0000000000000000000000000000000000000000..f928d49cf5f73156c1352e1a5cb8695a57a08c1c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/modeling_jukebox.py
@@ -0,0 +1,2670 @@
+# coding=utf-8
+# Copyright 2022 The OpenAI Team Authors and HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Jukebox model."""
+
+import math
+import os
+from typing import Optional
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import nn
+from torch.nn import LayerNorm as FusedLayerNorm
+
+from ....activations import ACT2FN
+from ....modeling_utils import PreTrainedModel
+from ....utils import add_start_docstrings, logging
+from ....utils.logging import tqdm
+from .configuration_jukebox import ATTENTION_PATTERNS, JukeboxConfig, JukeboxPriorConfig, JukeboxVQVAEConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+def filter_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
+ """
+ Filter a distribution of logits using top-k and/or nucleus (top-p) filtering
+
+ Args:
+ logits (`torch.Tensor`):
+ logits distribution shape (vocabulary size)
+ top_k (`int`, *optional*, defaults to 0):
+ When `top_k >0` keep only top key tokens with highest probability (top-k filtering).
+ top_p (`int`, *optional*, defaults to 0):
+ When `top_p>0.0` keep the top tokens with cumulative probability >= `top_p` (nucleus filtering).
+ """
+ logits = logits.clone()
+ top_k = min(top_k, logits.size(-1)) # Safety check
+
+ if top_k > 0:
+ # Remove all tokens with a probability less than the last token of the top-k
+ indices_to_remove = logits < torch.topk(logits, top_k, dim=-1)[0][..., -1:]
+ logits[indices_to_remove] = filter_value
+
+ if top_p > 0.0:
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
+
+ # Remove tokens with cumulative probability above the threshold
+ sorted_indices_to_remove = cumulative_probs > top_p
+ # Shift the indices to the right to keep also the first token above the threshold
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
+ sorted_indices_to_remove[..., 0] = 0
+
+ # indices_to_remove = sorted_indices[sorted_indices_to_remove]
+ indices_to_remove = torch.zeros_like(logits, dtype=torch.bool).scatter_(
+ dim=-1, index=sorted_indices, src=sorted_indices_to_remove
+ )
+ logits[indices_to_remove] = filter_value
+ return logits
+
+
+def get_relevant_lyric_tokens(full_tokens, max_n_lyric_tokens, total_length, offset, duration):
+ """
+ Extract only the relevant tokens based on the character position. A total of `max_n_lyric_tokens` tokens will be
+ returned. If the provided token sequence is smaller, it will be padded, otherwise, only characters ranging from the
+ midpoint - `max_n_lyric_tokens//2` to the midpoint + `max_n_lyric_tokens//2` will be returned. This *focuses* on
+ the most relevant tokens (in time) for the sequence.
+
+ Args:
+ full_tokens (`list[int]`):
+ List containing the token ids of the entire lyrics.
+ total_length (`int`):
+ Total expected length of the music (not all of it is generated, see duration), in samples.
+ offset (`int`):
+ Starting sample in the music. If the offset is greater than 0, the lyrics will be shifted take that into
+ account
+ duration (`int`):
+ Expected duration of the generated music, in samples. The duration has to be smaller than the total length,
+ which represent the overall length of the signal,
+ """
+ full_tokens = full_tokens[0]
+ if len(full_tokens) < max_n_lyric_tokens:
+ tokens = torch.cat(
+ [torch.zeros(max_n_lyric_tokens - len(full_tokens), dtype=torch.long).to(full_tokens.device), full_tokens]
+ )
+ indices = [-1] * (max_n_lyric_tokens - len(full_tokens)) + list(range(0, len(full_tokens)))
+ else:
+ midpoint = int(len(full_tokens) * (offset + duration / 2.0) / total_length)
+ midpoint = min(max(midpoint, max_n_lyric_tokens // 2), len(full_tokens) - max_n_lyric_tokens // 2)
+ tokens = full_tokens[midpoint - max_n_lyric_tokens // 2 : midpoint + max_n_lyric_tokens // 2]
+ indices = list(range(midpoint - max_n_lyric_tokens // 2, midpoint + max_n_lyric_tokens // 2))
+ return tokens.unsqueeze(dim=0), indices
+
+
+# Break total_length into hops/windows of size n_ctx separated by hop_length
+def get_starts(total_length, n_ctx, hop_length):
+ starts = []
+ for start in range(0, total_length - n_ctx + hop_length, hop_length):
+ if start + n_ctx >= total_length:
+ # Last hop could be smaller, we make it n_ctx to maximise context
+ start = total_length - n_ctx
+ starts.append(start)
+ return starts
+
+
+def get_alignment(music_tokens, labels, prior, config):
+ level = prior.levels - 1 # Top level used
+ n_ctx = prior.n_ctx
+ tokens = music_tokens[level]
+ batch_size, total_length = tokens.shape[0], tokens.shape[1]
+ if total_length < n_ctx:
+ padding_length = n_ctx - total_length
+ tokens = torch.cat(
+ [tokens, torch.zeros(batch_size, n_ctx - total_length, dtype=tokens.dtype, device=tokens.device)], dim=1
+ )
+ total_length = tokens.shape[1]
+ else:
+ padding_length = 0
+
+ hop_length = int(config.hop_fraction[-level - 1] * prior.n_ctx)
+ alignment_head, alignment_layer = config.prior_alignment_head[0], config.prior_alignment_layer[0]
+ attn_layers = {alignment_layer}
+ alignment_hops = {}
+ indices_hops = {}
+ for start in tqdm(get_starts(total_length, n_ctx, hop_length), desc="Computing lyric to music alignment "):
+ end = start + n_ctx
+ # set metadata offset, sample_length and lyrics tokens
+ metadata, indices_hop = prior.get_metadata(labels, start, config.sample_length, get_indices=True, offset=0)
+ tokens_bs = torch.chunk(tokens, batch_size, dim=0)
+ metadata_bs = torch.chunk(metadata, batch_size, dim=0)
+ w_hops = []
+ for tokens_i, metadata_i in zip(tokens_bs, metadata_bs):
+ w_hop = prior.forward_tokens(tokens_i[:, start:end], [], metadata_i, get_attn_weights=attn_layers)
+ w_hops.append(w_hop[0][:, alignment_head])
+ del w_hop
+ weights = torch.cat(w_hops, dim=0)
+ del w_hops
+ alignment_hop = weights.to(device="cpu", dtype=torch.float).numpy()
+ del weights
+
+ # alignment_hop has shape (bs, n_ctx, nb_relevant_lyric_tokens)
+ # indices_hop is a list of len=bs, each entry of len hps.nb_relevant_lyric_tokens
+ indices_hops[start] = indices_hop
+ alignment_hops[start] = alignment_hop
+
+ # Combine attn for each hop into attn for full range
+ # Use indices to place them into correct place for corresponding source tokens
+ alignments = []
+ for item in range(batch_size):
+ # Note each item has different length lyrics
+ full_tokens = labels[0, 3:]
+ alignment = np.zeros((total_length, len(full_tokens) + 1))
+ for start in reversed(get_starts(total_length, n_ctx, hop_length)):
+ end = start + n_ctx
+ alignment_hop = alignment_hops[start][item]
+ indices = indices_hops[start][item]
+ alignment[start:end, indices] = alignment_hop
+ alignment = alignment[: total_length - padding_length, :-1] # remove token padding, and last lyric index
+ alignments.append(alignment)
+ return alignments
+
+
+def save_temp_audio(fname, lvl, metas, aud):
+ aud = torch.clamp(aud, -1, 1).cpu().numpy()
+ for i in list(range(aud.shape[0])):
+ if metas is not None:
+ artists, genres, lyrics = list(metas)[i].values()
+ path = f"{fname}/lvl_{lvl}-{artists}-{genres}-{lyrics[:5]}-{i}"
+ np.save(path, aud[i])
+ else:
+ np.save(f"{fname}/lvl_{lvl}-sample-{i}", aud[i])
+
+
+def get_mask(mask, query_length, key_value_length, blocks, spread, device, sample, sample_t):
+ # returns a mask of shape 1 x 1 x query_length x key_value_length or None if masking is not needed.
+ if mask is None or query_length == 1:
+ return None
+ offset = sample_t - query_length if sample else max(key_value_length - query_length, 0)
+ if mask == "autoregressive":
+ # Masked dense
+ mask = torch.ones(query_length, key_value_length, device=device).tril(offset)
+ elif mask == "summary":
+ # Masked summary
+ mask = torch.ones(query_length, query_length, device=device).tril()
+ mask = torch.ones(query_length, query_length, device=device).tril()
+ mask = mask.view(query_length, blocks, query_length // blocks)[:, :-1, -key_value_length // blocks :]
+ mask = (
+ torch.nn.functional.pad(
+ mask,
+ (0, 0, 1, 0),
+ value=1,
+ )
+ .contiguous()
+ .view(query_length, key_value_length)
+ )
+ elif mask == "prime":
+ mask = torch.ones(query_length, key_value_length, device=device).tril(offset)
+ return mask.view(1, 1, query_length, key_value_length)
+
+
+class JukeboxConv1D(nn.Module):
+ def __init__(self, input_width, output_width):
+ super().__init__()
+ self.input_width = input_width
+ self.output_width = output_width
+ weight = torch.empty(input_width, output_width)
+ bias = torch.zeros(output_width)
+ self.weight = nn.Parameter(weight)
+ self.bias = nn.Parameter(bias)
+
+ def forward(self, hidden_states):
+ size_out = (*hidden_states.size()[:-1], self.output_width)
+ hidden_states = torch.addmm(
+ self.bias.type_as(hidden_states),
+ hidden_states.view(-1, hidden_states.size(-1)),
+ self.weight.type_as(hidden_states),
+ )
+ hidden_states = hidden_states.view(*size_out)
+ return hidden_states
+
+
+class JukeboxResConv1DBlock(nn.Module):
+ def __init__(self, config, conv_width, depth=1, res_scale=1.0):
+ super().__init__()
+ hidden_dim = config.res_convolution_multiplier * conv_width
+ dilation = config.res_dilation_growth_rate**depth
+ padding = dilation
+
+ self.res_scale = res_scale
+ self.activation = nn.ReLU()
+ self.conv1d_1 = nn.Conv1d(conv_width, hidden_dim, 3, 1, padding, dilation)
+ self.conv1d_2 = nn.Conv1d(hidden_dim, conv_width, 1, 1, 0)
+
+ def forward(self, hidden_states):
+ residuals = hidden_states
+ hidden_states = self.activation(hidden_states)
+ hidden_states = self.conv1d_1(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ hidden_states = self.conv1d_2(hidden_states)
+ return residuals + self.res_scale * hidden_states
+
+
+class JukeboxResnet1D(nn.Module):
+ def __init__(self, config, conv_width, n_depth, reverse_dilation=False):
+ super().__init__()
+ self.dilation_cycle = config.res_dilation_cycle
+ res_scale = 1.0 if not config.conv_res_scale else 1.0 / math.sqrt(n_depth)
+
+ blocks = []
+ for depth in range(n_depth):
+ block_depth = depth if self.dilation_cycle is None else depth % self.dilation_cycle
+ blocks.append(JukeboxResConv1DBlock(config, conv_width, block_depth, res_scale))
+
+ if reverse_dilation:
+ blocks = blocks[::-1]
+ self.resnet_block = nn.ModuleList(blocks)
+
+ def forward(self, hidden_states):
+ for block in self.resnet_block:
+ hidden_states = block(hidden_states)
+ return hidden_states
+
+
+class JukeboxEncoderConvBlock(nn.Module):
+ def __init__(self, config, embed_dim, hidden_dim, depth, down_t, stride_t):
+ super().__init__()
+ blocks = []
+ filter_t = stride_t * 2
+ pad_t = stride_t // 2
+ if down_t > 0:
+ for i in range(down_t):
+ blocks.append(nn.Conv1d(embed_dim if i == 0 else hidden_dim, hidden_dim, filter_t, stride_t, pad_t))
+ blocks.append(JukeboxResnet1D(config, hidden_dim, depth))
+ self.proj_out = nn.Conv1d(hidden_dim, config.embed_dim, 3, 1, 1)
+ self.downsample_block = nn.ModuleList(blocks)
+
+ def forward(self, hidden_states):
+ for block in self.downsample_block:
+ hidden_states = block(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+ return hidden_states
+
+
+class JukeboxEncoder(nn.Module):
+ def __init__(self, config, width, depth, levels, downs_t, strides_t):
+ super().__init__()
+ self.levels = levels
+ self.level_blocks = nn.ModuleList()
+
+ iterator = zip(list(range(self.levels)), downs_t, strides_t)
+ for i, down_t, stride_t in iterator:
+ self.level_blocks.append(
+ JukeboxEncoderConvBlock(
+ config, config.conv_input_shape if i == 0 else config.embed_dim, width, depth, down_t, stride_t
+ )
+ )
+
+ def forward(self, hidden_states):
+ all_hidden_states = []
+
+ # 64, 32, ...
+ for level in range(self.levels):
+ level_block = self.level_blocks[level]
+ hidden_states = level_block(hidden_states)
+ all_hidden_states.append(hidden_states)
+
+ return all_hidden_states
+
+
+class JukeboxDecoderConvBock(nn.Module):
+ def __init__(self, config, embed_dim, hidden_dim, depth, down_t, stride_t, reverse_dilation=True):
+ self.embed_dim = embed_dim
+ self.hidden_dim = hidden_dim
+ super().__init__()
+ blocks = []
+ if down_t > 0:
+ filter_t = stride_t * 2
+ pad_t = stride_t // 2
+ self.proj_in = nn.Conv1d(embed_dim, hidden_dim, 3, 1, 1)
+ for i in range(down_t):
+ blocks.append(JukeboxResnet1D(config, hidden_dim, depth, reverse_dilation))
+ blocks.append(
+ nn.ConvTranspose1d(
+ hidden_dim, hidden_dim if i < down_t - 1 else embed_dim, filter_t, stride_t, pad_t
+ )
+ )
+ self.upsample_block = nn.ModuleList(blocks)
+
+ def forward(self, hidden_states):
+ hidden_states = self.proj_in(hidden_states)
+ for block in self.upsample_block:
+ hidden_states = block(hidden_states)
+ return hidden_states
+
+
+class JukeboxDecoder(nn.Module):
+ def __init__(self, config, hidden_dim, depth, levels, downs_t, strides_t):
+ super().__init__()
+ self.levels = levels
+ self.level_blocks = nn.ModuleList()
+ for level, down_t, stride_t in zip(list(range(self.levels)), downs_t, strides_t):
+ self.level_blocks.append(
+ JukeboxDecoderConvBock(config, config.embed_dim, hidden_dim, depth, down_t, stride_t)
+ )
+
+ self.out = nn.Conv1d(config.embed_dim, config.conv_input_shape, 3, 1, 1)
+
+ def forward(self, hidden_states, all_levels=True):
+ hidden_state = hidden_states[-1]
+
+ # 32, 64 ...
+ for level in reversed(range(self.levels)):
+ level_block = self.level_blocks[level]
+ hidden_state = level_block(hidden_state)
+
+ if level != 0 and all_levels:
+ hidden_state = hidden_state + hidden_states[level - 1]
+
+ hidden_state = self.out(hidden_state)
+ return hidden_state
+
+
+class JukeboxBottleneckBlock(nn.Module):
+ def __init__(self, config: JukeboxVQVAEConfig):
+ super().__init__()
+ self.nb_discrete_codes = config.nb_discrete_codes
+ self.codebook_width = config.embed_dim
+ self.mu = config.lmu
+ self.threshold = 1.0
+ self.init = False
+ self.codebook_sum = None
+ self.codebook_elem = None
+ self.register_buffer("codebook", torch.zeros(self.nb_discrete_codes, self.codebook_width))
+
+ def _tile(self, hidden_states):
+ dim, embed_width = hidden_states.shape
+ if dim < self.nb_discrete_codes:
+ n_repeats = (self.nb_discrete_codes + dim - 1) // dim
+ std = 0.01 / np.sqrt(embed_width)
+ hidden_states = hidden_states.repeat(n_repeats, 1)
+ hidden_states = hidden_states + torch.randn_like(hidden_states) * std
+ return hidden_states
+
+ def init_codebook(self, hidden_states):
+ nb_discrete_codes = self.nb_discrete_codes
+ self.init = True
+ codes = self._tile(hidden_states)
+ self.codebook = codes[torch.randperm(codes.shape[0])][:nb_discrete_codes]
+ self.codebook_sum = self.codebook
+ self.codebook_elem = torch.ones(nb_discrete_codes, device=self.codebook.device)
+
+ def update_codebook(self, hidden_states, latent_states):
+ mu, codebook_width, nb_discrete_codes = self.mu, self.codebook_width, self.nb_discrete_codes
+ with torch.no_grad():
+ # Calculate new centres
+ # nb_discrete_codes, batch_size * seq_length
+ latent_states_onehot = torch.zeros(nb_discrete_codes, hidden_states.shape[0], device=hidden_states.device)
+ latent_states_onehot.scatter_(0, latent_states.view(1, hidden_states.shape[0]), 1)
+
+ _codebook_sum = torch.matmul(latent_states_onehot, hidden_states)
+ _codebook_elem = latent_states_onehot.sum(dim=-1) # nb_discrete_codes
+ codes = self._tile(hidden_states)
+ _random_codebook = codes[torch.randperm(codes.shape[0])][:nb_discrete_codes]
+
+ # Update centres
+ old_codebook = self.codebook
+ self.codebook_sum = mu * self.codebook_sum + (1.0 - mu) * _codebook_sum
+ self.codebook_elem = mu * self.codebook_elem + (1.0 - mu) * _codebook_elem # nb_discrete_codes
+ usage = (self.codebook_elem.view(nb_discrete_codes, 1) >= self.threshold).float()
+
+ norm_code = self.codebook_sum.view(nb_discrete_codes, codebook_width) / self.codebook_elem.view(
+ nb_discrete_codes, 1
+ )
+ self.codebook = usage * (norm_code) + (1 - usage) * _random_codebook
+ _codebook_prob = _codebook_elem / torch.sum(_codebook_elem) # prob of each bin
+ entropy = -torch.sum(_codebook_prob * torch.log(_codebook_prob + 1e-8)) # entropy ie how diverse
+ used_curr = (_codebook_elem >= self.threshold).sum()
+ usage = torch.sum(usage)
+ dk = torch.linalg.norm(self.codebook - old_codebook) / np.sqrt(np.prod(old_codebook.shape))
+ return {"entropy": entropy, "used_curr": used_curr, "usage": usage, "dk": dk}
+
+ def preprocess(self, hidden_states):
+ hidden_states = hidden_states.permute(0, 2, 1).contiguous()
+ hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
+
+ if hidden_states.shape[-1] == self.codebook_width:
+ prenorm = torch.linalg.norm(hidden_states - torch.mean(hidden_states)) / np.sqrt(
+ np.prod(hidden_states.shape)
+ )
+ elif hidden_states.shape[-1] == 2 * self.codebook_width:
+ x1, x2 = hidden_states[..., : self.codebook_width], hidden_states[..., self.codebook_width :]
+ prenorm = (torch.linalg.norm(x1 - torch.mean(x1)) / np.sqrt(np.prod(x1.shape))) + (
+ torch.linalg.norm(x2 - torch.mean(x2)) / np.sqrt(np.prod(x2.shape))
+ )
+
+ # Normalise
+ hidden_states = x1 + x2
+
+ return hidden_states, prenorm
+
+ def postprocess(self, latent_states, dequantised_states, x_shape):
+ batch_size, time = x_shape
+ dequantised_states = dequantised_states.view(batch_size, time, -1).permute(0, 2, 1).contiguous()
+ latent_states = latent_states.view(batch_size, time)
+ return latent_states, dequantised_states
+
+ def quantise(self, latent_states):
+ # Calculate latent code latent_states
+ codebook_weights = self.codebook.t()
+ distance = (
+ torch.sum(latent_states**2, dim=-1, keepdim=True)
+ - 2 * torch.matmul(latent_states, codebook_weights)
+ + torch.sum(codebook_weights**2, dim=0, keepdim=True)
+ ) # (batch_size * latent_states , codebook_weights)
+ min_distance, music_tokens = torch.min(distance, dim=-1)
+ fit = torch.mean(min_distance)
+ return music_tokens, fit
+
+ def dequantise(self, music_tokens):
+ dequantised_states = F.embedding(music_tokens, self.codebook)
+ return dequantised_states
+
+ def encode(self, latent_states):
+ samples, _, seq_len = latent_states.shape
+
+ # Preprocess.
+ latent_states, _ = self.preprocess(latent_states)
+
+ # Quantise
+ music_tokens, _ = self.quantise(latent_states)
+
+ # Postprocess.
+ music_tokens = music_tokens.view(samples, seq_len)
+ return music_tokens
+
+ def decode(self, music_tokens):
+ samples, seq_len = music_tokens.shape
+
+ # Dequantise
+ dequantised_states = self.dequantise(music_tokens)
+
+ # Postprocess
+ dequantised_states = (
+ dequantised_states.view(samples, seq_len, self.codebook_width).permute(0, 2, 1).contiguous()
+ )
+ return dequantised_states
+
+ def forward(self, hidden_states, update_codebook=True):
+ samples, _, seq_len = hidden_states.shape
+
+ # Preprocess
+ hidden_states, prenorm = self.preprocess(hidden_states)
+
+ # Init codebook if not inited
+ if update_codebook and not self.init:
+ self.init_codebook(hidden_states)
+
+ # Quantise and dequantise through bottleneck
+ music_tokens, fit = self.quantise(hidden_states)
+ dequantised_states = self.dequantise(music_tokens)
+
+ # Update embeddings
+ if update_codebook:
+ update_metrics = self.update_codebook(hidden_states, music_tokens)
+ else:
+ update_metrics = {}
+
+ # Loss
+ commit_loss = torch.linalg.norm(dequantised_states.detach() - hidden_states) ** 2 / np.prod(
+ hidden_states.shape
+ )
+
+ # Passthrough
+ dequantised_states = hidden_states + (dequantised_states - hidden_states).detach()
+
+ # Postprocess
+ music_tokens, dequantised_states = self.postprocess(music_tokens, dequantised_states, (samples, seq_len))
+ return music_tokens, dequantised_states, commit_loss, dict(fit=fit, pn=prenorm, **update_metrics)
+
+
+class JukeboxBottleneck(nn.Module):
+ def __init__(self, config, levels):
+ super().__init__()
+ self.levels = levels
+ self.level_blocks = nn.ModuleList()
+ for level in range(self.levels):
+ self.level_blocks.append(JukeboxBottleneckBlock(config))
+
+ def encode(self, raw_audio):
+ music_tokens = [
+ level_block.encode(hidden_states) for (level_block, hidden_states) in zip(self.level_blocks, raw_audio)
+ ]
+ return music_tokens
+
+ def decode(self, music_tokens, start_level=0, end_level=None):
+ if end_level is None:
+ end_level = self.levels
+ quantised_audio = [
+ level_block.decode(z) for (level_block, z) in zip(self.level_blocks[start_level:end_level], music_tokens)
+ ]
+ return quantised_audio
+
+ def forward(self, input_audio):
+ music_tokens, quantised_states, commit_losses, metrics = [], [], [], []
+ for level in range(self.levels):
+ level_block = self.level_blocks[-level - 1]
+ hidden_states = input_audio[level]
+ sampled_tokens, quantised_state, commit_loss, metric = level_block(
+ hidden_states, update_codebook=self.training
+ )
+ music_tokens.append(sampled_tokens)
+ if not self.training:
+ # Be extra paranoid and make sure the encoder weights can't
+ # change from straight-through estimator
+ quantised_state = quantised_state.detach()
+ quantised_states.append(quantised_state)
+ commit_losses.append(commit_loss)
+ if self.training:
+ metrics.append(metric)
+ return music_tokens, quantised_states, commit_losses, metrics
+
+
+JUKEBOX_START_DOCSTRING = r"""
+
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config (`JukeboxConfig`): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+
+@add_start_docstrings(
+ """The Hierarchical VQ-VAE model used in Jukebox. This model follows the Hierarchical VQVAE paper from [Will Williams, Sam
+Ringer, Tom Ash, John Hughes, David MacLeod, Jamie Dougherty](https://huggingface.co/papers/2002.08111).
+
+ """,
+ JUKEBOX_START_DOCSTRING,
+)
+class JukeboxVQVAE(PreTrainedModel):
+ config: JukeboxVQVAEConfig
+ base_model_prefix = "vqvae"
+
+ def _init_weights(self, module):
+ if isinstance(module, nn.Embedding): # embed_tokens
+ module.weight.data.normal_(mean=0.0, std=0.02 * self.config.init_scale)
+ elif isinstance(module, JukeboxConv1D):
+ if self.config.zero_out:
+ module.weight.data.zero_()
+ else:
+ module.weight.data.normal_(mean=0.0, std=0.02 * self.config.init_scale)
+ elif isinstance(module, JukeboxResConv1DBlock) and self.config.zero_out:
+ module.conv1d_2.weight.data.zero_()
+ module.conv1d_2.bias.data.zero_()
+ if isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ if isinstance(module, nn.Linear) and module.bias is not None:
+ module.bias.data.zero_()
+
+ def __init__(self, config: JukeboxVQVAEConfig):
+ super().__init__(config)
+ downs_t = config.res_downs_t
+ strides_t = config.res_strides_t
+ if not config.sample_length:
+ downsamples = [stride**down for stride, down in zip(strides_t, downs_t)]
+ top_raw_to_tokens = np.prod(downsamples)
+ config.sample_length = (
+ config.sample_length_in_seconds * config.sampling_rate // top_raw_to_tokens
+ ) * top_raw_to_tokens
+ config.sample_length = config.sample_length.astype(int)
+
+ self.nb_discrete_codes = config.nb_discrete_codes
+ self.commit = config.commit
+ self.sample_length = config.sample_length
+
+ self.downsamples = [stride**down for stride, down in zip(strides_t, downs_t)]
+ self.hop_lengths = np.cumprod(self.downsamples)
+ self.levels = levels = config.levels
+ self.music_tokens_shapes = [
+ (int(self.sample_length // self.hop_lengths[-level - 1])) for level in range(levels)
+ ]
+
+ self.multipliers = config.multipliers if config.multipliers is not None else [1] * levels
+
+ self.encoders = nn.ModuleList()
+ self.decoders = nn.ModuleList()
+ for level in range(levels):
+ width = config.res_conv_width * self.multipliers[level]
+ depth = config.res_conv_depth * self.multipliers[level]
+ self.encoders.append(
+ JukeboxEncoder(config, width, depth, level + 1, downs_t[: level + 1], strides_t[: level + 1])
+ )
+ self.decoders.append(
+ JukeboxDecoder(config, width, depth, level + 1, downs_t[: level + 1], strides_t[: level + 1])
+ )
+
+ self.bottleneck = JukeboxBottleneck(config, levels)
+
+ def _decode(self, music_tokens, start_level=0, end_level=None):
+ # Decode
+ if end_level is None:
+ end_level = self.levels
+ latent_states = self.bottleneck.decode(music_tokens, start_level=start_level, end_level=end_level)
+ # Use only lowest level
+ decoder, dequantised_state = self.decoders[start_level], latent_states[0:1]
+ dequantised_state = decoder(dequantised_state, all_levels=False)
+ dequantised_state = dequantised_state.permute(0, 2, 1)
+ return dequantised_state
+
+ def decode(self, music_tokens, start_level=0, end_level=None, bs_chunks=1) -> torch.Tensor:
+ """
+ Transforms the input `music_tokens` to their `raw_audio` representation.
+
+ Args:
+ music_tokens (`torch.LongTensor`):
+ Tensor of music tokens which will be decoded to raw audio by using the codebook. Each music token
+ should be an index to a corresponding `code` vector in the codebook.
+ start_level (`int`, *optional*):
+ Level at which the decoding process will start. Default to 0.
+ end_level (`int`, *optional*):
+ Level at which the decoding process will start. Default to None.
+ bs_chunks (int, *optional*):
+ Number of chunks to process at the same time.
+ """
+ token_chunks = [torch.chunk(token, bs_chunks, dim=0) for token in music_tokens]
+ dequantised_states = []
+ for i in range(bs_chunks):
+ music_tokens_i = [chunks[i] for chunks in token_chunks]
+ dequantised_state = self._decode(music_tokens_i, start_level=start_level, end_level=end_level)
+ dequantised_states.append(dequantised_state)
+ return torch.cat(dequantised_states, dim=0)
+
+ def _encode(self, raw_audio, start_level=0, end_level=None):
+ # Encode
+ if end_level is None:
+ end_level = self.levels
+ input_audio = raw_audio.permute(0, 2, 1).float()
+ latent_states = []
+ for level in range(self.levels):
+ encoder = self.encoders[level]
+ latent_state = encoder(input_audio)
+ latent_states.append(latent_state[-1])
+ music_tokens = self.bottleneck.encode(latent_states)
+ return music_tokens[start_level:end_level]
+
+ def encode(self, input_audio, start_level=0, end_level=None, bs_chunks=1):
+ """
+ Transforms the `input_audio` to a discrete representation made out of `music_tokens`.
+
+ Args:
+ input_audio (`torch.Tensor`):
+ Raw audio which will be encoded to its discrete representation using the codebook. The closest `code`
+ form the codebook will be computed for each sequence of samples.
+ start_level (`int`, *optional*, defaults to 0):
+ Level at which the encoding process will start. Default to 0.
+ end_level (`int`, *optional*):
+ Level at which the encoding process will start. Default to None.
+ bs_chunks (int, *optional*, defaults to 1):
+ Number of chunks of raw audio to process at the same time.
+ """
+ audio_chunks = torch.chunk(input_audio, bs_chunks, dim=0)
+ music_tokens_list = []
+ for chunk_i in audio_chunks:
+ music_tokens_i = self._encode(chunk_i, start_level=start_level, end_level=end_level)
+ music_tokens_list.append(music_tokens_i)
+ music_tokens = [torch.cat(music_tokens_level, dim=0) for music_tokens_level in zip(*music_tokens_list)]
+ return music_tokens
+
+ def sample(self, n_samples):
+ music_tokens = [
+ torch.randint(0, self.nb_discrete_codes, size=(n_samples, *music_tokens_shape), device="cpu")
+ for music_tokens_shape in self.music_tokens_shapes
+ ]
+ return self.decode(music_tokens)
+
+ def forward(self, raw_audio: torch.FloatTensor) -> tuple[torch.Tensor, torch.Tensor]:
+ """
+ Forward pass of the VQ-VAE, encodes the `raw_audio` to latent states, which are then decoded for each level.
+ The commit loss, which ensure that the encoder's computed embeddings are close to the codebook vectors, is
+ computed.
+
+ Args:
+ raw_audio (`torch.FloatTensor`):
+ Audio input which will be encoded and decoded.
+
+ Returns:
+ `tuple[torch.Tensor, torch.Tensor]`
+
+
+ Example:
+ ```python
+ >>> from transformers import JukeboxVQVAE, set_seed
+ >>> import torch
+
+ >>> model = JukeboxVQVAE.from_pretrained("openai/jukebox-1b-lyrics").eval()
+ >>> set_seed(0)
+ >>> zs = [torch.randint(100, (4, 1))]
+ >>> model.decode(zs).shape
+ torch.Size([4, 8, 1])
+ ```
+ """
+
+ # Encode/Decode
+ input_audio = raw_audio.permute(0, 2, 1).float()
+ latent_states = []
+ for level in range(self.levels):
+ encoder = self.encoders[level]
+ latent_state = encoder(input_audio)
+ latent_states.append(latent_state[-1])
+
+ _, music_tokens, commit_losses, _ = self.bottleneck(latent_states)
+ dequantised_states = []
+ for level in range(self.levels):
+ decoder = self.decoders[level]
+ dequantised_state = decoder(music_tokens[level : level + 1], all_levels=False)
+ dequantised_states.append(dequantised_state.permute(0, 2, 1))
+
+ commit_loss = sum(commit_losses)
+ loss = self.commit * commit_loss
+
+ return dequantised_states, loss
+
+
+class JukeboxMLP(nn.Module):
+ def __init__(self, config):
+ # a single channel is always used in original code
+ super().__init__()
+ embed_dim = config.hidden_size
+ hidden_dim = int(config.mlp_multiplier * embed_dim)
+
+ self.c_fc = JukeboxConv1D(embed_dim, hidden_dim)
+ self.c_proj = JukeboxConv1D(hidden_dim, embed_dim)
+ self.act = ACT2FN[config.act_fn]
+ self.dropout = nn.Dropout(config.resid_dropout)
+
+ def forward(self, hidden_states):
+ hidden_states = self.c_fc(hidden_states)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.c_proj(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states
+
+
+class JukeboxLayerNorm(FusedLayerNorm):
+ def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True):
+ super().__init__(normalized_shape, eps=eps, elementwise_affine=elementwise_affine)
+ self.width = np.prod(normalized_shape)
+ self.max_numel = 65535 * self.width
+
+ def forward(self, input):
+ if input.numel() > self.max_numel:
+ return F.layer_norm(input, self.normalized_shape, self.weight, self.bias, self.eps).type_as(input)
+ else:
+ return super().forward(input).type_as(input)
+
+
+class JukeboxAttention(nn.Module):
+ def __init__(self, config, n_ctx, attn_func="dense_attn"):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+ self.n_heads = config.n_heads
+ self.dropout = config.attn_dropout
+ hidden_dim = int(config.attention_multiplier * self.embed_dim)
+
+ self.head_dim = hidden_dim // config.n_heads
+ self.n_ctx = n_ctx
+ self.hidden_dim = hidden_dim
+ self.scale = self.head_dim**-0.25
+ self.mask = config.mask
+
+ if attn_func == "cross_attention":
+ self.c_attn = JukeboxConv1D(self.embed_dim, hidden_dim)
+ self.c_enc_kv = JukeboxConv1D(self.embed_dim, hidden_dim * 2)
+ else:
+ self.c_attn = JukeboxConv1D(self.embed_dim, hidden_dim * 3)
+
+ self.c_proj = JukeboxConv1D(hidden_dim, self.embed_dim)
+ self.attn_dropout = nn.Dropout(config.attn_dropout)
+ self.resid_dropout = nn.Dropout(config.resid_dropout)
+
+ # Sequence of length seq_len is factored as [blocks, seq_len // blocks]
+ self.attn_func = attn_func
+ if attn_func == "cross_attention":
+ self.qkv = self.decode_qkv
+ elif attn_func == "prime_attn":
+ self.qkv = self.prime_qkv
+ else:
+ self.qkv = self.factored_qkv
+
+ ATTENTION_MAP = {
+ "dense_attn": (self.dense_attn, "autoregressive"),
+ "block_attn": (self.block_attn, "autoregressive"),
+ "transpose_block_attn": (self.transpose_block_attn, "autoregressive"),
+ "prev_block_attn": (self.prev_block_attn, None),
+ "summary_attn": (self.summary_attn, "summary"),
+ "summary_spread_attn": (self.summary_spread_attn, "summary"),
+ "cross_attention": (self.dense_attn, None),
+ "prime_attn": (self.prime_attn, "prime"),
+ }
+ self.attn, self.attn_mask = ATTENTION_MAP[attn_func]
+
+ self.blocks = config.blocks
+ self.spread = config.spread
+ if self.blocks is not None:
+ self.block_ctx = self.n_ctx // self.blocks
+
+ self.sample_t = 0
+ self.cache = {}
+ self.encoder_len = config.nb_relevant_lyric_tokens # length of the encoder input ids
+ self.record_attn = False
+
+ def _attn(self, query_states, key_states, value_states, sample):
+ scale = self.scale
+ if self.training:
+ attention_weight = torch.matmul(query_states * scale, key_states * scale)
+ else:
+ attention_weight = torch.matmul(query_states, key_states)
+ attention_weight.mul_(scale * scale)
+ attn_weight_type = attention_weight.dtype
+ attention_weight = attention_weight.float()
+ if self.mask:
+ # Generate appropriate mask to mask out all positions before current
+ # Might take up lot of memory for dense, so can cache it
+ mask = get_mask(
+ self.attn_mask,
+ query_states.size(-2),
+ key_states.size(-1),
+ self.blocks,
+ self.spread,
+ attention_weight.device,
+ sample,
+ self.sample_t,
+ )
+ if mask is not None:
+ attention_weight = attention_weight * mask + -1e9 * (1 - mask)
+ attention_prob = F.softmax(attention_weight, dim=-1).type(attn_weight_type)
+ if self.record_attn:
+ self.attention_prob = attention_prob
+ if self.attn_func == "prime_attn":
+ # only keep music queries and lyrics keys/values
+ self.attention_prob = self.attention_prob[:, :, self.encoder_len :, : self.encoder_len]
+ attention_prob = self.attn_dropout(attention_prob)
+ context_states = torch.matmul(attention_prob, value_states)
+ return context_states
+
+ def merge_heads(self, hidden_states):
+ hidden_states = hidden_states.permute(0, 2, 1, 3).contiguous()
+ new_hidden_states_shape = (*hidden_states.size()[:-2], hidden_states.size(-2) * hidden_states.size(-1))
+ return hidden_states.view(*new_hidden_states_shape) # in Tensorflow implem: fct merge_states
+
+ def split_heads(self, hidden_states, is_key=False):
+ new_hidden_states_shape = (
+ *hidden_states.size()[:-1],
+ self.n_heads,
+ hidden_states.size(-1) // self.n_heads,
+ )
+ hidden_states = hidden_states.view(*new_hidden_states_shape) # in Tensorflow implem: fct split_states
+ if is_key:
+ return hidden_states.permute(0, 2, 3, 1)
+ else:
+ return hidden_states.permute(0, 2, 1, 3)
+
+ def dense_attn(self, query, key, value, sample):
+ query = self.split_heads(query)
+ key = self.split_heads(key, is_key=True)
+ value = self.split_heads(value)
+ context_states = self._attn(query, key, value, sample)
+ context_states = self.merge_heads(context_states)
+ return context_states
+
+ def block_attn(self, query, key, value, sample):
+ block_ctx = self.block_ctx
+ batch_size, seq_len, embed_dim = value.shape # For sample, query_len= 1, key_len = value_len = sample_t
+ if sample:
+ return self.dense_attn(query, key, value, sample).view(batch_size, 1, embed_dim)
+ else:
+ query_length = query.shape[1]
+ query = query.view(batch_size * query_length // block_ctx, block_ctx, embed_dim)
+ if query_length < seq_len:
+ seq_len = query_length
+ key = key[:, -seq_len:].contiguous()
+ value = value[:, -seq_len:].contiguous()
+ key = key.view(batch_size * seq_len // block_ctx, block_ctx, embed_dim)
+ value = value.view(batch_size * seq_len // block_ctx, block_ctx, embed_dim)
+ return self.dense_attn(query, key, value, sample).view(batch_size, seq_len, embed_dim)
+
+ def transpose_block_attn(self, query, key, value, sample):
+ block_ctx = self.block_ctx
+ batch_size, seq_len, embed_dim = value.shape # For sample, query_len= 1, key_len = value_len = sample_t
+ if sample:
+ block_len = (seq_len - 1) % block_ctx
+ key = key[:, block_len::block_ctx, :]
+ value = value[:, block_len::block_ctx, :]
+ return self.dense_attn(query, key, value, sample).view(batch_size, 1, embed_dim)
+ else:
+ query_length = query.shape[1]
+ query = query.view(batch_size, query_length // block_ctx, block_ctx, embed_dim)
+ query = query.transpose(1, 2).contiguous()
+ query = query.view(batch_size * block_ctx, query_length // block_ctx, embed_dim)
+
+ key = key.view(batch_size, seq_len // block_ctx, block_ctx, embed_dim)
+ key = key.transpose(1, 2).contiguous()
+ key = key.view(batch_size * block_ctx, seq_len // block_ctx, embed_dim)
+
+ value = value.view(batch_size, seq_len // block_ctx, block_ctx, embed_dim)
+ value = value.transpose(1, 2).contiguous()
+ value = value.view(batch_size * block_ctx, seq_len // block_ctx, embed_dim)
+
+ block_attn = self.dense_attn(query, key, value, sample)
+ block_attn = block_attn.view(batch_size, block_ctx, query_length // block_ctx, embed_dim)
+ block_attn = block_attn.transpose(1, 2).contiguous()
+ block_attn = block_attn.view(batch_size, query_length, embed_dim)
+
+ return block_attn
+
+ def prev_block_attn(self, query, key, value, sample):
+ block_ctx = self.block_ctx
+ batch_size, seq_len, embed_dim = value.shape # For sample, query_len= 1, key_len = value_len = sample_t
+ if sample:
+ block = (seq_len - 1) // block_ctx
+ prev_l = (block - 1) * block_ctx
+ if block > 0:
+ key = key[:, prev_l : prev_l + block_ctx, :]
+ value = value[:, prev_l : prev_l + block_ctx, :]
+ else:
+ key = torch.zeros(batch_size, block_ctx, embed_dim, device=query.device, dtype=query.dtype)
+ value = torch.zeros(batch_size, block_ctx, embed_dim, device=query.device, dtype=query.dtype)
+ return self.dense_attn(query, key, value, sample).view(batch_size, 1, embed_dim)
+ else:
+ query_length = query.shape[1]
+ query = query.view(batch_size * query_length // block_ctx, block_ctx, embed_dim)
+
+ key = key.view(batch_size, seq_len // block_ctx, block_ctx, embed_dim)[:, :-1, :, :]
+ key = torch.nn.functional.pad(key, (0, 0, 0, 0, 1, 0))
+ key = key.view(batch_size * seq_len // block_ctx, block_ctx, embed_dim)
+
+ value = value.view(batch_size, seq_len // block_ctx, block_ctx, embed_dim)[:, :-1, :, :]
+ value = torch.nn.functional.pad(value, (0, 0, 0, 0, 1, 0))
+ value = value.view(batch_size * seq_len // block_ctx, block_ctx, embed_dim)
+
+ if query_length < seq_len:
+ nb_query_blocks = query_length // block_ctx
+ nb_key_blocks = seq_len // block_ctx
+ seq_len = query_length
+ key = key.view(batch_size, nb_key_blocks, block_ctx, embed_dim)[:, -nb_query_blocks:]
+ key = key.contiguous().view(batch_size * nb_query_blocks, block_ctx, embed_dim)
+
+ value = value.view(batch_size, nb_key_blocks, block_ctx, embed_dim)[:, -nb_query_blocks:]
+ value = value.contiguous().view(batch_size * nb_query_blocks, block_ctx, embed_dim)
+
+ return self.dense_attn(query, key, value, sample).view(batch_size, seq_len, embed_dim)
+
+ def summary_attn(self, query, key, value, sample):
+ blocks = self.blocks
+ block_ctx = self.block_ctx
+ batch_size, seq_len, embed_dim = value.shape # For sample, query_len= 1, key_len = value_len = sample_t
+ if sample:
+ key = key[:, block_ctx - 1 : blocks * block_ctx - 1 : block_ctx, :]
+ key = torch.nn.functional.pad(key, (0, 0, 1, 0))
+
+ value = value[:, block_ctx - 1 : blocks * block_ctx - 1 : block_ctx, :]
+ value = torch.nn.functional.pad(value, (0, 0, 1, 0))
+ return self.dense_attn(query, key, value, sample).view(batch_size, 1, embed_dim)
+ else:
+ key = key.view(batch_size, blocks, seq_len // blocks, embed_dim)[:, :-1, -1, :]
+ key = torch.nn.functional.pad(key, (0, 0, 1, 0)) # batch_size, blocks, embed_dim
+
+ value = value.view(batch_size, blocks, seq_len // blocks, embed_dim)[:, :-1, -1, :]
+ value = torch.nn.functional.pad(value, (0, 0, 1, 0)) # batch_size, blocks, embed_dim
+ return self.dense_attn(query, key, value, sample).view(batch_size, seq_len, embed_dim)
+
+ def summary_spread_attn(self, query, key, value, sample):
+ blocks = self.blocks
+ spread = self.spread
+
+ batch_size, seq_len, embed_dim = value.shape # For sample, query_len= 1, key_len = value_len = sample_t
+ if sample:
+ raise NotImplementedError
+ else:
+ key = key.view(batch_size, blocks, seq_len // blocks, embed_dim)[:, :-1, -spread:, :]
+ key = torch.nn.functional.pad(key, (0, 0, 0, 0, 1, 0)).contiguous()
+ key = key.view(batch_size, blocks * spread, embed_dim)
+
+ value = value.view(batch_size, blocks, seq_len // blocks, embed_dim)[:, :-1, -spread:, :]
+ value = torch.nn.functional.pad(value, (0, 0, 0, 0, 1, 0)).contiguous()
+ value = value.view(batch_size, blocks * spread, embed_dim)
+
+ return self.dense_attn(query, key, value, sample).view(batch_size, seq_len, embed_dim)
+
+ def prime_attn(self, query, key, value, sample):
+ encoder_len = self._encoder_len
+ key = key[:, :encoder_len]
+ value = value[:, :encoder_len]
+ return self.dense_attn(query, key, value, sample)
+
+ def factored_qkv(self, hidden_states, last_encoder_hidden_states=None, sample=False):
+ curr_ctx = hidden_states.shape[1]
+ if last_encoder_hidden_states is not None:
+ raise TypeError("last_encoder_hidden_states should be None")
+
+ query, key, value = hidden_states.chunk(3, dim=2)
+ if sample:
+ self.sample_t += curr_ctx
+ key, value = self._append_cache(key, value)
+ l_cache = self._suff_cache_len()
+ if self._cache_len() > l_cache:
+ self._slice_cache(-l_cache)
+ if curr_ctx > 1:
+ if self.attn_func != "dense_attn":
+ query = self._pad_to_block_ctx(query, query=True)
+ key = self._pad_to_block_ctx(key)
+ value = self._pad_to_block_ctx(value)
+ sample = False
+ else:
+ key = self.cache["key"]
+ value = self.cache["value"]
+ return query, key, value, sample
+
+ def prime_qkv(self, hidden_states, last_encoder_hidden_states=None, sample=False):
+ curr_ctx = hidden_states.shape[1]
+ if last_encoder_hidden_states is not None:
+ raise TypeError("last_encoder_hidden_states should be None")
+ query, key, value = hidden_states.chunk(3, dim=2)
+ if sample:
+ if self._cache_len() < self._encoder_len:
+ self._append_cache(key, value)
+ if self._cache_len() > self._encoder_len:
+ self._slice_cache(0, self._encoder_len)
+ key, value = self.cache["key"], self.cache["value"]
+ self.sample_t += curr_ctx
+ return query, key, value, sample
+
+ def decode_qkv(self, hidden_states, last_encoder_hidden_states=None, sample=False):
+ curr_ctx = hidden_states.shape[1]
+ query = hidden_states
+ if sample:
+ if self.sample_t == 0:
+ self.cache["key"], self.cache["value"] = self.c_enc_kv(
+ last_encoder_hidden_states.type_as(hidden_states)
+ ).chunk(2, dim=2)
+ key, value = self.cache["key"], self.cache["value"]
+ self.sample_t += curr_ctx
+ else:
+ key, value = self.c_enc_kv(last_encoder_hidden_states.type_as(hidden_states)).chunk(2, dim=2)
+ return query, key, value, sample
+
+ def forward(self, hidden_states, last_encoder_hidden_states=None, sample=False):
+ curr_ctx = hidden_states.shape[1]
+ hidden_states = self.c_attn(hidden_states)
+ query, key, value, sample = self.qkv(
+ hidden_states, last_encoder_hidden_states=last_encoder_hidden_states, sample=sample
+ )
+ attention_scores = self.attn(query, key, value, sample)
+ if attention_scores.shape[1] != curr_ctx:
+ offset = self._offset(curr_ctx)
+ attention_scores = attention_scores[:, offset : offset + curr_ctx, :].contiguous()
+ attention_scores = self.c_proj(attention_scores)
+ return self.resid_dropout(attention_scores)
+
+ @property
+ def _encoder_len(self):
+ encoder_len = self.encoder_len
+ encoder_blocks = (encoder_len // self.blocks) + 1
+ return encoder_blocks * self.blocks
+
+ def _offset(self, curr_ctx):
+ if self.attn_func == "dense_attn":
+ return 0
+ return (self.sample_t - curr_ctx) % self.block_ctx
+
+ def _pad_to_block_ctx(self, hidden_states, query=False):
+ seq_len = hidden_states.shape[1]
+ offset = self._offset(seq_len) if query else 0
+ n_blocks = (seq_len + offset + self.block_ctx - 1) // self.block_ctx
+ pad = n_blocks * self.block_ctx - seq_len - offset
+ if pad == 0 and offset == 0:
+ return hidden_states
+ else:
+ return F.pad(hidden_states, (0, 0, offset, pad))
+
+ def _cache_len(self):
+ return 0 if "key" not in self.cache else self.cache["key"].shape[1]
+
+ def _suff_cache_len(self):
+ """
+ Precondition:
+ key and value are appended with the current context and self.sample_t reflects the 1-indexed sample
+ location in the context.
+ """
+ previous_block_length = (self.sample_t - 1) % self.block_ctx + 1 + self.block_ctx
+ REQUIRED_CACHE_LEN = {
+ "dense_attn": self.sample_t,
+ "block_attn": (self.sample_t - 1) % self.block_ctx + 1,
+ "transpose_block_attn": self.sample_t,
+ "prev_block_attn": self.sample_t if self.sample_t <= self.block_ctx else previous_block_length,
+ "cross_attn": self.encoder_len,
+ "prime_attn": min(self.sample_t, self._encoder_len),
+ }
+
+ return REQUIRED_CACHE_LEN[self.attn_func]
+
+ def _slice_cache(self, start, end=None):
+ self.cache["key"] = self.cache["key"][:, start:end]
+ self.cache["value"] = self.cache["value"][:, start:end]
+
+ def _append_cache(self, key, value):
+ if "key" not in self.cache:
+ self.cache["key"] = key
+ self.cache["value"] = value
+ else:
+ old_key, old_value = key, value
+ key = torch.cat([self.cache["key"], old_key], dim=1)
+ value = torch.cat([self.cache["value"], old_value], dim=1)
+ del self.cache["key"]
+ del self.cache["value"]
+ del old_key
+ del old_value
+ self.cache["key"] = key
+ self.cache["value"] = value
+ return self.cache["key"], self.cache["value"]
+
+ def del_cache(self):
+ self.sample_t = 0
+ if "key" in self.cache:
+ del self.cache["key"]
+ if "value" in self.cache:
+ del self.cache["value"]
+ self.cache = {}
+
+
+class JukeboxBlock(nn.Module):
+ def __init__(self, config, n_ctx, attn_func="dense_attn"):
+ super().__init__()
+ self.width = config.hidden_size
+ self.attn = JukeboxAttention(config, n_ctx, attn_func=attn_func)
+
+ self.layer_norm_0 = JukeboxLayerNorm(config.hidden_size)
+ self.mlp = JukeboxMLP(config)
+ self.layer_norm_1 = JukeboxLayerNorm(config.hidden_size)
+ self.res_scale = 1.0 / config.num_layers if config.attn_res_scale else 1.0
+ self.attn_func = attn_func
+
+ def forward(self, hidden_states, last_encoder_hidden_states, sample=False):
+ residuals = hidden_states
+ hidden_states = self.layer_norm_0(hidden_states)
+ hidden_states = self.attn(hidden_states, last_encoder_hidden_states, sample)
+
+ output_states = self.layer_norm_1(residuals + hidden_states)
+ output_states = self.mlp(output_states)
+ if self.res_scale == 1.0:
+ output = residuals + hidden_states + output_states
+ else:
+ output = residuals + self.res_scale * (hidden_states + output_states)
+ return output
+
+
+class JukeboxLayerStack(nn.Module):
+ def __init__(self, config, n_ctx):
+ super().__init__()
+ self.n_ctx = n_ctx
+ self.width = config.hidden_size
+ self.num_layers = config.num_layers
+ self.blocks = config.blocks
+ self.attention_pattern = config.attention_pattern
+ if self.blocks is not None:
+ self.block_ctx = n_ctx // self.blocks
+ self.encoder_len = config.nb_relevant_lyric_tokens
+ self.n_heads = config.n_heads
+
+ # Orders of attn_func
+ attention_pattern = ATTENTION_PATTERNS[self.attention_pattern]
+ self._attn_mods = nn.ModuleList()
+ for depth in range(self.num_layers):
+ self._attn_mods.append(JukeboxBlock(config, n_ctx, attn_func=attention_pattern(depth)))
+
+ self.saved_attn_weights = []
+
+ def set_record_attn(self, record_attn):
+ """
+ Makes forward prop dump self-attention softmaxes to self.saved_attn_weights.
+
+ Args:
+ record_attn (`Union[bool,set]`):
+ Either a set of layer indices indicating which layers to store, or a boolean value indicating Whether
+ to dump all.
+ """
+
+ def _should_record_attn(layer_idx):
+ if isinstance(record_attn, bool):
+ return record_attn
+ return layer_idx in record_attn
+
+ for i, layer in enumerate(self._attn_mods):
+ layer.attn.record_attn = _should_record_attn(i)
+
+ if not record_attn:
+ self.saved_attn_weights = []
+
+ def forward(self, hidden_states, last_encoder_hidden_states=None, sample=False):
+ # Blocks
+ for i, attn_layer in enumerate(self._attn_mods):
+ if attn_layer.attn_func == "cross_attention": # attend to the lyrics
+ hidden_states = attn_layer(
+ hidden_states, last_encoder_hidden_states=last_encoder_hidden_states, sample=sample
+ )
+ else:
+ hidden_states = attn_layer(hidden_states, last_encoder_hidden_states=None, sample=sample)
+ if attn_layer.attn.record_attn:
+ self.saved_attn_weights.append(attn_layer.attn.c_attn.weight)
+ return hidden_states
+
+ def del_cache(self):
+ for attn_layer in self._attn_mods:
+ attn_layer.attn.del_cache()
+
+
+class JukeboxPositionalEmbedding(nn.Module):
+ def __init__(self, embed_dim, width):
+ super().__init__()
+ self.pos_emb = nn.Parameter(torch.empty((embed_dim, width)))
+
+ def forward(self):
+ pos_emb = self.pos_emb
+ return pos_emb
+
+
+class JukeboxConditionalAutoregressive(nn.Module):
+ def __init__(
+ self,
+ config,
+ n_ctx=None,
+ embed_dim=None,
+ audio_conditioning=False,
+ metadata_conditioning=False,
+ is_encoder=False,
+ ):
+ """
+ Autoregressive model on either lyric tokens or music tokens, or both. The attention pattern should be properly
+ set for each configuration.
+
+ Args:
+ config (`JukeboxPriorConfig`):
+ Model configuration class with all the parameters of the model. Initializing with a config file does
+ not load the weights associated with the model, only the configuration. Check out the
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+ n_ctx (`int`, *optional*):
+ Number of tokens or lyrics tokens provided in a single pass.
+ embed_dim (`int`, *optional*):
+ Either equals to the dimension of the codebook, or the sum of n_vocab (lyrics) and codebook dimension,
+ if the model combines lyrics and music tokens, or simply n_vocab if the model is a separate encoder
+ audio_conditioning (`bool`, *optional*, defaults to `False`):
+ Whether or not the prior supports conditioning on audio.
+ metadata_conditioning (`bool`, *optional*, defaults to `False`):
+ Whether or not the prior supports conditioning on artitst, genres, lyrics and timing.
+ is_encoder (`bool`, *optional*, defaults to `False`):
+ Whether the model is an encoder only model.
+ """
+
+ super().__init__()
+ self.width = config.hidden_size
+ self.num_layers = config.num_layers
+ self.n_ctx = n_ctx if n_ctx is not None else config.n_ctx
+ self.embed_dim = embed_dim if embed_dim is not None else config.music_vocab_size
+ self.embed_tokens = nn.Embedding(self.embed_dim, config.hidden_size)
+ self.embed_tokens_dropout = nn.Dropout(config.emb_dropout)
+ self.metadata_conditioning = metadata_conditioning
+ self.audio_conditioning = audio_conditioning
+ if not metadata_conditioning:
+ self.start_token = nn.Parameter(torch.empty((1, config.hidden_size)))
+ self.pos_emb = JukeboxPositionalEmbedding(self.n_ctx, config.hidden_size)
+ self.pos_emb_dropout = nn.Dropout(config.emb_dropout)
+
+ self.transformer = JukeboxLayerStack(config, n_ctx=self.n_ctx)
+ self.is_encoder = is_encoder
+ self.encoder_len = config.nb_relevant_lyric_tokens
+
+ if config.merged_decoder:
+ # Merged piped model uses this setup
+ self.add_cond_after_transformer = False
+ self.share_embed_tokens_fc_proj_out = False
+ else:
+ self.add_cond_after_transformer = True
+ self.share_embed_tokens_fc_proj_out = True
+
+ if not is_encoder:
+ self.fc_proj_out = nn.Linear(config.hidden_size, self.embed_dim, bias=False)
+ if self.share_embed_tokens_fc_proj_out:
+ self.fc_proj_out.weight = self.embed_tokens.weight
+ self.loss = torch.nn.CrossEntropyLoss()
+
+ def forward(
+ self,
+ tokens,
+ audio_conditioning=None,
+ metadata_conditioning=None,
+ last_encoder_hidden_states=None,
+ get_preds=False,
+ get_acts=False,
+ get_sep_loss=False,
+ ):
+ """
+ Args:
+ tokens (`torch.tensor`):
+ Can represent music tokens, lyrics tokens or both, depending on the configuration.
+ """
+ # Preprocess.
+ batch_size = tokens.shape[0]
+ with torch.no_grad():
+ tokens = tokens.view(batch_size, -1).long()
+
+ if not self.audio_conditioning:
+ audio_conditioning = torch.zeros(
+ (batch_size, 1, self.width),
+ device=tokens.device,
+ dtype=self.transformer._attn_mods[0].mlp.c_fc.weight.dtype,
+ )
+
+ target = tokens # Target
+ hidden_states = self.embed_tokens(tokens)
+ # Shift by 1, and fill in start token
+ hidden_states = torch.cat((hidden_states[:, -1:], hidden_states[:, :-1]), dim=1)
+ if self.metadata_conditioning:
+ hidden_states[:, 0] = metadata_conditioning.view(batch_size, self.width)
+ else:
+ hidden_states[:, 0] = self.start_token
+
+ hidden_states = (
+ self.embed_tokens_dropout(hidden_states) + self.pos_emb_dropout(self.pos_emb()) + audio_conditioning
+ ) # Pos emb and dropout
+
+ hidden_states = self.transformer(
+ hidden_states, last_encoder_hidden_states=last_encoder_hidden_states
+ ) # Transformer
+ if self.add_cond_after_transformer: # Piped doesn't add x_cond
+ hidden_states = hidden_states + audio_conditioning
+
+ activations = hidden_states
+ if self.is_encoder:
+ return hidden_states
+
+ hidden_states = self.fc_proj_out(hidden_states) # Predictions
+ loss_fn = nn.CrossEntropyLoss()
+ if get_sep_loss:
+ lyric_hidden_states = hidden_states[:, : self.encoder_len].reshape(-1, self.embed_dim)
+ token_hidden_states = hidden_states[:, self.encoder_len :].reshape(-1, self.embed_dim)
+
+ lyric_loss = loss_fn(lyric_hidden_states, target[:, : self.encoder_len].reshape(-1)) / np.log(2.0)
+ music_token_loss = loss_fn(token_hidden_states, target[:, self.encoder_len :].reshape(-1)) / np.log(2.0)
+
+ loss = (lyric_loss, music_token_loss) # Note order! Lyric is first
+ else:
+ loss = loss_fn(hidden_states.view(-1, self.embed_dim), target.view(-1)) / np.log(2.0) # Loss
+
+ if get_preds:
+ return loss, hidden_states
+ elif get_acts:
+ return loss, activations
+ else:
+ return loss, None
+
+ def get_emb(self, sample_t, n_samples, tokens, audio_conditioning, metadata_conditioning):
+ if sample_t == 0:
+ hidden_states = torch.empty(n_samples, 1, self.width, dtype=self.embed_tokens.weight.dtype).to(
+ self.embed_tokens.weight.device
+ )
+ if self.metadata_conditioning:
+ hidden_states[:, 0] = metadata_conditioning.view(n_samples, self.width)
+ else:
+ hidden_states[:, 0] = self.start_token
+ else:
+ hidden_states = self.embed_tokens(tokens)
+ if audio_conditioning.shape == (n_samples, self.n_ctx, self.width):
+ cond = audio_conditioning[:, sample_t : sample_t + 1, :]
+ else:
+ cond = audio_conditioning
+ # Pos emb, dropout is identity at eval time
+ hidden_states = hidden_states + self.pos_emb()[sample_t : sample_t + 1] + cond
+ return hidden_states, cond
+
+ def sample(
+ self,
+ n_samples,
+ audio_conditioning=None,
+ metadata_conditioning=None,
+ last_encoder_hidden_states=None,
+ temp=1.0,
+ top_k=0,
+ top_p=0.0,
+ get_preds=False,
+ sample_tokens=None,
+ ):
+ if sample_tokens is None:
+ sample_tokens = self.n_ctx
+
+ if not self.audio_conditioning:
+ audio_conditioning = torch.zeros(
+ (n_samples, 1, self.width), dtype=self.transformer._attn_mods[0].mlp.c_fc.weight.dtype
+ ).to(self.fc_proj_out.device)
+
+ with torch.no_grad():
+ sampled_tokens = []
+ tokens = None
+ if get_preds:
+ preds = []
+
+ iter = tqdm(range(0, sample_tokens), leave=False)
+ for sample_t in iter:
+ iter.set_description(f"Ancestral sampling {sample_tokens} music tokens", refresh=True)
+ hidden_states, cond = self.get_emb(
+ sample_t, n_samples, tokens, audio_conditioning, metadata_conditioning
+ )
+
+ hidden_states = self.transformer(
+ hidden_states, last_encoder_hidden_states=last_encoder_hidden_states, sample=True
+ )
+ if self.add_cond_after_transformer:
+ hidden_states = hidden_states + cond
+ hidden_states = self.fc_proj_out(hidden_states) # Predictions
+ if get_preds:
+ preds.append(hidden_states.clone())
+ # Adjust logits
+ hidden_states = hidden_states / temp
+ hidden_states = filter_logits(hidden_states, top_k=top_k, top_p=top_p)
+ # Sample and replace hidden_states
+ tokens = torch.distributions.Categorical(logits=hidden_states).sample()
+ sampled_tokens.append(tokens.clone())
+
+ del tokens
+ self.transformer.del_cache()
+
+ tokens = torch.cat(sampled_tokens, dim=1)
+ if get_preds:
+ preds = torch.cat(preds, dim=1)
+ if get_preds:
+ return tokens, preds
+ else:
+ return tokens
+
+ def split_chunks(self, length, chunk_size):
+ n_passes = (length + chunk_size - 1) // chunk_size
+ chunk_sizes = [*[chunk_size] * (n_passes - 1), (length - 1) % chunk_size + 1]
+ return chunk_sizes
+
+ def primed_sample(
+ self,
+ n_samples,
+ lyric_and_music_tokens,
+ audio_conditioning=None,
+ metadata_conditioning=None,
+ last_encoder_hidden_states=None,
+ temp=1.0,
+ top_k=0,
+ top_p=0.0,
+ get_preds=False,
+ chunk_size=None,
+ sample_tokens=None,
+ ):
+ if sample_tokens is None:
+ sample_tokens = self.n_ctx
+ # Preprocess.
+ batch_size = lyric_and_music_tokens.shape[0]
+ with torch.no_grad():
+ lyric_and_music_tokens = lyric_and_music_tokens.view(batch_size, -1).long()
+
+ sampled_audio = torch.split(lyric_and_music_tokens, 1, dim=1)
+ sampled_audio = list(sampled_audio)
+
+ if not self.audio_conditioning:
+ audio_conditioning = torch.zeros(
+ (n_samples, 1, self.width), dtype=self.transformer._attn_mods[0].mlp.c_fc.weight.dtype
+ ).to(lyric_and_music_tokens.device)
+
+ with torch.no_grad():
+ if get_preds:
+ preds = []
+
+ # Fill up key/value cache for past context by running forward pass.
+ # We do so in chunks instead of doing the whole past in one forward pass to reduce max memory usage.
+ if chunk_size is None:
+ chunk_size = len(sampled_audio)
+ chunk_sizes = self.split_chunks(len(sampled_audio), chunk_size)
+ x_primes = []
+ start = 0
+ token = None
+
+ for current_chunk_size in tqdm(chunk_sizes, desc="Preparing past key value", leave=False):
+ sampled_audio_prime, conds_prime = [], []
+ for sample_t in range(start, start + current_chunk_size):
+ x_prime, cond_prime = self.get_emb(
+ sample_t, n_samples, token, audio_conditioning, metadata_conditioning
+ )
+ token = sampled_audio[sample_t]
+ sampled_audio_prime.append(x_prime)
+ conds_prime.append(cond_prime)
+ start = start + current_chunk_size
+ x_prime, cond_prime = torch.cat(sampled_audio_prime, dim=1), torch.cat(conds_prime, dim=1)
+ del sampled_audio_prime
+ del conds_prime
+ if not get_preds:
+ del cond_prime
+ x_prime = self.transformer(x_prime, last_encoder_hidden_states=last_encoder_hidden_states, sample=True)
+
+ if get_preds:
+ if self.add_cond_after_transformer:
+ x_prime = x_prime + cond_prime
+ del cond_prime
+ x_primes.append(x_prime)
+ else:
+ del x_prime
+
+ if get_preds:
+ x_prime = torch.cat(x_primes, dim=1)
+ x_prime = self.fc_proj_out(x_prime) # Predictions
+ preds.append(x_prime)
+
+ # the input of the encoder and decoder can be merged into (lyrics, music tokens)
+ input_tokens = sampled_audio[-1]
+
+ itererator = tqdm(
+ range(len(sampled_audio), sample_tokens),
+ desc=f"Sampling {len(range(len(sampled_audio), sample_tokens))} music tokens",
+ leave=False,
+ )
+ for sample_t in itererator:
+ hidden_states, cond = self.get_emb(
+ sample_t, n_samples, input_tokens, audio_conditioning, metadata_conditioning
+ )
+
+ hidden_states = self.transformer(
+ hidden_states, last_encoder_hidden_states=last_encoder_hidden_states, sample=True
+ )
+ if self.add_cond_after_transformer:
+ hidden_states = hidden_states + cond
+ hidden_states = self.fc_proj_out(hidden_states) # Predictions
+ if get_preds:
+ preds.append(hidden_states)
+ # Adjust logits
+ hidden_states = hidden_states / temp
+ hidden_states = filter_logits(hidden_states, top_k=top_k, top_p=top_p)
+ # only music tokens are sampled
+ music_tokens = torch.distributions.Categorical(logits=hidden_states).sample()
+ sampled_audio.append(music_tokens.clone())
+ input_tokens = music_tokens
+
+ del input_tokens, music_tokens
+ self.transformer.del_cache()
+
+ music_tokens = torch.cat(sampled_audio, dim=1)
+ if get_preds:
+ preds = torch.cat(preds, dim=1)
+ if get_preds:
+ return music_tokens, preds
+ else:
+ return music_tokens
+
+
+class JukeboxMusicTokenConditioner(nn.Module):
+ """
+ The `JukeboxMusicTokenConditioner` takes music tokens as an input (corresponding to the codes of the VQVAE's
+ codebook) and upsamples it using a single layer of decoder convolution block (the same is used in the VQVAE).
+ """
+
+ def __init__(self, config, level):
+ super().__init__()
+ self.embed_tokens = nn.Embedding(config.music_vocab_size, config.hidden_size)
+ config.embed_dim = config.music_vocab_size # setting correct argument for the `JukeboxDecoder`
+
+ self.upsampler = JukeboxDecoderConvBock(
+ config,
+ config.hidden_size,
+ config.res_conv_width,
+ config.res_conv_depth,
+ config.res_downs_t[level],
+ config.res_strides_t[level],
+ reverse_dilation=False,
+ )
+ self.layer_norm = JukeboxLayerNorm(config.hidden_size)
+
+ def forward(self, music_tokens, raw_audio_conditioning=None):
+ """
+ Args:
+ music_tokens (`torch.LongTensor`):
+ Music tokens form the upper level in range(nb_discrete_codes)
+ raw_audio_conditioning (`torch.LongTensor`, *optional*):
+ Audio used when primed sampling, raw audio information that conditions the generation
+ """
+ if raw_audio_conditioning is None:
+ raw_audio_conditioning = 0.0
+ # Embed music_tokens
+ music_tokens = music_tokens.long()
+ hidden_states = self.embed_tokens(music_tokens)
+ hidden_states = hidden_states + raw_audio_conditioning
+
+ # Run conditioner
+ hidden_states = hidden_states.permute(0, 2, 1)
+ hidden_states = self.upsampler(hidden_states)
+ hidden_states = hidden_states.permute(0, 2, 1)
+ hidden_states = self.layer_norm(hidden_states)
+ return hidden_states
+
+
+class JukeboxRangeEmbedding(nn.Module):
+ """
+ The `JukeboxRangeEmbedding` interpolate the given [pos_start, pos_end] to obtain an equivalent of time positional
+ embedding of length `n_ctx`.
+
+ Binning process : For each pos in position tensor, find its bin [start,end) mapped to [0,1,...,bins-1] [start,end)
+ -> [0,1) -> [0, bins) -> floor -> [0,...,bins-1] NOTE: Open ended interval on right, so start <= pos < end, not <=
+ end
+ """
+
+ def __init__(self, n_time, embed_dim, range, out_width, clamp=False):
+ super().__init__()
+ self.n_time = n_time
+ self.embed_dim = embed_dim
+ self.emb = nn.Embedding(embed_dim, out_width)
+ self.pos_min, self.pos_max = range
+ self.clamp = clamp
+
+ def forward(self, pos_start, pos_end=None):
+ # Check if [pos_start,pos_end] in [pos_min, pos_max)
+ if not len(pos_start.shape) == 2:
+ raise TypeError(f"Expected shape with 2 dims, got {pos_start.shape}")
+ if not (self.pos_min <= pos_start).all() and (pos_start < self.pos_max).all():
+ raise TypeError(f"Range is [{self.pos_min},{self.pos_max}), got {pos_start}")
+
+ pos_start = pos_start.float()
+ if pos_end is not None:
+ if self.clamp:
+ pos_end = pos_end.clamp(self.pos_min, self.pos_max)
+
+ pos_end = pos_end.float()
+ # Interpolate so that [pos_start, ..., pos_end] <-> position tensor of length n_ctx
+ n_time = self.n_time
+ if n_time != 1:
+ interpolation = (
+ torch.arange(0, n_time, dtype=torch.float, device=pos_start.device).view(1, n_time) / n_time
+ )
+ position = pos_start + (pos_end - pos_start) * interpolation
+ else:
+ position = pos_start
+
+ # Bin each value to bins_
+ # [0,1) -> [0,1..,embed_dim) -> [0,1...,embed_dim-1
+ normalised_position = (position - self.pos_min) / (self.pos_max - self.pos_min)
+ bins_ = (self.embed_dim * normalised_position).floor().long().detach()
+ return self.emb(bins_)
+
+
+class JukeboxLabelConditioner(nn.Module):
+ def __init__(self, config, include_time_signal):
+ super().__init__()
+
+ embed_dim = config.hidden_size
+ timing_dims = config.timing_dims
+ sampling_rate = config.sampling_rate
+ nb_genres, nb_artists = config.metadata_dims
+ music_tokens_shape = config.n_ctx
+
+ self.max_nb_genres = config.max_nb_genres
+ self.bow_genre_emb = nn.Embedding(nb_genres, embed_dim)
+ self.artist_emb = nn.Embedding(nb_artists, embed_dim)
+ self.include_time_signal = include_time_signal
+ if self.include_time_signal:
+ total_length_range = (config.min_duration * sampling_rate, config.max_duration * sampling_rate)
+ absolute_pos_range = (0.0, config.max_duration * sampling_rate)
+ relative_pos_range = (0.0, 1.0)
+ self.total_length_emb = JukeboxRangeEmbedding(1, timing_dims, total_length_range, embed_dim)
+ self.absolute_pos_emb = JukeboxRangeEmbedding(
+ music_tokens_shape, timing_dims, absolute_pos_range, embed_dim
+ )
+ self.relative_pos_emb = JukeboxRangeEmbedding(
+ music_tokens_shape, timing_dims, relative_pos_range, embed_dim, clamp=True
+ )
+
+ def forward(self, metadata):
+ total_length = metadata[:, 0:1]
+ offset = metadata[:, 1:2]
+ length = metadata[:, 2:3]
+ artist = metadata[:, 3:4]
+ genre = metadata[:, 4:]
+
+ # Start embedding of length 1
+ artist_emb = self.artist_emb(artist)
+ # Empty genre slots are denoted by -1. We mask these out.
+ mask = (genre >= 0).float().unsqueeze(2)
+ genre_emb = (self.bow_genre_emb(genre.clamp(0)) * mask).sum(dim=1, keepdim=True)
+ start_emb = genre_emb + artist_emb
+
+ # Pos embedding of length n_ctx
+ if self.include_time_signal:
+ start, end = offset, offset + length
+ total_length = total_length.float()
+ start = start.float()
+ end = end.float()
+ pos_emb = (
+ self.total_length_emb(total_length)
+ + self.absolute_pos_emb(start, end)
+ + self.relative_pos_emb(start / total_length, end / total_length)
+ )
+ else:
+ pos_emb = None
+ return start_emb, pos_emb
+
+
+class JukeboxPrior(PreTrainedModel):
+ """
+ The JukeboxPrior class, which is a wrapper around the various conditioning and the transformer. JukeboxPrior can be
+ seen as language models trained on music. They model the next `music token` prediction task. If a (lyric) `encoderù
+ is defined, it also models the `next character` prediction on the lyrics. Can be conditioned on timing, artist,
+ genre, lyrics and codes from lower-levels Priors.
+
+ Args:
+ config (`JukeboxPriorConfig`):
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
+ load the weights associated with the model, only the configuration. Check out the
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+ level (`int`, *optional*):
+ Current level of the Prior. Should be in range `[0,nb_priors]`.
+ nb_priors (`int`, *optional*, defaults to 3):
+ Total number of priors.
+ vqvae_encoder (`Callable`, *optional*):
+ Encoding method of the VQVAE encoder used in the forward pass of the model. Passing functions instead of
+ the vqvae module to avoid getting the parameters.
+ vqvae_decoder (`Callable`, *optional*):
+ Decoding method of the VQVAE decoder used in the forward pass of the model. Passing functions instead of
+ the vqvae module to avoid getting the parameters.
+ """
+
+ config: JukeboxPriorConfig
+
+ def _init_weights(self, module):
+ init_scale = self.config.init_scale
+
+ if isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=0.02 * init_scale)
+ elif isinstance(module, JukeboxConv1D):
+ if self.config.zero_out:
+ module.weight.data.zero_()
+ else:
+ module.weight.data.normal_(mean=0.0, std=0.02 * init_scale)
+ elif isinstance(module, JukeboxPositionalEmbedding):
+ module.pos_emb.data.normal_(mean=0.0, std=0.01 * init_scale)
+ elif isinstance(module, JukeboxRangeEmbedding):
+ module.emb.weight.data.normal_(mean=0.0, std=0.01 * init_scale)
+ elif isinstance(module, JukeboxConditionalAutoregressive) and hasattr(module, "lm_head"):
+ module.lm_head.weight.data.normal_(mean=0.0, std=0.02 * init_scale)
+ elif isinstance(module, JukeboxConditionalAutoregressive) and hasattr(module, "start_token"):
+ module.start_token.data.normal_(mean=0.0, std=0.01 * init_scale)
+ elif isinstance(module, JukeboxResConv1DBlock) and self.config.zero_out:
+ module.conv1d_2.weight.data.zero_()
+ module.conv1d_2.bias.data.zero_()
+ if isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ if isinstance(module, nn.Linear) and module.bias is not None:
+ module.bias.data.zero_()
+
+ def __init__(self, config: JukeboxPriorConfig, level=None, nb_priors=3, vqvae_encoder=None, vqvae_decoder=None):
+ super().__init__(config)
+ # Passing functions instead of the vqvae module to avoid getting params, only used in the
+ # forward loop
+ self.vqvae_encoder = vqvae_encoder
+ self.vqvae_decoder = vqvae_decoder
+
+ self.levels = nb_priors
+ self.level = level if level is not None else config.level
+
+ self.base_model_prefix = f"priors.{self.level}"
+
+ self.n_ctx = config.n_ctx
+
+ self.lyric_conditioning = config.nb_relevant_lyric_tokens > 0
+ self.nb_relevant_lyric_tokens = config.nb_relevant_lyric_tokens
+ self.encoder_loss_fraction = config.encoder_loss_fraction
+
+ # Audio conditioning : conditioning on music tokens (either from audio or from previous levels or both)
+ self.audio_conditioning = self.level != 0
+ self.cond_level = self.level - 1
+ if self.audio_conditioning:
+ self.conditioner_blocks = JukeboxMusicTokenConditioner(config, self.level)
+
+ # metadata conditioning : contioning on timing, genres, and artist
+ self.metadata_conditioning = config.metadata_conditioning
+ if self.metadata_conditioning:
+ self.metadata_embedding = JukeboxLabelConditioner(config, include_time_signal=not self.audio_conditioning)
+
+ # define encoder-decoder or encoder and decoder
+ self.is_encoder_decoder = config.is_encoder_decoder
+ if config.is_encoder_decoder:
+ # encoder-decoder transformer
+ self.input_shapes = [config.nb_relevant_lyric_tokens, config.n_ctx]
+ self.embed_dim_shift = [0, config.lyric_vocab_size]
+ self.width = config.hidden_size
+
+ self.nb_relevant_lyric_tokens = config.nb_relevant_lyric_tokens
+
+ self.prior = JukeboxConditionalAutoregressive(
+ config,
+ n_ctx=config.nb_relevant_lyric_tokens + config.n_ctx,
+ embed_dim=config.lyric_vocab_size + config.music_vocab_size,
+ audio_conditioning=(self.audio_conditioning or self.metadata_conditioning),
+ metadata_conditioning=True,
+ )
+
+ else:
+ # Separate encoder-decoder transformer
+ encoder_config = config.encoder_config
+
+ if self.nb_relevant_lyric_tokens != 0 and self.lyric_conditioning:
+ self.lyric_acts_width = encoder_config.hidden_size
+ self.encoder_width = config.hidden_size
+ self.encoder_dim = config.lyric_vocab_size
+ self.encoder = JukeboxConditionalAutoregressive(
+ encoder_config,
+ n_ctx=self.nb_relevant_lyric_tokens,
+ embed_dim=self.encoder_dim,
+ audio_conditioning=False,
+ metadata_conditioning=False,
+ is_encoder=True,
+ )
+ self.encoder.proj_in = JukeboxConv1D(encoder_config.hidden_size, config.hidden_size)
+ self.encoder.final_layer_norm = JukeboxLayerNorm(config.hidden_size)
+ self.encoder.lm_head = nn.Linear(config.hidden_size, config.lyric_vocab_size, bias=False)
+ else:
+ self.nb_relevant_lyric_tokens = 0
+
+ # decoder model on the tokens
+ self.prior = JukeboxConditionalAutoregressive(
+ config,
+ audio_conditioning=(self.audio_conditioning or self.metadata_conditioning),
+ metadata_conditioning=self.metadata_conditioning,
+ )
+
+ self.next_token_prediction_loss_dims = config.n_ctx
+ self.total_loss_dims = self.nb_relevant_lyric_tokens + self.next_token_prediction_loss_dims
+
+ self.downsamples = [stride**down for stride, down in zip(config.res_strides_t, config.res_downs_t)]
+ self.cond_downsample = self.downsamples[self.level] if self.level != 0 else None
+ self.raw_to_tokens = np.prod(self.downsamples[: nb_priors - self.level])
+ self.sample_length = self.n_ctx * self.raw_to_tokens
+
+ logger.info(
+ f"Level:{self.level}, Cond downsample:{self.cond_downsample}, Raw to tokens:{self.raw_to_tokens}, Sample"
+ f" length:{self.sample_length}"
+ )
+
+ def get_metadata(self, labels, start, total_length, offset, get_indices=False):
+ metadata = labels.clone()
+ metadata[:, 0] = total_length
+ # Set sample_length to match this level
+ metadata[:, 2] = int(self.sample_length)
+
+ # Set offset
+ metadata[:, 1:2] = int(offset * self.raw_to_tokens) + int(start * self.raw_to_tokens)
+ # here since metadata has the full token_list, we just need to selected the ones that are relevant
+
+ # Set lyric tokens
+ metadata, indices = self.set_metadata_lyric_tokens(metadata)
+ if get_indices:
+ return metadata, indices
+ else:
+ return metadata
+
+ def set_metadata_lyric_tokens(self, labels):
+ """
+ Processes the full labels to only retrieve the relevant lyric tokens and keep the metadata conditioning tokens.
+ """
+ if self.nb_relevant_lyric_tokens > 0:
+ tokens_list = torch.zeros(
+ (labels.shape[0], self.nb_relevant_lyric_tokens), dtype=torch.long, device=labels.device
+ )
+ indices_list = [] # what's the index of each current character in original array
+ for idx in range(labels.shape[0]):
+ full_tokens = labels.clone()[:, 4 + self.metadata_embedding.max_nb_genres :]
+ total_length, offset, duration = labels[idx, 0], labels[idx, 1], labels[idx, 2]
+ tokens, indices = get_relevant_lyric_tokens(
+ full_tokens, self.nb_relevant_lyric_tokens, total_length, offset, duration
+ )
+ tokens_list[idx, :] = tokens
+ indices_list.append(indices)
+
+ return (
+ torch.cat((labels[:, : 4 + self.metadata_embedding.max_nb_genres], tokens_list), dim=-1),
+ indices_list,
+ )
+ else:
+ return labels, None
+
+ def get_music_tokens_conds(self, music_tokens, start, end):
+ """
+ Extracts current level's conditioning music tokens.
+ """
+ if self.level != 0:
+ music_tokens_cond = music_tokens[self.level - 1]
+ music_tokens = music_tokens_cond[:, start // self.cond_downsample : end // self.cond_downsample]
+ missing_cond_len = self.n_ctx // self.cond_downsample - music_tokens_cond[-1].shape[-1]
+ if missing_cond_len > 0:
+ init_cond = torch.zeros(1, missing_cond_len).to(music_tokens_cond.device)
+ music_tokens_cond = torch.cat((music_tokens_cond, init_cond), dim=-1).long()
+ music_tokens_conds = [music_tokens_cond]
+ else:
+ music_tokens_conds = None
+ return music_tokens_conds
+
+ def prior_preprocess(self, tokens, conds):
+ """
+ Shifts the input tokens to account for the dictionary merge. The embed_dim_shift give by how much the music
+ tokens should be shifted by. It is equal to `lyric_vocab_size`.
+ """
+ batch_size = tokens[0].shape[0]
+ for i in range(len(tokens)):
+ tokens[i] = (tokens[i] + int(self.embed_dim_shift[i])).view(batch_size, -1)
+
+ for i in range(len(conds)):
+ if conds[i] is None:
+ conds[i] = torch.zeros(
+ (batch_size, self.input_shapes[i], self.width), dtype=tokens[0].dtype, device=tokens[0].device
+ )
+
+ return torch.cat(tokens, dim=1), torch.cat(conds, dim=1)
+
+ def prior_postprocess(self, tokens):
+ """
+ Shifts back the input tokens if the model uses an encoder decoder architecture. As the embedding layer is
+ shared, `prior_embed_dim_shift` shifts the music token ids by `lyric_vocab_size`. Only returns the music
+ tokens.
+ """
+ batch_size = tokens.shape[0]
+ dims = (self.input_shapes[0], tokens.shape[1] - self.input_shapes[0])
+ tokens = list(torch.split(tokens, dims, dim=1))
+
+ # Some of the input tokens might be shifted to take into account the voccabulary fusion
+ for i in range(len(tokens)):
+ bins_shift = int(self.embed_dim_shift[i])
+ tokens[i] = (tokens[i] - bins_shift).view(batch_size, -1)
+ tokens[i] = torch.clamp(tokens[i], min=0)
+ # If not masking loss, model may have generated lyric/midi tokens which are now shifted <0 by bin_shift
+ return tokens[-1]
+
+ def embed_tokens(self, music_tokens_conds):
+ """
+ Embeds the upper level music tokens and upsamples them to provide as audio conditioning.
+ """
+ music_tokens_conds = music_tokens_conds[: self.cond_level + 1]
+ audio_conditioning = None
+ for music_tokens_cond, conditioner_block in reversed(list(zip(music_tokens_conds, [self.conditioner_blocks]))):
+ audio_conditioning = conditioner_block(music_tokens_cond, audio_conditioning)
+ return audio_conditioning
+
+ def encode(self, hidden_states, start_level=None, end_level=None, bs_chunks=1):
+ """
+ Encodes the hidden states (raw audio) using the VQVAE's encoder. Returns latent_states.
+ """
+ if start_level is None:
+ start_level = self.level
+ if end_level is None:
+ end_level = self.levels
+ # Get latents
+ with torch.no_grad():
+ latent_states = self.vqvae_encoder(
+ hidden_states, start_level=start_level, end_level=end_level, bs_chunks=bs_chunks
+ )
+ return latent_states
+
+ def decode(self, music_tokens, start_level=None, end_level=None, bs_chunks=1):
+ """
+ Usamples the sequence of codebook vectors to a raw audio.
+ """
+ if start_level is None:
+ start_level = self.level
+ if end_level is None:
+ end_level = self.levels
+ with torch.no_grad():
+ output = self.vqvae_decoder(
+ music_tokens, start_level=start_level, end_level=end_level, bs_chunks=bs_chunks
+ )
+ return output
+
+ def get_cond(self, music_tokens_conds, metadata):
+ """
+ Converts the input tokens to input_embeddings. Splits the lyrics form the rest of the metadata. Lyric tokens
+ can be None.
+ """
+ if metadata is not None:
+ n_labels = metadata.shape[1] - self.nb_relevant_lyric_tokens
+ metadata, lyric_tokens = metadata[:, :n_labels], metadata[:, n_labels:]
+ else:
+ metadata, lyric_tokens = None, None
+ metadata_conditioning, metadata_pos = (
+ self.metadata_embedding(metadata) if self.metadata_conditioning else (None, None)
+ )
+ audio_conditioning = self.embed_tokens(music_tokens_conds) if self.audio_conditioning else metadata_pos
+ return audio_conditioning, metadata_conditioning, lyric_tokens
+
+ def sample(
+ self,
+ n_samples,
+ music_tokens=None,
+ music_tokens_conds=None,
+ metadata=None,
+ temp=1.0,
+ top_k=0,
+ top_p=0.0,
+ chunk_size=None,
+ sample_tokens=None,
+ ):
+ """
+ Ancestral/Prime sampling a window of tokens using the provided conditioning and metadatas.
+
+ Args:
+ n_samples (`int`):
+ Number of samples to generate.
+ music_tokens (`list[torch.LongTensor]`, *optional*):
+ Previously generated tokens at the current level. Used as context for the generation.
+ music_tokens_conds (`list[torch.FloatTensor]`, *optional*):
+ Upper-level music tokens generated by the previous prior model. Is `None` if the generation is not
+ conditioned on the upper-level tokens.
+ metadata (`list[torch.LongTensor]`, *optional*):
+ List containing the metadata tensor with the artist, genre and the lyric tokens.
+ temp (`float`, *optional*, defaults to 1.0):
+ Sampling temperature.
+ top_k (`int`, *optional*, defaults to 0):
+ Top k probabilities used for filtering.
+ top_p (`float`, *optional*, defaults to 0.0):
+ Top p probabilities used for filtering.
+ chunk_size (`int`, *optional*):
+ Size of the chunks used to prepare the cache of the transformer.
+ sample_tokens (`int`, *optional*):
+ Number of tokens to sample.
+
+ """
+ no_past_context = music_tokens is None or music_tokens.shape[1] == 0
+ name = {True: "Ancestral", False: "Primed"}[no_past_context]
+ logger.info(f"{name} sampling {n_samples} samples with temp={temp}, top_k={top_k}, top_p={top_p}")
+
+ with torch.no_grad():
+ # Currently audio_conditioning only uses immediately above layer
+ audio_conditioning, metadata_conditioning, lyric_tokens = self.get_cond(music_tokens_conds, metadata)
+ if self.is_encoder_decoder:
+ if no_past_context: # the prime_sample function will be used with music_tokens set to None
+ lyric_and_music_tokens, audio_conditioning = self.prior_preprocess(
+ [lyric_tokens], [None, audio_conditioning]
+ )
+ else:
+ lyric_and_music_tokens, audio_conditioning = self.prior_preprocess(
+ [lyric_tokens, music_tokens], [None, audio_conditioning]
+ )
+ if sample_tokens is not None:
+ sample_tokens += self.nb_relevant_lyric_tokens
+ music_tokens = self.prior.primed_sample(
+ n_samples,
+ lyric_and_music_tokens,
+ audio_conditioning,
+ metadata_conditioning,
+ temp=temp,
+ top_k=top_k,
+ top_p=top_p,
+ chunk_size=chunk_size,
+ sample_tokens=sample_tokens,
+ )
+ music_tokens = self.prior_postprocess(music_tokens)
+ else:
+ last_encoder_hidden_states = self.get_encoder_states(lyric_tokens, sample=True)
+ if no_past_context:
+ music_tokens = self.prior.sample(
+ n_samples,
+ audio_conditioning,
+ metadata_conditioning,
+ last_encoder_hidden_states,
+ temp=temp,
+ top_k=top_k,
+ top_p=top_p,
+ sample_tokens=sample_tokens,
+ )
+ else:
+ music_tokens = self.prior.primed_sample(
+ n_samples,
+ music_tokens,
+ audio_conditioning,
+ metadata_conditioning,
+ last_encoder_hidden_states,
+ temp=temp,
+ top_k=top_k,
+ top_p=top_p,
+ chunk_size=chunk_size,
+ sample_tokens=sample_tokens,
+ )
+ return music_tokens
+
+ def get_encoder_states(self, lyric_tokens, sample=False):
+ """
+ Retrieve the last hidden_states of the lyric encoder that will be attended to by the decoder. Forwards through
+ the lyric encoder.
+ """
+ if self.nb_relevant_lyric_tokens != 0 and self.lyric_conditioning:
+ if sample:
+ self.encoder = self.encoder.to(lyric_tokens.device)
+ lyric_acts = self.encoder(lyric_tokens, None, None, None)
+ lyric_acts = self.encoder.proj_in(lyric_acts)
+ last_encoder_hidden_states = self.encoder.final_layer_norm(lyric_acts)
+ else:
+ last_encoder_hidden_states = None
+ return last_encoder_hidden_states
+
+ def get_encoder_loss(self, last_encoder_hidden_states, target_lyrics):
+ """
+ Computes the loss for the lyric encoder: next lyric token prediction.
+ """
+ if self.lyric_conditioning:
+ last_encoder_hidden_states = self.encoder.lm_head(last_encoder_hidden_states)
+ encoder_loss = nn.functional.cross_entropy(
+ last_encoder_hidden_states.view(-1, self.encoder_dim), target_lyrics.view(-1)
+ ) / np.log(2.0)
+ else:
+ encoder_loss = torch.tensor(0.0, device=last_encoder_hidden_states.device)
+ return encoder_loss
+
+ def forward_tokens(
+ self, music_tokens, music_tokens_conds=[], metadata=None, get_preds=False, get_attn_weights=False
+ ):
+ """
+ Applies a forward pass using the conditioning tokens. Different from the classic forward as it does not use the
+ vqvae's encoding layers.
+ """
+ if get_attn_weights:
+ self.prior.transformer.set_record_attn(get_attn_weights)
+ audio_conditioning, metadata_conditioning, lyric_tokens = self.get_cond(music_tokens_conds, metadata)
+
+ if self.is_encoder_decoder: # the preprocess returns the full tokens (Lyrics and Music tokens), shifted
+ tokens, audio_conditioning = self.prior_preprocess(
+ [lyric_tokens, music_tokens], [None, audio_conditioning]
+ )
+ (encoder_loss, next_token_prediction_loss), preds = self.prior(
+ tokens, audio_conditioning, metadata_conditioning, get_sep_loss=True, get_preds=get_preds
+ )
+ else:
+ last_encoder_hidden_states = self.get_encoder_states(lyric_tokens)
+ encoder_loss = self.get_encoder_loss(last_encoder_hidden_states, lyric_tokens)
+ next_token_prediction_loss, preds = self.prior(
+ music_tokens,
+ audio_conditioning,
+ metadata_conditioning,
+ last_encoder_hidden_states,
+ get_preds=get_preds,
+ )
+ loss = self.encoder_loss_fraction * encoder_loss * self.nb_relevant_lyric_tokens / self.total_loss_dims
+ loss += next_token_prediction_loss * self.next_token_prediction_loss_dims / self.total_loss_dims
+
+ metrics = {
+ "bpd": next_token_prediction_loss.detach().clone(),
+ "encoder_loss": encoder_loss.detach().clone(),
+ "next_token_prediction_loss": next_token_prediction_loss.detach().clone(),
+ }
+ if get_preds:
+ metrics["preds"] = preds.detach().clone()
+ if get_attn_weights:
+ saved_attn_weights = self.prior.transformer.saved_attn_weights
+ self.prior.transformer.set_record_attn(False)
+ return saved_attn_weights
+ else:
+ return loss, metrics
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ metadata: Optional[list[torch.LongTensor]],
+ decode: Optional[bool] = False,
+ get_preds: Optional[bool] = False,
+ ) -> list[torch.Tensor]:
+ """
+ Encode the hidden states using the `vqvae` encoder, and then predicts the next token in the `forward_tokens`
+ function. The loss is the sum of the `encoder` loss and the `decoder` loss.
+
+ Args:
+ hidden_states (`torch.Tensor`):
+ Hidden states which should be raw audio
+ metadata (`list[torch.LongTensor]`, *optional*):
+ List containing the metadata conditioning tensor with the lyric and the metadata tokens.
+ decode (`bool`, *optional*, defaults to `False`):
+ Whether or not to decode the encoded to tokens.
+ get_preds (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the actual predictions of the model.
+ """
+ batch_size = hidden_states.shape[0]
+ music_tokens, *music_tokens_conds = self.encode(hidden_states, bs_chunks=batch_size)
+ loss, metrics = self.forward_tokens(
+ music_tokens=music_tokens,
+ music_tokens_conds=music_tokens_conds,
+ metadata=metadata,
+ get_preds=get_preds,
+ )
+ if decode:
+ dequantised_states = self.decode([music_tokens, *music_tokens_conds])
+ else:
+ dequantised_states = None
+ return dequantised_states, loss, metrics
+
+
+class JukeboxPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: JukeboxConfig
+ base_model_prefix = "jukebox"
+ supports_gradient_checkpointing = False
+
+ def _init_weights(self, module):
+ if isinstance(module, (JukeboxPrior, JukeboxVQVAE)):
+ module.apply(module._init_weights)
+
+ def __init__(self, *inputs, **kwargs):
+ super().__init__(*inputs, **kwargs)
+
+
+JUKEBOX_SAMPLING_INPUT_DOCSTRING = r"""
+ labels (`list[torch.LongTensor]` of length `n_sample`, and shape `(self.levels, self.config.max_nb_genre + lyric_sequence_length)` :
+ List of metadata such as `artist_id`, `genre_id` and the full list of lyric tokens which are used to
+ condition the generation.
+ sampling_kwargs (`dict[Any]`):
+ Various additional sampling arguments that are used by the `_sample` function. A detail list of the
+ arguments can bee seen in the [`_sample`] function documentation.
+"""
+
+
+@add_start_docstrings(
+ """The bare JUKEBOX Model used for music generation. 4 sampling techniques are supported : `primed_sample`, `upsample`,
+ `continue_sample` and `ancestral_sample`. It does not have a `forward` method as the training is not end to end. If
+ you want to fine-tune the model, it is recommended to use the `JukeboxPrior` class and train each prior
+ individually.
+ """,
+ JUKEBOX_START_DOCSTRING,
+)
+class JukeboxModel(JukeboxPreTrainedModel):
+ _no_split_modules = ["JukeboxBlock"]
+
+ def __init__(self, config):
+ super().__init__(config)
+ vqvae_config = config.vqvae_config
+ self.vqvae = JukeboxVQVAE(vqvae_config)
+ self.set_shared_params(config)
+ self.priors = nn.ModuleList(
+ [JukeboxPrior(config.prior_configs[level], level) for level in range(config.nb_priors)]
+ )
+
+ def set_shared_params(self, model_config):
+ """
+ Initialises the parameters that are shared. This has to be done here because the list of `JukeboxPriorConfig`
+ is nest, and is thus unreachable in the `from_dict` function
+ """
+ for config in model_config.prior_configs:
+ config.sampling_rate = model_config.sampling_rate
+ config.timing_dims = model_config.timing_dims
+ config.min_duration = model_config.min_duration
+ config.max_duration = model_config.max_duration
+ config.max_nb_genres = model_config.max_nb_genres
+ config.metadata_conditioning = model_config.metadata_conditioning
+
+ def decode(self, music_tokens, start_level=0, end_level=None, bs_chunks=1):
+ return self.vqvae.decode(music_tokens, start_level, end_level, bs_chunks)
+
+ def encode(self, input_audio, start_level=0, end_level=None, bs_chunks=1):
+ return self.vqvae.encode(input_audio, start_level, end_level, bs_chunks)
+
+ def split_batch(self, obj, n_samples, split_size):
+ n_passes = (n_samples + split_size - 1) // split_size
+ if isinstance(obj, torch.Tensor):
+ return torch.split(obj, split_size, dim=0)
+ elif isinstance(obj, list):
+ return list(zip(*[torch.split(item, split_size, dim=0) for item in obj]))
+ elif obj is None:
+ return [None] * n_passes
+ else:
+ raise TypeError("Unknown input type")
+
+ # Sample a partial window of length= self.priors[level].n_ctx:
+ iterator = get_starts(total_length, self.priors[level].n_ctx, hop_length)
+ for start in iterator:
+ music_tokens = self.sample_single_window(
+ music_tokens, labels, offset, sampling_kwargs, level, start, max_batch_size
+ )
+
+ else:
+ music_tokens = self.sample_partial_window(
+ music_tokens, labels, offset, sampling_kwargs, level, total_length, max_batch_size
+ )
+ return music_tokens
+
+ @torch.no_grad()
+ def _sample(
+ self,
+ music_tokens,
+ labels,
+ sample_levels,
+ metas=None,
+ chunk_size=32,
+ sampling_temperature=0.98,
+ lower_batch_size=16,
+ max_batch_size=16,
+ sample_length_in_seconds=24,
+ compute_alignments=False,
+ sample_tokens=None,
+ offset=0,
+ save_results=True,
+ sample_length=None,
+ ) -> list[torch.LongTensor]:
+ """
+ Core sampling function used to generate music tokens. Iterates over the provided list of levels, while saving
+ the generated raw audio at each step.
+
+ Args:
+ music_tokens (`list[torch.LongTensor]`):
+ A sequence of music tokens of length `self.levels` which will be used as context to continue the
+ sampling process. Should have `self.levels` tensors, each corresponding to the generation at a certain
+ level.
+ labels (`list[torch.LongTensor]`):
+ List of length `n_sample`, and shape `(self.levels, 4 + self.config.max_nb_genre +
+ lyric_sequence_length)` metadata such as `artist_id`, `genre_id` and the full list of lyric tokens
+ which are used to condition the generation.
+ sample_levels (`list[int]`):
+ List of the desired levels at which the sampling will be done. A level is equivalent to the index of
+ the prior in the list of priors
+ metas (`list[Any]`, *optional*):
+ Metadatas used to generate the `labels`
+ chunk_size (`int`, *optional*, defaults to 32):
+ Size of a chunk of audio, used to fill up the memory in chunks to prevent OOM errors. Bigger chunks
+ means faster memory filling but more consumption.
+ sampling_temperature (`float`, *optional*, defaults to 0.98):
+ Temperature used to adjust the randomness of the sampling.
+ lower_batch_size (`int`, *optional*, defaults to 16):
+ Maximum batch size for the lower level priors
+ max_batch_size (`int`, *optional*, defaults to 16):
+ Maximum batch size for the top level priors
+ sample_length_in_seconds (`int`, *optional*, defaults to 24):
+ Desired length of the generation in seconds
+ compute_alignments (`bool`, *optional*, defaults to `False`):
+ Whether or not to compute the alignment between the lyrics and the audio using the top_prior
+ sample_tokens (`int`, *optional*):
+ Precise number of tokens that should be sampled at each level. This is mostly useful for running dummy
+ experiments
+ offset (`int`, *optional*, defaults to 0):
+ Audio offset used as conditioning, corresponds to the starting sample in the music. If the offset is
+ greater than 0, the lyrics will be shifted take that intoaccount
+ save_results (`bool`, *optional*, defaults to `True`):
+ Whether or not to save the intermediate results. If `True`, will generate a folder named with the start
+ time.
+ sample_length (`int`, *optional*):
+ Desired length of the generation in samples.
+
+ Returns: torch.Tensor
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, JukeboxModel, set_seed
+ >>> import torch
+
+ >>> metas = dict(artist="Zac Brown Band", genres="Country", lyrics="I met a traveller from an antique land")
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/jukebox-1b-lyrics")
+ >>> model = JukeboxModel.from_pretrained("openai/jukebox-1b-lyrics", min_duration=0).eval()
+
+ >>> labels = tokenizer(**metas)["input_ids"]
+ >>> set_seed(0)
+ >>> zs = [torch.zeros(1, 0, dtype=torch.long) for _ in range(3)]
+ >>> zs = model._sample(zs, labels, [0], sample_length=40 * model.priors[0].raw_to_tokens, save_results=False)
+ >>> zs[0]
+ tensor([[1853, 1369, 1150, 1869, 1379, 1789, 519, 710, 1306, 1100, 1229, 519,
+ 353, 1306, 1379, 1053, 519, 653, 1631, 1467, 1229, 1229, 10, 1647,
+ 1254, 1229, 1306, 1528, 1789, 216, 1631, 1434, 653, 475, 1150, 1528,
+ 1804, 541, 1804, 1434]])
+ ```
+ """
+
+ top_prior = self.priors[0]
+ if sample_length is not None:
+ total_length = sample_length
+ else:
+ total_length = (
+ int(sample_length_in_seconds * self.config.sampling_rate) // top_prior.raw_to_tokens
+ ) * top_prior.raw_to_tokens
+
+ if sample_levels is None:
+ sample_levels = range(len(self.priors))
+
+ # total length of the signal, might be bit different from the actual generated length
+ self.total_length = total_length
+ for level in sample_levels:
+ sampling_kwargs = {
+ "temp": 0.99 if level == len(self.priors) - 1 else sampling_temperature,
+ "chunk_size": chunk_size,
+ "sample_tokens": sample_tokens,
+ }
+ # Set correct total_length, hop_length, labels and sampling_kwargs for level
+
+ total_token_to_sample = total_length // self.priors[level].raw_to_tokens
+ hop_length = int(self.config.hop_fraction[level] * self.priors[level].n_ctx)
+ max_batch_size = lower_batch_size if level != sample_levels else max_batch_size
+ music_tokens = self.sample_level(
+ music_tokens,
+ labels[level],
+ offset,
+ sampling_kwargs,
+ level,
+ total_token_to_sample,
+ hop_length,
+ max_batch_size,
+ )
+
+ if save_results:
+ self.vqvae.to(music_tokens[level].device)
+ # Decode sample
+ with torch.no_grad():
+ start_level = len(self.priors) - level - 1 # vqvae levels are reversed
+ raw_audio = self.vqvae.decode(
+ music_tokens[: level + 1], start_level=start_level, bs_chunks=music_tokens[level].shape[0]
+ )
+ logdir = f"jukebox/level_{level}"
+ if not os.path.exists(logdir):
+ os.makedirs(logdir)
+ save_temp_audio(logdir, level, metas=metas, aud=raw_audio.float())
+ if compute_alignments and self.priors[0] is not None and self.priors[0].nb_relevant_lyric_tokens > 0:
+ with torch.no_grad():
+ alignments = get_alignment(music_tokens, labels[0], self.priors[0], self.config)
+ torch.save({"alignments": alignments}, f"{logdir}/lyric_alignments.pt")
+
+ return music_tokens
+
+ @add_start_docstrings(
+ """
+ Generates music tokens based on the provided `labels. Will start at the desired prior level and automatically
+ upsample the sequence. If you want to create the audio, you should call `model.decode(tokens)`, which will use
+ the VQ-VAE decoder to convert the music tokens to raw audio.
+
+ Args:
+ labels (`list[torch.LongTensor]`) :
+ List of length `n_sample`, and shape `(self.levels, 4 + self.config.max_nb_genre +
+ lyric_sequence_length)` metadata such as `artist_id`, `genre_id` and the full list of lyric tokens
+ which are used to condition the generation.
+ n_samples (`int`, *optional*, default to 1) :
+ Number of samples to be generated in parallel.
+ """,
+ )
+ def ancestral_sample(self, labels, n_samples=1, **sampling_kwargs) -> list[torch.LongTensor]:
+ """
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, JukeboxModel, set_seed
+
+ >>> model = JukeboxModel.from_pretrained("openai/jukebox-1b-lyrics", min_duration=0).eval()
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/jukebox-1b-lyrics")
+
+ >>> lyrics = "Hey, are you awake? Can you talk to me?"
+ >>> artist = "Zac Brown Band"
+ >>> genre = "Country"
+ >>> metas = tokenizer(artist=artist, genres=genre, lyrics=lyrics)
+ >>> set_seed(0)
+ >>> music_tokens = model.ancestral_sample(metas.input_ids, sample_length=400)
+
+ >>> with torch.no_grad():
+ ... model.decode(music_tokens)[:, :10].squeeze(-1)
+ tensor([[-0.0219, -0.0679, -0.1050, -0.1203, -0.1271, -0.0936, -0.0396, -0.0405,
+ -0.0818, -0.0697]])
+ ```
+ """
+
+ sample_levels = sampling_kwargs.pop("sample_levels", list(range(len(self.priors))))
+ music_tokens = [
+ torch.zeros(n_samples, 0, dtype=torch.long, device=labels[0].device) for _ in range(len(self.priors))
+ ]
+ music_tokens = self._sample(music_tokens, labels, sample_levels, **sampling_kwargs)
+ return music_tokens
+
+ @add_start_docstrings(
+ """Generates a continuation of the previously generated tokens.
+
+ Args:
+ music_tokens (`list[torch.LongTensor]` of length `self.levels` ) :
+ A sequence of music tokens which will be used as context to continue the sampling process. Should have
+ `self.levels` tensors, each corresponding to the generation at a certain level.
+ """,
+ JUKEBOX_SAMPLING_INPUT_DOCSTRING,
+ )
+ def continue_sample(self, music_tokens, labels, **sampling_kwargs) -> list[torch.LongTensor]:
+ sample_levels = sampling_kwargs.pop("sample_levels", list(range(len(self.priors))))
+ music_tokens = self._sample(music_tokens, labels, sample_levels, **sampling_kwargs)
+ return music_tokens
+
+ @add_start_docstrings(
+ """Upsamples a sequence of music tokens using the prior at level `level`.
+
+ Args:
+ music_tokens (`list[torch.LongTensor]` of length `self.levels` ) :
+ A sequence of music tokens which will be used as context to continue the sampling process. Should have
+ `self.levels` tensors, each corresponding to the generation at a certain level.
+ """,
+ JUKEBOX_SAMPLING_INPUT_DOCSTRING,
+ )
+ def upsample(self, music_tokens, labels, **sampling_kwargs) -> list[torch.LongTensor]:
+ sample_levels = sampling_kwargs.pop("sample_levels", list(range(len(self.priors) - 1)))
+ music_tokens = self._sample(music_tokens, labels, sample_levels, **sampling_kwargs)
+ return music_tokens
+
+ @add_start_docstrings(
+ """Generate a raw audio conditioned on the provided `raw_audio` which is used as conditioning at each of the
+ generation levels. The audio is encoded to music tokens using the 3 levels of the VQ-VAE. These tokens are
+ used: as conditioning for each level, which means that no ancestral sampling is required.
+
+ Args:
+ raw_audio (`list[torch.Tensor]` of length `n_samples` ) :
+ A list of raw audio that will be used as conditioning information for each samples that will be
+ generated.
+ """,
+ JUKEBOX_SAMPLING_INPUT_DOCSTRING,
+ )
+ def primed_sample(self, raw_audio, labels, **sampling_kwargs) -> list[torch.LongTensor]:
+ sample_levels = sampling_kwargs.pop("sample_levels", list(range(len(self.priors))))
+ self.vqvae.to(raw_audio.device).float()
+ with torch.no_grad():
+ music_tokens = self.vqvae.encode(
+ raw_audio, start_level=0, end_level=len(self.priors), bs_chunks=raw_audio.shape[0]
+ )
+ music_tokens = self._sample(music_tokens, labels, sample_levels, **sampling_kwargs)
+ return music_tokens
+
+
+__all__ = ["JukeboxModel", "JukeboxPreTrainedModel", "JukeboxVQVAE", "JukeboxPrior"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/tokenization_jukebox.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/tokenization_jukebox.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec2162db2cce52876fee37d9806c89b4dbabca2f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/jukebox/tokenization_jukebox.py
@@ -0,0 +1,407 @@
+# coding=utf-8
+# Copyright 2022 The Open AI Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for OpenAI Jukebox."""
+
+import json
+import os
+import re
+import unicodedata
+from json.encoder import INFINITY
+from typing import Any, Optional, Union
+
+import numpy as np
+import regex
+
+from ....tokenization_utils import AddedToken, PreTrainedTokenizer
+from ....tokenization_utils_base import BatchEncoding
+from ....utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging
+from ....utils.generic import _is_jax, _is_numpy
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {
+ "artists_file": "artists.json",
+ "lyrics_file": "lyrics.json",
+ "genres_file": "genres.json",
+}
+
+
+class JukeboxTokenizer(PreTrainedTokenizer):
+ """
+ Constructs a Jukebox tokenizer. Jukebox can be conditioned on 3 different inputs :
+ - Artists, unique ids are associated to each artist from the provided dictionary.
+ - Genres, unique ids are associated to each genre from the provided dictionary.
+ - Lyrics, character based tokenization. Must be initialized with the list of characters that are inside the
+ vocabulary.
+
+ This tokenizer does not require training. It should be able to process a different number of inputs:
+ as the conditioning of the model can be done on the three different queries. If None is provided, defaults values will be used.:
+
+ Depending on the number of genres on which the model should be conditioned (`n_genres`).
+ ```python
+ >>> from transformers import JukeboxTokenizer
+
+ >>> tokenizer = JukeboxTokenizer.from_pretrained("openai/jukebox-1b-lyrics")
+ >>> tokenizer("Alan Jackson", "Country Rock", "old town road")["input_ids"]
+ [tensor([[ 0, 0, 0, 6785, 546, 41, 38, 30, 76, 46, 41, 49,
+ 40, 76, 44, 41, 27, 30]]), tensor([[ 0, 0, 0, 145, 0]]), tensor([[ 0, 0, 0, 145, 0]])]
+ ```
+
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
+
+
+
+ If nothing is provided, the genres and the artist will either be selected randomly or set to None
+
+
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to:
+ this superclass for more information regarding those methods.
+
+ However the code does not allow that and only supports composing from various genres.
+
+ Args:
+ artists_file (`str`):
+ Path to the vocabulary file which contains a mapping between artists and ids. The default file supports
+ both "v2" and "v3"
+ genres_file (`str`):
+ Path to the vocabulary file which contain a mapping between genres and ids.
+ lyrics_file (`str`):
+ Path to the vocabulary file which contains the accepted characters for the lyrics tokenization.
+ version (`list[str]`, `optional`, default to `["v3", "v2", "v2"]`) :
+ List of the tokenizer versions. The `5b-lyrics`'s top level prior model was trained using `v3` instead of
+ `v2`.
+ n_genres (`int`, `optional`, defaults to 1):
+ Maximum number of genres to use for composition.
+ max_n_lyric_tokens (`int`, `optional`, defaults to 512):
+ Maximum number of lyric tokens to keep.
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ artists_file,
+ genres_file,
+ lyrics_file,
+ version=["v3", "v2", "v2"],
+ max_n_lyric_tokens=512,
+ n_genres=5,
+ unk_token="<|endoftext|>",
+ **kwargs,
+ ):
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
+ self.version = version
+ self.max_n_lyric_tokens = max_n_lyric_tokens
+ self.n_genres = n_genres
+ self._added_tokens_decoder = {0: unk_token}
+
+ with open(artists_file, encoding="utf-8") as vocab_handle:
+ self.artists_encoder = json.load(vocab_handle)
+
+ with open(genres_file, encoding="utf-8") as vocab_handle:
+ self.genres_encoder = json.load(vocab_handle)
+
+ with open(lyrics_file, encoding="utf-8") as vocab_handle:
+ self.lyrics_encoder = json.load(vocab_handle)
+
+ oov = r"[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+"
+ # In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters.
+ if len(self.lyrics_encoder) == 79:
+ oov = oov.replace(r"\-'", r"\-+'")
+
+ self.out_of_vocab = regex.compile(oov)
+ self.artists_decoder = {v: k for k, v in self.artists_encoder.items()}
+ self.genres_decoder = {v: k for k, v in self.genres_encoder.items()}
+ self.lyrics_decoder = {v: k for k, v in self.lyrics_encoder.items()}
+ super().__init__(
+ unk_token=unk_token,
+ n_genres=n_genres,
+ version=version,
+ max_n_lyric_tokens=max_n_lyric_tokens,
+ **kwargs,
+ )
+
+ @property
+ def vocab_size(self):
+ return len(self.artists_encoder) + len(self.genres_encoder) + len(self.lyrics_encoder)
+
+ def get_vocab(self):
+ return {
+ "artists_encoder": self.artists_encoder,
+ "genres_encoder": self.genres_encoder,
+ "lyrics_encoder": self.lyrics_encoder,
+ }
+
+ def _convert_token_to_id(self, list_artists, list_genres, list_lyrics):
+ """Converts the artist, genre and lyrics tokens to their index using the vocabulary.
+ The total_length, offset and duration have to be provided in order to select relevant lyrics and add padding to
+ the lyrics token sequence.
+ """
+ artists_id = [self.artists_encoder.get(artist, 0) for artist in list_artists]
+ for genres in range(len(list_genres)):
+ list_genres[genres] = [self.genres_encoder.get(genre, 0) for genre in list_genres[genres]]
+ list_genres[genres] = list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres]))
+
+ lyric_ids = [[self.lyrics_encoder.get(character, 0) for character in list_lyrics[0]], [], []]
+ return artists_id, list_genres, lyric_ids
+
+ def _tokenize(self, lyrics):
+ """
+ Converts a string into a sequence of tokens (string), using the tokenizer. Split in words for word-based
+ vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
+
+ Do NOT take care of added tokens. Only the lyrics are split into character for the character-based vocabulary.
+ """
+ # only lyrics are not tokenized, but character based is easily handled
+ return list(lyrics)
+
+ def tokenize(self, artist, genre, lyrics, **kwargs):
+ """
+ Converts three strings in a 3 sequence of tokens using the tokenizer
+ """
+ artist, genre, lyrics = self.prepare_for_tokenization(artist, genre, lyrics)
+ lyrics = self._tokenize(lyrics)
+ return artist, genre, lyrics
+
+ def prepare_for_tokenization(
+ self, artists: str, genres: str, lyrics: str, is_split_into_words: bool = False
+ ) -> tuple[str, str, str, dict[str, Any]]:
+ """
+ Performs any necessary transformations before tokenization.
+
+ Args:
+ artist (`str`):
+ The artist name to prepare. This will mostly lower the string
+ genres (`str`):
+ The genre name to prepare. This will mostly lower the string.
+ lyrics (`str`):
+ The lyrics to prepare.
+ is_split_into_words (`bool`, *optional*, defaults to `False`):
+ Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the
+ tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace)
+ which it will tokenize. This is useful for NER or token classification.
+ """
+ for idx in range(len(self.version)):
+ if self.version[idx] == "v3":
+ artists[idx] = artists[idx].lower()
+ genres[idx] = [genres[idx].lower()]
+ else:
+ artists[idx] = self._normalize(artists[idx]) + ".v2"
+ genres[idx] = [
+ self._normalize(genre) + ".v2" for genre in genres[idx].split("_")
+ ] # split is for the full dictionary with combined genres
+
+ if self.version[0] == "v2":
+ self.out_of_vocab = regex.compile(r"[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+")
+ vocab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+'\"()[] \t\n"
+ self.vocab = {vocab[index]: index + 1 for index in range(len(vocab))}
+ self.vocab[""] = 0
+ self.n_vocab = len(vocab) + 1
+ self.lyrics_encoder = self.vocab
+ self.lyrics_decoder = {v: k for k, v in self.vocab.items()}
+ self.lyrics_decoder[0] = ""
+ else:
+ self.out_of_vocab = regex.compile(r"[^A-Za-z0-9.,:;!?\-+'\"()\[\] \t\n]+")
+
+ lyrics = self._run_strip_accents(lyrics)
+ lyrics = lyrics.replace("\\", "\n")
+ lyrics = self.out_of_vocab.sub("", lyrics), [], []
+ return artists, genres, lyrics
+
+ def _run_strip_accents(self, text):
+ """Strips accents from a piece of text."""
+ text = unicodedata.normalize("NFD", text)
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat == "Mn":
+ continue
+ output.append(char)
+ return "".join(output)
+
+ def _normalize(self, text: str) -> str:
+ """
+ Normalizes the input text. This process is for the genres and the artist
+
+ Args:
+ text (`str`):
+ Artist or Genre string to normalize
+ """
+
+ accepted = (
+ [chr(i) for i in range(ord("a"), ord("z") + 1)]
+ + [chr(i) for i in range(ord("A"), ord("Z") + 1)]
+ + [chr(i) for i in range(ord("0"), ord("9") + 1)]
+ + ["."]
+ )
+ accepted = frozenset(accepted)
+ pattern = re.compile(r"_+")
+ text = "".join([c if c in accepted else "_" for c in text.lower()])
+ text = pattern.sub("_", text).strip("_")
+ return text
+
+ def convert_lyric_tokens_to_string(self, lyrics: list[str]) -> str:
+ return " ".join(lyrics)
+
+ def convert_to_tensors(
+ self, inputs, tensor_type: Optional[Union[str, TensorType]] = None, prepend_batch_axis: bool = False
+ ):
+ """
+ Convert the inner content to tensors.
+
+ Args:
+ tensor_type (`str` or [`~utils.TensorType`], *optional*):
+ The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If
+ unset, no modification is done.
+ prepend_batch_axis (`int`, *optional*, defaults to `False`):
+ Whether or not to add the batch dimension during the conversion.
+ """
+ # Convert to TensorType
+ if not isinstance(tensor_type, TensorType):
+ tensor_type = TensorType(tensor_type)
+
+ # Get a function reference for the correct framework
+ if tensor_type == TensorType.TENSORFLOW:
+ if not is_tf_available():
+ raise ImportError(
+ "Unable to convert output to TensorFlow tensors format, TensorFlow is not installed."
+ )
+ import tensorflow as tf
+
+ as_tensor = tf.constant
+ is_tensor = tf.is_tensor
+ elif tensor_type == TensorType.PYTORCH:
+ if not is_torch_available():
+ raise ImportError("Unable to convert output to PyTorch tensors format, PyTorch is not installed.")
+ import torch
+
+ as_tensor = torch.tensor
+ is_tensor = torch.is_tensor
+ elif tensor_type == TensorType.JAX:
+ if not is_flax_available():
+ raise ImportError("Unable to convert output to JAX tensors format, JAX is not installed.")
+ import jax.numpy as jnp # noqa: F811
+
+ as_tensor = jnp.array
+ is_tensor = _is_jax
+ else:
+ as_tensor = np.asarray
+ is_tensor = _is_numpy
+
+ # Do the tensor conversion in batch
+
+ try:
+ if prepend_batch_axis:
+ inputs = [inputs]
+
+ if not is_tensor(inputs):
+ inputs = as_tensor(inputs)
+ except: # noqa E722
+ raise ValueError(
+ "Unable to create tensor, you should probably activate truncation and/or padding "
+ "with 'padding=True' 'truncation=True' to have batched tensors with the same length."
+ )
+
+ return inputs
+
+ def __call__(self, artist, genres, lyrics="", return_tensors="pt") -> BatchEncoding:
+ """Convert the raw string to a list of token ids
+
+ Args:
+ artist (`str`):
+ Name of the artist.
+ genres (`str`):
+ List of genres that will be mixed to condition the audio
+ lyrics (`str`, *optional*, defaults to `""`):
+ Lyrics used to condition the generation
+ """
+ input_ids = [0, 0, 0]
+ artist = [artist] * len(self.version)
+ genres = [genres] * len(self.version)
+
+ artists_tokens, genres_tokens, lyrics_tokens = self.tokenize(artist, genres, lyrics)
+ artists_id, genres_ids, full_tokens = self._convert_token_to_id(artists_tokens, genres_tokens, lyrics_tokens)
+
+ attention_masks = [-INFINITY] * len(full_tokens[-1])
+ input_ids = [
+ self.convert_to_tensors(
+ [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]], tensor_type=return_tensors
+ )
+ for i in range(len(self.version))
+ ]
+ return BatchEncoding({"input_ids": input_ids, "attention_masks": attention_masks})
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ """
+ Saves the tokenizer's vocabulary dictionary to the provided save_directory.
+
+ Args:
+ save_directory (`str`):
+ A path to the directory where to saved. It will be created if it doesn't exist.
+
+ filename_prefix (`Optional[str]`, *optional*):
+ A prefix to add to the names of the files saved by the tokenizer.
+
+ """
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+
+ artists_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["artists_file"]
+ )
+ with open(artists_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self.artists_encoder, ensure_ascii=False))
+
+ genres_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["genres_file"]
+ )
+ with open(genres_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self.genres_encoder, ensure_ascii=False))
+
+ lyrics_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["lyrics_file"]
+ )
+ with open(lyrics_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self.lyrics_encoder, ensure_ascii=False))
+
+ return (artists_file, genres_file, lyrics_file)
+
+ def _convert_id_to_token(self, artists_index, genres_index, lyric_index):
+ """
+ Converts an index (integer) in a token (str) using the vocab.
+
+ Args:
+ artists_index (`int`):
+ Index of the artist in its corresponding dictionary.
+ genres_index (`Union[list[int], int]`):
+ Index of the genre in its corresponding dictionary.
+ lyric_index (`list[int]`):
+ List of character indices, which each correspond to a character.
+ """
+ artist = self.artists_decoder.get(artists_index)
+ genres = [self.genres_decoder.get(genre) for genre in genres_index]
+ lyrics = [self.lyrics_decoder.get(character) for character in lyric_index]
+ return artist, genres, lyrics
+
+
+__all__ = ["JukeboxTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..53ec5ed37c13614266d04cde838ff7360946a451
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_mctct import *
+ from .feature_extraction_mctct import *
+ from .modeling_mctct import *
+ from .processing_mctct import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1bbc1b092c3748c7afb7b7f1b7baa9ae6d258582
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/configuration_mctct.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/configuration_mctct.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..308a6449d099ce65aa7ca44ed5ae6ce36800cce8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/configuration_mctct.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/feature_extraction_mctct.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/feature_extraction_mctct.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7d8c42849b9b09486a8bba4f105f4eac50e26f78
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/feature_extraction_mctct.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/modeling_mctct.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/modeling_mctct.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b597eb4ff98cab7bf526023114008f43bb2f749e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/modeling_mctct.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/processing_mctct.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/processing_mctct.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b7f46f9b5ffbfe829b0b56fc118574bb4c82f47
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/__pycache__/processing_mctct.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/configuration_mctct.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/configuration_mctct.py
new file mode 100644
index 0000000000000000000000000000000000000000..984dca4a62bfa726bae9081183cd18853381d3ad
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/configuration_mctct.py
@@ -0,0 +1,184 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""M-CTC-T model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class MCTCTConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`MCTCTModel`]. It is used to instantiate an
+ M-CTC-T model according to the specified arguments, defining the model architecture. Instantiating a configuration
+ with the defaults will yield a similar configuration to that of the M-CTC-T
+ [speechbrain/m-ctc-t-large](https://huggingface.co/speechbrain/m-ctc-t-large) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 8065):
+ Vocabulary size of the M-CTC-T model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`MCTCTModel`].
+ hidden_size (`int`, *optional*, defaults to 1536):
+ Dimension of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 36):
+ Number of hidden layers in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 6144):
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 4):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ attention_head_dim (`int`, *optional*, defaults to 384):
+ Dimensions of each attention head for each attention layer in the Transformer encoder.
+ max_position_embeddings (`int`, *optional*, defaults to 920):
+ The maximum sequence length that this model might ever be used with (after log-mel spectrogram extraction).
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
+ The epsilon used by the layer normalization layers.
+ layerdrop (`float`, *optional*, defaults to 0.3):
+ The probability of dropping an encoder layer during training. The default 0.3 value is used in the original
+ implementation.
+ hidden_act (`str` or `function`, *optional*, defaults to `"relu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.3):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.3):
+ The dropout ratio for the attention probabilities.
+ pad_token_id (`int`, *optional*, defaults to 1):
+ The tokenizer index of the pad token.
+ bos_token_id (`int`, *optional*, defaults to 0):
+ The tokenizer index of the bos token.
+ eos_token_id (`int`, *optional*, defaults to 2):
+ The tokenizer index of the eos token.
+ conv_glu_dim (`int`, *optional*, defaults to 1):
+ The dimension of the output of the `Conv1dSubsampler` layer in which GLU is applied on. Though the original
+ Flashlight code uses the value of 2, here it's adapted to 1 due to transposition differences.
+ conv_dropout (`int`, *optional*, defaults to 0.3):
+ The probability of randomly dropping the `Conv1dSubsampler` layer during training.
+ num_conv_layers (`int`, *optional*, defaults to 1):
+ Number of convolution layers before applying transformer encoder layers.
+ conv_kernel (`Sequence[int]`, *optional*, defaults to `(7,)`):
+ The kernel size of the 1D convolution applied before transformer layers. `len(conv_kernel)` must be equal
+ to `num_conv_layers`.
+ conv_stride (`Sequence[int]`, *optional*, defaults to `(3,)`):
+ The stride length of the 1D convolution applied before transformer layers. `len(conv_stride)` must be equal
+ to `num_conv_layers`.
+ input_feat_per_channel (`int`, *optional*, defaults to 80):
+ Feature dimensions of the channels of the input to the Conv1D layer.
+ input_channels (`int`, *optional*, defaults to 1):
+ Number of input channels of the input to the Conv1D layer.
+ conv_channels (`list[int]`, *optional*):
+ Channel sizes of intermediate Conv1D layers.
+ ctc_loss_reduction (`str`, *optional*, defaults to `"sum"`):
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training an
+ instance of [`MCTCTForCTC`].
+ ctc_zero_infinity (`bool`, *optional*, defaults to `False`):
+ Whether to zero infinite losses and the associated gradients of `torch.nn.CTCLoss`. Infinite losses mainly
+ occur when the inputs are too short to be aligned to the targets. Only relevant when training an instance
+ of [`MCTCTForCTC`].
+
+ Example:
+
+ ```python
+ >>> from transformers import MCTCTConfig, MCTCTModel
+
+ >>> # Initializing a M-CTC-T mctct-large style configuration
+ >>> configuration = MCTCTConfig()
+
+ >>> # Initializing a model (with random weights) from the mctct-large style configuration
+ >>> model = MCTCTModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "mctct"
+
+ def __init__(
+ self,
+ vocab_size=8065,
+ hidden_size=1536,
+ num_hidden_layers=36,
+ intermediate_size=6144,
+ num_attention_heads=4,
+ attention_head_dim=384,
+ max_position_embeddings=920,
+ layer_norm_eps=1e-5,
+ layerdrop=0.3,
+ hidden_act="relu",
+ initializer_range=0.02,
+ hidden_dropout_prob=0.3,
+ attention_probs_dropout_prob=0.3,
+ pad_token_id=1,
+ bos_token_id=0,
+ eos_token_id=2,
+ conv_glu_dim=1,
+ conv_dropout=0.3,
+ num_conv_layers=1,
+ conv_kernel=(7,),
+ conv_stride=(3,),
+ input_feat_per_channel=80,
+ input_channels=1,
+ conv_channels=None,
+ ctc_loss_reduction="sum",
+ ctc_zero_infinity=False,
+ **kwargs,
+ ):
+ super().__init__(**kwargs, pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id)
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.intermediate_size = intermediate_size
+ self.num_attention_heads = num_attention_heads
+ self.attention_head_dim = attention_head_dim
+ self.max_position_embeddings = max_position_embeddings
+ self.layer_norm_eps = layer_norm_eps
+ self.layerdrop = layerdrop
+ self.hidden_act = hidden_act
+ self.initializer_range = initializer_range
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.pad_token_id = pad_token_id
+ self.bos_token_id = bos_token_id
+ self.eos_token_id = eos_token_id
+ self.conv_glu_dim = conv_glu_dim
+ self.conv_dropout = conv_dropout
+ self.num_conv_layers = num_conv_layers
+ self.input_feat_per_channel = input_feat_per_channel
+ self.input_channels = input_channels
+ self.conv_channels = conv_channels
+ self.ctc_loss_reduction = ctc_loss_reduction
+ self.ctc_zero_infinity = ctc_zero_infinity
+
+ # prevents config testing fail with exporting to json
+ self.conv_kernel = list(conv_kernel)
+ self.conv_stride = list(conv_stride)
+
+ if len(self.conv_kernel) != self.num_conv_layers:
+ raise ValueError(
+ "Configuration for convolutional module is incorrect. "
+ "It is required that `len(config.conv_kernel)` == `config.num_conv_layers` "
+ f"but is `len(config.conv_kernel) = {len(self.conv_kernel)}`, "
+ f"`config.num_conv_layers = {self.num_conv_layers}`."
+ )
+
+
+__all__ = ["MCTCTConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/feature_extraction_mctct.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/feature_extraction_mctct.py
new file mode 100644
index 0000000000000000000000000000000000000000..65d18c78821182a59f625e7ce154739d7213a3a4
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/feature_extraction_mctct.py
@@ -0,0 +1,291 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Feature extractor class for M-CTC-T
+"""
+
+from typing import Optional, Union
+
+import numpy as np
+
+from ....audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
+from ....feature_extraction_sequence_utils import SequenceFeatureExtractor
+from ....feature_extraction_utils import BatchFeature
+from ....file_utils import PaddingStrategy, TensorType
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class MCTCTFeatureExtractor(SequenceFeatureExtractor):
+ r"""
+ Constructs a M-CTC-T feature extractor.
+
+ This feature extractor inherits from [`~feature_extraction_sequence_utils.SequenceFeatureExtractor`] which contains
+ most of the main methods. Users should refer to this superclass for more information regarding those methods. This
+ code has been adapted from Flashlight's C++ code. For more information about the implementation, one can refer to
+ this [notebook](https://colab.research.google.com/drive/1GLtINkkhzms-IsdcGy_-tVCkv0qNF-Gt#scrollTo=pMCRGMmUC_an)
+ that takes the user step-by-step in the implementation.
+
+ Args:
+ feature_size (`int`, defaults to 80):
+ The feature dimension of the extracted features. This is the number of mel_frequency
+ sampling_rate (`int`, defaults to 16000):
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
+ padding_value (`float`, defaults to 0.0):
+ The value that is used to fill the padding values.
+ hop_length (`int`, defaults to 10):
+ Number of audio samples between windows. Otherwise referred to as "shift" in many papers.
+ win_length (`int`, defaults to 25):
+ Number of ms per window
+ win_function (`str`, defaults to `"hamming_window"`):
+ Name for the window function used for windowing, must be accessible via `torch.{win_function}`
+ frame_signal_scale (`float`, defaults to 32768.0):
+ Constant multiplied in creating the frames before applying DFT.
+ preemphasis_coeff (`float`, defaults to 0.97):
+ Constant multiplied in applying Pre-emphasis before DFT.
+ mel_floor (`float` defaults to 1.0):
+ Minimum value of mel frequency banks.
+ normalize_means (`bool`, *optional*, defaults to `True`):
+ Whether or not to zero-mean normalize the extracted features.
+ normalize_vars (`bool`, *optional*, defaults to `True`):
+ Whether or not to unit-variance normalize the extracted features.
+ """
+
+ model_input_names = ["input_features", "attention_mask"]
+
+ def __init__(
+ self,
+ feature_size=80,
+ sampling_rate=16000,
+ padding_value=0.0,
+ hop_length=10,
+ win_length=25,
+ win_function="hamming_window",
+ frame_signal_scale=32768.0,
+ preemphasis_coeff=0.97,
+ mel_floor=1.0,
+ normalize_means=True,
+ normalize_vars=True,
+ return_attention_mask=False,
+ **kwargs,
+ ):
+ super().__init__(feature_size=feature_size, sampling_rate=sampling_rate, padding_value=padding_value, **kwargs)
+
+ self.feature_size = feature_size
+ self.sampling_rate = sampling_rate
+ self.padding_value = padding_value
+ self.hop_length = hop_length
+ self.win_length = win_length
+ self.frame_signal_scale = frame_signal_scale
+ self.preemphasis_coeff = preemphasis_coeff
+ self.mel_floor = mel_floor
+ self.normalize_means = normalize_means
+ self.normalize_vars = normalize_vars
+ self.win_function = win_function
+ self.return_attention_mask = return_attention_mask
+
+ self.sample_size = win_length * sampling_rate // 1000
+ self.sample_stride = hop_length * sampling_rate // 1000
+
+ self.n_fft = optimal_fft_length(self.sample_size)
+ self.n_freqs = (self.n_fft // 2) + 1
+
+ def _extract_mfsc_features(self, one_waveform: np.array) -> np.ndarray:
+ """
+ Extracts MFSC Features for one waveform vector (unbatched). Adapted from Flashlight's C++ MFSC code.
+ """
+ if self.win_function == "hamming_window":
+ window = window_function(window_length=self.sample_size, name=self.win_function, periodic=False)
+ else:
+ window = window_function(window_length=self.sample_size, name=self.win_function)
+
+ fbanks = mel_filter_bank(
+ num_frequency_bins=self.n_freqs,
+ num_mel_filters=self.feature_size,
+ min_frequency=0.0,
+ max_frequency=self.sampling_rate / 2.0,
+ sampling_rate=self.sampling_rate,
+ )
+
+ msfc_features = spectrogram(
+ one_waveform * self.frame_signal_scale,
+ window=window,
+ frame_length=self.sample_size,
+ hop_length=self.sample_stride,
+ fft_length=self.n_fft,
+ center=False,
+ preemphasis=self.preemphasis_coeff,
+ mel_filters=fbanks,
+ mel_floor=self.mel_floor,
+ log_mel="log",
+ )
+ return msfc_features.T
+
+ def _normalize_one(self, x, input_length, padding_value):
+ # make sure we normalize float32 arrays
+ if self.normalize_means:
+ mean = x[:input_length].mean(axis=0)
+ x = np.subtract(x, mean)
+ if self.normalize_vars:
+ std = x[:input_length].std(axis=0)
+ x = np.divide(x, std)
+
+ if input_length < x.shape[0]:
+ x[input_length:] = padding_value
+
+ # make sure array is in float32
+ x = x.astype(np.float32)
+
+ return x
+
+ def normalize(
+ self, input_features: list[np.ndarray], attention_mask: Optional[np.ndarray] = None
+ ) -> list[np.ndarray]:
+ lengths = attention_mask.sum(-1) if attention_mask is not None else [x.shape[0] for x in input_features]
+ return [self._normalize_one(x, n, self.padding_value) for x, n in zip(input_features, lengths)]
+
+ def __call__(
+ self,
+ raw_speech: Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]],
+ padding: Union[bool, str, PaddingStrategy] = False,
+ max_length: Optional[int] = None,
+ truncation: bool = False,
+ pad_to_multiple_of: Optional[int] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ sampling_rate: Optional[int] = None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Main method to featurize and prepare for the model one or several sequence(s). sequences. It returns the
+ log-mel spectrogram of the input audio, as implemented in the original Flashlight MFSC feature extraction code.
+
+ Args:
+ raw_speech (`torch.Tensor`, `np.ndarray`, `list[float]`, `list[torch.Tensor]`, `list[np.ndarray]`, `list[list[float]]`):
+ The sequence or batch of sequences to be padded. Each sequence can be a tensor, a numpy array, a list
+ of float values, a list of tensors, a list of numpy arrays or a list of list of float values. Must be
+ mono channel audio, not stereo, i.e. single float per timestep.
+ padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
+ Select a strategy to pad the returned sequences (according to the model's padding side and padding
+ index) among:
+
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
+ sequence if provided).
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided.
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
+ lengths).
+ max_length (`int`, *optional*):
+ Maximum length of the returned list and optionally padding length (see above).
+ truncation (`bool`):
+ Activates truncation to cut input sequences longer than *max_length* to *max_length*.
+ pad_to_multiple_of (`int`, *optional*):
+ If set will pad the sequence to a multiple of the provided value.
+
+ This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability
+ `>= 7.5` (Volta), or on TPUs which benefit from having sequence lengths be a multiple of 128.
+ return_attention_mask (`bool`, *optional*):
+ Whether to return the attention mask. If left to the default, will return the attention mask according
+ to the specific feature_extractor's default.
+
+ [What are attention masks?](../glossary#attention-mask)
+
+ return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
+ If set, will return tensors instead of list of python integers. Acceptable values are:
+
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return Numpy `np.ndarray` objects.
+ sampling_rate (`int`, *optional*):
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
+ `sampling_rate` at the forward call to prevent silent errors.
+ padding_value (`float`, defaults to 0.0):
+ """
+
+ if sampling_rate is not None:
+ if sampling_rate != self.sampling_rate:
+ raise ValueError(
+ f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
+ f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
+ f" {self.sampling_rate} and not {sampling_rate}."
+ )
+ else:
+ logger.warning(
+ "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
+ "Failing to do so can result in silent errors that might be hard to debug."
+ )
+
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
+ if is_batched_numpy and len(raw_speech.shape) > 2:
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
+ is_batched = is_batched_numpy or (
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
+ )
+
+ if is_batched:
+ raw_speech = [np.asarray(speech, dtype=np.float32) for speech in raw_speech]
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
+ raw_speech = np.asarray(raw_speech, dtype=np.float32)
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
+ raw_speech = raw_speech.astype(np.float32)
+
+ # always return batch
+ if not is_batched:
+ raw_speech = [raw_speech]
+
+ # extract fbank features
+ features = [self._extract_mfsc_features(one_waveform) for one_waveform in raw_speech]
+
+ # convert into correct format for padding
+ encoded_inputs = BatchFeature({"input_features": features})
+
+ padded_inputs = self.pad(
+ encoded_inputs,
+ padding=padding,
+ max_length=max_length,
+ truncation=truncation,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_attention_mask=True,
+ **kwargs,
+ )
+ # make sure list is in array format
+ input_features = padded_inputs.get("input_features")
+ if isinstance(input_features[0], list):
+ padded_inputs["input_features"] = [np.asarray(feature, dtype=np.float32) for feature in input_features]
+
+ attention_mask = padded_inputs.get("attention_mask")
+ if attention_mask is not None:
+ padded_inputs["attention_mask"] = [np.asarray(array, dtype=np.int32) for array in attention_mask]
+
+ if self.normalize_means or self.normalize_vars:
+ attention_mask = (
+ np.array(attention_mask, dtype=np.int32)
+ if self._get_padding_strategies(padding, max_length=max_length) is not PaddingStrategy.DO_NOT_PAD
+ and padding
+ else None
+ )
+ padded_inputs["input_features"] = self.normalize(
+ padded_inputs["input_features"], attention_mask=attention_mask
+ )
+
+ if return_tensors is not None:
+ padded_inputs = padded_inputs.convert_to_tensors(return_tensors)
+
+ return padded_inputs
+
+
+__all__ = ["MCTCTFeatureExtractor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/modeling_mctct.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/modeling_mctct.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c9d259e82158d1095f406d1a65368a464c95fd3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/modeling_mctct.py
@@ -0,0 +1,779 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch M-CTC-T model."""
+
+import math
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+
+from ....activations import ACT2FN
+from ....file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
+from ....integrations.deepspeed import is_deepspeed_zero3_enabled
+from ....integrations.fsdp import is_fsdp_managed_module
+from ....modeling_attn_mask_utils import _prepare_4d_attention_mask
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_outputs import BaseModelOutput, CausalLMOutput
+from ....modeling_utils import PreTrainedModel
+from ....pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
+from ....utils import logging
+from .configuration_mctct import MCTCTConfig
+
+
+logger = logging.get_logger(__name__)
+
+_HIDDEN_STATES_START_POSITION = 1
+
+_CONFIG_FOR_DOC = "MCTCTConfig"
+
+# Base docstring
+_CHECKPOINT_FOR_DOC = "speechbrain/m-ctc-t-large"
+_EXPECTED_OUTPUT_SHAPE = [1, 195, 1536]
+
+# CTC docstring
+_CTC_EXPECTED_OUTPUT = '"Mr. Quilter is the apostle of the middle classes, and we\'re glad to welcome his gospel."'
+_CTC_EXPECTED_LOSS = 1885.65
+
+
+class MCTCTConv1dSubsampler(nn.Module):
+ """
+ Convolutional subsampler: a stack of 1D convolution (along temporal dimension) followed by non-linear activation
+ via gated linear units (https://huggingface.co/papers/1911.08460)
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.glu_dim = config.conv_glu_dim
+
+ self.dropout = nn.Dropout(config.conv_dropout)
+
+ self.num_layers = config.num_conv_layers
+ self.in_channels = config.input_feat_per_channel * config.input_channels
+
+ if self.num_layers > 1:
+ if config.conv_channels is None:
+ raise ValueError(
+ "Need to specify `conv_channels` configuration in `MCTCTConfig` to use multiple convolution"
+ " layers."
+ )
+
+ self.mid_channels = config.conv_channels
+ else:
+ self.mid_channels = None
+
+ self.out_channels = config.hidden_size * 2 # considering GLU halving
+ self.kernel_size = config.conv_kernel
+ self.stride = config.conv_stride
+
+ # NOTE: MCTCT by construction only uses one convolution kernel. I've made this flexible to allow for
+ # multiple layers of convolutions, but not sure if this model definition should just restrict it
+ # to one layer. This becomes especially relevant when considering the padding like line 1 of forward().
+ self.conv_layers = nn.ModuleList(
+ nn.Conv1d(
+ self.in_channels if i == 0 else self.mid_channels[i],
+ self.mid_channels[i] if i < self.num_layers - 1 else self.out_channels,
+ kernel_size=k,
+ stride=self.stride[i],
+ padding="valid",
+ )
+ for i, k in enumerate(self.kernel_size)
+ )
+
+ def forward(self, input_features):
+ # NOTE: in reference to the NOTE in __init__, right now it just calculates padding as if
+ # there will be just one conv layer.
+ padding = sum([size // 2 for size in self.kernel_size]) # (7, 7) -> (3, 3)
+
+ input_features = torch.nn.functional.pad(input_features, (0, 0, padding, padding), "constant", 0)
+ hidden_states = input_features.transpose(1, 2).contiguous() # -> Batch x Frame x Time
+ for conv in self.conv_layers:
+ hidden_states = conv(hidden_states)
+ hidden_states = nn.functional.glu(hidden_states, dim=self.glu_dim)
+ hidden_states = self.dropout(hidden_states)
+
+ hidden_states = hidden_states.transpose(1, 2).contiguous() # -> Batch x Time x Frame
+ return hidden_states
+
+
+class MCTCTEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
+ # any TensorFlow checkpoint file
+ # self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.LayerNorm = MCTCTLayerNorm()
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids",
+ torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
+ persistent=False,
+ )
+
+ def forward(
+ self, input_features=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
+ ):
+ input_shape = input_features.size() if input_features is not None else inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_features)
+
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+
+ embeddings = inputs_embeds + token_type_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class MCTCTSelfAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = config.attention_head_dim
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=False)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ self.max_position_embeddings = config.max_position_embeddings
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
+
+ self.is_decoder = config.is_decoder
+
+ def transpose_for_scores(self, x):
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
+ x = x.view(*new_x_shape)
+ return x.permute(0, 2, 1, 3)
+
+ def reshape_fortran(self, x, shape):
+ if len(x.shape) > 0:
+ x = x.permute(*reversed(range(len(x.shape))))
+ return x.reshape(*reversed(shape)).permute(*reversed(range(len(shape))))
+
+ def relative_position_embedding_rotate(self, scores):
+ # NOTE: should re-evaluate whether this re-implementation was truly necessary
+ # or the reason why my complete re-haul worked was due to some other part
+ # of the code. Adding this and the reshape fortrain code seems very undesirable.
+ scores = scores.permute(0, 2, 3, 1) # e.g. [10, 1839, 14, 4]
+
+ batch, hidden_state, seq_len, heads = scores.shape
+
+ # e.g. [10, 1853, 14, 4]
+ scores = torch.cat((scores, torch.zeros((batch, seq_len, seq_len, heads), device=scores.device)), dim=1)
+
+ # e.g. [10, 25942, 1, 4]
+ scores = self.reshape_fortran(scores, [batch, (hidden_state + seq_len) * seq_len, 1, heads])
+
+ # e.g. [10, 25928, 1, 4]
+ scores = scores[:, : (seq_len + hidden_state - 1) * seq_len]
+
+ # e.g. [10, 1852, 14, 4]
+ scores = self.reshape_fortran(scores, [batch, hidden_state + seq_len - 1, seq_len, heads])
+
+ halfpoint = hidden_state // 2
+ scores = scores[:, halfpoint : halfpoint + seq_len].transpose(1, 2) # e.g. [10, 14, 14, 4]
+
+ return scores.permute(0, 3, 1, 2)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ output_attentions=False,
+ ):
+ mixed_query_layer = self.query(hidden_states)
+ mixed_query_layer = mixed_query_layer / math.sqrt(self.attention_head_size)
+
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ # relative key position embeddings
+ positional_embedding = self.distance_embedding.weight
+ relative_position_scores = torch.einsum("lh, bche -> bcle", positional_embedding, query_layer.transpose(2, 3))
+
+ relative_position_scores = self.relative_position_embedding_rotate(relative_position_scores)
+ attention_scores = attention_scores + relative_position_scores
+
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in MCTCTModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = attention_probs * head_mask
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).flatten(start_dim=-2)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+class MCTCTLayerNorm(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.singleton_weight = nn.Parameter(torch.ones(1))
+ self.singleton_bias = nn.Parameter(torch.zeros(1))
+
+ def forward(self, hidden_states):
+ return (hidden_states * self.singleton_weight) + self.singleton_bias
+
+
+class MCTCTSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class MCTCTAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.self = MCTCTSelfAttention(config)
+ self.output = MCTCTSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.self.query = prune_linear_layer(self.self.query, index)
+ self.self.key = prune_linear_layer(self.self.key, index)
+ self.self.value = prune_linear_layer(self.self.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ output_attentions=False,
+ ):
+ self_outputs = self.self(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ output_attentions,
+ )
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+
+ return outputs
+
+
+class MCTCTIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class MCTCTOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class MCTCTLayer(GradientCheckpointingLayer):
+ def __init__(self, config: MCTCTConfig):
+ super().__init__()
+
+ self.seq_len_dim = 1
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+
+ self.intermediate = MCTCTIntermediate(config)
+ self.attention = MCTCTAttention(config)
+ self.is_decoder = config.is_decoder
+ self.output = MCTCTOutput(config)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ output_attentions=False,
+ ):
+ self_attention_outputs = self.attention(
+ hidden_states, attention_mask, head_mask, output_attentions=output_attentions
+ )
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class MCTCTPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: MCTCTConfig
+ base_model_prefix = "mctct"
+ main_input_name = "input_features"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ std = self.config.initializer_range
+ if isinstance(module, nn.Linear):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ elif isinstance(module, MCTCTLayerNorm):
+ module.singleton_weight.data.fill_(1.0)
+ module.singleton_bias.data.zero_()
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+
+ def _get_feat_extract_output_lengths(self, input_lengths: torch.LongTensor):
+ """
+ Computes the output length of the convolutional layers
+ """
+ dilation = 1
+ for _, kernel_sz, stride in zip(
+ range(self.config.num_conv_layers), self.config.conv_kernel, self.config.conv_stride
+ ):
+ padding = kernel_sz // 2
+ input_lengths = input_lengths + 2 * padding - dilation * (kernel_sz - 1) - 1
+ input_lengths = torch.div(input_lengths, stride, rounding_mode="trunc") + 1
+
+ return input_lengths
+
+ def _get_feature_vector_attention_mask(self, feature_vector_length, attention_mask):
+ # generate creates 3D attention mask, because of the shape of input_features
+ # convert it to 2D if that's the case
+ if len(attention_mask.shape) > 2:
+ attention_mask = attention_mask[:, :, -1]
+
+ # subsampled_lengths = attention_mask.sum(-1)
+ subsampled_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1))
+ bsz = attention_mask.size()[0]
+ attention_mask = torch.zeros(
+ (bsz, feature_vector_length), dtype=attention_mask.dtype, device=attention_mask.device
+ )
+
+ # these two operations makes sure that all values
+ # before the output lengths indices are attended to
+ attention_mask[(torch.arange(bsz, device=attention_mask.device), subsampled_lengths - 1)] = 1
+ attention_mask = attention_mask.flip([-1]).cumsum(-1).flip([-1]).long()
+ return attention_mask
+
+
+MCTCT_START_DOCSTRING = r"""
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
+ behavior.
+
+ Parameters:
+ config ([`MCTCTConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+MCTCT_INPUTS_DOCSTRING = r"""
+ Args:
+ input_features (`torch.LongTensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`Wav2Vec2CTCTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+class MCTCTEncoder(MCTCTPreTrainedModel):
+ def __init__(self, config: MCTCTConfig):
+ super().__init__(config)
+ self.hidden_dropout_prob = config.hidden_dropout_prob
+
+ self.layer_norm = MCTCTLayerNorm()
+ self.conv = MCTCTConv1dSubsampler(config)
+ self.layers = nn.ModuleList([MCTCTLayer(config) for _ in range(config.num_hidden_layers)])
+
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ input_features: torch.Tensor,
+ attention_mask: torch.Tensor,
+ head_mask: torch.Tensor,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ) -> Union[tuple, BaseModelOutput]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ input_features = self.layer_norm(input_features)
+
+ inputs_embeds = self.conv(input_features)
+
+ # subsample attention mask if necessary
+ if attention_mask is not None:
+ attention_mask = self._get_feature_vector_attention_mask(inputs_embeds.shape[1], attention_mask)
+
+ hidden_states = nn.functional.dropout(inputs_embeds, p=self.hidden_dropout_prob, training=self.training)
+
+ # expand attention_mask
+ if attention_mask is not None:
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
+
+ encoder_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+
+ # check if head_mask has a correct number of layers specified if desired
+ if head_mask is not None:
+ if head_mask.size()[0] != len(self.layers):
+ raise ValueError(
+ f"The head_mask should be specified for {len(self.layers)} layers, "
+ f"but it is for {head_mask.size()[0]}."
+ )
+
+ synced_gpus = is_deepspeed_zero3_enabled() or is_fsdp_managed_module(self)
+ for idx, encoder_layer in enumerate(self.layers):
+ if output_hidden_states:
+ encoder_states = encoder_states + (hidden_states,)
+
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ dropout_probability = torch.rand([])
+
+ skip_the_layer = self.training and dropout_probability < self.config.layerdrop
+ if not skip_the_layer or synced_gpus:
+ # under fsdp or deepspeed zero3 all gpus must run in sync
+ layer_outputs = encoder_layer(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if skip_the_layer:
+ layer_outputs = (None, None)
+
+ if output_attentions:
+ all_attentions = all_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ encoder_states = encoder_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
+ )
+
+
+@add_start_docstrings(
+ "The bare M-CTC-T Model transformer outputting raw hidden-states without any specific head on top.",
+ MCTCT_START_DOCSTRING,
+)
+class MCTCTModel(MCTCTPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+
+ self.encoder = MCTCTEncoder(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(MCTCT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=BaseModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ modality="audio",
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
+ )
+ def forward(
+ self,
+ input_features: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, BaseModelOutput]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if input_features is None:
+ raise ValueError("You have to specify input_features.")
+
+ encoder_outputs = self.encoder(
+ input_features,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+
+ if not return_dict:
+ return (sequence_output,) + encoder_outputs[1:]
+
+ return BaseModelOutput(
+ last_hidden_state=sequence_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """MCTCT Model with a `language modeling` head on top for Connectionist Temporal Classification (CTC).""",
+ MCTCT_START_DOCSTRING,
+)
+class MCTCTForCTC(MCTCTPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.mctct = MCTCTModel(config)
+
+ if config.vocab_size is None:
+ raise ValueError(
+ f"You are trying to instantiate {self.__class__} with a configuration that "
+ "does not define the vocabulary size of the language model head. Please "
+ "instantiate the model as follows: `MCTCTForCTC.from_pretrained(..., vocab_size=vocab_size)`. "
+ "or define `vocab_size` of your model's configuration."
+ )
+ output_hidden_size = config.hidden_size
+
+ self.ctc_head = nn.Linear(output_hidden_size, config.vocab_size)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(MCTCT_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=CausalLMOutput,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output=_CTC_EXPECTED_OUTPUT,
+ expected_loss=_CTC_EXPECTED_LOSS,
+ )
+ def forward(
+ self,
+ input_features: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ labels: Optional[torch.LongTensor] = None,
+ ) -> Union[tuple, CausalLMOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, target_length)`, *optional*):
+ Labels for connectionist temporal classification. Note that `target_length` has to be smaller or equal to
+ the sequence length of the output logits. Indices are selected in `[-100, 0, ..., config.vocab_size - 1]`.
+ All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ...,
+ config.vocab_size - 1]`.
+ """
+ if labels is not None and labels.max() >= self.config.vocab_size:
+ raise ValueError(f"Label values must be <= vocab_size: {self.config.vocab_size}")
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ outputs = self.mctct(
+ input_features,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+
+ logits = self.ctc_head(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # retrieve loss input_lengths from attention_mask
+ attention_mask = (
+ attention_mask
+ if attention_mask is not None
+ else torch.ones(input_features.shape[:-1], dtype=torch.long)
+ )
+ input_lengths = self._get_feat_extract_output_lengths(attention_mask.sum(-1)).to(torch.long)
+ # assuming that padded tokens are filled with -100
+ # when not being attended to
+ labels_mask = labels >= 0
+ target_lengths = labels_mask.sum(-1)
+ flattened_targets = labels.masked_select(labels_mask)
+
+ # ctc_loss doesn't support fp16
+ log_probs = nn.functional.log_softmax(logits, dim=-1, dtype=torch.float32).transpose(0, 1)
+
+ with torch.backends.cudnn.flags(enabled=False):
+ loss = nn.functional.ctc_loss(
+ log_probs,
+ flattened_targets,
+ input_lengths,
+ target_lengths,
+ blank=self.config.pad_token_id,
+ reduction=self.config.ctc_loss_reduction,
+ zero_infinity=self.config.ctc_zero_infinity,
+ )
+
+ if not return_dict:
+ output = (logits,) + outputs[_HIDDEN_STATES_START_POSITION:]
+ return ((loss,) + output) if loss is not None else output
+
+ return CausalLMOutput(
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
+ )
+
+
+__all__ = ["MCTCTForCTC", "MCTCTModel", "MCTCTPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/processing_mctct.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/processing_mctct.py
new file mode 100644
index 0000000000000000000000000000000000000000..9661a5082d4838b4e60042be2ceb747c03e045ce
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mctct/processing_mctct.py
@@ -0,0 +1,139 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Speech processor class for M-CTC-T
+"""
+
+import warnings
+from contextlib import contextmanager
+
+from ....processing_utils import ProcessorMixin
+
+
+class MCTCTProcessor(ProcessorMixin):
+ r"""
+ Constructs a MCTCT processor which wraps a MCTCT feature extractor and a MCTCT tokenizer into a single processor.
+
+ [`MCTCTProcessor`] offers all the functionalities of [`MCTCTFeatureExtractor`] and [`AutoTokenizer`]. See the
+ [`~MCTCTProcessor.__call__`] and [`~MCTCTProcessor.decode`] for more information.
+
+ Args:
+ feature_extractor (`MCTCTFeatureExtractor`):
+ An instance of [`MCTCTFeatureExtractor`]. The feature extractor is a required input.
+ tokenizer (`AutoTokenizer`):
+ An instance of [`AutoTokenizer`]. The tokenizer is a required input.
+ """
+
+ feature_extractor_class = "MCTCTFeatureExtractor"
+ tokenizer_class = "AutoTokenizer"
+
+ def __init__(self, feature_extractor, tokenizer):
+ super().__init__(feature_extractor, tokenizer)
+ self.current_processor = self.feature_extractor
+ self._in_target_context_manager = False
+
+ def __call__(self, *args, **kwargs):
+ """
+ When used in normal mode, this method forwards all its arguments to MCTCTFeatureExtractor's
+ [`~MCTCTFeatureExtractor.__call__`] and returns its output. If used in the context
+ [`~MCTCTProcessor.as_target_processor`] this method forwards all its arguments to AutoTokenizer's
+ [`~AutoTokenizer.__call__`]. Please refer to the docstring of the above two methods for more information.
+ """
+ # For backward compatibility
+ if self._in_target_context_manager:
+ return self.current_processor(*args, **kwargs)
+
+ if "raw_speech" in kwargs:
+ warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.")
+ audio = kwargs.pop("raw_speech")
+ else:
+ audio = kwargs.pop("audio", None)
+ sampling_rate = kwargs.pop("sampling_rate", None)
+ text = kwargs.pop("text", None)
+ if len(args) > 0:
+ audio = args[0]
+ args = args[1:]
+
+ if audio is None and text is None:
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
+
+ if audio is not None:
+ inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
+ if text is not None:
+ encodings = self.tokenizer(text, **kwargs)
+
+ if text is None:
+ return inputs
+ elif audio is None:
+ return encodings
+ else:
+ inputs["labels"] = encodings["input_ids"]
+ return inputs
+
+ def pad(self, *args, **kwargs):
+ """
+ When used in normal mode, this method forwards all its arguments to MCTCTFeatureExtractor's
+ [`~MCTCTFeatureExtractor.pad`] and returns its output. If used in the context
+ [`~MCTCTProcessor.as_target_processor`] this method forwards all its arguments to PreTrainedTokenizer's
+ [`~PreTrainedTokenizer.pad`]. Please refer to the docstring of the above two methods for more information.
+ """
+ # For backward compatibility
+ if self._in_target_context_manager:
+ return self.current_processor.pad(*args, **kwargs)
+
+ input_features = kwargs.pop("input_features", None)
+ labels = kwargs.pop("labels", None)
+ if len(args) > 0:
+ input_features = args[0]
+ args = args[1:]
+
+ if input_features is not None:
+ input_features = self.feature_extractor.pad(input_features, *args, **kwargs)
+ if labels is not None:
+ labels = self.tokenizer.pad(labels, **kwargs)
+
+ if labels is None:
+ return input_features
+ elif input_features is None:
+ return labels
+ else:
+ input_features["labels"] = labels["input_ids"]
+ return input_features
+
+ def decode(self, *args, **kwargs):
+ """
+ This method forwards all its arguments to AutoTokenizer's [`~PreTrainedTokenizer.decode`]. Please refer to the
+ docstring of this method for more information.
+ """
+ return self.tokenizer.decode(*args, **kwargs)
+
+ @contextmanager
+ def as_target_processor(self):
+ """
+ Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning MCTCT.
+ """
+ warnings.warn(
+ "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
+ "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
+ "your audio inputs, or in a separate call."
+ )
+ self._in_target_context_manager = True
+ self.current_processor = self.tokenizer
+ yield
+ self.current_processor = self.feature_extractor
+ self._in_target_context_manager = False
+
+
+__all__ = ["MCTCTProcessor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cff2c19505f9306c28edb5bdabb66f668363f5fa
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_mega import *
+ from .modeling_mega import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c47fc21e7ef595b6f34c39a4d8d633a6f6603882
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__pycache__/configuration_mega.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__pycache__/configuration_mega.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9e1bcfd1a33bd312db5163c0f0a89ce0f83c333
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__pycache__/configuration_mega.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__pycache__/modeling_mega.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__pycache__/modeling_mega.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec541a4d1c237ba3579d2c262a399cd1f1fae069
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/__pycache__/modeling_mega.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b3601a65250a98052efc0dd66dc1e70ae8847f6bb46273ccf1ecb2bd6dc91021
+size 113413
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/configuration_mega.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/configuration_mega.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ede2cac66bf292c448b488d18af4d2e6e2c716a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/configuration_mega.py
@@ -0,0 +1,243 @@
+# coding=utf-8
+# Copyright 2023 The Mega Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""MEGA configuration"""
+
+from collections import OrderedDict
+from collections.abc import Mapping
+
+from ....configuration_utils import PretrainedConfig
+from ....onnx import OnnxConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class MegaConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`MegaModel`]. It is used to instantiate a Mega
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the Mega
+ [mnaylor/mega-base-wikitext](https://huggingface.co/mnaylor/mega-base-wikitext) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 30522):
+ Vocabulary size of the Mega model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`MegaModel`].
+ hidden_size (`int`, *optional*, defaults to 128):
+ Dimensionality of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 4):
+ Number of hidden layers in the Mega encoder.
+ intermediate_size (`int`, *optional*, defaults to 256):
+ Dimensionality of the hidden size (self-attention value projection) within the Mega encoder
+ ema_projection_size (`int`, *optional*, defaults to 16):
+ Dimensionality of the MegaMultiDimensionDampedEma
+ bidirectional (`bool`, *optional*, defaults to `True`):
+ Whether the MegaMultiDimensionDampedEma used in Mega's self-attention should work bidirectionally (`True`)
+ or unidirectionally (`False`). Bidirectional EMA is incompatible with causal decoding, so this should be
+ False if you intend to use the model as a decoder.
+ shared_representation_size (`int`, *optional*, defaults to 64):
+ Dimensionality of the linear projection for shared representation of self-attention queries and keys
+ use_chunking (`bool`, *optional*, defaults to `False`):
+ Whether to chunk inputs for linear self-attention complexity (described as Mega-chunk in the paper)
+ chunk_size (`int`, *optional*, defaults to -1):
+ If `use_chunking` is set to `True`, determines the size of the chunks to apply to the input sequence. If
+ chunking is used, input sequences must be padded to a multiple of `chunk_size`
+ truncation (`int`, *optional*):
+ If specified, the sequence length for which to truncate MegaMultiDimensionDampedEma
+ normalize_before_mega (`bool`, *optional*, defaults to `True`):
+ Whether to normalize before (`True`) or after (`False`) passing through Mega encoder blocks
+ normalization_type (`str`, *optional*, defaults to `"scalenorm"`):
+ Type of normalization to use in Mega encoder blocks. Choose one of `"scalenorm"`, `"layernorm"`,
+ `"rmsnorm"`, `"batchnorm"`, or `"syncbatchnorm"` (GPU required for syncbatchnorm)
+ norm_affine (`bool`, *optional*, defaults to `True`):
+ If `True`, applies a parameterized affine transformation to inputs during normalization
+ activation (`str`, *optional*, defaults to `"silu"`):
+ Activation function to apply within Mega encoder blocks. Choose one of `"silu"`, `"relu"`, `"linear"`,
+ `"gelu"`, or `"gelu_accurate"`
+ attention_activation (`str`, *optional*, defaults to `"softmax"`):
+ Activation function to apply for single-headed self-attention (a la Transformer). Choose one of
+ `"softmax"`, `"laplace"`, or `"relu2"`
+ dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for EMA self-attention
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention probabilities.
+ use_feature_dropout (`bool`, *optional*, defaults to `False`):
+ Whether to use feature-based (`True`) or standard dropout (`False`)
+ use_normalized_ffn (`bool`, *optional*, defaults to `True`):
+ Whether to use the normalized feed-forward sub-layer in Mega blocks (`True`) or pass Mega encoder output
+ as-is (`False`)
+ nffn_hidden_size (`int`, *optional*, defaults to 256):
+ If using the normalized feed-forward network (NFFN) layer within Mega (`use_normalized_ffn = True`), this
+ is the hidden size of the NFFN
+ normalize_before_ffn (`bool`, *optional*, defaults to `True`):
+ Whether to normalize before (`True`) or after (`False`) the feed-forward portion of NFFN
+ nffn_activation_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the NFFN component.
+ max_positions (`int`, *optional*, defaults to 2048):
+ The maximum sequence length to use for positional representations. For `"simple"` relative positional bias,
+ this is a hard limit on input length; `"rotary"` relative positional bias will extrapolate to longer
+ sequences
+ add_token_type_embeddings (`bool`, *optional*, defaults to `True`):
+ Whether to account for token types in embeddings. Left as optional to maintain compatibility with original
+ implementation while adding support for token types.
+ type_vocab_size (`int`, *optional*, defaults to 2):
+ The vocabulary size of the `token_type_ids` passed when calling [`MegaModel`]. Only used if
+ `add_token_type_embeddings = True`
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ ema_delta_alpha_range (`float`, *optional*, defaults to 0.2):
+ The standard deviation for initializing the delta (damping factor) and alpha (decay factor) parameters in
+ MegaMultiDimensionDampedEma.
+ ema_beta_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation for initializing the beta parameter (expansion matrix) in
+ MegaMultiDimensionDampedEma.
+ ema_gamma_omega_range (`float`, *optional*, defaults to 1.0):
+ The standard deviation for initializing the gamma (projection matrix) and omega (residual weight)
+ parameters in MultiDimensionEMA.
+ relative_positional_bias (`str`, *optional*, defaults to `"rotary"`):
+ Type of relative positional encoding. Choose one of `"rotary"` or `"simple"`. If `"simple"` is selected,
+ `max_positions` is used as a limit on input size, while `"rotary"` extrapolates beyond `max_positions`.
+ is_decoder (`bool`, *optional*, defaults to `False`):
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+ classifier_dropout (`float`, *optional*):
+ The dropout ratio for the classification head.
+ add_lm_hidden_dense_layer (`bool`, *optional*, defaults to `True`):
+ Whether to include a hidden layer for projection between encoder outputs and LM heads (`True`) or pass
+ hidden states directly to LM head (`False`). Remains optional for compatibility with original
+ implementation
+
+ Examples:
+
+ ```python
+ >>> from transformers import MegaConfig, MegaModel
+
+ >>> # Initializing a Mega configuration
+ >>> configuration = MegaConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = MegaModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "mega"
+
+ def __init__(
+ self,
+ vocab_size=30522,
+ hidden_size=128,
+ num_hidden_layers=4,
+ intermediate_size=256,
+ ema_projection_size=16,
+ bidirectional=True,
+ shared_representation_size=64,
+ use_chunking=False,
+ chunk_size=-1,
+ truncation=None,
+ normalize_before_mega=True,
+ normalization_type="scalenorm",
+ norm_affine=True,
+ activation="silu",
+ attention_activation="softmax",
+ dropout_prob=0.1,
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ use_feature_dropout=False,
+ use_normalized_ffn=True,
+ nffn_hidden_size=256,
+ normalize_before_ffn=True,
+ nffn_activation_dropout_prob=0.1,
+ max_positions=2048,
+ add_token_type_embeddings=False,
+ type_vocab_size=2,
+ initializer_range=0.02,
+ ema_delta_alpha_range=0.2,
+ ema_beta_range=0.02,
+ ema_gamma_omega_range=1.0,
+ pad_token_id=1,
+ bos_token_id=0,
+ eos_token_id=2,
+ relative_positional_bias="rotary",
+ classifier_dropout=None,
+ use_cache=True,
+ add_lm_hidden_dense_layer=True,
+ **kwargs,
+ ):
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
+
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.activation = activation
+ self.attention_activation = attention_activation
+ self.intermediate_size = intermediate_size
+ self.ema_projection_size = ema_projection_size
+ self.bidirectional = bidirectional
+ self.shared_representation_size = shared_representation_size
+ self.use_chunking = use_chunking
+ self.chunk_size = chunk_size
+ self.truncation = truncation
+ self.normalize_before_mega = normalize_before_mega
+ self.normalization_type = normalization_type
+ self.norm_affine = norm_affine
+ self.dropout_prob = dropout_prob
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.use_feature_dropout = use_feature_dropout
+ self.use_normalized_ffn = use_normalized_ffn
+ self.nffn_hidden_size = nffn_hidden_size
+ self.normalize_before_ffn = normalize_before_ffn
+ self.nffn_activation_dropout_prob = nffn_activation_dropout_prob
+ self.max_positions = max_positions
+ self.add_token_type_embeddings = add_token_type_embeddings
+ self.type_vocab_size = type_vocab_size
+ self.initializer_range = initializer_range
+ self.ema_delta_alpha_range = ema_delta_alpha_range
+ self.ema_beta_range = ema_beta_range
+ self.ema_gamma_omega_range = ema_gamma_omega_range
+ self.relative_positional_bias = relative_positional_bias
+ self.use_cache = use_cache
+ self.classifier_dropout = classifier_dropout
+ self.add_lm_hidden_dense_layer = add_lm_hidden_dense_layer
+ self.num_attention_heads = 1 # not used but required by Hugging Face
+
+
+class MegaOnnxConfig(OnnxConfig):
+ @property
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
+ if self.task == "multiple-choice":
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
+ else:
+ dynamic_axis = {0: "batch", 1: "sequence"}
+ return OrderedDict(
+ [
+ ("input_ids", dynamic_axis),
+ ("attention_mask", dynamic_axis),
+ ]
+ )
+
+
+__all__ = ["MegaConfig", "MegaOnnxConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/modeling_mega.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/modeling_mega.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc77cb2874e684b52841ffd9b23fccf72c6ec441
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mega/modeling_mega.py
@@ -0,0 +1,2276 @@
+# coding=utf-8
+# Copyright 2023 The Mega Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch MEGA model."""
+
+import math
+from typing import Optional, Union
+
+import torch
+import torch.nn.functional as F
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_outputs import (
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ....modeling_utils import PreTrainedModel
+from ....utils import (
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+ replace_return_docstrings,
+)
+from ....utils.deprecation import deprecate_kwarg
+from .configuration_mega import MegaConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "mnaylor/mega-base-wikitext"
+_CONFIG_FOR_DOC = "MegaConfig"
+
+
+class MegaEmbeddings(nn.Module):
+ """
+ Mega's basic implementation does not incorporate token type embeddings, so this is a stripped-down version of
+ RoBERTa's embeddings which optionally includes token types
+ """
+
+ def __init__(self, config: MegaConfig):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.use_token_types = config.add_token_type_embeddings
+ if self.use_token_types:
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+ # registering a buffer here allows model tracing when not passing optional token type IDs
+ # more info at transformers issue #5664
+ self.register_buffer(
+ "token_type_ids", torch.zeros(config.max_positions, dtype=torch.long).expand((1, -1)), persistent=False
+ )
+
+ self.padding_idx = config.pad_token_id
+
+ def forward(self, input_ids=None, token_type_ids=None, inputs_embeds=None):
+ if (input_ids is None) and (inputs_embeds is None):
+ raise ValueError("Must provide one of input_ids or inputs_embeds")
+ elif input_ids is not None:
+ input_shape = input_ids.size()
+ device = input_ids.device
+
+ # get the word embeddings if only IDs are provided
+ inputs_embeds = self.word_embeddings(input_ids)
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+ device = inputs_embeds.device
+
+ # the original Mega implementation did not include token type embeddings, so we add
+ # an option to use them if desired; if embeddings are present and token type IDs are
+ # not provided, we will use a registered buffer (which helps with tracing)
+ if self.use_token_types:
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, : input_shape[1]]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], input_shape[1])
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ # access token type embeddings
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ # add the token type embeddings to the word embeddings
+ embeddings = inputs_embeds + token_type_embeddings
+ else:
+ embeddings = inputs_embeds
+ return embeddings
+
+
+class MegaSimpleRelativePositionalBias(nn.Module):
+ """
+ Simple relative positional embeddings copied from the Mega repo; renamed variables for better readability
+ """
+
+ def __init__(self, config: MegaConfig):
+ super().__init__()
+ self.config = config
+ self.max_positions = self.config.max_positions if self.config.chunk_size < 0 else self.config.chunk_size
+ self.rel_pos_bias = nn.Parameter(torch.Tensor(2 * config.max_positions - 1))
+
+ def forward(self, seq_len):
+ if seq_len > self.max_positions:
+ raise ValueError(f"Sequence length {seq_len} going beyond max length {self.max_positions}")
+
+ # seq_len * 2 - 1
+ bias = self.rel_pos_bias[(self.max_positions - seq_len) : (self.max_positions + seq_len - 1)]
+ # seq_len * 3 - 1
+ tile = F.pad(bias, (0, seq_len))
+ # (seq_len * 3 - 1) * seq_len
+ tile = torch.tile(tile, (seq_len,))
+ tile = tile[:-seq_len]
+ # seq_len x (3 * seq_len - 2)
+ tile = tile.view(seq_len, 3 * seq_len - 2)
+ start = (2 * seq_len - 1) // 2
+ end = tile.size(1) - start
+ tile = tile[:, start:end]
+ return tile
+
+
+class MegaRotaryRelativePositionalBias(nn.Module):
+ """
+ Rotary relative bias for positional information; similar in concept to RoPE (i.e. RoFormer) but taken from the Mega
+ repo due to differences in implementation.
+
+ When initialized, produces a positional bias which ranges from position 0 to config.max_positions, but can
+ extrapolate to longer sequences. Can be indexed according to input position IDs
+ """
+
+ def __init__(self, config: MegaConfig):
+ super().__init__()
+ if config.hidden_size % 2 != 0:
+ raise RuntimeError("Rotary positional bias requires `hidden_size` to be a multiple of 2")
+ self.config = config
+ self.embed_dim = config.shared_representation_size
+ self.max_positions = self.config.max_positions if self.config.chunk_size < 0 else self.config.chunk_size
+ self.sine, self.cosine = MegaRotaryRelativePositionalBias.get_sinusoid_embeddings(
+ config.max_positions, self.embed_dim
+ )
+ # alpha and beta parameters for the rotary bias; beta renamed to b_param to avoid clashes with tf/flax weight handling
+ # in loading pretrained weights
+ self.alpha = nn.Parameter(torch.Tensor(1, self.embed_dim))
+ self.b_param = nn.Parameter(torch.Tensor(1, self.embed_dim))
+ self.register_buffer("_float_tensor", torch.FloatTensor([0.0]))
+
+ @staticmethod
+ def get_sinusoid_embeddings(max_positions: int, embedding_dim: int):
+ half_dim = embedding_dim // 2
+ emb = math.log(10000) / half_dim
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
+ emb = torch.arange(max_positions, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)
+ return torch.sin(emb), torch.cos(emb)
+
+ def rotary(self, input):
+ seq_len, embed_dim = input.size()
+ chunk_1, chunk_2 = torch.chunk(input, 2, dim=-1)
+ if self.sine is None or seq_len > self.sine.size(0):
+ self.sine, self.cosine = MegaRotaryRelativePositionalBias.get_sinusoid_embeddings(seq_len, embed_dim)
+ self.max_positions = seq_len
+ self.sine = self.sine.to(self._float_tensor)
+ self.cosine = self.cosine.to(self._float_tensor)
+
+ sin = self.sine[:seq_len]
+ cos = self.cosine[:seq_len]
+ return torch.cat([chunk_1 * cos - chunk_2 * sin, chunk_2 * cos + chunk_1 * sin], dim=1)
+
+ def forward(self, seq_len):
+ rotary_alpha = self.rotary(self.alpha.expand(seq_len, self.embed_dim))
+ rotary_beta = self.rotary(self.b_param.expand(seq_len, self.embed_dim))
+ bias = torch.einsum("mk,nk->mn", rotary_alpha, rotary_beta)
+ return bias
+
+
+class MegaDropout(nn.Module):
+ """
+ A unified class for standard dropout functionality and featurewise dropout.
+
+ The original fairseq Mega repo used 2 classes for these, which included some unnecessary handling of training logic
+ and an unused `inplace` option. The original implementation used torch.nn.functional instead of submodules, which
+ is retained here as well.
+ """
+
+ def __init__(self, dropout_probability, is_featurewise=False):
+ super().__init__()
+ self.dropout_probability = dropout_probability
+ self.is_featurewise = is_featurewise
+
+ def forward(self, input, batch_first: bool = False):
+ if self.is_featurewise:
+ if batch_first:
+ # (batch_size X sequence_length X feature_dimension)
+ # -> (batch_size X feature_dimension X sequence_length)
+ # -> (batch_size X sequence_length X feature_dimension)
+ return F.dropout2d(
+ input.transpose(-1, -2), p=self.dropout_probability, training=self.training
+ ).transpose(-1, -2)
+ else:
+ if input.dim() != 3:
+ raise ValueError(
+ "Feature dropout inputs must be exactly 3-dimensional if inputs are ordered [sequence length, batch size, hidden dimension]"
+ )
+ # (sequence_length X batch_size X feature_dimension)
+ # -> (batch_size X feature_dimension X sequence_length)
+ # -> (sequence_length X batch_size X feature_dimension)
+ return F.dropout2d(input.permute(1, 2, 0), p=self.dropout_probability, training=self.training).permute(
+ 2, 0, 1
+ )
+ else:
+ return F.dropout(input, p=self.dropout_probability, training=self.training)
+
+
+class MegaRMSNorm(nn.Module):
+ """
+ RMSNorm used in Mega implementation. Differs from T5's RMSNorm by applying the weight prior to taking the square
+ root (as opposed to after in T5)
+ """
+
+ def __init__(self, number_features, eps=1e-6, affine=True):
+ super().__init__()
+ self.num_features = number_features
+ self.eps = eps
+ self.affine = affine
+ if affine:
+ self.weight = nn.Parameter(torch.Tensor(self.num_features))
+ else:
+ self.register_parameter("weight", None)
+
+ def forward(self, input):
+ mean_square = torch.mean(torch.square(input), dim=-1, keepdim=True)
+ if self.weight is not None:
+ input = input * self.weight
+
+ input * torch.rsqrt(mean_square + self.eps)
+ return input
+
+ def extra_repr(self):
+ return f"{self.num_features}, eps={self.eps}, affine={self.affine}"
+
+
+class MegaScaleNorm(nn.Module):
+ """
+ Scale normalization introduced in MEGA which is similar to RMSNorm, but uses a single parameter for scalar
+ multiplication instead of a vector, and applies over a specified dimension
+ """
+
+ def __init__(self, dim, eps=1e-6, affine=True):
+ super().__init__()
+ self.dim = dim
+ self.eps = eps
+ self.affine = affine
+ if affine:
+ self.scalar = nn.Parameter(torch.Tensor(1))
+ else:
+ self.register_parameter("scalar", None)
+
+ def forward(self, input):
+ mean_square = torch.mean(torch.square(input), dim=self.dim, keepdim=True)
+ if self.scalar is not None:
+ input = self.scalar * input
+
+ output = input * torch.rsqrt(mean_square + self.eps)
+ return output
+
+
+class MegaSequenceNorm(nn.Module):
+ """
+ A wrapper class for various layer normalization options used in Mega. Used to handle differences in expectations on
+ input axis locations for different normalization methods.
+ """
+
+ def __init__(self, norm_type, embedding_dim, eps=1e-5, affine=True, export=False):
+ super().__init__()
+ if norm_type == "layernorm":
+ self.norm = nn.LayerNorm(embedding_dim, eps, elementwise_affine=affine)
+ elif norm_type == "scalenorm":
+ self.norm = MegaScaleNorm(dim=-1, eps=eps, affine=affine)
+ elif norm_type == "rmsnorm":
+ self.norm = MegaRMSNorm(embedding_dim, eps=eps, affine=affine)
+ elif norm_type == "batchnorm":
+ self.norm = nn.BatchNorm1d(embedding_dim, eps=eps, affine=affine)
+ elif norm_type == "syncbatchnorm":
+ self.norm = nn.SyncBatchNorm(embedding_dim, eps=eps, affine=affine)
+ else:
+ raise ValueError(f"Unknown norm type: {norm_type}")
+
+ def forward(self, input):
+ if isinstance(self.norm, nn.modules.batchnorm._BatchNorm):
+ if input.dim() != 3:
+ raise ValueError("BatchNorm inputs must be exactly 3-dimensional")
+ input = input.permute(1, 2, 0)
+ input = self.norm(input)
+ return input.permute(2, 0, 1)
+ else:
+ return self.norm(input)
+
+
+class MegaMultiDimensionDampedEma(nn.Module):
+ """
+ Mega's Exponential Moving Average layer, largely left unmodified from the original repo with the exception of
+ variable names and moving away from the stateful representation of incremental decoding state. See
+ "https://huggingface.co/papers/2209.10655" for more details.
+ """
+
+ def __init__(self, config: MegaConfig):
+ super().__init__()
+
+ self.config = config
+
+ self.embed_dim = config.hidden_size
+ self.ndim = config.ema_projection_size
+ self.bidirectional = config.bidirectional
+ self.truncation = config.truncation
+ self.scale = math.sqrt(1.0 / self.ndim)
+
+ kernel_dim = 2 * config.hidden_size if self.bidirectional else config.hidden_size
+ # renamed delta (damping_factor) and alpha (decay_factor) to be more descriptive of what the parameters are doing
+ self.damping_factor = nn.Parameter(torch.Tensor(kernel_dim, self.ndim, 1))
+ self.decay_factor = nn.Parameter(torch.Tensor(kernel_dim, self.ndim, 1))
+ # renamed gamma (kernel_projection_matrix) and beta (ema_expansion_matrix) respectively to avoid HF renaming
+ # things and align with the paper's description of these params' behavior
+ self.ema_expansion_matrix = nn.Parameter(torch.Tensor(kernel_dim, self.ndim, 1))
+ self.kernel_projection_matrix = nn.Parameter(torch.Tensor(kernel_dim, self.ndim))
+ # renamed omega to residual_weight to describe what it's doing
+ self.residual_weight = nn.Parameter(torch.Tensor(config.hidden_size))
+ self._kernel = None
+ self._coeffs = None
+
+ def _compute_ema_coefficients(self):
+ self._coeffs = None
+ # convert the alpha and delta parameters (kernel_dim x EMA projection size x 1) to [0, 1] with sigmoid
+ damping_factor = torch.sigmoid(self.damping_factor)
+ decay_factor = torch.sigmoid(self.decay_factor)
+ previous_timestep_weight = 1.0 - damping_factor * decay_factor
+ return damping_factor, previous_timestep_weight
+
+ def _compute_efficient_ema_kernel(self, length: int):
+ # computes the kernel used for efficient damped EMA applied via FFT convolution
+ self._kernel = None
+ # p and q have shape (kernel_dim x ema_projection_size x 1)
+ damping_factor, previous_timestep_weight = self._compute_ema_coefficients()
+ # extend the kernel to (kernel_dim X ema_projection_size X sequence_length) and
+ # multiply q by sequential ints up to the sequence length
+ vander = torch.arange(length).to(damping_factor).view(1, 1, length) * torch.log(previous_timestep_weight)
+ kernel = (damping_factor * self.ema_expansion_matrix) * torch.exp(vander)
+ # (kernel_dim X ema_projection_size X sequence_length) -> (kernel_dim, sequence_length)
+ return torch.einsum("dnl,dn->dl", kernel, self.kernel_projection_matrix * self.scale)
+
+ def get_ema_coefficients(self):
+ if self.training:
+ return self._compute_ema_coefficients()
+ else:
+ if self._coeffs is None:
+ self._coeffs = self._compute_ema_coefficients()
+ return self._coeffs
+
+ def get_ema_kernel(self, length: int):
+ kernel_size = length if self.truncation is None else min(self.truncation, length)
+ if self.training:
+ return self._compute_efficient_ema_kernel(kernel_size)
+ else:
+ if self._kernel is None or self._kernel.size(-1) < kernel_size:
+ self._kernel = self._compute_efficient_ema_kernel(kernel_size)
+ return self._kernel[..., :kernel_size]
+
+ def fft_convolution(self, inputs, kernel, length):
+ # this is a wrapper for repeated use of EMA calculation via FFT (fast Fourier transform) convolution
+ inputs_fft = torch.fft.rfft(inputs.float(), n=2 * length)
+ kernel_fft = torch.fft.rfft(kernel.float(), n=2 * length)
+ convolved_sequence = torch.fft.irfft(inputs_fft * kernel_fft, n=2 * length)
+ return convolved_sequence
+
+ def ema_step(self, inputs, length, past_state=None):
+ if length == 1:
+ return self.one_ema_step(inputs, past_state=past_state)
+
+ # (kernel_dim X ema_projection_size X 1)
+ damping_factor, previous_timestep_weight = self.get_ema_coefficients()
+ # (kernel_dim X ema_projection_size X 1+sequence_length)
+ vander = torch.arange(length + 1).to(damping_factor).view(1, 1, length + 1) * torch.log(
+ previous_timestep_weight
+ )
+ vander = torch.exp(vander)
+ if past_state is not None:
+ # (kernel_dim X ema_projection_size X sequence_length) * (kernel_dim X ema_projection_size X 1)
+ # -> (kernel_dim X ema_projection_size X sequence_length)
+ past_ema_proj = vander[:, :, 1:] * (self.kernel_projection_matrix * self.scale).unsqueeze(-1)
+ # past_state will be (batch_size, kernel_dim, ema_projection_size)
+ past_ema_state = torch.einsum("bdn,dnl->bdl", past_state, past_ema_proj)
+ # (kernel_dim X ema_projection_size) * (batch_size X kernel_dim X ema_projection_size)
+ # -> (batch_size X kernel_dim X ema_projection_size)
+ past_vandermonde = vander[:, :, -1] * past_state
+ else:
+ past_ema_state = None
+ past_vandermonde = None
+
+ # (kernel_dim X ema_projection_size X sequence_length)
+ vander = vander[:, :, :-1]
+ kernel = (damping_factor * self.ema_expansion_matrix) * vander
+ kernel_proj = torch.einsum("dnl,dn->dl", kernel, self.kernel_projection_matrix * self.scale)
+
+ ema_output = self.fft_convolution(inputs, kernel_proj, length=length)[..., 0:length]
+ ema_output = ema_output.type_as(inputs)
+ if past_ema_state is not None:
+ ema_output = ema_output + past_ema_state
+
+ updated_hidden_state = torch.einsum("bdl,dnl->bdn", inputs, torch.flip(kernel, dims=[2]))
+ if past_vandermonde is not None:
+ updated_hidden_state = updated_hidden_state + past_vandermonde
+ # return a tuple:
+ # (sequence_length, batch_size, kernel_dim)
+ # (batch_size, kernel_dim, ema_projection_size)
+ return ema_output.permute(2, 0, 1), updated_hidden_state
+
+ def one_ema_step(self, inputs, past_state=None):
+ damping_factor, previous_timestep_weight = self.get_ema_coefficients()
+ # (kernel_dim X ema_projection_size) x (batch_size X kernel_dim X 1)
+ # -> (batch_size X kernel_dim X ema_projection_size)
+ updated_state = (damping_factor * self.ema_expansion_matrix).squeeze(-1) * inputs
+ if past_state is not None:
+ updated_state = updated_state + previous_timestep_weight.squeeze(-1) * past_state
+ # (batch_size X kernel_dim)
+ out = torch.einsum("bdn,dn->bd", updated_state, self.kernel_projection_matrix * self.scale)
+ # (1 X batch_size X kernel_dim), (batch_size X kernel_dim X ema_projection_size)
+ return out.unsqueeze(0), updated_state
+
+ def forward(
+ self,
+ inputs,
+ attention_mask: Optional[torch.Tensor] = None,
+ prev_state: Optional[torch.Tensor] = None,
+ use_cache: bool = False,
+ ) -> torch.Tensor:
+ """
+ Mega's exponential moving average (EMA) sub-layer applied prior to single-headed (traditional) self-attention
+
+ Args:
+ inputs (`torch.Tensor` of shape `(sequence_length, batch_size, hidden_size)`):
+ Hidden state / embedding input to update via EMA based on FFT convolution
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indicates which inputs are to be ignored (mostly due to padding), where elements are either 1 for *not
+ masked* or 0 for *masked*
+ prev_state (`torch.Tensor` of shape `(batch_size, config.ndim)`, *optional*):
+ The hidden state returned from the previous timestep during incremental decoding.
+ use_cache (`bool`, default `False`):
+ Whether to perform incremental decoding; uses `prev_state` as the prior timestep, and returns the
+ updated EMA hidden state for use in the next step
+
+ Returns:
+ `tuple(torch.FloatTensor)` containing various elements depending on configuration ([`MegaConfig`]) and
+ inputs:
+ - **hidden_states** (`torch.FloatTensor` of shape `(sequence_length, batch_size, hidden_size)`) -- Hidden
+ states updated by EMA, with same shapes as inputs
+ - **updated_state** (*optional*, returned when `use_cache=True`) `torch.FloatTensor of shape `(batch_size,
+ config.ndim)` -- The incremental EMA state for use in the next step of incremental decoding
+ """
+
+ seq_len, bsz, embed_dim = inputs.size()
+ if embed_dim != self.embed_dim:
+ raise ValueError(
+ f"Unexpected embedding dimension received: input is {embed_dim}, model expects {self.embed_dim}"
+ )
+
+ # sequence_length X batch_size X hidden_size
+ residual = inputs * self.residual_weight
+
+ # (sequence_length x batch_size x hidden_size) -> (batch_size x hidden_size x sequence_length)
+ inputs = inputs.permute(1, 2, 0)
+ # mask the input: output is a tensor with 0 in the masked positions
+ if attention_mask is not None:
+ inputs = inputs * (attention_mask.unsqueeze(1).type_as(inputs))
+
+ if self.bidirectional and use_cache:
+ raise RuntimeError("Bidirectional EMA does not support incremental state")
+
+ if use_cache:
+ out, updated_state = self.ema_step(inputs, seq_len, past_state=prev_state)
+
+ # (batch_size X hidden_size) -> (1 x batch_size x hidden_size)
+ out = F.silu(out + residual)
+
+ # if incremental decoding, return the new state along with the output
+ return out, updated_state
+ else:
+ # (hidden_size x sequence_length)
+ kernel = self.get_ema_kernel(seq_len)
+ fft_len = seq_len
+ s_index = 0
+ kernel_size = kernel.size(1)
+ if self.bidirectional:
+ # split the kernel for each direction of EMA
+ k1, k2 = torch.split(kernel, [self.embed_dim, self.embed_dim], dim=0)
+ # (hidden_size X 2*sequence_length - 1)
+ kernel = F.pad(k1, (kernel_size - 1, 0)) + F.pad(k2.flip(-1), (0, kernel_size - 1))
+ inputs = F.pad(inputs, (kernel_size - 1, 0))
+ fft_len = fft_len + kernel_size - 1
+ s_index = 2 * kernel_size - 2
+
+ ema_output = self.fft_convolution(inputs, kernel, length=fft_len)[..., s_index : s_index + seq_len]
+ ema_output = ema_output.type_as(inputs)
+ # (batch_size X hidden_size X sequence_length) -> (sequence_length X batch_size X hidden_size)
+ gated_ema_output = F.silu(ema_output.permute(2, 0, 1) + residual)
+
+ return gated_ema_output, None
+
+
+class MegaGatedCrossAttention(nn.Module):
+ """
+ Gated Structured State Attention for use in encoder-decoder model. See Mega paper for more details. Only
+ modifications from original implementation are variable names, removing the unnecessary `before_attn_fn` and
+ `static_kv` arguments, and the stateful representation of incremental decoder state.
+ """
+
+ def __init__(self, config: MegaConfig):
+ super().__init__()
+
+ self.config = config
+ self.activation = ACT2FN[self.config.activation]
+ self.attention_activation = self.config.attention_activation
+ self.scaling = self.config.shared_representation_size**-0.5 if self.attention_activation == "softmax" else None
+
+ self.dropout = MegaDropout(self.config.dropout_prob, is_featurewise=self.config.use_feature_dropout)
+ self.hidden_dropout = MegaDropout(
+ self.config.hidden_dropout_prob, is_featurewise=self.config.use_feature_dropout
+ )
+ # Attention dropout is standard dropout
+ self.attention_dropout = MegaDropout(self.config.attention_probs_dropout_prob, is_featurewise=False)
+
+ self.prenorm = self.config.normalize_before_mega
+ self.norm = MegaSequenceNorm(
+ self.config.normalization_type, self.config.hidden_size, affine=self.config.norm_affine
+ )
+
+ self.k_proj = nn.Linear(self.config.hidden_size, self.config.shared_representation_size)
+ self.v_proj = nn.Linear(self.config.hidden_size, self.config.hidden_size)
+ self.q_proj = nn.Linear(
+ self.config.hidden_size, 2 * self.config.hidden_size + self.config.shared_representation_size
+ )
+ self.h_proj = nn.Linear(self.config.hidden_size, self.config.hidden_size)
+
+ if self.config.relative_positional_bias == "simple":
+ self.rel_pos_bias = MegaSimpleRelativePositionalBias(config)
+ elif self.config.relative_positional_bias == "rotary":
+ self.rel_pos_bias = MegaRotaryRelativePositionalBias(config)
+ else:
+ raise ValueError(f"unknown relative position bias: {self.config.relative_positional_bias}")
+
+ self.softmax = nn.Softmax(dim=-1)
+
+ def element_attention(self, query, key, key_padding_mask, pidx):
+ bsz, src_len, _ = key.size()
+ tgt_len = query.size(1) if pidx is None else pidx + 1
+ if key_padding_mask is not None:
+ # (batch_size X source_sequence_length) --> (batch_size X 1 X 1)
+ lengths = key_padding_mask.sum(dim=-1).view(bsz, 1, 1)
+ else:
+ lengths = src_len
+
+ # (target_sequence_length X source_sequence_length)
+ bias = self.rel_pos_bias(max(tgt_len, src_len))[:, :src_len]
+ if pidx is not None:
+ if query.size(1) != 1:
+ raise ValueError("Position offset provided with queries longer than 1 token")
+ # source_sequence_length
+ bias = bias[pidx]
+ else:
+ # (target_sequence_length X source_sequence_length)
+ bias = bias[:tgt_len]
+
+ # (batch_size X target_sequence_length X source_sequence_length)
+ qk = torch.bmm(query, key.transpose(1, 2)) / lengths + bias
+
+ attn_weights = ACT2FN[self.attention_activation](qk).type_as(qk)
+
+ if key_padding_mask is not None:
+ attn_weights = attn_weights * key_padding_mask.unsqueeze(1)
+
+ return attn_weights
+
+ def softmax_attention(self, query, key, key_padding_mask, pidx):
+ bsz, src_len, _ = key.size()
+ tgt_len = query.size(1) if pidx is None else pidx + 1
+
+ # (target_sequence_length X source_sequence_length)
+ bias = self.rel_pos_bias(max(tgt_len, src_len))[:, :src_len]
+ if pidx is not None:
+ if query.size(1) != 1:
+ raise ValueError("Position offset provided with queries longer than 1 token")
+ # source_sequence_length
+ bias = bias[pidx]
+ else:
+ # (target_sequence_length X source_sequence_length)
+ bias = bias[:tgt_len]
+
+ # scaled attention
+ query = query * self.scaling
+ # (batch_size X target_sequence_length X source_sequence_length)
+ qk = torch.bmm(query, key.transpose(1, 2)) + bias
+
+ if key_padding_mask is not None:
+ qk = qk.masked_fill((1 - key_padding_mask).unsqueeze(1).to(torch.bool), float("-inf"))
+
+ attn_weights = self.softmax(qk).type_as(qk)
+ return attn_weights
+
+ def forward(
+ self,
+ query,
+ key: Optional[torch.Tensor],
+ value: Optional[torch.Tensor],
+ key_padding_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
+ output_attentions: bool = False,
+ use_cache: bool = False,
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
+ """
+ Gated cross-attention used in Mega
+
+ Args:
+ query (`torch.Tensor` of shape `(target_sequence_length, batch_size, hidden_size)`):
+ The self (or target) sequence input used as query inputs for cross-attention
+ key (`torch.Tensor` of shape `(source_sequence_length, batch_size, hidden_size)`):
+ The cross (or source) sequence input with shape used as keys in cross-attention
+ value (`torch.Tensor` of shape `(source_sequence_length, batch_size, hidden_size)`):
+ The cross (or source) sequence input with shape used as values in cross-attention
+ key_padding_mask (`torch.LongTensor` of shape `(batch_size, source_sequence_length)`, *optional*):
+ Padding mask corresponding to the source sequence, where entries are 1 for *not masked* and 0 for
+ *masked* tokens
+ past_key_values (`tuple(torch.FloatTensor)`, *optional*):
+ If provided, the hidden state returned from the previous timestep during incremental decoding; expects
+ that prior cross-attention keys and values will be the last two items in the tuple
+ output_attentions (`bool`, defaults to `False`):
+ Whether or not to return the cross-attention weights.
+ use_cache (`bool`, defaults to `False`):
+ Whether to perform incremental decoding; uses `prev_state` as the prior timestep, and returns the
+ updated EMA hidden state for use in the next step
+
+ Returns:
+ `tuple(torch.FloatTensor)` containing various elements depending on configuration ([`MegaConfig`]) and
+ inputs:
+ - **hidden_states** (`torch.FloatTensor` of shape `(target_sequence_length, batch_size, hidden_size)`) --
+ Hidden states from target sequence updated by gated cross-attention
+ - **attn_weights** (*optional*, returned when `output_attentions=True`) `torch.FloatTensor` of shape
+ `(batch_size, source_sequence_length, target_sequence_length)` -- The pairwise cross-attention weights
+ corresponding to each token in the source and target sequences
+ - **cross_key** (*optional*, returned when `use_cache=True`) `torch.FloatTensor` of shape `(batch_size,
+ source_sequence_length, config.shared_representation_size)` -- The cross-attention key state for use in
+ the next step of incremental decoding
+ - **cross_value** (*optional*, returned when `use_cache=True`) `torch.FloatTensor` of shape `(batch_size,
+ source_sequence_length, config.hidden_size)` -- The cross-attention value state for use in the next step
+ of incremental decoding
+ """
+
+ seq_len, bsz, embed_dim = query.size()
+ if embed_dim != self.config.hidden_size:
+ raise ValueError(
+ f"Unexpected embedding dimension received: input is {embed_dim} but expected {self.config.hidden_size}"
+ )
+
+ if past_key_values is not None:
+ # make sure the inputs only have a sequence length of 1 if we're doing incremental decoding
+ if seq_len != 1:
+ raise ValueError(f"Incremental decoding requested with self-sequence length > 1: {seq_len}")
+ # expect past_key_values to have (self_key, self_value, self_ema, cross_key, cross_value)
+ prev_cross_key, prev_cross_value = past_key_values[-2:]
+ key = value = None
+
+ # use the self-attention cache to get the position id of the current step
+ prev_self_key = past_key_values[0]
+ num_incremental_steps = prev_self_key.size(1) + 1
+ else:
+ prev_cross_key = prev_cross_value = None
+ # we still need the position id if we're doing incremental decoding (past_key_values will be None for the first step)
+ num_incremental_steps = 0 if use_cache and (seq_len == 1) else None
+
+ full_query = query
+ if self.prenorm:
+ full_query = self.norm(full_query)
+
+ # (target_sequence_length X batch_size X 2*hidden_size + shared_representation_size)
+ query_projected = self.q_proj(full_query)
+ # split the query projections into separate components
+ # - residual_weight is passed through sigmoid and sent through elementwise multiplication to the gated/weighted targets prior to being added to the query directly
+ # - target_gate is a silu-gated tensor that is multiplied by the attention-weighted target below prior to residual connection
+ # - attention_query is the part that is passed to the attention function
+ residual_weight, target_gate, attention_query = torch.split(
+ query_projected,
+ [self.config.hidden_size, self.config.hidden_size, self.config.shared_representation_size],
+ dim=-1,
+ )
+
+ # (target_sequence_length X batch_size X hidden_size)
+ residual_weight = torch.sigmoid(residual_weight)
+ target_gate = F.silu(target_gate)
+
+ if key is None:
+ if value is not None:
+ raise ValueError("Key and value must be `None` simultaneously")
+ projected_key = projected_value = None
+ else:
+ # (source_sequence_length X batch_size X shared_representation_size)
+ projected_key = self.k_proj(key)
+ # (source_sequence_length X batch_size X hidden_size)
+ projected_value = self.activation(self.v_proj(key))
+
+ # (target_sequence_length X batch_size X shared_representation_size)
+ # -> (batch_size X target_sequence_length X shared_representation_size)
+ attention_query = attention_query.transpose(0, 1)
+ if projected_key is not None:
+ projected_key = projected_key.transpose(0, 1)
+ if projected_value is not None:
+ projected_value = projected_value.transpose(0, 1)
+
+ # if we're doing incremental decoding, k and v are None and need to be overwritten with past values
+ if past_key_values is not None:
+ projected_key = prev_cross_key
+ projected_value = prev_cross_value
+
+ # if we're returning the cache for later use, store these now for later return (can be done without having past_key_values provided)
+ if use_cache:
+ updated_cross_key = projected_key
+ updated_cross_value = projected_value
+
+ ctx_len = projected_key.size(1)
+ # This is part of a workaround to get around fork/join parallelism
+ # not supporting Optional types.
+ if key_padding_mask is not None and key_padding_mask.dim() == 0:
+ key_padding_mask = None
+
+ if key_padding_mask is not None:
+ if key_padding_mask.size(0) != bsz:
+ raise ValueError("Key padding mask does not align on the batch dimension")
+ if key_padding_mask.size(1) != ctx_len:
+ raise ValueError("Key padding mask does not align on the sequence length dimension")
+
+ if self.attention_activation == "softmax":
+ attn_weights = self.softmax_attention(
+ attention_query, projected_key, key_padding_mask, num_incremental_steps
+ )
+ else:
+ attn_weights = self.element_attention(
+ attention_query, projected_key, key_padding_mask, num_incremental_steps
+ )
+
+ projected_value = self.hidden_dropout(projected_value, batch_first=True)
+ kernel = self.attention_dropout(attn_weights)
+ # (batch_size X target_sequence_length X hidden_size)
+ # -> (target_sequence_length X batch_size X hidden_size)
+ weighted_targets = torch.bmm(kernel, projected_value).transpose(0, 1)
+ # (target_sequence_length X batch_size X hidden_size)
+ weighted_targets = self.activation(self.h_proj(weighted_targets * target_gate))
+ weighted_targets = self.dropout(weighted_targets)
+ out = torch.addcmul(query, residual_weight, weighted_targets - query)
+
+ if not self.prenorm:
+ out = self.norm(out)
+
+ outputs = (out, attn_weights) if output_attentions else (out,)
+ if use_cache:
+ outputs = outputs + (updated_cross_key, updated_cross_value)
+
+ return outputs
+
+
+class MegaMovingAverageGatedAttention(nn.Module):
+ """
+ Pure PyTorch implementation of Mega block; see https://huggingface.co/papers/2209.10655 and original fairseq implementation
+ at https://github.com/facebookresearch/mega (copyright Meta Research, licensed under MIT License)
+
+ Differences from original implementation include hidden state refactor and fixed inconsistency with additive /
+ multiplicative attention masks
+ """
+
+ def __init__(self, config: MegaConfig):
+ super().__init__()
+ self.config = config
+ self.activation = ACT2FN[self.config.activation]
+ self.scaling = (
+ self.config.shared_representation_size**-0.5 if self.config.attention_activation == "softmax" else None
+ )
+ self.dropout = MegaDropout(self.config.dropout_prob, is_featurewise=self.config.use_feature_dropout)
+ self.hidden_dropout = MegaDropout(
+ self.config.hidden_dropout_prob, is_featurewise=self.config.use_feature_dropout
+ )
+ # attention dropout is standard dropout
+ self.attention_dropout = MegaDropout(self.config.attention_probs_dropout_prob, is_featurewise=False)
+
+ self.norm = MegaSequenceNorm(
+ self.config.normalization_type, self.config.hidden_size, affine=self.config.norm_affine
+ )
+ self.ema_gate = MegaMultiDimensionDampedEma(config)
+
+ self.v_proj = nn.Linear(self.config.hidden_size, self.config.intermediate_size)
+ self.mx_proj = nn.Linear(
+ self.config.hidden_size,
+ self.config.shared_representation_size + self.config.intermediate_size + 2 * self.config.hidden_size,
+ )
+ self.h_proj = nn.Linear(self.config.intermediate_size, self.config.hidden_size)
+
+ self.qk_weight = nn.Parameter(torch.Tensor(2, self.config.shared_representation_size))
+ self.qk_bias = nn.Parameter(torch.Tensor(2, self.config.shared_representation_size))
+
+ if self.config.relative_positional_bias == "simple":
+ self.rel_pos_bias = MegaSimpleRelativePositionalBias(config)
+ elif self.config.relative_positional_bias == "rotary":
+ self.rel_pos_bias = MegaRotaryRelativePositionalBias(config)
+ else:
+ raise ValueError(f"Unknown relative positional bias: {self.config.relative_positional_bias}")
+
+ self.softmax = nn.Softmax(dim=-1)
+ self.attention_function = (
+ self.softmax_attention if self.config.attention_activation == "softmax" else self.element_attention
+ )
+
+ def element_attention(self, query, key, padding_mask, causal_mask):
+ """
+ Apply element-wise attention via relu^2 or laplace. Same as original implementation but with standardized
+ causal attention mask. Expects the Hugging Face standard attention mask paradigm: 1 for not masked, and 0 for
+ masked.
+ """
+ seq_len = key.size(2)
+ if padding_mask is not None:
+ # (batch_size X number of chunks X 1)
+ lengths = padding_mask.sum(-1, keepdim=True)
+ # (batch_size X number of chunks X 1 X 1)
+ lengths = lengths.clamp(min=1.0).unsqueeze(-1)
+ else:
+ lengths = seq_len
+
+ if causal_mask is not None:
+ lengths = causal_mask.sum(dim=-1, keepdim=True)
+
+ # (sequence_length X sequence_length)
+ bias = self.rel_pos_bias(seq_len)
+ if seq_len != query.size(2):
+ if query.size(2) != 1:
+ raise ValueError("Size mismatch between Q and K in element attention")
+ # (1 X sequence_length)
+ bias = bias[-1:]
+
+ # (batch_size X number of chunks X sequence_length X sequence_length)
+ qk = torch.matmul(query, key.transpose(2, 3)) / lengths + bias
+
+ attn_weights = ACT2FN[self.config.attention_activation](qk).type_as(qk)
+
+ if padding_mask is not None:
+ attn_weights = attn_weights * padding_mask.unsqueeze(2)
+
+ if causal_mask is not None:
+ attn_weights = attn_weights * causal_mask
+
+ return attn_weights
+
+ def softmax_attention(self, query, key, padding_mask, causal_mask):
+ "Standard softmax self-attention, as in the original Transformer paper"
+ seq_len = key.size(2)
+ # (sequence_length X sequence_length)
+ bias = self.rel_pos_bias(seq_len)
+ if seq_len != query.size(2):
+ if query.size(2) != 1:
+ raise ValueError("Size mismatch between Q and K in softmax attention")
+ # (1 X sequence_length)
+ bias = bias[-1:]
+
+ # scaled attention
+ query = query * self.scaling
+
+ # (batch_size x number of chunks x chunk_size x chunk_size) if chunking
+ # (batch_size x 1 x sequence_length x sequence_length) otherwise
+ qk = torch.matmul(query, key.transpose(2, 3)) + bias
+
+ # apply causal mask (presumed to be 1/0 for not masked / masked)
+ # additive, but convert to 0/-inf (which is not explicitly in the Mega source code)
+ if causal_mask is not None:
+ additive_causal_mask = torch.zeros_like(causal_mask, dtype=qk.dtype)
+ additive_causal_mask = additive_causal_mask.masked_fill((1 - causal_mask).bool(), float("-inf"))
+ qk = qk + additive_causal_mask
+
+ if padding_mask is not None:
+ # 1 for tokens which are *not masked*
+ # 0 for tokens which are *masked*
+ # replace masked tokens with -inf to make softmax ignore them
+ # need to invert the padding mask to match what mega original did
+ padding_mask = 1 - padding_mask
+ padding_mask_all = padding_mask.all(dim=-1, keepdim=True)
+ padding_mask = torch.logical_and(padding_mask, ~padding_mask_all)
+ qk = qk.masked_fill(padding_mask.unsqueeze(2).to(torch.bool), float("-inf"))
+
+ attn_weights = self.softmax(qk).type_as(qk)
+ return attn_weights
+
+ def forward(
+ self,
+ input,
+ padding_mask: Optional[torch.Tensor] = None,
+ causal_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
+ output_attentions=False,
+ use_cache=False,
+ ):
+ """
+ Mega's self-attention block, which combines multi-headed EMA with traditional self-attention
+
+ Args:
+ input (`torch.Tensor` of shape `(sequence_length, batch_size, hidden_size)`):
+ Hidden states to be updated by Mega's self-attention
+ padding_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indicates which inputs are to be ignored due to padding, where elements are either 1 for *not masked*
+ or 0 for *masked*
+ causal_mask (`torch.LongTensor` of shape `(sequence_length, sequence_length)`, *optional*):
+ Indicates which inputs are to be ignored due to causal attention, where elements are either 1 for *not
+ masked* or 0 for *masked*
+ past_key_values (`tuple(torch.Tensor)`, *optional*):
+ The hidden states returned from the previous timestep during incremental decoding; expects that
+ self-attention key, value, and EMA states are the first 3 entries in the tuple
+ output_attentions (`bool`, default `False`):
+ Whether to return self-attention weights
+ use_cache (`bool`, default `False`):
+ Whether to perform incremental decoding; uses `past_key_values` as prior state, and returns the updated
+ states for use in the next step
+
+ Returns:
+ `tuple(torch.FloatTensor)` containing various elements depending on configuration ([`MegaConfig`]) and
+ inputs:
+ - **hidden_states** (`torch.FloatTensor` of shape `(sequence_length, batch_size, hidden_size)`) -- Hidden
+ states from target sequence updated by Mega's self-attention
+ - **attn_weights** (*optional*, returned when `output_attentions=True`) `torch.FloatTensor` of shape
+ `(batch_size, 1, sequence_length, sequence_length)` -- The self-attention weights corresponding to how
+ each token in the input sequence attends to every other token
+ - **self_key** (*optional*, returned when `use_cache=True`) `torch.FloatTensor` of shape `(batch_size,
+ sequence_length, config.shared_representation_size)` -- The self-attention key state for use in the next
+ step of incremental decoding
+ - **self_value** (*optional*, returned when `use_cache=True`) `torch.FloatTensor` of shape `(batch_size,
+ sequence_length, config.hidden_size)` -- The self-attention value state for use in the next step of
+ incremental decoding
+ - **self_ema_state** (*optional*, returned when `use_cache=True`) `torch.FloatTensor` of shape
+ `(batch_size, config.ndim)` The incremental EMA state for use in the next step of incremental decoding.
+ """
+
+ seq_len, bsz, embed_dim = input.size()
+ if embed_dim != self.config.hidden_size:
+ raise ValueError(f"Input embedding dimension should be {self.config.hidden_size}; received {embed_dim}")
+
+ # store inputs for residual connection and handle pre-norm if requested
+ residual = input
+ if self.config.normalize_before_mega:
+ input = self.norm(input)
+
+ # (sequence_length X batch_size X hidden_size) -> (sequence_length X batch_size X intermediate_size)
+ value = self.activation(self.v_proj(input))
+
+ # unpack the incremental state if provided
+ # assumed to be (self K, self V, self EMA state, cross K, cross V)
+ # also assumes that incremental decoding is working one token at a time, so input sequence length must be 1
+ if self.config.is_decoder and (past_key_values is not None):
+ if seq_len > 1:
+ raise ValueError(f"Incremental decoding only supports self sequence length of 1; received {seq_len}")
+ # the first 3 items in the saved states will be these regardless of whether cross-attention is present
+ prev_self_key, prev_self_value, prev_ema_state = past_key_values[0:3]
+ else:
+ prev_self_key = prev_self_value = prev_ema_state = None
+
+ # ema output is (sequence_length x batch_size x hidden_size)
+ # updated_ema_state will be None if use_cache=False; otherwise (batch_size, config.ndim)
+ ema_out, updated_ema_state = self.ema_gate(
+ input, attention_mask=padding_mask, prev_state=prev_ema_state, use_cache=use_cache
+ )
+ ema_out = self.dropout(ema_out)
+
+ # (sequence_length X batch_size X hidden_size)
+ # -> (sequence_length X batch_size X 2*hidden_size + config.shared_representation_size + config.intermediate_size)
+ # - residual_weight -> sigmoid -> applied to residual connection in torch.addcmul
+ # - query_key_gates -> split into two components: query_key becomes query and key for attention input, gates becomes gating for self-attention output
+ # - intermediate_state -> added to weighted attention output, sent through activation, and has inputs subtracted during
+ # torch.addcmul to create the final layer output
+ base = self.mx_proj(ema_out)
+ residual_weight, query_key_gates, intermediate_state = torch.split(
+ base,
+ [
+ self.config.hidden_size,
+ self.config.shared_representation_size + self.config.intermediate_size,
+ self.config.hidden_size,
+ ],
+ dim=-1,
+ )
+
+ # (sequence_length X batch_size X hidden_size)
+ residual_weight = torch.sigmoid(residual_weight)
+
+ # (sequence_length X batch_size X shared_representation_size + intermediate_size)
+ query_key_gates = F.silu(query_key_gates)
+
+ # split into two different tensors: one for Q/K usage and the other for gating self-attention
+ query_key, attention_gate = torch.split(
+ query_key_gates, [self.config.shared_representation_size, self.config.intermediate_size], dim=-1
+ )
+
+ # (sequence_length X batch_size X shared_representation_size)
+ # -> (sequence_length X batch_size X 1 X shared_representation_size)
+ # -> (sequence_length X batch_size X 2 X shared_representation_size)
+ query_key = query_key.unsqueeze(2) * self.qk_weight + self.qk_bias
+
+ # (sequence_length X batch_size X 2 X shared_representation_size)
+ # -> 2 tensors of (sequence_length X batch_size X shared_representation_size)
+ query, key = torch.unbind(query_key, dim=2)
+
+ # (sequence_length X batch_size X dimension)
+ # -> (batch_size X sequence_length X dimension)
+ # where `dimension` is either shared_representation_size (queries and keys) or intermediate_size (values)
+ query = query.transpose(0, 1)
+ key = key.transpose(0, 1)
+ value = value.transpose(0, 1)
+
+ if self.config.is_decoder:
+ # combine history and current to save updated state (if history is provided)
+ # when chunking is applied, the past states will be None at the end of the chunk, in
+ # which case, proceed as if no K/V history had been provided
+ # saved states are stored with shape (batch_size X sequence_length X dimension)
+ if prev_self_key is not None:
+ key = torch.cat([prev_self_key, key], dim=1)
+ if prev_self_value is not None:
+ value = torch.cat([prev_self_value, value], dim=1)
+
+ # if not chunking, store as-is
+ if not self.config.use_chunking:
+ updated_self_key = key
+ updated_self_value = value
+ else:
+ curr_len = key.size(1) % self.config.chunk_size
+ if curr_len == 0:
+ # if we're chunking and have reached the end of a chunk, wipe out the saved state
+ updated_self_key = None
+ updated_self_value = None
+ else:
+ updated_self_key = key
+ updated_self_value = value
+
+ ctx_len = key.size(1) # potentially differs from seq_len because of incremental decoding
+ if not self.config.use_chunking:
+ # if we're not chunking, treat the entire sequence as one long chunk
+ # (batch_size X sequence_length X dimension) -> (batch_size X 1 X sequence_length X dimension)
+ query = query.unsqueeze(1)
+ key = key.unsqueeze(1)
+ value = value.unsqueeze(1)
+ if padding_mask is not None:
+ # (batch_size X sequence_length) -> (batch_size X 1 X sequence_length)
+ padding_mask = padding_mask.unsqueeze(1)
+ else:
+ # otherwise, split the sequences in the batch into `n_chunks` chunks of size `chunk_size`
+ if seq_len < self.config.chunk_size:
+ query = query.unsqueeze(1)
+ else:
+ # (batch_size X sequence_length X dimension) -> (batch_size X n_chunks X chunk_size X dimension)
+ n_chunks = seq_len // self.config.chunk_size
+ query = query.reshape(bsz, n_chunks, self.config.chunk_size, self.config.shared_representation_size)
+
+ if ctx_len < self.config.chunk_size:
+ key = key.unsqueeze(1)
+ value = value.unsqueeze(1)
+ if padding_mask is not None:
+ padding_mask = padding_mask.unsqueeze(1)
+ else:
+ # (batch_size X sequence_length X dimension) -> (batch_size X n_chunks X chunk_size X dimension)
+ n_chunks = ctx_len // self.config.chunk_size
+ key = key.reshape(bsz, n_chunks, self.config.chunk_size, self.config.shared_representation_size)
+ value = value.reshape(bsz, n_chunks, self.config.chunk_size, self.config.intermediate_size)
+ if padding_mask is not None:
+ padding_mask = padding_mask.view(bsz, n_chunks, self.config.chunk_size)
+
+ # this is in the original Mega implementation to work around fork/join parallelism not supporting optional types
+ if padding_mask is not None and padding_mask.dim() == 0:
+ padding_mask = None
+
+ attn_weights = self.attention_function(query, key, padding_mask=padding_mask, causal_mask=causal_mask)
+
+ value = self.hidden_dropout(value, batch_first=True)
+ kernel = self.attention_dropout(attn_weights)
+
+ # (batch_size x n_chunks x chunk_size x intermediate_size) -> (sequence_length X batch_size X intermediate_size)
+ weighted_self_output = (
+ torch.matmul(kernel, value).view(bsz, seq_len, self.config.intermediate_size).transpose(0, 1)
+ )
+
+ # (sequence_length X batch_size X intermediate_size) -> (sequence_length X batch_size X hidden_size)
+ weighted_self_output = self.activation(intermediate_state + self.h_proj(weighted_self_output * attention_gate))
+ weighted_self_output = self.dropout(weighted_self_output)
+ # (sequence_length X batch_size X hidden_size)
+ out = torch.addcmul(residual, residual_weight, weighted_self_output - residual)
+
+ if not self.config.normalize_before_mega:
+ out = self.norm(out)
+
+ return_values = (out, attn_weights) if output_attentions else (out,)
+
+ if self.config.is_decoder:
+ return_values = return_values + (updated_self_key, updated_self_value, updated_ema_state)
+
+ return return_values
+
+
+class MegaNormalizedFeedForwardNetwork(nn.Module):
+ """
+ Normalized feed-forward network used in Mega blocks. Left as-is from original Mega repo aside from retrieving args
+ from Hugging Face config
+ """
+
+ def __init__(self, config: MegaConfig):
+ super().__init__()
+
+ self.config = config
+ self.hidden_dim = config.nffn_hidden_size
+ self.act_fn = config.activation
+ self.activation = ACT2FN[config.activation]
+
+ self.dropout = MegaDropout(self.config.dropout_prob, is_featurewise=self.config.use_feature_dropout)
+ self.hidden_dropout = MegaDropout(
+ self.config.nffn_activation_dropout_prob, is_featurewise=self.config.use_feature_dropout
+ )
+
+ self.prenorm = self.config.normalize_before_ffn
+ self.norm = MegaSequenceNorm(
+ self.config.normalization_type, self.config.hidden_size, affine=self.config.norm_affine
+ )
+
+ self.fc1 = nn.Linear(self.config.hidden_size, self.config.nffn_hidden_size)
+ self.fc2 = nn.Linear(self.config.nffn_hidden_size, self.config.hidden_size)
+
+ def forward(self, inputs):
+ residual = inputs
+
+ if self.prenorm:
+ inputs = self.norm(inputs)
+
+ hidden = self.activation(self.fc1(inputs))
+ hidden = self.hidden_dropout(hidden)
+ output = self.fc2(hidden)
+ output = self.dropout(output)
+ output = output + residual
+
+ if not self.prenorm:
+ output = self.norm(output)
+
+ return output
+
+
+class MegaBlock(nn.Module):
+ def __init__(self, config: MegaConfig):
+ super().__init__()
+ self.seq_len_dim = 1
+ self.mega_layer = MegaMovingAverageGatedAttention(config)
+ self.nffn = MegaNormalizedFeedForwardNetwork(config) if config.use_normalized_ffn else None
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.cross_attn = MegaGatedCrossAttention(config)
+ else:
+ self.cross_attn = None
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.LongTensor] = None,
+ causal_mask: Optional[torch.LongTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[torch.FloatTensor]] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: bool = False,
+ ) -> tuple[torch.Tensor]:
+ """
+ A single Mega layer: either encoder or decoder, with optional cross-attention and optional normalized
+ feed-forward layer
+
+ Args:
+ hidden_states (`torch.Tensor` of shape `(target_sequence_length, batch_size, hidden_size)`):
+ Hidden states to be updated by the Mega block
+ attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indicates which entries in the self/target sequence are to be ignored (mostly due to padding), where
+ elements are either 1 for *not masked* or 0 for *masked*. Causal attention is enforced internally.
+ causal_mask (`torch.LongTensor` of shape `(sequence_length, sequence_length)`, *optional*):
+ Indicates which inputs are to be ignored due to causal attention, where elements are either 1 for *not
+ masked* or 0 for *masked*
+ encoder_hidden_states (`torch.Tensor`, of shape `(source_sequence_length, batch_size, hidden_size)`, *optional*):
+ Encoder hidden states to be used for cross-attention (and required for encoder-decoder model setup)
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, source_sequence_length)`, *optional*):
+ Indicates which entries in the cross/source sequence are to be ignored (mostly due to padding), where
+ elements are either 1 for *not masked* or 0 for *masked*.
+ past_key_values (`tuple(torch.Tensor)`, *optional*):
+ The hidden states returned from the previous timestep during incremental decoding; expects that
+ self-attention key, value, and EMA states are the first 3 entries in the tuple, and (if doing
+ cross-attention) cross-attention key and value are the last 2 entries in the tuple
+ output_attentions (`bool`, default `False`):
+ Whether to return self-attention weights
+ use_cache (`bool`, default `False`):
+ Whether to perform incremental decoding; uses `past_key_values` as prior state, and returns the updated
+ states for use in the next step
+
+ Returns:
+ `tuple(torch.FloatTensor)` containing various elements depending on configuration ([`MegaConfig`]) and
+ inputs:
+ - **hidden_states** (`torch.FloatTensor` of shape `(target_sequence_length, batch_size, hidden_size)`) --
+ Hidden states from target sequence updated by Mega
+ - **self_attn_weights** (*optional*, returned when `output_attentions=True`) `torch.FloatTensor` of shape
+ `(batch_size, 1, target_sequence_length, target_sequence_length)` -- The self-attention weights
+ corresponding to how each token in the input sequence attends to every other token
+ - **cross_attn_weights** (*optional*, returned when `output_attentions=True` and
+ `config.add_cross_attention=True`) `torch.FloatTensor` of shape `(batch_size, source_sequence_length,
+ target_sequence_length)` -- Pairwise cross-attention weights between every entry in the source sequence
+ and target sequence
+ - **self_key** (*optional*, returned when `use_cache=True`) `torch.FloatTensor` of shape `(batch_size,
+ sequence_length, config.shared_representation_size)` -- The self-attention key state for use in the next
+ step of incremental decoding
+ - **self_value** (*optional*, returned when `use_cache=True`) `torch.FloatTensor` of shape `(batch_size,
+ sequence_length, config.hidden_size)` -- The self-attention value state for use in the next step of
+ incremental decoding
+ - **self_ema_state** (*optional*, returned when `use_cache=True`) `torch.FloatTensor` of shape
+ `(batch_size, config.ndim)` The incremental EMA state for use in the next step of incremental decoding.
+ - **cross_key** (*optional*, returned when `use_cache=True` and `config.is_decoder=True`)
+ `torch.FloatTensor` of shape `(batch_size, source_sequence_length, config.shared_representation_size)` --
+ The cross-attention key state for use in the next step of incremental decoding
+ - **cross_value** (*optional*, returned when `use_cache=True` and `config.is_decoder=True`)
+ `torch.FloatTensor` of shape `(batch_size, source_sequence_length, config.hidden_size)` -- The
+ cross-attention value state for use in the next step of incremental decoding
+ """
+
+ # incremental decoding in the MegaMultiDimensionDampedEma module requires that the attention mask has the same
+ # sequence length as the input tensor; if we're caching incremental states, we assume the input
+ # sequence length is 1 (Mega will break otherwise), so we take the padding mask for the final
+ # token in the input (mask is received as [batch X sequence length])
+ if use_cache and (past_key_values is not None) and (attention_mask is not None):
+ mega_padding_mask = attention_mask[:, -1].unsqueeze(-1)
+ else:
+ mega_padding_mask = attention_mask
+
+ mega_outputs = self.mega_layer(
+ input=hidden_states,
+ padding_mask=mega_padding_mask,
+ causal_mask=causal_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ )
+
+ new_hidden_states = mega_outputs[0]
+ self_key, self_value, self_ema_state = mega_outputs[-3:] if use_cache else (None, None, None)
+ self_attention_weights = mega_outputs[1] if output_attentions else None
+
+ # optional cross attention
+ if self.cross_attn is not None:
+ if encoder_hidden_states is None:
+ raise ValueError("Requested cross-attention without providing encoder hidden states")
+
+ cross_attn_outputs = self.cross_attn(
+ query=new_hidden_states,
+ key=encoder_hidden_states,
+ value=encoder_hidden_states,
+ key_padding_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ )
+
+ # update the hidden state from cross attention
+ new_hidden_states = cross_attn_outputs[0]
+ # store cross-attention k/v if caching
+ cross_key, cross_value = cross_attn_outputs[-2:] if use_cache else (None, None)
+ cross_attention_weights = cross_attn_outputs[1] if output_attentions else None
+
+ # optional NFFN follows cross attention
+ if self.nffn is not None:
+ new_hidden_states = self.nffn(new_hidden_states)
+
+ outs = (new_hidden_states,)
+ if output_attentions:
+ outs = outs + (self_attention_weights,)
+ if self.cross_attn is not None:
+ outs = outs + (cross_attention_weights,)
+
+ if use_cache:
+ new_key_values = (
+ self_key,
+ self_value,
+ self_ema_state,
+ )
+ if self.cross_attn is not None:
+ new_key_values = new_key_values + (cross_key, cross_value)
+
+ outs = outs + (new_key_values,)
+
+ return outs
+
+
+# copied from transformers.models.roberta.modeling_roberta.RobertaPooler with Roberta->Mega
+class MegaPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+class MegaPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: MegaConfig
+ base_model_prefix = "mega"
+ supports_gradient_checkpointing = False
+ _no_split_modules = ["MegaMovingAverageGatedAttention"]
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, MegaMultiDimensionDampedEma):
+ with torch.no_grad():
+ # delta & alpha
+ nn.init.normal_(module.damping_factor, mean=0.0, std=self.config.ema_delta_alpha_range)
+ nn.init.normal_(module.decay_factor, mean=0.0, std=self.config.ema_delta_alpha_range)
+ # beta [1, -1, 1, -1, ...] seems more stable.
+ val = torch.ones(self.config.ema_projection_size, 1)
+ if self.config.ema_projection_size > 1:
+ idx = torch.tensor(list(range(1, self.config.ema_projection_size, 2)))
+ val.index_fill_(0, idx, -1.0)
+ module.ema_expansion_matrix.normal_(mean=0.0, std=self.config.ema_beta_range).add_(val)
+ # gamma & omega
+ nn.init.normal_(module.kernel_projection_matrix, mean=0.0, std=self.config.ema_gamma_omega_range)
+ nn.init.normal_(module.residual_weight, mean=0.0, std=self.config.ema_gamma_omega_range)
+ elif isinstance(module, MegaSimpleRelativePositionalBias):
+ nn.init.normal_(module.rel_pos_bias, mean=0.0, std=self.config.initializer_range)
+ elif isinstance(module, MegaRotaryRelativePositionalBias):
+ nn.init.normal_(module.alpha, mean=0.0, std=self.config.initializer_range)
+ nn.init.normal_(module.b_param, mean=0.0, std=self.config.initializer_range)
+ elif isinstance(module, MegaScaleNorm):
+ if self.config.norm_affine:
+ nn.init.constant_(module.scalar, 1.0)
+ elif isinstance(module, MegaRMSNorm):
+ if self.config.norm_affine:
+ nn.init.constant_(module.weight, 1.0)
+ elif isinstance(module, MegaMovingAverageGatedAttention):
+ # linear layers covered separately by the generic nn.Linear init below
+ nn.init.normal_(module.qk_weight, mean=0.0, std=self.config.initializer_range)
+ nn.init.constant_(module.qk_bias, 0.0)
+ elif isinstance(module, nn.Linear):
+ # initializes all linear layers in the entire network
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+MEGA_START_DOCSTRING = r"""
+
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`MegaConfig`]): Model configuration class with all the parameters of the
+ model. Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+MEGA_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `add_token_type_embeddings` parameter
+ set to `True`. All the value in this tensor should be always < config.type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare MEGA Model transformer outputting raw hidden-states without any specific head on top.",
+ MEGA_START_DOCSTRING,
+)
+class MegaModel(MegaPreTrainedModel):
+ """
+
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added after self-attention, following the architecture described in *Mega: Moving Average
+ Equipped Gated Attention*_ by Xuezhe Ma, Chunting Zhou, Xiang Kong, Junxian He, Liangke Gui, Graham Neubig,
+ Jonathan May, and Luke Zettlemoyer
+
+ To behave as a decoder the model needs to be initialized with the `is_decoder` argument of the configuration set to
+ `True` and `bidirectional` set to `False`. To be used in a Seq2Seq model, the model needs to initialized with both
+ `is_decoder=True` and `bidirectional=False` argument as well as `add_cross_attention` set to `True`; an
+ `encoder_hidden_states` is then expected as an input to the forward pass.
+
+ .. _*Mega: Moving Average Equipped Gated Attention*: https://huggingface.co/papers/2209.10655
+
+ """
+
+ def __init__(self, config: MegaConfig, add_pooling_layer=True):
+ super().__init__(config)
+ self.config = config
+
+ self.embedding_layer = MegaEmbeddings(config)
+ self.layers = nn.ModuleList([MegaBlock(config) for _ in range(config.num_hidden_layers)])
+
+ self.pooler = MegaPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing (retained from RoBERTa code)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embedding_layer.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embedding_layer.word_embeddings = value
+
+ @add_start_docstrings_to_model_forward(MEGA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+ """
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ device = input_ids.device
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ device = inputs_embeds.device
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ if self.config.use_chunking:
+ input_shape = torch.tensor([input_shape[0], self.config.chunk_size])
+
+ batch_size, sequence_length = input_shape
+
+ if self.config.use_chunking and (sequence_length > self.config.chunk_size):
+ if sequence_length % self.config.chunk_size != 0:
+ raise ValueError(
+ f"config.use_chunking is activated; input sequence length must be shorter than or a multiple of config.chunk_size\nreceived sequence length of {sequence_length} with chunk size {self.config.chunk_size}"
+ )
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ # Mega expects the causal mask to be a 2D square matrix of (from) x (to) over the input sequence length
+ # the HF utility function generates a 3D causal mask which includes batch size, so we'll create a dummy
+ # mask with the correct device and all ones
+ temp_mask_for_extension = torch.ones((1, sequence_length), dtype=torch.long, device=device)
+ causal_mask = self.create_extended_attention_mask_for_decoder(input_shape, temp_mask_for_extension)
+
+ # get rid of batch dimension in the generated mask; result is (sequence_length X sequence_length)
+ causal_mask = causal_mask.squeeze(0)
+ else:
+ use_cache = False
+ causal_mask = None
+
+ # if using cache, make sure we have a tuple of tuples which matches the length of our hidden layers
+ if (past_key_values is not None) and (len(past_key_values) != self.config.num_hidden_layers):
+ raise ValueError(
+ f"Received past key/value cache with size mismatch; expected {self.config.num_hidden_layers}, received {len(past_key_values)}"
+ )
+
+ # get embeddings (batch X sequence length X embed dim)
+ embedding_output = self.embedding_layer(
+ input_ids=input_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
+ )
+
+ # transpose for Mega --> (seq len X batch X embed dim)
+ hidden_states = embedding_output.transpose(0, 1)
+
+ # we expect encoder hidden states to also have batch first in line
+ # with typical Hugging Face behavior (which is also how we return them)
+ # Mega expects sequence length first, so do the same transpose here
+ if encoder_hidden_states is not None:
+ encoder_hidden_states = encoder_hidden_states.transpose(0, 1)
+
+ # pass through mega layers
+ all_hidden_states = (embedding_output,) if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
+ next_decoder_cache = () if use_cache else None
+ for i, mega_layer in enumerate(self.layers):
+ current_decoder_cache = past_key_values[i] if past_key_values is not None else None
+ mega_outputs = mega_layer(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ causal_mask=causal_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=current_decoder_cache,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ )
+
+ hidden_states = mega_outputs[0]
+ if output_hidden_states:
+ # store layer-wise hidden states in the way that the user expects
+ # (seq len X batch X embed dim) --> (batch X seq len X embed dim)
+ all_hidden_states += (hidden_states.transpose(0, 1),)
+ if output_attentions:
+ self_attn_weights = mega_outputs[1]
+ all_self_attentions += (self_attn_weights,)
+ if self.config.add_cross_attention:
+ cross_attn_weights = mega_outputs[2]
+ all_cross_attentions += (cross_attn_weights,)
+ if use_cache:
+ updated_cache = mega_outputs[-1]
+ next_decoder_cache += (updated_cache,)
+
+ # transpose final hidden states
+ hidden_states = hidden_states.transpose(0, 1)
+
+ # optional pooling layer
+ pooled_output = self.pooler(hidden_states) if self.pooler is not None else None
+
+ if not return_dict:
+ return (hidden_states, pooled_output) + (
+ all_hidden_states,
+ next_decoder_cache,
+ all_self_attentions,
+ all_cross_attentions,
+ )
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ pooler_output=pooled_output,
+ past_key_values=next_decoder_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+@add_start_docstrings(
+ """MEGA Model with a `language modeling` head on top for CLM fine-tuning.""", MEGA_START_DOCSTRING
+)
+class MegaForCausalLM(MegaPreTrainedModel):
+ _tied_weights_keys = ["lm_head.weight"]
+
+ def __init__(self, config: MegaConfig):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `MegaForCausalLM` as a standalone, add `is_decoder=True.`")
+
+ self.mega = MegaModel(config, add_pooling_layer=False)
+
+ if config.add_lm_hidden_dense_layer:
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.hidden_activation = nn.Tanh()
+ else:
+ self.dense = None
+ self.hidden_activation = None
+
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(MEGA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, MegaForCausalLM, AutoConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("mnaylor/mega-base-wikitext")
+ >>> config = AutoConfig.from_pretrained("mnaylor/mega-base-wikitext")
+ >>> config.is_decoder = True
+ >>> config.bidirectional = False
+ >>> model = MegaForCausalLM.from_pretrained(
+ ... "mnaylor/mega-base-wikitext", config=config, ignore_mismatched_sizes=True
+ ... )
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ if labels is not None:
+ use_cache = False
+
+ outputs = self.mega(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ if self.dense is not None:
+ sequence_output = self.dense(sequence_output)
+ sequence_output = self.hidden_activation(sequence_output)
+
+ prediction_scores = self.lm_head(sequence_output)
+
+ lm_loss = None
+ if labels is not None:
+ # we are doing next-token prediction; shift prediction scores and input ids by one
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
+ labels = labels[:, 1:].contiguous()
+ loss_fct = CrossEntropyLoss()
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((lm_loss,) + output) if lm_loss is not None else output
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=lm_loss,
+ logits=prediction_scores,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
+ input_shape = input_ids.shape
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
+ if attention_mask is None:
+ attention_mask = input_ids.new_ones(input_shape)
+
+ # cut decoder_input_ids if past is used
+ if past_key_values is not None:
+ input_ids = input_ids[:, -1:]
+
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
+
+ def _reorder_cache(self, past_key_values, beam_idx):
+ reordered_past = ()
+ for layer_past in past_key_values:
+ reordered_past += (
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
+ )
+ return reordered_past
+
+
+@add_start_docstrings("""MEGA Model with a `language modeling` head on top.""", MEGA_START_DOCSTRING)
+class MegaForMaskedLM(MegaPreTrainedModel):
+ _tied_weights_keys = ["mlm_head.weight"]
+
+ def __init__(self, config: MegaConfig):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `MegaForMaskedLM`, set `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.mega = MegaModel(config, add_pooling_layer=False)
+ if config.add_lm_hidden_dense_layer:
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.hidden_activation = nn.Tanh()
+ else:
+ self.dense = None
+ self.hidden_activation = None
+ self.mlm_head = nn.Linear(config.hidden_size, config.vocab_size)
+ self.dropout = nn.Dropout(config.dropout_prob)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.mlm_head
+
+ def set_output_embeddings(self, new_embeddings):
+ self.mlm_head = new_embeddings
+
+ @add_start_docstrings_to_model_forward(MEGA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=MaskedLMOutput,
+ config_class=_CONFIG_FOR_DOC,
+ mask="",
+ expected_output="' Paris'",
+ expected_loss=0.1,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], MaskedLMOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ kwargs (`dict[str, any]`, optional, defaults to *{}*):
+ Used to hide legacy arguments that have been deprecated.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.mega(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+ if self.dense is not None:
+ sequence_output = self.dense(sequence_output)
+ sequence_output = self.hidden_activation(sequence_output)
+ prediction_scores = self.mlm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ MEGA Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
+ output) e.g. for GLUE tasks.
+ """,
+ MEGA_START_DOCSTRING,
+)
+class MegaForSequenceClassification(MegaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.mega = MegaModel(config, add_pooling_layer=False)
+ self.classifier = MegaClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(MEGA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=SequenceClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.mega(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ MEGA Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
+ softmax) e.g. for RocStories/SWAG tasks.
+ """,
+ MEGA_START_DOCSTRING,
+)
+class MegaForMultipleChoice(MegaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.mega = MegaModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(MEGA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=MultipleChoiceModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], MultipleChoiceModelOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.mega(
+ flat_input_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ inputs_embeds=flat_inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ MEGA Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
+ Named-Entity-Recognition (NER) tasks.
+ """,
+ MEGA_START_DOCSTRING,
+)
+class MegaForTokenClassification(MegaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.mega = MegaModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(MEGA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TokenClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.mega(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead with Roberta->Mega
+class MegaClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@add_start_docstrings(
+ """
+ MEGA Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """,
+ MEGA_START_DOCSTRING,
+)
+class MegaForQuestionAnswering(MegaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.mega = MegaModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(MEGA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=QuestionAnsweringModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ start_positions: Optional[torch.LongTensor] = None,
+ end_positions: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
+ r"""
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.mega(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[2:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "MegaForCausalLM",
+ "MegaForMaskedLM",
+ "MegaForMultipleChoice",
+ "MegaForQuestionAnswering",
+ "MegaForSequenceClassification",
+ "MegaForTokenClassification",
+ "MegaModel",
+ "MegaPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..03b556e2eddf6d5f81f6f4a15346596dd5a32f85
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_mmbt import *
+ from .modeling_mmbt import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ddcd2e05a41353b03e5a29831aaf9a8dfd83d9e3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__pycache__/configuration_mmbt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__pycache__/configuration_mmbt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e08888950d27a57dd1fc2096c269528b29fdb0c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__pycache__/configuration_mmbt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__pycache__/modeling_mmbt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__pycache__/modeling_mmbt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..136afff025b629daeb31e1ad6dd1c090d7c17f40
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/__pycache__/modeling_mmbt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/configuration_mmbt.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/configuration_mmbt.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c58e4e6cdd0d0a8c87b9b94ca896c87970b5654
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/configuration_mmbt.py
@@ -0,0 +1,45 @@
+# coding=utf-8
+# Copyright (c) Facebook, Inc. and its affiliates.
+# Copyright (c) HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""MMBT configuration"""
+
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class MMBTConfig:
+ """
+ This is the configuration class to store the configuration of a [`MMBTModel`]. It is used to instantiate a MMBT
+ model according to the specified arguments, defining the model architecture.
+
+ Args:
+ config ([`PreTrainedConfig`]):
+ Config of the underlying Transformer models. Its values are copied over to use a single config.
+ num_labels (`int`, *optional*):
+ Size of final Linear layer for classification.
+ modal_hidden_size (`int`, *optional*, defaults to 2048):
+ Embedding dimension of the non-text modality encoder.
+ """
+
+ def __init__(self, config, num_labels=None, modal_hidden_size=2048):
+ self.__dict__ = config.__dict__
+ self.modal_hidden_size = modal_hidden_size
+ if num_labels:
+ self.num_labels = num_labels
+
+
+__all__ = ["MMBTConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/modeling_mmbt.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/modeling_mmbt.py
new file mode 100644
index 0000000000000000000000000000000000000000..45ae577f7fced2d276f4f54c5bf859e27e08ebae
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/mmbt/modeling_mmbt.py
@@ -0,0 +1,410 @@
+# coding=utf-8
+# Copyright (c) Facebook, Inc. and its affiliates.
+# Copyright (c) HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch MMBT model."""
+
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss, MSELoss
+
+from ....modeling_outputs import BaseModelOutputWithPooling, SequenceClassifierOutput
+from ....modeling_utils import ModuleUtilsMixin
+from ....utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
+
+
+logger = logging.get_logger(__name__)
+
+_CONFIG_FOR_DOC = "MMBTConfig"
+
+
+class ModalEmbeddings(nn.Module):
+ """Generic Modal Embeddings which takes in an encoder, and a transformer embedding."""
+
+ def __init__(self, config, encoder, embeddings):
+ super().__init__()
+ self.config = config
+ self.encoder = encoder
+ self.proj_embeddings = nn.Linear(config.modal_hidden_size, config.hidden_size)
+ self.position_embeddings = embeddings.position_embeddings
+ self.token_type_embeddings = embeddings.token_type_embeddings
+ self.word_embeddings = embeddings.word_embeddings
+ self.LayerNorm = embeddings.LayerNorm
+ self.dropout = nn.Dropout(p=config.hidden_dropout_prob)
+
+ def forward(self, input_modal, start_token=None, end_token=None, position_ids=None, token_type_ids=None):
+ token_embeddings = self.proj_embeddings(self.encoder(input_modal))
+ seq_length = token_embeddings.size(1)
+
+ if start_token is not None:
+ start_token_embeds = self.word_embeddings(start_token)
+ seq_length += 1
+ token_embeddings = torch.cat([start_token_embeds.unsqueeze(1), token_embeddings], dim=1)
+
+ if end_token is not None:
+ end_token_embeds = self.word_embeddings(end_token)
+ seq_length += 1
+ token_embeddings = torch.cat([token_embeddings, end_token_embeds.unsqueeze(1)], dim=1)
+
+ if position_ids is None:
+ position_ids = torch.arange(seq_length, dtype=torch.long, device=input_modal.device)
+ position_ids = position_ids.unsqueeze(0).expand(input_modal.size(0), seq_length)
+
+ if token_type_ids is None:
+ token_type_ids = torch.zeros(
+ (input_modal.size(0), seq_length), dtype=torch.long, device=input_modal.device
+ )
+
+ position_embeddings = self.position_embeddings(position_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+ embeddings = token_embeddings + position_embeddings + token_type_embeddings
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+MMBT_START_DOCSTRING = r"""
+ MMBT model was proposed in [Supervised Multimodal Bitransformers for Classifying Images and
+ Text](https://github.com/facebookresearch/mmbt) by Douwe Kiela, Suvrat Bhooshan, Hamed Firooz, Davide Testuggine.
+ It's a supervised multimodal bitransformer model that fuses information from text and other image encoders, and
+ obtain state-of-the-art performance on various multimodal classification benchmark tasks.
+
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`MMBTConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration.
+ transformer (`nn.Module`): A text transformer that is used by MMBT.
+ It should have embeddings, encoder, and pooler attributes.
+ encoder (`nn.Module`): Encoder for the second modality.
+ It should take in a batch of modal inputs and return k, n dimension embeddings.
+"""
+
+MMBT_INPUTS_DOCSTRING = r"""
+ Args:
+ input_modal (`torch.FloatTensor` of shape `(batch_size, ***)`):
+ The other modality data. It will be the shape that the encoder for that type expects. e.g. With an Image
+ Encoder, the shape would be (batch_size, channels, height, width)
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. It does not expect [CLS] token to be added as it's
+ appended to the end of other modality embeddings. Indices can be obtained using [`AutoTokenizer`]. See
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ modal_start_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Optional start token to be added to Other Modality Embedding. [CLS] Most commonly used for classification
+ tasks.
+ modal_end_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Optional end token to be added to Other Modality Embedding. [SEP] Most commonly used.
+ attention_mask (*optional*) `torch.FloatTensor` of shape `(batch_size, sequence_length)`:
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, sequence_length)`:
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ modal_token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, modal_sequence_length)`:
+ Segment token indices to indicate different portions of the non-text modality. The embeddings from these
+ tokens will be summed with the respective token embeddings for the non-text modality.
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ modal_position_ids (`torch.LongTensor` of shape `(batch_size, modal_sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings for the non-text modality.
+ Selected in the range `[0, config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, embedding_dim)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare MMBT Model outputting raw hidden-states without any specific head on top.",
+ MMBT_START_DOCSTRING,
+)
+class MMBTModel(nn.Module, ModuleUtilsMixin):
+ def __init__(self, config, transformer, encoder):
+ super().__init__()
+ self.config = config
+ self.transformer = transformer
+ self.modal_encoder = ModalEmbeddings(config, encoder, transformer.embeddings)
+
+ @add_start_docstrings_to_model_forward(MMBT_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_modal,
+ input_ids=None,
+ modal_start_tokens=None,
+ modal_end_tokens=None,
+ attention_mask=None,
+ token_type_ids=None,
+ modal_token_type_ids=None,
+ position_ids=None,
+ modal_position_ids=None,
+ head_mask=None,
+ inputs_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ ):
+ r"""
+ Returns:
+
+ Examples:
+
+ ```python
+ # For example purposes. Not runnable.
+ transformer = BertModel.from_pretrained("google-bert/bert-base-uncased")
+ encoder = ImageEncoder(args)
+ mmbt = MMBTModel(config, transformer, encoder)
+ ```"""
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_txt_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_txt_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ modal_embeddings = self.modal_encoder(
+ input_modal,
+ start_token=modal_start_tokens,
+ end_token=modal_end_tokens,
+ position_ids=modal_position_ids,
+ token_type_ids=modal_token_type_ids,
+ )
+
+ input_modal_shape = modal_embeddings.size()[:-1]
+
+ if token_type_ids is None:
+ token_type_ids = torch.ones(input_txt_shape, dtype=torch.long, device=device)
+
+ txt_embeddings = self.transformer.embeddings(
+ input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds
+ )
+
+ embedding_output = torch.cat([modal_embeddings, txt_embeddings], 1)
+
+ input_shape = embedding_output.size()[:-1]
+
+ if attention_mask is None:
+ attention_mask = torch.ones(input_shape, device=device)
+ else:
+ attention_mask = torch.cat(
+ [torch.ones(input_modal_shape, device=device, dtype=torch.long), attention_mask], dim=1
+ )
+ if encoder_attention_mask is None:
+ encoder_attention_mask = torch.ones(input_shape, device=device)
+ else:
+ encoder_attention_mask = torch.cat(
+ [torch.ones(input_modal_shape, device=device), encoder_attention_mask], dim=1
+ )
+
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ encoder_outputs = self.transformer.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.transformer.pooler(sequence_output)
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+
+@add_start_docstrings(
+ """
+ MMBT Model with a sequence classification/regression head on top (a linear layer on top of the pooled output)
+ """,
+ MMBT_START_DOCSTRING,
+ MMBT_INPUTS_DOCSTRING,
+)
+class MMBTForClassification(nn.Module):
+ r"""
+ **labels**: (*optional*) `torch.LongTensor` of shape `(batch_size,)`:
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+
+ Returns: *Tuple* comprising various elements depending on the configuration (config) and inputs: **loss**:
+ (*optional*, returned when `labels` is provided) `torch.FloatTensor` of shape `(1,)`: Classification (or
+ regression if config.num_labels==1) loss. **logits**:
+ `torch.FloatTensor` of shape `(batch_size, config.num_labels)` Classification (or regression if
+ config.num_labels==1) scores (before SoftMax).
+ **hidden_states**: (*optional*, returned when `output_hidden_states=True`) list of `torch.FloatTensor` (one for
+ the output of each layer + the output of the embeddings) of shape `(batch_size, sequence_length, hidden_size)`:
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs. **attentions**:
+ (*optional*, returned when `output_attentions=True`) list of `torch.FloatTensor` (one for each layer) of shape
+ `(batch_size, num_heads, sequence_length, sequence_length)`: Attentions weights after the attention softmax, used
+ to compute the weighted average in the self-attention heads.
+
+ Examples:
+
+ ```python
+ # For example purposes. Not runnable.
+ transformer = BertModel.from_pretrained("google-bert/bert-base-uncased")
+ encoder = ImageEncoder(args)
+ model = MMBTForClassification(config, transformer, encoder)
+ outputs = model(input_modal, input_ids, labels=labels)
+ loss, logits = outputs[:2]
+ ```"""
+
+ def __init__(self, config, transformer, encoder):
+ super().__init__()
+ self.num_labels = config.num_labels
+
+ self.mmbt = MMBTModel(config, transformer, encoder)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(
+ self,
+ input_modal,
+ input_ids=None,
+ modal_start_tokens=None,
+ modal_end_tokens=None,
+ attention_mask=None,
+ token_type_ids=None,
+ modal_token_type_ids=None,
+ position_ids=None,
+ modal_position_ids=None,
+ head_mask=None,
+ inputs_embeds=None,
+ labels=None,
+ return_dict=None,
+ ):
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.mmbt(
+ input_modal=input_modal,
+ input_ids=input_ids,
+ modal_start_tokens=modal_start_tokens,
+ modal_end_tokens=modal_end_tokens,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ modal_token_type_ids=modal_token_type_ids,
+ position_ids=position_ids,
+ modal_position_ids=modal_position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ if self.num_labels == 1:
+ # We are doing regression
+ loss_fct = MSELoss()
+ loss = loss_fct(logits.view(-1), labels.view(-1))
+ else:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["MMBTForClassification", "MMBTModel", "ModalEmbeddings"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5373969ce7831491b0d5fa5495078fb1d3f6e4e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_nat import *
+ from .modeling_nat import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d1f74e93af43af0008bc4fd496aa8cfd962c006
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__pycache__/configuration_nat.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__pycache__/configuration_nat.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0025e84b6cc96da796e47300ec884c2e186585e8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__pycache__/configuration_nat.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__pycache__/modeling_nat.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__pycache__/modeling_nat.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..25366f5c2115d847d3226b82f462d44879c23870
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/__pycache__/modeling_nat.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/configuration_nat.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/configuration_nat.py
new file mode 100644
index 0000000000000000000000000000000000000000..002eaa7f82b6927ab383523e9b9a6abc5c2433a9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/configuration_nat.py
@@ -0,0 +1,148 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Neighborhood Attention Transformer model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+from ....utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices
+
+
+logger = logging.get_logger(__name__)
+
+
+class NatConfig(BackboneConfigMixin, PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`NatModel`]. It is used to instantiate a Nat model
+ according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the Nat
+ [shi-labs/nat-mini-in1k-224](https://huggingface.co/shi-labs/nat-mini-in1k-224) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ patch_size (`int`, *optional*, defaults to 4):
+ The size (resolution) of each patch. NOTE: Only patch size of 4 is supported at the moment.
+ num_channels (`int`, *optional*, defaults to 3):
+ The number of input channels.
+ embed_dim (`int`, *optional*, defaults to 64):
+ Dimensionality of patch embedding.
+ depths (`list[int]`, *optional*, defaults to `[3, 4, 6, 5]`):
+ Number of layers in each level of the encoder.
+ num_heads (`list[int]`, *optional*, defaults to `[2, 4, 8, 16]`):
+ Number of attention heads in each layer of the Transformer encoder.
+ kernel_size (`int`, *optional*, defaults to 7):
+ Neighborhood Attention kernel size.
+ mlp_ratio (`float`, *optional*, defaults to 3.0):
+ Ratio of MLP hidden dimensionality to embedding dimensionality.
+ qkv_bias (`bool`, *optional*, defaults to `True`):
+ Whether or not a learnable bias should be added to the queries, keys and values.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
+ The dropout probability for all fully connected layers in the embeddings and encoder.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+ drop_path_rate (`float`, *optional*, defaults to 0.1):
+ Stochastic depth rate.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder. If string, `"gelu"`, `"relu"`,
+ `"selu"` and `"gelu_new"` are supported.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
+ The epsilon used by the layer normalization layers.
+ layer_scale_init_value (`float`, *optional*, defaults to 0.0):
+ The initial value for the layer scale. Disabled if <=0.
+ out_features (`list[str]`, *optional*):
+ If used as backbone, list of features to output. Can be any of `"stem"`, `"stage1"`, `"stage2"`, etc.
+ (depending on how many stages the model has). If unset and `out_indices` is set, will default to the
+ corresponding stages. If unset and `out_indices` is unset, will default to the last stage. Must be in the
+ same order as defined in the `stage_names` attribute.
+ out_indices (`list[int]`, *optional*):
+ If used as backbone, list of indices of features to output. Can be any of 0, 1, 2, etc. (depending on how
+ many stages the model has). If unset and `out_features` is set, will default to the corresponding stages.
+ If unset and `out_features` is unset, will default to the last stage. Must be in the
+ same order as defined in the `stage_names` attribute.
+
+ Example:
+
+ ```python
+ >>> from transformers import NatConfig, NatModel
+
+ >>> # Initializing a Nat shi-labs/nat-mini-in1k-224 style configuration
+ >>> configuration = NatConfig()
+
+ >>> # Initializing a model (with random weights) from the shi-labs/nat-mini-in1k-224 style configuration
+ >>> model = NatModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "nat"
+
+ attribute_map = {
+ "num_attention_heads": "num_heads",
+ "num_hidden_layers": "num_layers",
+ }
+
+ def __init__(
+ self,
+ patch_size=4,
+ num_channels=3,
+ embed_dim=64,
+ depths=[3, 4, 6, 5],
+ num_heads=[2, 4, 8, 16],
+ kernel_size=7,
+ mlp_ratio=3.0,
+ qkv_bias=True,
+ hidden_dropout_prob=0.0,
+ attention_probs_dropout_prob=0.0,
+ drop_path_rate=0.1,
+ hidden_act="gelu",
+ initializer_range=0.02,
+ layer_norm_eps=1e-5,
+ layer_scale_init_value=0.0,
+ out_features=None,
+ out_indices=None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.embed_dim = embed_dim
+ self.depths = depths
+ self.num_layers = len(depths)
+ self.num_heads = num_heads
+ self.kernel_size = kernel_size
+ self.mlp_ratio = mlp_ratio
+ self.qkv_bias = qkv_bias
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.drop_path_rate = drop_path_rate
+ self.hidden_act = hidden_act
+ self.layer_norm_eps = layer_norm_eps
+ self.initializer_range = initializer_range
+ # we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel
+ # this indicates the channel dimension after the last stage of the model
+ self.hidden_size = int(embed_dim * 2 ** (len(depths) - 1))
+ self.layer_scale_init_value = layer_scale_init_value
+ self.stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, len(depths) + 1)]
+ self._out_features, self._out_indices = get_aligned_output_features_output_indices(
+ out_features=out_features, out_indices=out_indices, stage_names=self.stage_names
+ )
+
+
+__all__ = ["NatConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/modeling_nat.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/modeling_nat.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a951623bc7cfa0761f2a66c2c0cb65f34ff6324
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nat/modeling_nat.py
@@ -0,0 +1,953 @@
+# coding=utf-8
+# Copyright 2022 SHI Labs and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Neighborhood Attention Transformer model."""
+
+import math
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_outputs import BackboneOutput
+from ....modeling_utils import PreTrainedModel
+from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
+from ....utils import (
+ ModelOutput,
+ OptionalDependencyNotAvailable,
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ is_natten_available,
+ logging,
+ replace_return_docstrings,
+ requires_backends,
+)
+from ....utils.backbone_utils import BackboneMixin
+from .configuration_nat import NatConfig
+
+
+if is_natten_available():
+ from natten.functional import natten2dav, natten2dqkrpb
+else:
+
+ def natten2dqkrpb(*args, **kwargs):
+ raise OptionalDependencyNotAvailable()
+
+ def natten2dav(*args, **kwargs):
+ raise OptionalDependencyNotAvailable()
+
+
+logger = logging.get_logger(__name__)
+
+# General docstring
+_CONFIG_FOR_DOC = "NatConfig"
+
+# Base docstring
+_CHECKPOINT_FOR_DOC = "shi-labs/nat-mini-in1k-224"
+_EXPECTED_OUTPUT_SHAPE = [1, 7, 7, 512]
+
+# Image classification docstring
+_IMAGE_CLASS_CHECKPOINT = "shi-labs/nat-mini-in1k-224"
+_IMAGE_CLASS_EXPECTED_OUTPUT = "tiger cat"
+
+
+# drop_path and NatDropPath are from the timm library.
+
+
+@dataclass
+class NatEncoderOutput(ModelOutput):
+ """
+ Nat encoder's outputs, with potential hidden states and attentions.
+
+ Args:
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the model.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ last_hidden_state: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+ reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+class NatModelOutput(ModelOutput):
+ """
+ Nat model's outputs that also contains a pooling of the last hidden states.
+
+ Args:
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the model.
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
+ Average pooling of the last layer hidden-state.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ last_hidden_state: Optional[torch.FloatTensor] = None
+ pooler_output: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+ reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+class NatImageClassifierOutput(ModelOutput):
+ """
+ Nat outputs for image classification.
+
+ Args:
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
+ shape `(batch_size, hidden_size, height, width)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
+ include the spatial dimensions.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+ reshaped_hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+class NatEmbeddings(nn.Module):
+ """
+ Construct the patch and position embeddings.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.patch_embeddings = NatPatchEmbeddings(config)
+
+ self.norm = nn.LayerNorm(config.embed_dim)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, pixel_values: Optional[torch.FloatTensor]) -> tuple[torch.Tensor]:
+ embeddings = self.patch_embeddings(pixel_values)
+ embeddings = self.norm(embeddings)
+
+ embeddings = self.dropout(embeddings)
+
+ return embeddings
+
+
+class NatPatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, height, width, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ patch_size = config.patch_size
+ num_channels, hidden_size = config.num_channels, config.embed_dim
+ self.num_channels = num_channels
+
+ if patch_size == 4:
+ pass
+ else:
+ # TODO: Support arbitrary patch sizes.
+ raise ValueError("Dinat only supports patch size of 4 at the moment.")
+
+ self.projection = nn.Sequential(
+ nn.Conv2d(self.num_channels, hidden_size // 2, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
+ nn.Conv2d(hidden_size // 2, hidden_size, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1)),
+ )
+
+ def forward(self, pixel_values: Optional[torch.FloatTensor]) -> torch.Tensor:
+ _, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+ embeddings = self.projection(pixel_values)
+ embeddings = embeddings.permute(0, 2, 3, 1)
+
+ return embeddings
+
+
+class NatDownsampler(nn.Module):
+ """
+ Convolutional Downsampling Layer.
+
+ Args:
+ dim (`int`):
+ Number of input channels.
+ norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
+ Normalization layer class.
+ """
+
+ def __init__(self, dim: int, norm_layer: nn.Module = nn.LayerNorm) -> None:
+ super().__init__()
+ self.dim = dim
+ self.reduction = nn.Conv2d(dim, 2 * dim, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)
+ self.norm = norm_layer(2 * dim)
+
+ def forward(self, input_feature: torch.Tensor) -> torch.Tensor:
+ input_feature = self.reduction(input_feature.permute(0, 3, 1, 2)).permute(0, 2, 3, 1)
+ input_feature = self.norm(input_feature)
+ return input_feature
+
+
+def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
+ """
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
+
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
+ argument.
+ """
+ if drop_prob == 0.0 or not training:
+ return input
+ keep_prob = 1 - drop_prob
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
+ random_tensor.floor_() # binarize
+ output = input.div(keep_prob) * random_tensor
+ return output
+
+
+class NatDropPath(nn.Module):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
+
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ return drop_path(hidden_states, self.drop_prob, self.training)
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+class NeighborhoodAttention(nn.Module):
+ def __init__(self, config, dim, num_heads, kernel_size):
+ super().__init__()
+ if dim % num_heads != 0:
+ raise ValueError(
+ f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})"
+ )
+
+ self.num_attention_heads = num_heads
+ self.attention_head_size = int(dim / num_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.kernel_size = kernel_size
+
+ # rpb is learnable relative positional biases; same concept is used Swin.
+ self.rpb = nn.Parameter(torch.zeros(num_heads, (2 * self.kernel_size - 1), (2 * self.kernel_size - 1)))
+
+ self.query = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
+ self.key = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
+ self.value = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ def transpose_for_scores(self, x):
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
+ x = x.view(new_x_shape)
+ return x.permute(0, 3, 1, 2, 4)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ query_layer = self.transpose_for_scores(self.query(hidden_states))
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+
+ # Apply the scale factor before computing attention weights. It's usually more efficient because
+ # attention weights are typically a bigger tensor compared to query.
+ # It gives identical results because scalars are commutable in matrix multiplication.
+ query_layer = query_layer / math.sqrt(self.attention_head_size)
+
+ # Compute NA between "query" and "key" to get the raw attention scores, and add relative positional biases.
+ attention_scores = natten2dqkrpb(query_layer, key_layer, self.rpb, self.kernel_size, 1)
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ context_layer = natten2dav(attention_probs, value_layer, self.kernel_size, 1)
+ context_layer = context_layer.permute(0, 2, 3, 1, 4).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+class NeighborhoodAttentionOutput(nn.Module):
+ def __init__(self, config, dim):
+ super().__init__()
+ self.dense = nn.Linear(dim, dim)
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ return hidden_states
+
+
+class NeighborhoodAttentionModule(nn.Module):
+ def __init__(self, config, dim, num_heads, kernel_size):
+ super().__init__()
+ self.self = NeighborhoodAttention(config, dim, num_heads, kernel_size)
+ self.output = NeighborhoodAttentionOutput(config, dim)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.self.query = prune_linear_layer(self.self.query, index)
+ self.self.key = prune_linear_layer(self.self.key, index)
+ self.self.value = prune_linear_layer(self.self.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ self_outputs = self.self(hidden_states, output_attentions)
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+class NatIntermediate(nn.Module):
+ def __init__(self, config, dim):
+ super().__init__()
+ self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class NatOutput(nn.Module):
+ def __init__(self, config, dim):
+ super().__init__()
+ self.dense = nn.Linear(int(config.mlp_ratio * dim), dim)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states
+
+
+class NatLayer(nn.Module):
+ def __init__(self, config, dim, num_heads, drop_path_rate=0.0):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.kernel_size = config.kernel_size
+ self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
+ self.attention = NeighborhoodAttentionModule(config, dim, num_heads, kernel_size=self.kernel_size)
+ self.drop_path = NatDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
+ self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
+ self.intermediate = NatIntermediate(config, dim)
+ self.output = NatOutput(config, dim)
+ self.layer_scale_parameters = (
+ nn.Parameter(config.layer_scale_init_value * torch.ones((2, dim)), requires_grad=True)
+ if config.layer_scale_init_value > 0
+ else None
+ )
+
+ def maybe_pad(self, hidden_states, height, width):
+ window_size = self.kernel_size
+ pad_values = (0, 0, 0, 0, 0, 0)
+ if height < window_size or width < window_size:
+ pad_l = pad_t = 0
+ pad_r = max(0, window_size - width)
+ pad_b = max(0, window_size - height)
+ pad_values = (0, 0, pad_l, pad_r, pad_t, pad_b)
+ hidden_states = nn.functional.pad(hidden_states, pad_values)
+ return hidden_states, pad_values
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ batch_size, height, width, channels = hidden_states.size()
+ shortcut = hidden_states
+
+ hidden_states = self.layernorm_before(hidden_states)
+ # pad hidden_states if they are smaller than kernel size
+ hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
+
+ _, height_pad, width_pad, _ = hidden_states.shape
+
+ attention_outputs = self.attention(hidden_states, output_attentions=output_attentions)
+
+ attention_output = attention_outputs[0]
+
+ was_padded = pad_values[3] > 0 or pad_values[5] > 0
+ if was_padded:
+ attention_output = attention_output[:, :height, :width, :].contiguous()
+
+ if self.layer_scale_parameters is not None:
+ attention_output = self.layer_scale_parameters[0] * attention_output
+
+ hidden_states = shortcut + self.drop_path(attention_output)
+
+ layer_output = self.layernorm_after(hidden_states)
+ layer_output = self.output(self.intermediate(layer_output))
+
+ if self.layer_scale_parameters is not None:
+ layer_output = self.layer_scale_parameters[1] * layer_output
+
+ layer_output = hidden_states + self.drop_path(layer_output)
+
+ layer_outputs = (layer_output, attention_outputs[1]) if output_attentions else (layer_output,)
+ return layer_outputs
+
+
+class NatStage(nn.Module):
+ def __init__(self, config, dim, depth, num_heads, drop_path_rate, downsample):
+ super().__init__()
+ self.config = config
+ self.dim = dim
+ self.layers = nn.ModuleList(
+ [
+ NatLayer(
+ config=config,
+ dim=dim,
+ num_heads=num_heads,
+ drop_path_rate=drop_path_rate[i],
+ )
+ for i in range(depth)
+ ]
+ )
+
+ # patch merging layer
+ if downsample is not None:
+ self.downsample = downsample(dim=dim, norm_layer=nn.LayerNorm)
+ else:
+ self.downsample = None
+
+ self.pointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ _, height, width, _ = hidden_states.size()
+ for i, layer_module in enumerate(self.layers):
+ layer_outputs = layer_module(hidden_states, output_attentions)
+ hidden_states = layer_outputs[0]
+
+ hidden_states_before_downsampling = hidden_states
+ if self.downsample is not None:
+ hidden_states = self.downsample(hidden_states_before_downsampling)
+
+ stage_outputs = (hidden_states, hidden_states_before_downsampling)
+
+ if output_attentions:
+ stage_outputs += layer_outputs[1:]
+ return stage_outputs
+
+
+class NatEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.num_levels = len(config.depths)
+ self.config = config
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")]
+ self.levels = nn.ModuleList(
+ [
+ NatStage(
+ config=config,
+ dim=int(config.embed_dim * 2**i_layer),
+ depth=config.depths[i_layer],
+ num_heads=config.num_heads[i_layer],
+ drop_path_rate=dpr[sum(config.depths[:i_layer]) : sum(config.depths[: i_layer + 1])],
+ downsample=NatDownsampler if (i_layer < self.num_levels - 1) else None,
+ )
+ for i_layer in range(self.num_levels)
+ ]
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ output_attentions: Optional[bool] = False,
+ output_hidden_states: Optional[bool] = False,
+ output_hidden_states_before_downsampling: Optional[bool] = False,
+ return_dict: Optional[bool] = True,
+ ) -> Union[tuple, NatEncoderOutput]:
+ all_hidden_states = () if output_hidden_states else None
+ all_reshaped_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ if output_hidden_states:
+ # rearrange b h w c -> b c h w
+ reshaped_hidden_state = hidden_states.permute(0, 3, 1, 2)
+ all_hidden_states += (hidden_states,)
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
+
+ for i, layer_module in enumerate(self.levels):
+ layer_outputs = layer_module(hidden_states, output_attentions)
+
+ hidden_states = layer_outputs[0]
+ hidden_states_before_downsampling = layer_outputs[1]
+
+ if output_hidden_states and output_hidden_states_before_downsampling:
+ # rearrange b h w c -> b c h w
+ reshaped_hidden_state = hidden_states_before_downsampling.permute(0, 3, 1, 2)
+ all_hidden_states += (hidden_states_before_downsampling,)
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
+ elif output_hidden_states and not output_hidden_states_before_downsampling:
+ # rearrange b h w c -> b c h w
+ reshaped_hidden_state = hidden_states.permute(0, 3, 1, 2)
+ all_hidden_states += (hidden_states,)
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
+
+ if output_attentions:
+ all_self_attentions += layer_outputs[2:]
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+
+ return NatEncoderOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ reshaped_hidden_states=all_reshaped_hidden_states,
+ )
+
+
+class NatPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: NatConfig
+ base_model_prefix = "nat"
+ main_input_name = "pixel_values"
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+NAT_START_DOCSTRING = r"""
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
+ behavior.
+
+ Parameters:
+ config ([`NatConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+
+NAT_INPUTS_DOCSTRING = r"""
+ Args:
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ViTImageProcessor.__call__`]
+ for details.
+
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare Nat Model transformer outputting raw hidden-states without any specific head on top.",
+ NAT_START_DOCSTRING,
+)
+class NatModel(NatPreTrainedModel):
+ def __init__(self, config, add_pooling_layer=True):
+ super().__init__(config)
+
+ requires_backends(self, ["natten"])
+
+ self.config = config
+ self.num_levels = len(config.depths)
+ self.num_features = int(config.embed_dim * 2 ** (self.num_levels - 1))
+
+ self.embeddings = NatEmbeddings(config)
+ self.encoder = NatEncoder(config)
+
+ self.layernorm = nn.LayerNorm(self.num_features, eps=config.layer_norm_eps)
+ self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.patch_embeddings
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ @add_start_docstrings_to_model_forward(NAT_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=NatModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ modality="vision",
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
+ )
+ def forward(
+ self,
+ pixel_values: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, NatModelOutput]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ embedding_output = self.embeddings(pixel_values)
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = encoder_outputs[0]
+ sequence_output = self.layernorm(sequence_output)
+
+ pooled_output = None
+ if self.pooler is not None:
+ pooled_output = self.pooler(sequence_output.flatten(1, 2).transpose(1, 2))
+ pooled_output = torch.flatten(pooled_output, 1)
+
+ if not return_dict:
+ output = (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return output
+
+ return NatModelOutput(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
+ )
+
+
+@add_start_docstrings(
+ """
+ Nat Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
+ the [CLS] token) e.g. for ImageNet.
+ """,
+ NAT_START_DOCSTRING,
+)
+class NatForImageClassification(NatPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ requires_backends(self, ["natten"])
+
+ self.num_labels = config.num_labels
+ self.nat = NatModel(config)
+
+ # Classifier head
+ self.classifier = (
+ nn.Linear(self.nat.num_features, config.num_labels) if config.num_labels > 0 else nn.Identity()
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(NAT_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
+ output_type=NatImageClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
+ )
+ def forward(
+ self,
+ pixel_values: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, NatImageClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.nat(
+ pixel_values,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return NatImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ reshaped_hidden_states=outputs.reshaped_hidden_states,
+ )
+
+
+@add_start_docstrings(
+ "NAT backbone, to be used with frameworks like DETR and MaskFormer.",
+ NAT_START_DOCSTRING,
+)
+class NatBackbone(NatPreTrainedModel, BackboneMixin):
+ def __init__(self, config):
+ super().__init__(config)
+ super()._init_backbone(config)
+
+ requires_backends(self, ["natten"])
+
+ self.embeddings = NatEmbeddings(config)
+ self.encoder = NatEncoder(config)
+ self.num_features = [config.embed_dim] + [int(config.embed_dim * 2**i) for i in range(len(config.depths))]
+
+ # Add layer norms to hidden states of out_features
+ hidden_states_norms = {}
+ for stage, num_channels in zip(self.out_features, self.channels):
+ hidden_states_norms[stage] = nn.LayerNorm(num_channels)
+ self.hidden_states_norms = nn.ModuleDict(hidden_states_norms)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.patch_embeddings
+
+ @add_start_docstrings_to_model_forward(NAT_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=BackboneOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ pixel_values: torch.Tensor,
+ output_hidden_states: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> BackboneOutput:
+ """
+ Returns:
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoBackbone
+ >>> import torch
+ >>> from PIL import Image
+ >>> import requests
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> processor = AutoImageProcessor.from_pretrained("shi-labs/nat-mini-in1k-224")
+ >>> model = AutoBackbone.from_pretrained(
+ ... "shi-labs/nat-mini-in1k-224", out_features=["stage1", "stage2", "stage3", "stage4"]
+ ... )
+
+ >>> inputs = processor(image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+
+ >>> feature_maps = outputs.feature_maps
+ >>> list(feature_maps[-1].shape)
+ [1, 512, 7, 7]
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ embedding_output = self.embeddings(pixel_values)
+
+ outputs = self.encoder(
+ embedding_output,
+ output_attentions=output_attentions,
+ output_hidden_states=True,
+ output_hidden_states_before_downsampling=True,
+ return_dict=True,
+ )
+
+ hidden_states = outputs.reshaped_hidden_states
+
+ feature_maps = ()
+ for stage, hidden_state in zip(self.stage_names, hidden_states):
+ if stage in self.out_features:
+ # TODO can we simplify this?
+ batch_size, num_channels, height, width = hidden_state.shape
+ hidden_state = hidden_state.permute(0, 2, 3, 1).contiguous()
+ hidden_state = hidden_state.view(batch_size, height * width, num_channels)
+ hidden_state = self.hidden_states_norms[stage](hidden_state)
+ hidden_state = hidden_state.view(batch_size, height, width, num_channels)
+ hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
+ feature_maps += (hidden_state,)
+
+ if not return_dict:
+ output = (feature_maps,)
+ if output_hidden_states:
+ output += (outputs.hidden_states,)
+ return output
+
+ return BackboneOutput(
+ feature_maps=feature_maps,
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["NatForImageClassification", "NatModel", "NatPreTrainedModel", "NatBackbone"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0690129ae9edf84829278790b5e065bbd6608ee
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_nezha import *
+ from .modeling_nezha import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af5804a93fe9727135f138f89889d8291e55bf30
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__pycache__/configuration_nezha.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__pycache__/configuration_nezha.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..34c5a7589cd86ea9b9628b900cb3ce372a7b7c66
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__pycache__/configuration_nezha.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__pycache__/modeling_nezha.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__pycache__/modeling_nezha.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b4381fa6a96e8e272d14990e3e8de6a5da72e466
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/__pycache__/modeling_nezha.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/configuration_nezha.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/configuration_nezha.py
new file mode 100644
index 0000000000000000000000000000000000000000..00d193cd1ae68655e1631b7caea2220987a29f0b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/configuration_nezha.py
@@ -0,0 +1,105 @@
+from .... import PretrainedConfig
+
+
+class NezhaConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of an [`NezhaModel`]. It is used to instantiate an Nezha
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the Nezha
+ [sijunhe/nezha-cn-base](https://huggingface.co/sijunhe/nezha-cn-base) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, optional, defaults to 21128):
+ Vocabulary size of the NEZHA model. Defines the different tokens that can be represented by the
+ *inputs_ids* passed to the forward method of [`NezhaModel`].
+ hidden_size (`int`, optional, defaults to 768):
+ Dimensionality of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, optional, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, optional, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, optional, defaults to 3072):
+ The dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `function`, optional, defaults to "gelu"):
+ The non-linear activation function (function or string) in the encoder and pooler.
+ hidden_dropout_prob (`float`, optional, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, optional, defaults to 0.1):
+ The dropout ratio for the attention probabilities.
+ max_position_embeddings (`int`, optional, defaults to 512):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ (e.g., 512 or 1024 or 2048).
+ type_vocab_size (`int`, optional, defaults to 2):
+ The vocabulary size of the *token_type_ids* passed into [`NezhaModel`].
+ initializer_range (`float`, optional, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, optional, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ classifier_dropout (`float`, optional, defaults to 0.1):
+ The dropout ratio for attached classifiers.
+ is_decoder (`bool`, *optional*, defaults to `False`):
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
+
+ Example:
+
+ ```python
+ >>> from transformers import NezhaConfig, NezhaModel
+
+ >>> # Initializing an Nezha configuration
+ >>> configuration = NezhaConfig()
+
+ >>> # Initializing a model (with random weights) from the Nezha-base style configuration model
+ >>> model = NezhaModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "nezha"
+
+ def __init__(
+ self,
+ vocab_size=21128,
+ hidden_size=768,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=512,
+ max_relative_position=64,
+ type_vocab_size=2,
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ classifier_dropout=0.1,
+ pad_token_id=0,
+ bos_token_id=2,
+ eos_token_id=3,
+ use_cache=True,
+ **kwargs,
+ ):
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
+
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.hidden_act = hidden_act
+ self.intermediate_size = intermediate_size
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.max_position_embeddings = max_position_embeddings
+ self.max_relative_position = max_relative_position
+ self.type_vocab_size = type_vocab_size
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.classifier_dropout = classifier_dropout
+ self.use_cache = use_cache
+
+
+__all__ = ["NezhaConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/modeling_nezha.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/modeling_nezha.py
new file mode 100644
index 0000000000000000000000000000000000000000..635a078c6a13c3894e1c70e72bdca9dedec4f764
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/nezha/modeling_nezha.py
@@ -0,0 +1,1689 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Nezha model."""
+
+import math
+import os
+import warnings
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ NextSentencePredictorOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ....modeling_utils import PreTrainedModel
+from ....pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
+from ....utils import (
+ ModelOutput,
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+ replace_return_docstrings,
+)
+from ....utils.deprecation import deprecate_kwarg
+from .configuration_nezha import NezhaConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "sijunhe/nezha-cn-base"
+_CONFIG_FOR_DOC = "NezhaConfig"
+
+
+def load_tf_weights_in_nezha(model, config, tf_checkpoint_path):
+ """Load tf checkpoints in a pytorch model."""
+ try:
+ import re
+
+ import numpy as np
+ import tensorflow as tf
+ except ImportError:
+ logger.error(
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
+ "https://www.tensorflow.org/install/ for installation instructions."
+ )
+ raise
+ tf_path = os.path.abspath(tf_checkpoint_path)
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
+ # Load weights from TF model
+ init_vars = tf.train.list_variables(tf_path)
+ names = []
+ arrays = []
+ for name, shape in init_vars:
+ logger.info(f"Loading TF weight {name} with shape {shape}")
+ array = tf.train.load_variable(tf_path, name)
+ names.append(name)
+ arrays.append(array)
+
+ for name, array in zip(names, arrays):
+ name = name.split("/")
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
+ # which are not required for using pretrained model
+ if any(
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
+ for n in name
+ ):
+ logger.info(f"Skipping {'/'.join(name)}")
+ continue
+ pointer = model
+ for m_name in name:
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
+ scope_names = re.split(r"_(\d+)", m_name)
+ else:
+ scope_names = [m_name]
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
+ pointer = getattr(pointer, "weight")
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
+ pointer = getattr(pointer, "bias")
+ elif scope_names[0] == "output_weights":
+ pointer = getattr(pointer, "weight")
+ elif scope_names[0] == "squad":
+ pointer = getattr(pointer, "classifier")
+ else:
+ try:
+ pointer = getattr(pointer, scope_names[0])
+ except AttributeError:
+ logger.info(f"Skipping {'/'.join(name)}")
+ continue
+ if len(scope_names) >= 2:
+ num = int(scope_names[1])
+ pointer = pointer[num]
+ if m_name[-11:] == "_embeddings":
+ pointer = getattr(pointer, "weight")
+ elif m_name == "kernel":
+ array = np.transpose(array)
+ try:
+ if pointer.shape != array.shape:
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
+ except AssertionError as e:
+ e.args += (pointer.shape, array.shape)
+ raise
+ logger.info(f"Initialize PyTorch weight {name}")
+ pointer.data = torch.from_numpy(array)
+ return model
+
+
+class NezhaRelativePositionsEncoding(nn.Module):
+ """Implement the Functional Relative Position Encoding"""
+
+ def __init__(self, length, depth, max_relative_position=127):
+ super().__init__()
+ vocab_size = max_relative_position * 2 + 1
+ range_vec = torch.arange(length)
+ range_mat = range_vec.repeat(length).view(length, length)
+ distance_mat = range_mat - torch.t(range_mat)
+ distance_mat_clipped = torch.clamp(distance_mat, -max_relative_position, max_relative_position)
+ final_mat = distance_mat_clipped + max_relative_position
+
+ embeddings_table = torch.zeros(vocab_size, depth)
+ position = torch.arange(0, vocab_size, dtype=torch.int64).float().unsqueeze(1)
+ div_term = torch.exp(torch.arange(0, depth, 2).float() * (-math.log(10000.0) / depth))
+ embeddings_table[:, 0::2] = torch.sin(position * div_term)
+ embeddings_table[:, 1::2] = torch.cos(position * div_term)
+
+ flat_relative_positions_matrix = final_mat.view(-1)
+ one_hot_relative_positions_matrix = torch.nn.functional.one_hot(
+ flat_relative_positions_matrix, num_classes=vocab_size
+ ).float()
+ positions_encoding = torch.matmul(one_hot_relative_positions_matrix, embeddings_table)
+ my_shape = list(final_mat.size())
+ my_shape.append(depth)
+ positions_encoding = positions_encoding.view(my_shape)
+ self.register_buffer("positions_encoding", positions_encoding, persistent=False)
+
+ def forward(self, length):
+ return self.positions_encoding[:length, :length, :]
+
+
+class NezhaEmbeddings(nn.Module):
+ """Construct the embeddings from word and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
+ # any TensorFlow checkpoint file
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.register_buffer(
+ "token_type_ids", torch.zeros((1, config.max_position_embeddings), dtype=torch.long), persistent=False
+ )
+
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ ) -> torch.Tensor:
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=inputs_embeds.device)
+
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+
+ embeddings = inputs_embeds + token_type_embeddings
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class NezhaSelfAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.relative_positions_encoding = NezhaRelativePositionsEncoding(
+ length=config.max_position_embeddings,
+ depth=self.attention_head_size,
+ max_relative_position=config.max_relative_position,
+ )
+ self.is_decoder = config.is_decoder
+
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
+ x = x.view(new_x_shape)
+ return x.permute(0, 2, 1, 3)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ mixed_query_layer = self.query(hidden_states)
+
+ # If this is instantiated as a cross-attention module, the keys
+ # and values come from an encoder; the attention mask needs to be
+ # such that the encoder's padding tokens are not attended to.
+ is_cross_attention = encoder_hidden_states is not None
+
+ if is_cross_attention and past_key_values is not None:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values[0]
+ value_layer = past_key_values[1]
+ attention_mask = encoder_attention_mask
+ elif is_cross_attention:
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
+ attention_mask = encoder_attention_mask
+ elif past_key_values is not None:
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+ key_layer = torch.cat([past_key_values[0], key_layer], dim=2)
+ value_layer = torch.cat([past_key_values[1], value_layer], dim=2)
+ else:
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ if self.is_decoder:
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
+ # Further calls to cross_attention layer can then reuse all cross-attention
+ # key/value_states (first "if" case)
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
+ past_key_values = (key_layer, value_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ batch_size, num_attention_heads, from_seq_length, to_seq_length = attention_scores.size()
+ relations_keys = self.relative_positions_encoding(to_seq_length)
+ query_layer_t = query_layer.permute(2, 0, 1, 3)
+
+ query_layer_r = query_layer_t.contiguous().view(
+ from_seq_length, batch_size * num_attention_heads, self.attention_head_size
+ )
+ key_position_scores = torch.matmul(query_layer_r, relations_keys.permute(0, 2, 1))
+ key_position_scores_r = key_position_scores.view(
+ from_seq_length, batch_size, num_attention_heads, from_seq_length
+ )
+ key_position_scores_r_t = key_position_scores_r.permute(1, 2, 0, 3)
+ attention_scores = attention_scores + key_position_scores_r_t
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in NezhaModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = attention_probs * head_mask
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+ relations_values = self.relative_positions_encoding(to_seq_length)
+ attention_probs_t = attention_probs.permute(2, 0, 1, 3)
+ attentions_probs_r = attention_probs_t.contiguous().view(
+ from_seq_length, batch_size * num_attention_heads, to_seq_length
+ )
+ value_position_scores = torch.matmul(attentions_probs_r, relations_values)
+ value_position_scores_r = value_position_scores.view(
+ from_seq_length, batch_size, num_attention_heads, self.attention_head_size
+ )
+ value_position_scores_r_t = value_position_scores_r.permute(1, 2, 0, 3)
+ context_layer = context_layer + value_position_scores_r_t
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ if self.is_decoder:
+ outputs = outputs + (past_key_values,)
+ return outputs
+
+
+class NezhaSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class NezhaAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.self = NezhaSelfAttention(config)
+ self.output = NezhaSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.self.query = prune_linear_layer(self.self.query, index)
+ self.self.key = prune_linear_layer(self.self.key, index)
+ self.self.value = prune_linear_layer(self.self.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ self_outputs = self.self(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values,
+ output_attentions,
+ )
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+class NezhaIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class NezhaOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class NezhaLayer(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = NezhaAttention(config)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = NezhaAttention(config)
+ self.intermediate = NezhaIntermediate(config)
+ self.output = NezhaOutput(config)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
+ self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
+ self_attention_outputs = self.attention(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ output_attentions=output_attentions,
+ past_key_values=self_attn_past_key_value,
+ )
+ attention_output = self_attention_outputs[0]
+
+ # if decoder, the last output is tuple of self-attn cache
+ if self.is_decoder:
+ outputs = self_attention_outputs[1:-1]
+ present_key_value = self_attention_outputs[-1]
+ else:
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ cross_attn_present_key_value = None
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_values tuple
+ cross_attn_past_key_value = past_key_values[-2:] if past_key_values is not None else None
+ cross_attention_outputs = self.crossattention(
+ attention_output,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ cross_attn_past_key_value,
+ output_attentions,
+ )
+ attention_output = cross_attention_outputs[0]
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
+
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
+ cross_attn_present_key_value = cross_attention_outputs[-1]
+ present_key_value = present_key_value + cross_attn_present_key_value
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ outputs = (layer_output,) + outputs
+
+ # if decoder, return the attn key/values as the last output
+ if self.is_decoder:
+ outputs = outputs + (present_key_value,)
+
+ return outputs
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class NezhaEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([NezhaLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = False,
+ output_hidden_states: Optional[bool] = False,
+ return_dict: Optional[bool] = True,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
+
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ next_decoder_cache = () if use_cache else None
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+
+ layer_outputs = layer_module(
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values[i] if past_key_values is not None else None,
+ output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+ if use_cache:
+ next_decoder_cache += (layer_outputs[-1],)
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+ if self.config.add_cross_attention:
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ hidden_states,
+ next_decoder_cache,
+ all_hidden_states,
+ all_self_attentions,
+ all_cross_attentions,
+ ]
+ if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=next_decoder_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+class NezhaPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+class NezhaPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+class NezhaLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = NezhaPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
+ self.decoder.bias = self.bias
+
+ def _tie_weights(self):
+ self.decoder.bias = self.bias
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+class NezhaOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = NezhaLMPredictionHead(config)
+
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+class NezhaOnlyNSPHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
+
+ def forward(self, pooled_output):
+ seq_relationship_score = self.seq_relationship(pooled_output)
+ return seq_relationship_score
+
+
+class NezhaPreTrainingHeads(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = NezhaLMPredictionHead(config)
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
+
+ def forward(self, sequence_output, pooled_output):
+ prediction_scores = self.predictions(sequence_output)
+ seq_relationship_score = self.seq_relationship(pooled_output)
+ return prediction_scores, seq_relationship_score
+
+
+class NezhaPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: NezhaConfig
+ load_tf_weights = load_tf_weights_in_nezha
+ base_model_prefix = "nezha"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+@dataclass
+class NezhaForPreTrainingOutput(ModelOutput):
+ """
+ Output type of [`NezhaForPreTraining`].
+
+ Args:
+ loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
+ Total loss as the sum of the masked language modeling loss and the next sequence prediction
+ (classification) loss.
+ prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
+ Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
+ before SoftMax).
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ prediction_logits: Optional[torch.FloatTensor] = None
+ seq_relationship_logits: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+NEZHA_START_DOCSTRING = r"""
+
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`NezhaConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+NEZHA_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare Nezha Model transformer outputting raw hidden-states without any specific head on top.",
+ NEZHA_START_DOCSTRING,
+)
+class NezhaModel(NezhaPreTrainedModel):
+ """
+
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
+
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
+ """
+
+ def __init__(self, config, add_pooling_layer=True):
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = NezhaEmbeddings(config)
+ self.encoder = NezhaEncoder(config)
+
+ self.pooler = NezhaPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ batch_size, seq_length = input_shape
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ # past_key_values_length
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ if attention_mask is None:
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
+
+ if token_type_ids is None:
+ if hasattr(self.embeddings, "token_type_ids"):
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
+ # ourselves in which case we just need to make it broadcastable to all heads.
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
+
+ # If a 2D or 3D attention mask is provided for the cross-attention
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ if self.config.is_decoder and encoder_hidden_states is not None:
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
+ if encoder_attention_mask is None:
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
+ else:
+ encoder_extended_attention_mask = None
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ )
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ Nezha Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
+ sentence prediction (classification)` head.
+ """,
+ NEZHA_START_DOCSTRING,
+)
+class NezhaForPreTraining(NezhaPreTrainedModel):
+ _tied_weights_keys = ["cls.predictions.decoder"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.nezha = NezhaModel(config)
+ self.cls = NezhaPreTrainingHeads(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @replace_return_docstrings(output_type=NezhaForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ next_sentence_label: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], NezhaForPreTrainingOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
+ the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
+ pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
+
+ - 0 indicates sequence B is a continuation of sequence A,
+ - 1 indicates sequence B is a random sequence.
+ kwargs (`dict[str, any]`, optional, defaults to *{}*):
+ Used to hide legacy arguments that have been deprecated.
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, NezhaForPreTraining
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("sijunhe/nezha-cn-base")
+ >>> model = NezhaForPreTraining.from_pretrained("sijunhe/nezha-cn-base")
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.prediction_logits
+ >>> seq_relationship_logits = outputs.seq_relationship_logits
+ ```
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.nezha(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output, pooled_output = outputs[:2]
+ prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
+
+ total_loss = None
+ if labels is not None and next_sentence_label is not None:
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+ next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
+ total_loss = masked_lm_loss + next_sentence_loss
+
+ if not return_dict:
+ output = (prediction_scores, seq_relationship_score) + outputs[2:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return NezhaForPreTrainingOutput(
+ loss=total_loss,
+ prediction_logits=prediction_scores,
+ seq_relationship_logits=seq_relationship_score,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings("""Nezha Model with a `language modeling` head on top.""", NEZHA_START_DOCSTRING)
+class NezhaForMaskedLM(NezhaPreTrainedModel):
+ _tied_weights_keys = ["cls.predictions.decoder"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `NezhaForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.nezha = NezhaModel(config, add_pooling_layer=False)
+ self.cls = NezhaOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=MaskedLMOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], MaskedLMOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.nezha(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.cls(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
+ input_shape = input_ids.shape
+ effective_batch_size = input_shape[0]
+
+ # add a dummy token
+ if self.config.pad_token_id is None:
+ raise ValueError("The PAD token should be defined for generation")
+
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
+ dummy_token = torch.full(
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
+ )
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
+
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
+
+
+@add_start_docstrings(
+ """Nezha Model with a `next sentence prediction (classification)` head on top.""",
+ NEZHA_START_DOCSTRING,
+)
+class NezhaForNextSentencePrediction(NezhaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.nezha = NezhaModel(config)
+ self.cls = NezhaOnlyNSPHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs,
+ ) -> Union[tuple[torch.Tensor], NextSentencePredictorOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
+
+ - 0 indicates sequence B is a continuation of sequence A,
+ - 1 indicates sequence B is a random sequence.
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, NezhaForNextSentencePrediction
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("sijunhe/nezha-cn-base")
+ >>> model = NezhaForNextSentencePrediction.from_pretrained("sijunhe/nezha-cn-base")
+
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
+
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
+ >>> logits = outputs.logits
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
+ ```
+ """
+
+ if "next_sentence_label" in kwargs:
+ warnings.warn(
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
+ " `labels` instead.",
+ FutureWarning,
+ )
+ labels = kwargs.pop("next_sentence_label")
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.nezha(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ seq_relationship_scores = self.cls(pooled_output)
+
+ next_sentence_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
+
+ if not return_dict:
+ output = (seq_relationship_scores,) + outputs[2:]
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
+
+ return NextSentencePredictorOutput(
+ loss=next_sentence_loss,
+ logits=seq_relationship_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ Nezha Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
+ output) e.g. for GLUE tasks.
+ """,
+ NEZHA_START_DOCSTRING,
+)
+class NezhaForSequenceClassification(NezhaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.nezha = NezhaModel(config)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=SequenceClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.nezha(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ Nezha Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
+ softmax) e.g. for RocStories/SWAG tasks.
+ """,
+ NEZHA_START_DOCSTRING,
+)
+class NezhaForMultipleChoice(NezhaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.nezha = NezhaModel(config)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=MultipleChoiceModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], MultipleChoiceModelOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.nezha(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+ print(pooled_output.shape)
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ print(logits.shape)
+ print(num_choices)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ Nezha Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
+ Named-Entity-Recognition (NER) tasks.
+ """,
+ NEZHA_START_DOCSTRING,
+)
+class NezhaForTokenClassification(NezhaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.nezha = NezhaModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TokenClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.nezha(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ Nezha Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """,
+ NEZHA_START_DOCSTRING,
+)
+class NezhaForQuestionAnswering(NezhaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.nezha = NezhaModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(NEZHA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=QuestionAnsweringModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ start_positions: Optional[torch.Tensor] = None,
+ end_positions: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
+ r"""
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.nezha(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[2:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "NezhaForNextSentencePrediction",
+ "NezhaForMaskedLM",
+ "NezhaForPreTraining",
+ "NezhaForMultipleChoice",
+ "NezhaForQuestionAnswering",
+ "NezhaForSequenceClassification",
+ "NezhaForTokenClassification",
+ "NezhaModel",
+ "NezhaPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b3964d194bed041987c6236b5c60bfcf3b7caf4
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2023 EleutherAI and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_open_llama import *
+ from .modeling_open_llama import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f034b1616c451f56e68c65046ece4d695022c1ed
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__pycache__/configuration_open_llama.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__pycache__/configuration_open_llama.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01c57b39149110a320862dc33adacb2960d087dd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__pycache__/configuration_open_llama.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__pycache__/modeling_open_llama.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__pycache__/modeling_open_llama.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a23443df80b0a2ac46a341dda83705b340d359bd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/__pycache__/modeling_open_llama.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/configuration_open_llama.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/configuration_open_llama.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4bc9cc72a7661fe571cce6649b40f2307d9b3ce
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/configuration_open_llama.py
@@ -0,0 +1,169 @@
+# coding=utf-8
+# Copyright 2023 EleutherAI and the HuggingFace Inc. team. All rights reserved.
+#
+# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
+# and OPT implementations in this library. It has been modified from its
+# original forms to accommodate minor architectural differences compared
+# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Open-Llama model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class OpenLlamaConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`OpenLlamaModel`]. It is used to instantiate an
+ Open-Llama model according to the specified arguments, defining the model architecture. Instantiating a
+ configuration with the defaults will yield a similar configuration to that of the
+ [s-JoL/Open-Llama-V1](https://huggingface.co/s-JoL/Open-Llama-V1).
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 32000):
+ Vocabulary size of the Open-Llama model. Defines the number of different tokens that can be represented by
+ the `inputs_ids` passed when calling [`OpenLlamaModel`]
+ hidden_size (`int`, *optional*, defaults to 4096):
+ Dimension of the hidden representations.
+ intermediate_size (`int`, *optional*, defaults to 11008):
+ Dimension of the MLP representations.
+ num_hidden_layers (`int`, *optional*, defaults to 32):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 32):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ hidden_act (`str` or `function`, *optional*, defaults to `"silu"`):
+ The non-linear activation function (function or string) in the decoder.
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ rms_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the rms normalization layers.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+ tie_word_embeddings(`bool`, *optional*, defaults to `False`):
+ Whether to tie weight embeddings
+ rope_theta (`float`, *optional*, defaults to 10000.0):
+ The base period of the RoPE embeddings.
+ rope_scaling (`Dict`, *optional*):
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
+ these scaling strategies behave:
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
+ experimental feature, subject to breaking API changes in future versions.
+
+ Example:
+
+ ```python
+ >>> from transformers import OpenLlamaModel, OpenLlamaConfig
+
+ >>> # Initializing a Open-Llama open_llama-7b style configuration
+ >>> configuration = OpenLlamaConfig()
+
+ >>> # Initializing a model from the open_llama-7b style configuration
+ >>> model = OpenLlamaModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "open-llama"
+
+ def __init__(
+ self,
+ vocab_size=100000,
+ hidden_size=4096,
+ intermediate_size=11008,
+ num_hidden_layers=32,
+ num_attention_heads=32,
+ hidden_act="silu",
+ max_position_embeddings=2048,
+ initializer_range=0.02,
+ rms_norm_eps=1e-6,
+ use_cache=True,
+ pad_token_id=0,
+ bos_token_id=1,
+ eos_token_id=2,
+ tie_word_embeddings=False,
+ use_memory_efficient_attention=True,
+ hidden_dropout_prob=0.1,
+ attention_dropout_prob=0.1,
+ use_stable_embedding=True,
+ shared_input_output_embedding=True,
+ rope_theta=10000.0,
+ rope_scaling=None,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.max_position_embeddings = max_position_embeddings
+ self.hidden_size = hidden_size
+ self.intermediate_size = intermediate_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.hidden_act = hidden_act
+ self.initializer_range = initializer_range
+ self.rms_norm_eps = rms_norm_eps
+ self.use_cache = use_cache
+ self.use_memory_efficient_attention = kwargs.pop(
+ "use_memorry_efficient_attention", use_memory_efficient_attention
+ )
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_dropout_prob = attention_dropout_prob
+ self.use_stable_embedding = use_stable_embedding
+ self.shared_input_output_embedding = shared_input_output_embedding
+ self.rope_theta = rope_theta
+ self.rope_scaling = rope_scaling
+ self._rope_scaling_validation()
+
+ super().__init__(
+ pad_token_id=pad_token_id,
+ bos_token_id=bos_token_id,
+ eos_token_id=eos_token_id,
+ tie_word_embeddings=tie_word_embeddings,
+ **kwargs,
+ )
+
+ def _rope_scaling_validation(self):
+ """
+ Validate the `rope_scaling` configuration.
+ """
+ if self.rope_scaling is None:
+ return
+
+ if not isinstance(self.rope_scaling, dict) or len(self.rope_scaling) != 2:
+ raise ValueError(
+ f"`rope_scaling` must be a dictionary with two fields, `type` and `factor`, got {self.rope_scaling}"
+ )
+ rope_scaling_type = self.rope_scaling.get("type", None)
+ rope_scaling_factor = self.rope_scaling.get("factor", None)
+ if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
+ raise ValueError(
+ f"`rope_scaling`'s type field must be one of ['linear', 'dynamic'], got {rope_scaling_type}"
+ )
+ if rope_scaling_factor is None or not isinstance(rope_scaling_factor, float) or rope_scaling_factor <= 1.0:
+ raise ValueError(f"`rope_scaling`'s factor field must be a float > 1, got {rope_scaling_factor}")
+
+
+__all__ = ["OpenLlamaConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/modeling_open_llama.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/modeling_open_llama.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6c6ab449685e86bf5873384e7c30cc0983a13ff
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/open_llama/modeling_open_llama.py
@@ -0,0 +1,940 @@
+# coding=utf-8
+# Copyright 2023 EleutherAI and the HuggingFace Inc. team. All rights reserved.
+#
+# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
+# and OPT implementations in this library. It has been modified from its
+# original forms to accommodate minor architectural differences compared
+# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Open-Llama model."""
+
+import math
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
+from ....modeling_utils import PreTrainedModel
+from ....utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
+from ....utils.deprecation import deprecate_kwarg
+from .configuration_open_llama import OpenLlamaConfig
+
+
+logger = logging.get_logger(__name__)
+
+try:
+ from xformers import ops as xops
+except ImportError:
+ xops = None
+
+
+_CONFIG_FOR_DOC = "OpenLlamaConfig"
+
+
+class OpenLlamaRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps=1e-6):
+ """
+ OpenLlamaRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class OpenLlamaRotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+ cos_cached: torch.Tensor
+ sin_cached: torch.Tensor
+
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
+ super().__init__()
+
+ self.dim = dim
+ self.max_position_embeddings = max_position_embeddings
+ self.base = base
+ inv_freq = 1.0 / (
+ self.base
+ ** (torch.arange(0, self.dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / self.dim)
+ )
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+
+ # Build here to make `torch.jit.trace` work.
+ self._set_cos_sin_cache(
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
+ )
+
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
+ self.max_seq_len_cached = seq_len
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
+
+ freqs = torch.outer(t, self.inv_freq)
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
+ emb = torch.cat((freqs, freqs), dim=-1)
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
+
+ def forward(self, x, seq_len=None):
+ # x: [bs, num_attention_heads, seq_len, head_size]
+ if seq_len > self.max_seq_len_cached:
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
+
+ return (
+ self.cos_cached[:seq_len].to(dtype=x.dtype),
+ self.sin_cached[:seq_len].to(dtype=x.dtype),
+ )
+
+
+class OpenLlamaLinearScalingRotaryEmbedding(OpenLlamaRotaryEmbedding):
+ """OpenLlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
+
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
+ self.scaling_factor = scaling_factor
+ super().__init__(dim, max_position_embeddings, base, device)
+
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
+ self.max_seq_len_cached = seq_len
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
+ t = t / self.scaling_factor
+
+ freqs = torch.outer(t, self.inv_freq)
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
+ emb = torch.cat((freqs, freqs), dim=-1)
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
+
+
+class OpenLlamaDynamicNTKScalingRotaryEmbedding(OpenLlamaRotaryEmbedding):
+ """OpenLlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
+
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
+ self.scaling_factor = scaling_factor
+ super().__init__(dim, max_position_embeddings, base, device)
+
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
+ self.max_seq_len_cached = seq_len
+
+ if seq_len > self.max_position_embeddings:
+ base = self.base * (
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
+ ) ** (self.dim / (self.dim - 2))
+ inv_freq = 1.0 / (
+ base
+ ** (torch.arange(0, self.dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / self.dim)
+ )
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq)
+
+ freqs = torch.outer(t, self.inv_freq)
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
+ emb = torch.cat((freqs, freqs), dim=-1)
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ position_ids (`torch.Tensor`):
+ The position indices of the tokens corresponding to the query and key tensors. For example, this can be
+ used to pass offsetted position ids when working with a KV-cache.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos[position_ids].unsqueeze(unsqueeze_dim)
+ sin = sin[position_ids].unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+class OpenLlamaMLP(nn.Module):
+ def __init__(
+ self,
+ hidden_size: int,
+ intermediate_size: int,
+ hidden_act: str,
+ dropout_prob: float,
+ ):
+ super().__init__()
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
+ self.act_fn = ACT2FN[hidden_act]
+ self.dropout = nn.Dropout(dropout_prob)
+
+ def forward(self, x):
+ out = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return self.dropout(out)
+
+
+class OpenLlamaAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: OpenLlamaConfig):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.hidden_size // self.num_heads
+ self.max_position_embeddings = config.max_position_embeddings
+ self.dropout_prob = config.attention_dropout_prob
+ self.rope_theta = config.rope_theta
+
+ if (self.head_dim * self.num_heads) != self.hidden_size:
+ raise ValueError(
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
+ f" and `num_heads`: {self.num_heads})."
+ )
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
+ self._init_rope()
+
+ def _init_rope(self):
+ if self.config.rope_scaling is None:
+ self.rotary_emb = OpenLlamaRotaryEmbedding(
+ self.head_dim,
+ max_position_embeddings=self.max_position_embeddings,
+ base=self.rope_theta,
+ )
+ else:
+ scaling_type = self.config.rope_scaling["type"]
+ scaling_factor = self.config.rope_scaling["factor"]
+ if scaling_type == "linear":
+ self.rotary_emb = OpenLlamaLinearScalingRotaryEmbedding(
+ self.head_dim,
+ max_position_embeddings=self.max_position_embeddings,
+ scaling_factor=scaling_factor,
+ base=self.rope_theta,
+ )
+ elif scaling_type == "dynamic":
+ self.rotary_emb = OpenLlamaDynamicNTKScalingRotaryEmbedding(
+ self.head_dim,
+ max_position_embeddings=self.max_position_embeddings,
+ scaling_factor=scaling_factor,
+ base=self.rope_theta,
+ )
+ else:
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
+ output_attentions: bool = False,
+ use_cache: bool = False,
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
+ bsz, q_len, _ = hidden_states.size()
+
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
+
+ kv_seq_len = key_states.shape[-2]
+ if past_key_values is not None:
+ kv_seq_len += past_key_values[0].shape[-2]
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
+ # [bsz, nh, t, hd]
+
+ if past_key_values is not None:
+ # reuse k, v, self_attention
+ key_states = torch.cat([past_key_values[0], key_states], dim=2)
+ value_states = torch.cat([past_key_values[1], value_states], dim=2)
+
+ past_key_values = (key_states, value_states) if use_cache else None
+
+ if self.config.use_memory_efficient_attention and xops is not None and self.training:
+ attn_weights = None
+ query_states = query_states.transpose(1, 2)
+ key_states = key_states.transpose(1, 2)
+ value_states = value_states.transpose(1, 2)
+ attn_output = xops.memory_efficient_attention(
+ query_states, key_states, value_states, attn_bias=xops.LowerTriangularMask(), p=self.dropout_prob
+ )
+ else:
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
+
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
+ raise ValueError(
+ f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
+ f" {attn_weights.size()}"
+ )
+
+ if attention_mask is not None:
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
+ raise ValueError(
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
+ )
+ attn_weights = attn_weights + attention_mask
+ attn_weights = torch.max(
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min, device=attn_weights.device)
+ )
+
+ # upcast attention to fp32
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
+ attn_output = torch.matmul(attn_weights, value_states)
+
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
+ f" {attn_output.size()}"
+ )
+
+ attn_output = attn_output.transpose(1, 2)
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
+
+ attn_output = self.o_proj(attn_output)
+
+ if not output_attentions:
+ attn_weights = None
+
+ return attn_output, attn_weights, past_key_values
+
+
+class OpenLlamaDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: OpenLlamaConfig):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+ self.self_attn = OpenLlamaAttention(config=config)
+ self.mlp = OpenLlamaMLP(
+ hidden_size=self.hidden_size,
+ intermediate_size=config.intermediate_size,
+ hidden_act=config.hidden_act,
+ dropout_prob=config.hidden_dropout_prob,
+ )
+ self.input_layernorm = OpenLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.post_attention_layernorm = OpenLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ past_key_values (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
+ """
+
+ residual = hidden_states
+
+ hidden_states = self.input_layernorm(hidden_states)
+
+ # Self Attention
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ )
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.post_attention_layernorm(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights,)
+
+ if use_cache:
+ outputs += (present_key_value,)
+
+ return outputs
+
+
+OPEN_LLAMA_START_DOCSTRING = r"""
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`OpenLlamaConfig`]):
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
+ load the weights associated with the model, only the configuration. Check out the
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+
+@add_start_docstrings(
+ "The bare Open-Llama Model outputting raw hidden-states without any specific head on top.",
+ OPEN_LLAMA_START_DOCSTRING,
+)
+class OpenLlamaPreTrainedModel(PreTrainedModel):
+ config: OpenLlamaConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["OpenLlamaDecoderLayer"]
+
+ def _init_weights(self, module):
+ std = self.config.initializer_range
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ if self.config.use_stable_embedding:
+ torch.nn.init.xavier_normal_(module.weight.data)
+ else:
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+
+
+OPEN_LLAMA_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
+ it.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
+ `past_key_values`).
+
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
+ and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
+ information on the default strategy.
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.n_positions - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare Open-Llama Model outputting raw hidden-states without any specific head on top.",
+ OPEN_LLAMA_START_DOCSTRING,
+)
+class OpenLlamaModel(OpenLlamaPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OpenLlamaDecoderLayer`]
+
+ Args:
+ config: OpenLlamaConfig
+ """
+
+ def __init__(self, config: OpenLlamaConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ if config.use_stable_embedding:
+ self.embed_layer_norm = nn.LayerNorm(config.hidden_size)
+ else:
+ self.embed_layer_norm = None
+ self.layers = nn.ModuleList([OpenLlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.norm = OpenLlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(OPEN_LLAMA_INPUTS_DOCSTRING)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, BaseModelOutputWithPast]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # retrieve input_ids and inputs_embeds
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
+ elif input_ids is not None:
+ batch_size, seq_length = input_ids.shape
+ elif inputs_embeds is not None:
+ batch_size, seq_length, _ = inputs_embeds.shape
+ else:
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
+
+ seq_length_with_past = seq_length
+ past_key_values_length = 0
+
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ if past_key_values is not None:
+ past_key_values_length = past_key_values.get_seq_length()
+ seq_length_with_past = seq_length_with_past + past_key_values_length
+
+ if position_ids is None:
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+ position_ids = torch.arange(
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
+ )
+ position_ids = position_ids.unsqueeze(0)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+ if self.embed_layer_norm:
+ inputs_embeds = self.embed_layer_norm(inputs_embeds)
+ # embed positions
+ if self.config.use_memory_efficient_attention and self.training:
+ attention_mask = None
+ elif attention_mask is None:
+ attention_mask = torch.ones(
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
+ )
+
+ input_shape = (batch_size, seq_length)
+ attention_mask = _prepare_4d_causal_attention_mask(
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
+ )
+
+ hidden_states = inputs_embeds
+
+ # decoder layers
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+ next_decoder_cache = () if use_cache else None
+
+ for idx, decoder_layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ layer_outputs = decoder_layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values[idx] if past_key_values is not None else None,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if use_cache:
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
+
+ if output_attentions:
+ all_self_attns += (layer_outputs[1],)
+
+ hidden_states = self.norm(hidden_states)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ next_cache = next_decoder_cache if use_cache else None
+ if not return_dict:
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
+ return BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=next_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ )
+
+
+class OpenLlamaForCausalLM(OpenLlamaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = OpenLlamaModel(config)
+ if config.shared_input_output_embedding:
+ self.lm_head = None
+ else:
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(OPEN_LLAMA_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, CausalLMOutputWithPast]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, OpenLlamaForCausalLM
+
+ >>> model = OpenLlamaForCausalLM.from_pretrained("openlm-research/open_llama_7b")
+ >>> tokenizer = AutoTokenizer.from_pretrained("openlm-research/open_llama_7b")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ if self.config.shared_input_output_embedding:
+ logits = torch.einsum(
+ "blh,vh->blv", hidden_states.to(self.model.embed_tokens.weight.device), self.model.embed_tokens.weight
+ )
+ else:
+ logits = self.lm_head(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device to enable model parallelism
+ labels = labels.to(logits.device)
+ # Shift so that tokens < n predict n
+ shift_logits = logits[..., :-1, :].contiguous()
+ shift_labels = labels[..., 1:].contiguous()
+ # Flatten the tokens
+ loss_fct = CrossEntropyLoss()
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
+ shift_labels = shift_labels.view(-1)
+ # Enable model parallelism
+ shift_labels = shift_labels.to(shift_logits.device)
+ loss = loss_fct(shift_logits, shift_labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return (loss,) + output if loss is not None else output
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
+ ):
+ if past_key_values is not None:
+ past_length = past_key_values.get_seq_length()
+
+ # Some generation methods already pass only the last input ID
+ if input_ids.shape[1] > past_length:
+ remove_prefix_length = past_length
+ else:
+ # Default to old behavior: keep only final ID
+ remove_prefix_length = input_ids.shape[1] - 1
+
+ input_ids = input_ids[:, remove_prefix_length:]
+
+ position_ids = kwargs.get("position_ids")
+ if attention_mask is not None and position_ids is None:
+ # create position_ids on the fly for batch generation
+ position_ids = attention_mask.long().cumsum(-1) - 1
+ position_ids.masked_fill_(attention_mask == 0, 1)
+ if past_key_values:
+ position_ids = position_ids[:, -input_ids.shape[1] :]
+
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
+ if inputs_embeds is not None and past_key_values is None:
+ model_inputs = {"inputs_embeds": inputs_embeds}
+ else:
+ model_inputs = {"input_ids": input_ids}
+
+ model_inputs.update(
+ {
+ "position_ids": position_ids,
+ "past_key_values": past_key_values,
+ "use_cache": kwargs.get("use_cache"),
+ "attention_mask": attention_mask,
+ }
+ )
+ return model_inputs
+
+ @staticmethod
+ def _reorder_cache(past_key_values, beam_idx):
+ reordered_past = ()
+ for layer_past in past_key_values:
+ reordered_past += (
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
+ )
+ return reordered_past
+
+
+@add_start_docstrings(
+ """
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
+
+ [`OpenLlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal
+ models (e.g. GPT-2) do.
+
+ Since it does classification on the last token, it requires to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """,
+ OPEN_LLAMA_START_DOCSTRING,
+)
+class OpenLlamaForSequenceClassification(OpenLlamaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.model = OpenLlamaModel(config)
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(OPEN_LLAMA_INPUTS_DOCSTRING)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, SequenceClassifierOutputWithPast]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ hidden_states = transformer_outputs[0]
+ logits = self.score(hidden_states)
+
+ if input_ids is not None:
+ batch_size = input_ids.shape[0]
+ else:
+ batch_size = inputs_embeds.shape[0]
+
+ if self.config.pad_token_id is None and batch_size != 1:
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
+ if self.config.pad_token_id is None:
+ sequence_lengths = -1
+ else:
+ if input_ids is not None:
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
+ sequence_lengths = sequence_lengths.to(logits.device)
+ else:
+ sequence_lengths = -1
+
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
+
+ loss = None
+ if labels is not None:
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(pooled_logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(pooled_logits, labels)
+ if not return_dict:
+ output = (pooled_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = ["OpenLlamaPreTrainedModel", "OpenLlamaModel", "OpenLlamaForCausalLM", "OpenLlamaForSequenceClassification"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..864b321bc2ee3a521e3d6da5403cab7363dea56b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2021 NVIDIA Corporation and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_qdqbert import *
+ from .modeling_qdqbert import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..12ea50a83efc18eca2e8fe8597a8abf0ef6988a3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__pycache__/configuration_qdqbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__pycache__/configuration_qdqbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e02189e9cb9cccd50004f88f39e8de846de9c467
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__pycache__/configuration_qdqbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__pycache__/modeling_qdqbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__pycache__/modeling_qdqbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..da24630a0c1ebbd6a38e3adcc4345382f59be11a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/__pycache__/modeling_qdqbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/configuration_qdqbert.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/configuration_qdqbert.py
new file mode 100644
index 0000000000000000000000000000000000000000..91ac82bc5a0292355ac659548c7c3d4336f2536c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/configuration_qdqbert.py
@@ -0,0 +1,123 @@
+# coding=utf-8
+# Copyright 2021 NVIDIA Corporation and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""QDQBERT model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class QDQBertConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`QDQBertModel`]. It is used to instantiate an
+ QDQBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration
+ with the defaults will yield a similar configuration to that of the BERT
+ [google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 30522):
+ Vocabulary size of the QDQBERT model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`QDQBertModel`].
+ hidden_size (`int`, *optional*, defaults to 768):
+ Dimension of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 3072):
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention probabilities.
+ max_position_embeddings (`int`, *optional*, defaults to 512):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ type_vocab_size (`int`, *optional*, defaults to 2):
+ The vocabulary size of the `token_type_ids` passed when calling [`QDQBertModel`].
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ is_decoder (`bool`, *optional*, defaults to `False`):
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import QDQBertModel, QDQBertConfig
+
+ >>> # Initializing a QDQBERT google-bert/bert-base-uncased style configuration
+ >>> configuration = QDQBertConfig()
+
+ >>> # Initializing a model from the google-bert/bert-base-uncased style configuration
+ >>> model = QDQBertModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "qdqbert"
+
+ def __init__(
+ self,
+ vocab_size=30522,
+ hidden_size=768,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=512,
+ type_vocab_size=2,
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ use_cache=True,
+ pad_token_id=1,
+ bos_token_id=0,
+ eos_token_id=2,
+ **kwargs,
+ ):
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
+
+ self.vocab_size = vocab_size
+ self.max_position_embeddings = max_position_embeddings
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.initializer_range = initializer_range
+ self.type_vocab_size = type_vocab_size
+ self.layer_norm_eps = layer_norm_eps
+ self.use_cache = use_cache
+
+
+__all__ = ["QDQBertConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/modeling_qdqbert.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/modeling_qdqbert.py
new file mode 100644
index 0000000000000000000000000000000000000000..cfa66aaf0250d91f8093d74f3c9adc8ae5e3059f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/qdqbert/modeling_qdqbert.py
@@ -0,0 +1,1736 @@
+# coding=utf-8
+# Copyright 2021 NVIDIA Corporation and The HuggingFace Team.
+# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch QDQBERT model."""
+
+import math
+import os
+import warnings
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ NextSentencePredictorOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ....modeling_utils import PreTrainedModel
+from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
+from ....utils import (
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ is_pytorch_quantization_available,
+ logging,
+ replace_return_docstrings,
+ requires_backends,
+)
+from ....utils.deprecation import deprecate_kwarg
+from .configuration_qdqbert import QDQBertConfig
+
+
+logger = logging.get_logger(__name__)
+
+# soft dependency
+if is_pytorch_quantization_available():
+ try:
+ from pytorch_quantization import nn as quant_nn
+ from pytorch_quantization.nn.modules.tensor_quantizer import TensorQuantizer
+ except OSError:
+ logger.error(
+ "QDQBERT model are not usable since `pytorch_quantization` can't be loaded. Please try to reinstall it"
+ " following the instructions here:"
+ " https://github.com/NVIDIA/TensorRT/tree/master/tools/pytorch-quantization."
+ )
+
+_CHECKPOINT_FOR_DOC = "google-bert/bert-base-uncased"
+_CONFIG_FOR_DOC = "QDQBertConfig"
+
+
+def load_tf_weights_in_qdqbert(model, tf_checkpoint_path):
+ """Load tf checkpoints in a pytorch model."""
+ try:
+ import re
+
+ import numpy as np
+ import tensorflow as tf
+ except ImportError:
+ logger.error(
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
+ "https://www.tensorflow.org/install/ for installation instructions."
+ )
+ raise
+ tf_path = os.path.abspath(tf_checkpoint_path)
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
+ # Load weights from TF model
+ init_vars = tf.train.list_variables(tf_path)
+ names = []
+ arrays = []
+ for name, shape in init_vars:
+ logger.info(f"Loading TF weight {name} with shape {shape}")
+ array = tf.train.load_variable(tf_path, name)
+ names.append(name)
+ arrays.append(array)
+
+ for name, array in zip(names, arrays):
+ name = name.split("/")
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
+ # which are not required for using pretrained model
+ if any(
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
+ for n in name
+ ):
+ logger.info(f"Skipping {'/'.join(name)}")
+ continue
+ pointer = model
+ for m_name in name:
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
+ scope_names = re.split(r"_(\d+)", m_name)
+ else:
+ scope_names = [m_name]
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
+ pointer = getattr(pointer, "weight")
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
+ pointer = getattr(pointer, "bias")
+ elif scope_names[0] == "output_weights":
+ pointer = getattr(pointer, "weight")
+ elif scope_names[0] == "squad":
+ pointer = getattr(pointer, "classifier")
+ else:
+ try:
+ pointer = getattr(pointer, scope_names[0])
+ except AttributeError:
+ logger.info(f"Skipping {'/'.join(name)}")
+ continue
+ if len(scope_names) >= 2:
+ num = int(scope_names[1])
+ pointer = pointer[num]
+ if m_name[-11:] == "_embeddings":
+ pointer = getattr(pointer, "weight")
+ elif m_name == "kernel":
+ array = np.transpose(array)
+ try:
+ if pointer.shape != array.shape:
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
+ except AssertionError as e:
+ e.args += (pointer.shape, array.shape)
+ raise
+ logger.info(f"Initialize PyTorch weight {name}")
+ pointer.data = torch.from_numpy(array)
+ return model
+
+
+class QDQBertEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
+ # any TensorFlow checkpoint file
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+
+ embeddings = inputs_embeds + token_type_embeddings
+ if self.position_embedding_type == "absolute":
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings += position_embeddings
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class QDQBertSelfAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = quant_nn.QuantLinear(config.hidden_size, self.all_head_size)
+ self.key = quant_nn.QuantLinear(config.hidden_size, self.all_head_size)
+ self.value = quant_nn.QuantLinear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ self.max_position_embeddings = config.max_position_embeddings
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
+
+ self.is_decoder = config.is_decoder
+
+ self.matmul_q_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
+ self.matmul_k_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
+ self.matmul_v_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
+ self.matmul_a_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
+
+ def transpose_for_scores(self, x):
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
+ x = x.view(*new_x_shape)
+ return x.permute(0, 2, 1, 3)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ output_attentions=False,
+ ):
+ mixed_query_layer = self.query(hidden_states)
+
+ # If this is instantiated as a cross-attention module, the keys
+ # and values come from an encoder; the attention mask needs to be
+ # such that the encoder's padding tokens are not attended to.
+ is_cross_attention = encoder_hidden_states is not None
+
+ if is_cross_attention and past_key_values is not None:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values[0]
+ value_layer = past_key_values[1]
+ attention_mask = encoder_attention_mask
+ elif is_cross_attention:
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
+ attention_mask = encoder_attention_mask
+ elif past_key_values is not None:
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+ key_layer = torch.cat([past_key_values[0], key_layer], dim=2)
+ value_layer = torch.cat([past_key_values[1], value_layer], dim=2)
+ else:
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ if self.is_decoder:
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
+ # Further calls to cross_attention layer can then reuse all cross-attention
+ # key/value_states (first "if" case)
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
+ past_key_values = (key_layer, value_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(
+ self.matmul_q_input_quantizer(query_layer), self.matmul_k_input_quantizer(key_layer.transpose(-1, -2))
+ )
+
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ seq_length = hidden_states.size()[1]
+ position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
+ position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
+ distance = position_ids_l - position_ids_r
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
+
+ if self.position_embedding_type == "relative_key":
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores
+ elif self.position_embedding_type == "relative_key_query":
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in QDQBertModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = attention_probs * head_mask
+
+ context_layer = torch.matmul(
+ self.matmul_a_input_quantizer(attention_probs), self.matmul_v_input_quantizer(value_layer)
+ )
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ if self.is_decoder:
+ outputs = outputs + (past_key_values,)
+ return outputs
+
+
+class QDQBertSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ # Quantize Linear layer
+ self.dense = quant_nn.QuantLinear(config.hidden_size, config.hidden_size)
+
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # Quantize the inputs to the residual add
+ self.add_local_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
+ self.add_residual_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ # Quantize the inputs to the residual add
+ add_local = self.add_local_input_quantizer(hidden_states)
+ add_residual = self.add_residual_input_quantizer(input_tensor)
+ hidden_states = self.LayerNorm(add_local + add_residual)
+ return hidden_states
+
+
+# Based on transformers.models.bert.modeling_bert.BertAttention with Bert -> QDQBert
+class QDQBertAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.self = QDQBertSelfAttention(config)
+ self.output = QDQBertSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.self.query = prune_linear_layer(self.self.query, index)
+ self.self.key = prune_linear_layer(self.self.key, index)
+ self.self.value = prune_linear_layer(self.self.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ output_attentions=False,
+ ):
+ self_outputs = self.self(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values,
+ output_attentions,
+ )
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+class QDQBertIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ # Quantize Linear layer
+ self.dense = quant_nn.QuantLinear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class QDQBertOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ # Quantize Linear layer
+ self.dense = quant_nn.QuantLinear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # Quantize the inputs to the residual add
+ self.add_local_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
+ self.add_residual_input_quantizer = TensorQuantizer(quant_nn.QuantLinear.default_quant_desc_input)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ # Quantize the inputs to the residual add
+ add_local = self.add_local_input_quantizer(hidden_states)
+ add_residual = self.add_residual_input_quantizer(input_tensor)
+ hidden_states = self.LayerNorm(add_local + add_residual)
+ return hidden_states
+
+
+# Based on transformers.models.bert.modeling_bert.BertLayer with Bert -> QDQBert
+class QDQBertLayer(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.seq_len_dim = 1
+ self.attention = QDQBertAttention(config)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = QDQBertAttention(config)
+ self.intermediate = QDQBertIntermediate(config)
+ self.output = QDQBertOutput(config)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ output_attentions=False,
+ ):
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
+ self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
+ self_attention_outputs = self.attention(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ output_attentions=output_attentions,
+ past_key_values=self_attn_past_key_value,
+ )
+ attention_output = self_attention_outputs[0]
+
+ # if decoder, the last output is tuple of self-attn cache
+ if self.is_decoder:
+ outputs = self_attention_outputs[1:-1]
+ present_key_value = self_attention_outputs[-1]
+ else:
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ cross_attn_present_key_value = None
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_values tuple
+ cross_attn_past_key_value = past_key_values[-2:] if past_key_values is not None else None
+ cross_attention_outputs = self.crossattention(
+ attention_output,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ cross_attn_past_key_value,
+ output_attentions,
+ )
+ attention_output = cross_attention_outputs[0]
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
+
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
+ cross_attn_present_key_value = cross_attention_outputs[-1]
+ present_key_value = present_key_value + cross_attn_present_key_value
+
+ layer_output = self.feed_forward_chunk(attention_output)
+ outputs = (layer_output,) + outputs
+
+ # if decoder, return the attn key/values as the last output
+ if self.is_decoder:
+ outputs = outputs + (present_key_value,)
+
+ return outputs
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+# Based on transformers.models.bert.modeling_bert.BertEncoder with Bert -> QDQBert
+class QDQBertEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([QDQBertLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ use_cache=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
+
+ next_decoder_cache = () if use_cache else None
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+
+ layer_outputs = layer_module(
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values[i] if past_key_values is not None else None,
+ output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+ if use_cache:
+ next_decoder_cache += (layer_outputs[-1],)
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+ if self.config.add_cross_attention:
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ hidden_states,
+ next_decoder_cache,
+ all_hidden_states,
+ all_self_attentions,
+ all_cross_attentions,
+ ]
+ if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=next_decoder_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+class QDQBertPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+class QDQBertPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+# Based on transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert -> QDQBert
+class QDQBertLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = QDQBertPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
+ self.decoder.bias = self.bias
+
+ def _tie_weights(self):
+ self.decoder.bias = self.bias
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+# Based on transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert -> QDQBert
+class QDQBertOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = QDQBertLMPredictionHead(config)
+
+ def forward(self, sequence_output):
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+class QDQBertOnlyNSPHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
+
+ def forward(self, pooled_output):
+ seq_relationship_score = self.seq_relationship(pooled_output)
+ return seq_relationship_score
+
+
+# Based on transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert -> QDQBert
+class QDQBertPreTrainingHeads(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = QDQBertLMPredictionHead(config)
+ self.seq_relationship = nn.Linear(config.hidden_size, 2)
+
+ def forward(self, sequence_output, pooled_output):
+ prediction_scores = self.predictions(sequence_output)
+ seq_relationship_score = self.seq_relationship(pooled_output)
+ return prediction_scores, seq_relationship_score
+
+
+# Based on transformers.models.bert.modeling_bert.BertPreTrainedModel with Bert -> QDQBert
+class QDQBertPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: QDQBertConfig
+ load_tf_weights = load_tf_weights_in_qdqbert
+ base_model_prefix = "bert"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+QDQBERT_START_DOCSTRING = r"""
+
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`QDQBertConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+QDQBERT_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare QDQBERT Model transformer outputting raw hidden-states without any specific head on top.",
+ QDQBERT_START_DOCSTRING,
+)
+class QDQBertModel(QDQBertPreTrainedModel):
+ """
+
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in [Attention is
+ all you need](https://huggingface.co/papers/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
+ Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
+
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
+ """
+
+ def __init__(self, config, add_pooling_layer: bool = True):
+ requires_backends(self, "pytorch_quantization")
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = QDQBertEmbeddings(config)
+ self.encoder = QDQBertEncoder(config)
+
+ self.pooler = QDQBertPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ def _prune_heads(self, heads_to_prune: dict[int, list[int]]):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=BaseModelOutputWithPoolingAndCrossAttentions,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, BaseModelOutputWithPoolingAndCrossAttentions]:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ batch_size, seq_length = input_shape
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ batch_size, seq_length = input_shape
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ # past_key_values_length
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ if attention_mask is None:
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
+
+ if token_type_ids is None:
+ if hasattr(self.embeddings, "token_type_ids"):
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
+ # ourselves in which case we just need to make it broadcastable to all heads.
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
+
+ # If a 2D or 3D attention mask is provided for the cross-attention
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ if self.config.is_decoder and encoder_hidden_states is not None:
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
+ if encoder_attention_mask is None:
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
+ else:
+ encoder_extended_attention_mask = None
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+@add_start_docstrings(
+ """QDQBERT Model with a `language modeling` head on top for CLM fine-tuning.""", QDQBERT_START_DOCSTRING
+)
+class QDQBertLMHeadModel(QDQBertPreTrainedModel):
+ _tied_weights_keys = ["predictions.decoder.weight", "predictions.decoder.bias"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `QDQBertLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.bert = QDQBertModel(config, add_pooling_layer=False)
+ self.cls = QDQBertOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.LongTensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, CausalLMOutputWithCrossAttentions]:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, QDQBertLMHeadModel, QDQBertConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
+ >>> config = QDQBertConfig.from_pretrained("google-bert/bert-base-cased")
+ >>> config.is_decoder = True
+ >>> model = QDQBertLMHeadModel.from_pretrained("google-bert/bert-base-cased", config=config)
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ if labels is not None:
+ use_cache = False
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.cls(sequence_output)
+
+ lm_loss = None
+ if labels is not None:
+ # we are doing next-token prediction; shift prediction scores and input ids by one
+ shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
+ labels = labels[:, 1:].contiguous()
+ loss_fct = CrossEntropyLoss()
+ lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((lm_loss,) + output) if lm_loss is not None else output
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=lm_loss,
+ logits=prediction_scores,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids: Optional[torch.LongTensor],
+ past_key_values=None,
+ attention_mask: Optional[torch.Tensor] = None,
+ **model_kwargs,
+ ):
+ input_shape = input_ids.shape
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
+ if attention_mask is None:
+ attention_mask = input_ids.new_ones(input_shape)
+
+ # cut decoder_input_ids if past_key_values is used
+ if past_key_values is not None:
+ past_length = past_key_values.get_seq_length()
+
+ # Some generation methods already pass only the last input ID
+ if input_ids.shape[1] > past_length:
+ remove_prefix_length = past_length
+ else:
+ # Default to old behavior: keep only final ID
+ remove_prefix_length = input_ids.shape[1] - 1
+
+ input_ids = input_ids[:, remove_prefix_length:]
+
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
+
+ def _reorder_cache(self, past_key_values, beam_idx):
+ reordered_past = ()
+ for layer_past in past_key_values:
+ reordered_past += (
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
+ )
+ return reordered_past
+
+
+@add_start_docstrings("""QDQBERT Model with a `language modeling` head on top.""", QDQBERT_START_DOCSTRING)
+class QDQBertForMaskedLM(QDQBertPreTrainedModel):
+ _tied_weights_keys = ["predictions.decoder.weight", "predictions.decoder.bias"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `QDQBertForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.bert = QDQBertModel(config, add_pooling_layer=False)
+ self.cls = QDQBertOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=MaskedLMOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, MaskedLMOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.cls(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self, input_ids: torch.LongTensor, attention_mask: Optional[torch.FloatTensor] = None, **model_kwargs
+ ):
+ input_shape = input_ids.shape
+ effective_batch_size = input_shape[0]
+
+ # add a dummy token
+ if self.config.pad_token_id is None:
+ raise ValueError("The PAD token should be defined for generation")
+
+ attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
+ dummy_token = torch.full(
+ (effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device
+ )
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
+
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
+
+
+@add_start_docstrings(
+ """Bert Model with a `next sentence prediction (classification)` head on top.""",
+ QDQBERT_START_DOCSTRING,
+)
+class QDQBertForNextSentencePrediction(QDQBertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.bert = QDQBertModel(config)
+ self.cls = QDQBertOnlyNSPHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs,
+ ) -> Union[tuple, NextSentencePredictorOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
+ (see `input_ids` docstring). Indices should be in `[0, 1]`:
+
+ - 0 indicates sequence B is a continuation of sequence A,
+ - 1 indicates sequence B is a random sequence.
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, QDQBertForNextSentencePrediction
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-uncased")
+ >>> model = QDQBertForNextSentencePrediction.from_pretrained("google-bert/bert-base-uncased")
+
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
+ >>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
+ >>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
+
+ >>> outputs = model(**encoding, labels=torch.LongTensor([1]))
+ >>> logits = outputs.logits
+ >>> assert logits[0, 0] < logits[0, 1] # next sentence was random
+ ```"""
+
+ if "next_sentence_label" in kwargs:
+ warnings.warn(
+ "The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
+ " `labels` instead.",
+ FutureWarning,
+ )
+ labels = kwargs.pop("next_sentence_label")
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ seq_relationship_scores = self.cls(pooled_output)
+
+ next_sentence_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
+
+ if not return_dict:
+ output = (seq_relationship_scores,) + outputs[2:]
+ return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
+
+ return NextSentencePredictorOutput(
+ loss=next_sentence_loss,
+ logits=seq_relationship_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
+ output) e.g. for GLUE tasks.
+ """,
+ QDQBERT_START_DOCSTRING,
+)
+class QDQBertForSequenceClassification(QDQBertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.bert = QDQBertModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=SequenceClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, SequenceClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ Bert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
+ softmax) e.g. for RocStories/SWAG tasks.
+ """,
+ QDQBERT_START_DOCSTRING,
+)
+class QDQBertForMultipleChoice(QDQBertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.bert = QDQBertModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=MultipleChoiceModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, MultipleChoiceModelOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ QDQBERT Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
+ Named-Entity-Recognition (NER) tasks.
+ """,
+ QDQBERT_START_DOCSTRING,
+)
+class QDQBertForTokenClassification(QDQBertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.bert = QDQBertModel(config, add_pooling_layer=False)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TokenClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, TokenClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ QDQBERT Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """,
+ QDQBERT_START_DOCSTRING,
+)
+class QDQBertForQuestionAnswering(QDQBertPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.bert = QDQBertModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(QDQBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=QuestionAnsweringModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ start_positions: Optional[torch.LongTensor] = None,
+ end_positions: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, QuestionAnsweringModelOutput]:
+ r"""
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.bert(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[2:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "QDQBertForMaskedLM",
+ "QDQBertForMultipleChoice",
+ "QDQBertForNextSentencePrediction",
+ "QDQBertForQuestionAnswering",
+ "QDQBertForSequenceClassification",
+ "QDQBertForTokenClassification",
+ "QDQBertLayer",
+ "QDQBertLMHeadModel",
+ "QDQBertModel",
+ "QDQBertPreTrainedModel",
+ "load_tf_weights_in_qdqbert",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdfdeb5d179c8e954c9c6822d3f154d632394964
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__init__.py
@@ -0,0 +1,30 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_realm import *
+ from .modeling_realm import *
+ from .retrieval_realm import *
+ from .tokenization_realm import *
+ from .tokenization_realm_fast import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..69637942ff2f91cb22b78d2b61eb5ecc57bc42c1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/configuration_realm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/configuration_realm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29248178228aa811fb827108a9321a15da917082
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/configuration_realm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/modeling_realm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/modeling_realm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5a62c773c57be3571d14874cfa0e2f879fbc812
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/modeling_realm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/retrieval_realm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/retrieval_realm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d259173305294635cc3142b1ab422b16adff6595
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/retrieval_realm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/tokenization_realm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/tokenization_realm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cdfde3637efcfcf3d1f64019ff7085df86865e26
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/tokenization_realm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/tokenization_realm_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/tokenization_realm_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc73bd5fd08f89be993098447390ee6de75a4005
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/__pycache__/tokenization_realm_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/configuration_realm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/configuration_realm.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbf32378a604beca939ff6e0241f69f4c4382120
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/configuration_realm.py
@@ -0,0 +1,169 @@
+# coding=utf-8
+# Copyright 2022 The REALM authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""REALM model configuration."""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class RealmConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of
+
+ 1. [`RealmEmbedder`]
+ 2. [`RealmScorer`]
+ 3. [`RealmKnowledgeAugEncoder`]
+ 4. [`RealmRetriever`]
+ 5. [`RealmReader`]
+ 6. [`RealmForOpenQA`]
+
+ It is used to instantiate an REALM model according to the specified arguments, defining the model architecture.
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the REALM
+ [google/realm-cc-news-pretrained-embedder](https://huggingface.co/google/realm-cc-news-pretrained-embedder)
+ architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 30522):
+ Vocabulary size of the REALM model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`RealmEmbedder`], [`RealmScorer`], [`RealmKnowledgeAugEncoder`], or
+ [`RealmReader`].
+ hidden_size (`int`, *optional*, defaults to 768):
+ Dimension of the encoder layers and the pooler layer.
+ retriever_proj_size (`int`, *optional*, defaults to 128):
+ Dimension of the retriever(embedder) projection.
+ num_hidden_layers (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ num_candidates (`int`, *optional*, defaults to 8):
+ Number of candidates inputted to the RealmScorer or RealmKnowledgeAugEncoder.
+ intermediate_size (`int`, *optional*, defaults to 3072):
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu_new"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention probabilities.
+ max_position_embeddings (`int`, *optional*, defaults to 512):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ type_vocab_size (`int`, *optional*, defaults to 2):
+ The vocabulary size of the `token_type_ids` passed when calling [`RealmEmbedder`], [`RealmScorer`],
+ [`RealmKnowledgeAugEncoder`], or [`RealmReader`].
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ span_hidden_size (`int`, *optional*, defaults to 256):
+ Dimension of the reader's spans.
+ max_span_width (`int`, *optional*, defaults to 10):
+ Max span width of the reader.
+ reader_layer_norm_eps (`float`, *optional*, defaults to 1e-3):
+ The epsilon used by the reader's layer normalization layers.
+ reader_beam_size (`int`, *optional*, defaults to 5):
+ Beam size of the reader.
+ reader_seq_len (`int`, *optional*, defaults to 288+32):
+ Maximum sequence length of the reader.
+ num_block_records (`int`, *optional*, defaults to 13353718):
+ Number of block records.
+ searcher_beam_size (`int`, *optional*, defaults to 5000):
+ Beam size of the searcher. Note that when eval mode is enabled, *searcher_beam_size* will be the same as
+ *reader_beam_size*.
+
+ Example:
+
+ ```python
+ >>> from transformers import RealmConfig, RealmEmbedder
+
+ >>> # Initializing a REALM realm-cc-news-pretrained-* style configuration
+ >>> configuration = RealmConfig()
+
+ >>> # Initializing a model (with random weights) from the google/realm-cc-news-pretrained-embedder style configuration
+ >>> model = RealmEmbedder(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "realm"
+
+ def __init__(
+ self,
+ vocab_size=30522,
+ hidden_size=768,
+ retriever_proj_size=128,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ num_candidates=8,
+ intermediate_size=3072,
+ hidden_act="gelu_new",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=512,
+ type_vocab_size=2,
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ span_hidden_size=256,
+ max_span_width=10,
+ reader_layer_norm_eps=1e-3,
+ reader_beam_size=5,
+ reader_seq_len=320, # 288 + 32
+ num_block_records=13353718,
+ searcher_beam_size=5000,
+ pad_token_id=1,
+ bos_token_id=0,
+ eos_token_id=2,
+ **kwargs,
+ ):
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
+
+ # Common config
+ self.vocab_size = vocab_size
+ self.max_position_embeddings = max_position_embeddings
+ self.hidden_size = hidden_size
+ self.retriever_proj_size = retriever_proj_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.num_candidates = num_candidates
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.initializer_range = initializer_range
+ self.type_vocab_size = type_vocab_size
+ self.layer_norm_eps = layer_norm_eps
+
+ # Reader config
+ self.span_hidden_size = span_hidden_size
+ self.max_span_width = max_span_width
+ self.reader_layer_norm_eps = reader_layer_norm_eps
+ self.reader_beam_size = reader_beam_size
+ self.reader_seq_len = reader_seq_len
+
+ # Retrieval config
+ self.num_block_records = num_block_records
+ self.searcher_beam_size = searcher_beam_size
+
+
+__all__ = ["RealmConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/modeling_realm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/modeling_realm.py
new file mode 100644
index 0000000000000000000000000000000000000000..8021a142dd80fa5352c8ada4f01d22ef49be4091
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/modeling_realm.py
@@ -0,0 +1,1854 @@
+# coding=utf-8
+# Copyright 2022 The REALM authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch REALM model."""
+
+import math
+import os
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ....activations import ACT2FN
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ MaskedLMOutput,
+ ModelOutput,
+)
+from ....modeling_utils import PreTrainedModel
+from ....pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
+from ....utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
+from ....utils.deprecation import deprecate_kwarg
+from .configuration_realm import RealmConfig
+
+
+logger = logging.get_logger(__name__)
+_EMBEDDER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-embedder"
+_ENCODER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-encoder"
+_SCORER_CHECKPOINT_FOR_DOC = "google/realm-cc-news-pretrained-scorer"
+_CONFIG_FOR_DOC = "RealmConfig"
+
+
+def load_tf_weights_in_realm(model, config, tf_checkpoint_path):
+ """Load tf checkpoints in a pytorch model."""
+ try:
+ import re
+
+ import numpy as np
+ import tensorflow as tf
+ except ImportError:
+ logger.error(
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
+ "https://www.tensorflow.org/install/ for installation instructions."
+ )
+ raise
+ tf_path = os.path.abspath(tf_checkpoint_path)
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
+ # Load weights from TF model
+ init_vars = tf.train.list_variables(tf_path)
+ names = []
+ arrays = []
+
+ for name, shape in init_vars:
+ logger.info(f"Loading TF weight {name} with shape {shape}")
+ array = tf.train.load_variable(tf_path, name)
+ names.append(name)
+ arrays.append(array)
+
+ for name, array in zip(names, arrays):
+ if isinstance(model, RealmReader) and "reader" not in name:
+ logger.info(f"Skipping {name} as it is not {model.__class__.__name__}'s parameter")
+ continue
+
+ # For pretrained openqa reader
+ if (name.startswith("bert") or name.startswith("cls")) and isinstance(model, RealmForOpenQA):
+ name = name.replace("bert/", "reader/realm/")
+ name = name.replace("cls/", "reader/cls/")
+
+ # For pretrained encoder
+ if (name.startswith("bert") or name.startswith("cls")) and isinstance(model, RealmKnowledgeAugEncoder):
+ name = name.replace("bert/", "realm/")
+
+ # For finetuned reader
+ if name.startswith("reader"):
+ reader_prefix = "" if isinstance(model, RealmReader) else "reader/"
+ name = name.replace("reader/module/bert/", f"{reader_prefix}realm/")
+ name = name.replace("reader/module/cls/", f"{reader_prefix}cls/")
+ name = name.replace("reader/dense/", f"{reader_prefix}qa_outputs/dense_intermediate/")
+ name = name.replace("reader/dense_1/", f"{reader_prefix}qa_outputs/dense_output/")
+ name = name.replace("reader/layer_normalization", f"{reader_prefix}qa_outputs/layer_normalization")
+
+ # For embedder and scorer
+ if name.startswith("module/module/module/"): # finetuned
+ embedder_prefix = "" if isinstance(model, RealmEmbedder) else "embedder/"
+ name = name.replace("module/module/module/module/bert/", f"{embedder_prefix}realm/")
+ name = name.replace("module/module/module/LayerNorm/", f"{embedder_prefix}cls/LayerNorm/")
+ name = name.replace("module/module/module/dense/", f"{embedder_prefix}cls/dense/")
+ name = name.replace("module/module/module/module/cls/predictions/", f"{embedder_prefix}cls/predictions/")
+ name = name.replace("module/module/module/bert/", f"{embedder_prefix}realm/")
+ name = name.replace("module/module/module/cls/predictions/", f"{embedder_prefix}cls/predictions/")
+ elif name.startswith("module/module/"): # pretrained
+ embedder_prefix = "" if isinstance(model, RealmEmbedder) else "embedder/"
+ name = name.replace("module/module/LayerNorm/", f"{embedder_prefix}cls/LayerNorm/")
+ name = name.replace("module/module/dense/", f"{embedder_prefix}cls/dense/")
+
+ name = name.split("/")
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
+ # which are not required for using pretrained model
+ if any(
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
+ for n in name
+ ):
+ logger.info(f"Skipping {'/'.join(name)}")
+ continue
+ pointer = model
+ for m_name in name:
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
+ scope_names = re.split(r"_(\d+)", m_name)
+ else:
+ scope_names = [m_name]
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
+ pointer = getattr(pointer, "weight")
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
+ pointer = getattr(pointer, "bias")
+ else:
+ try:
+ pointer = getattr(pointer, scope_names[0])
+ except AttributeError:
+ logger.info(f"Skipping {'/'.join(name)}")
+ continue
+ if len(scope_names) >= 2:
+ num = int(scope_names[1])
+ pointer = pointer[num]
+ if m_name[-11:] == "_embeddings":
+ pointer = getattr(pointer, "weight")
+ elif m_name == "kernel":
+ array = np.transpose(array)
+ try:
+ assert pointer.shape == array.shape, (
+ f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
+ )
+ except AssertionError as e:
+ e.args += (pointer.shape, array.shape)
+ raise
+ logger.info(f"Initialize PyTorch weight {name}")
+ pointer.data = torch.from_numpy(array)
+ return model
+
+
+class RealmEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
+ # any TensorFlow checkpoint file
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+
+ embeddings = inputs_embeds + token_type_embeddings
+ if self.position_embedding_type == "absolute":
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings += position_embeddings
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class RealmSelfAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.position_embedding_type = position_embedding_type or getattr(
+ config, "position_embedding_type", "absolute"
+ )
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ self.max_position_embeddings = config.max_position_embeddings
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
+
+ self.is_decoder = config.is_decoder
+
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
+ x = x.view(new_x_shape)
+ return x.permute(0, 2, 1, 3)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ mixed_query_layer = self.query(hidden_states)
+
+ # If this is instantiated as a cross-attention module, the keys
+ # and values come from an encoder; the attention mask needs to be
+ # such that the encoder's padding tokens are not attended to.
+ is_cross_attention = encoder_hidden_states is not None
+
+ if is_cross_attention and past_key_values is not None:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_values[0]
+ value_layer = past_key_values[1]
+ attention_mask = encoder_attention_mask
+ elif is_cross_attention:
+ key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
+ value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
+ attention_mask = encoder_attention_mask
+ elif past_key_values is not None:
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+ key_layer = torch.cat([past_key_values[0], key_layer], dim=2)
+ value_layer = torch.cat([past_key_values[1], value_layer], dim=2)
+ else:
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ use_cache = past_key_values is not None
+ if self.is_decoder:
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
+ # Further calls to cross_attention layer can then reuse all cross-attention
+ # key/value_states (first "if" case)
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
+ past_key_values = (key_layer, value_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
+ if use_cache:
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
+ -1, 1
+ )
+ else:
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
+ distance = position_ids_l - position_ids_r
+
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
+
+ if self.position_embedding_type == "relative_key":
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores
+ elif self.position_embedding_type == "relative_key_query":
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in RealmModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = attention_probs * head_mask
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ if self.is_decoder:
+ outputs = outputs + (past_key_values,)
+ return outputs
+
+
+class RealmSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+REALM_SELF_ATTENTION_CLASSES = {
+ "eager": RealmSelfAttention,
+}
+
+
+class RealmAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None):
+ super().__init__()
+ self.self = REALM_SELF_ATTENTION_CLASSES[config._attn_implementation](
+ config, position_embedding_type=position_embedding_type
+ )
+ self.output = RealmSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.self.query = prune_linear_layer(self.self.query, index)
+ self.self.key = prune_linear_layer(self.self.key, index)
+ self.self.value = prune_linear_layer(self.self.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ self_outputs = self.self(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values,
+ output_attentions,
+ )
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+class RealmIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class RealmOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class RealmLayer(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = RealmAttention(config)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = RealmAttention(config, position_embedding_type="absolute")
+ self.intermediate = RealmIntermediate(config)
+ self.output = RealmOutput(config)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
+ self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
+ self_attention_outputs = self.attention(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ output_attentions=output_attentions,
+ past_key_values=self_attn_past_key_value,
+ )
+ attention_output = self_attention_outputs[0]
+
+ # if decoder, the last output is tuple of self-attn cache
+ if self.is_decoder:
+ outputs = self_attention_outputs[1:-1]
+ present_key_value = self_attention_outputs[-1]
+ else:
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ cross_attn_present_key_value = None
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_values tuple
+ cross_attn_past_key_value = past_key_values[-2:] if past_key_values is not None else None
+ cross_attention_outputs = self.crossattention(
+ attention_output,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ cross_attn_past_key_value,
+ output_attentions,
+ )
+ attention_output = cross_attention_outputs[0]
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
+
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
+ cross_attn_present_key_value = cross_attention_outputs[-1]
+ present_key_value = present_key_value + cross_attn_present_key_value
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ outputs = (layer_output,) + outputs
+
+ # if decoder, return the attn key/values as the last output
+ if self.is_decoder:
+ outputs = outputs + (present_key_value,)
+
+ return outputs
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class RealmEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([RealmLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = False,
+ output_hidden_states: Optional[bool] = False,
+ return_dict: Optional[bool] = True,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
+
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ next_decoder_cache = () if use_cache else None
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+
+ layer_outputs = layer_module(
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values[i] if past_key_values is not None else None,
+ output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+ if use_cache:
+ next_decoder_cache += (layer_outputs[-1],)
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+ if self.config.add_cross_attention:
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ hidden_states,
+ next_decoder_cache,
+ all_hidden_states,
+ all_self_attentions,
+ all_cross_attentions,
+ ]
+ if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=next_decoder_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+class RealmPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@dataclass
+class RealmEmbedderOutput(ModelOutput):
+ """
+ Outputs of [`RealmEmbedder`] models.
+
+ Args:
+ projected_score (`torch.FloatTensor` of shape `(batch_size, config.retriever_proj_size)`):
+
+ Projected score.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ projected_score: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+@dataclass
+class RealmScorerOutput(ModelOutput):
+ """
+ Outputs of [`RealmScorer`] models.
+
+ Args:
+ relevance_score (`torch.FloatTensor` of shape `(batch_size, config.num_candidates)`):
+ The relevance score of document candidates (before softmax).
+ query_score (`torch.FloatTensor` of shape `(batch_size, config.retriever_proj_size)`):
+ Query score derived from the query embedder.
+ candidate_score (`torch.FloatTensor` of shape `(batch_size, config.num_candidates, config.retriever_proj_size)`):
+ Candidate score derived from the embedder.
+ """
+
+ relevance_score: Optional[torch.FloatTensor] = None
+ query_score: Optional[torch.FloatTensor] = None
+ candidate_score: Optional[torch.FloatTensor] = None
+
+
+@dataclass
+class RealmReaderOutput(ModelOutput):
+ """
+ Outputs of [`RealmReader`] models.
+
+ Args:
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `start_positions`, `end_positions`, `has_answers` are provided):
+ Total loss.
+ retriever_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `start_positions`, `end_positions`, `has_answers` are provided):
+ Retriever loss.
+ reader_loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `start_positions`, `end_positions`, `has_answers` are provided):
+ Reader loss.
+ retriever_correct (`torch.BoolTensor` of shape `(config.searcher_beam_size,)`, *optional*):
+ Whether or not an evidence block contains answer.
+ reader_correct (`torch.BoolTensor` of shape `(config.reader_beam_size, num_candidates)`, *optional*):
+ Whether or not a span candidate contains answer.
+ block_idx (`torch.LongTensor` of shape `()`):
+ The index of the retrieved evidence block in which the predicted answer is most likely.
+ candidate (`torch.LongTensor` of shape `()`):
+ The index of the retrieved span candidates in which the predicted answer is most likely.
+ start_pos (`torch.IntTensor` of shape `()`):
+ Predicted answer starting position in *RealmReader*'s inputs.
+ end_pos (`torch.IntTensor` of shape `()`):
+ Predicted answer ending position in *RealmReader*'s inputs.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ retriever_loss: Optional[torch.FloatTensor] = None
+ reader_loss: Optional[torch.FloatTensor] = None
+ retriever_correct: torch.BoolTensor = None
+ reader_correct: torch.BoolTensor = None
+ block_idx: Optional[torch.LongTensor] = None
+ candidate: Optional[torch.LongTensor] = None
+ start_pos: torch.int32 = None
+ end_pos: torch.int32 = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+@dataclass
+class RealmForOpenQAOutput(ModelOutput):
+ """
+
+ Outputs of [`RealmForOpenQA`] models.
+
+ Args:
+ reader_output (`dict`):
+ Reader output.
+ predicted_answer_ids (`torch.LongTensor` of shape `(answer_sequence_length)`):
+ Predicted answer ids.
+ """
+
+ reader_output: dict = None
+ predicted_answer_ids: Optional[torch.LongTensor] = None
+
+
+class RealmPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+class RealmLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = RealmPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
+ self.decoder.bias = self.bias
+
+ def _tie_weights(self):
+ self.decoder.bias = self.bias
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+class RealmOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = RealmLMPredictionHead(config)
+
+ def forward(self, sequence_output):
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+class RealmScorerProjection(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = RealmLMPredictionHead(config)
+ self.dense = nn.Linear(config.hidden_size, config.retriever_proj_size)
+ self.LayerNorm = nn.LayerNorm(config.retriever_proj_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+class RealmReaderProjection(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.dense_intermediate = nn.Linear(config.hidden_size, config.span_hidden_size * 2)
+ self.dense_output = nn.Linear(config.span_hidden_size, 1)
+ self.layer_normalization = nn.LayerNorm(config.span_hidden_size, eps=config.reader_layer_norm_eps)
+ self.relu = nn.ReLU()
+
+ def forward(self, hidden_states, block_mask):
+ def span_candidates(masks):
+ """
+ Generate span candidates.
+
+ Args:
+ masks: [num_retrievals, max_sequence_len]
+
+ Returns:
+ starts: [num_spans] ends: [num_spans] span_masks: [num_retrievals, num_spans]
+ whether spans locate in evidence block.
+ """
+ _, max_sequence_len = masks.shape
+
+ def _spans_given_width(width):
+ current_starts = torch.arange(max_sequence_len - width + 1, device=masks.device)
+ current_ends = torch.arange(width - 1, max_sequence_len, device=masks.device)
+ return current_starts, current_ends
+
+ starts, ends = zip(*(_spans_given_width(w + 1) for w in range(self.config.max_span_width)))
+
+ # [num_spans]
+ starts = torch.cat(starts, 0)
+ ends = torch.cat(ends, 0)
+
+ # [num_retrievals, num_spans]
+ start_masks = torch.index_select(masks, dim=-1, index=starts)
+ end_masks = torch.index_select(masks, dim=-1, index=ends)
+ span_masks = start_masks * end_masks
+
+ return starts, ends, span_masks
+
+ def mask_to_score(mask, dtype=torch.float32):
+ return (1.0 - mask.type(dtype)) * torch.finfo(dtype).min
+
+ # [reader_beam_size, max_sequence_len, span_hidden_size * 2]
+ hidden_states = self.dense_intermediate(hidden_states)
+ # [reader_beam_size, max_sequence_len, span_hidden_size]
+ start_projection, end_projection = hidden_states.chunk(2, dim=-1)
+
+ candidate_starts, candidate_ends, candidate_mask = span_candidates(block_mask)
+
+ candidate_start_projections = torch.index_select(start_projection, dim=1, index=candidate_starts)
+ candidate_end_projections = torch.index_select(end_projection, dim=1, index=candidate_ends)
+ candidate_hidden = candidate_start_projections + candidate_end_projections
+
+ # [reader_beam_size, num_candidates, span_hidden_size]
+ candidate_hidden = self.relu(candidate_hidden)
+ # [reader_beam_size, num_candidates, span_hidden_size]
+ candidate_hidden = self.layer_normalization(candidate_hidden)
+ # [reader_beam_size, num_candidates]
+ reader_logits = self.dense_output(candidate_hidden).squeeze(-1)
+ # [reader_beam_size, num_candidates]
+ reader_logits += mask_to_score(candidate_mask, dtype=reader_logits.dtype)
+
+ return reader_logits, candidate_starts, candidate_ends
+
+
+REALM_START_DOCSTRING = r"""
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
+ behavior.
+
+ Parameters:
+ config ([`RealmConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+REALM_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+class RealmPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: RealmConfig
+ load_tf_weights = load_tf_weights_in_realm
+ base_model_prefix = "realm"
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+ def _flatten_inputs(self, *inputs):
+ """Flatten inputs' shape to (-1, input_shape[-1])"""
+ flattened_inputs = []
+ for tensor in inputs:
+ if tensor is None:
+ flattened_inputs.append(None)
+ else:
+ input_shape = tensor.shape
+ if len(input_shape) > 2:
+ tensor = tensor.view((-1, input_shape[-1]))
+ flattened_inputs.append(tensor)
+ return flattened_inputs
+
+
+class RealmBertModel(RealmPreTrainedModel):
+ """
+ Same as the original BertModel but remove docstrings.
+ """
+
+ def __init__(self, config, add_pooling_layer=True):
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = RealmEmbeddings(config)
+ self.encoder = RealmEncoder(config)
+
+ self.pooler = RealmPooler(config) if add_pooling_layer else None
+
+ # Weights initialization is mostly managed by other Realm models,
+ # but we also have them initialized here to keep a consistency.
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ def forward(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ token_type_ids=None,
+ position_ids=None,
+ head_mask=None,
+ inputs_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ use_cache=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ ):
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ batch_size, seq_length = input_shape
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ # past_key_values_length
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ if attention_mask is None:
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
+
+ if token_type_ids is None:
+ if hasattr(self.embeddings, "token_type_ids"):
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
+ # ourselves in which case we just need to make it broadcastable to all heads.
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
+
+ # If a 2D or 3D attention mask is provided for the cross-attention
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ if self.config.is_decoder and encoder_hidden_states is not None:
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
+ if encoder_attention_mask is None:
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
+ else:
+ encoder_extended_attention_mask = None
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+@add_start_docstrings(
+ "The embedder of REALM outputting projected score that will be used to calculate relevance score.",
+ REALM_START_DOCSTRING,
+)
+class RealmEmbedder(RealmPreTrainedModel):
+ _tied_weights_keys = ["cls.predictions.decoder.bias"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.realm = RealmBertModel(self.config)
+ self.cls = RealmScorerProjection(self.config)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.realm.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.realm.embeddings.word_embeddings = value
+
+ @add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @replace_return_docstrings(output_type=RealmEmbedderOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, RealmEmbedderOutput]:
+ r"""
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, RealmEmbedder
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/realm-cc-news-pretrained-embedder")
+ >>> model = RealmEmbedder.from_pretrained("google/realm-cc-news-pretrained-embedder")
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> projected_score = outputs.projected_score
+ ```
+ """
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ realm_outputs = self.realm(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ # [batch_size, hidden_size]
+ pooler_output = realm_outputs[1]
+ # [batch_size, retriever_proj_size]
+ projected_score = self.cls(pooler_output)
+
+ if not return_dict:
+ return (projected_score,) + realm_outputs[2:4]
+ else:
+ return RealmEmbedderOutput(
+ projected_score=projected_score,
+ hidden_states=realm_outputs.hidden_states,
+ attentions=realm_outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ "The scorer of REALM outputting relevance scores representing the score of document candidates (before softmax).",
+ REALM_START_DOCSTRING,
+)
+class RealmScorer(RealmPreTrainedModel):
+ r"""
+ Args:
+ query_embedder ([`RealmEmbedder`]):
+ Embedder for input sequences. If not specified, it will use the same embedder as candidate sequences.
+ """
+
+ def __init__(self, config, query_embedder=None):
+ super().__init__(config)
+
+ self.embedder = RealmEmbedder(self.config)
+
+ self.query_embedder = query_embedder if query_embedder is not None else self.embedder
+
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @replace_return_docstrings(output_type=RealmScorerOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ candidate_input_ids: Optional[torch.LongTensor] = None,
+ candidate_attention_mask: Optional[torch.FloatTensor] = None,
+ candidate_token_type_ids: Optional[torch.LongTensor] = None,
+ candidate_inputs_embeds: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, RealmScorerOutput]:
+ r"""
+ candidate_input_ids (`torch.LongTensor` of shape `(batch_size, num_candidates, sequence_length)`):
+ Indices of candidate input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ candidate_attention_mask (`torch.FloatTensor` of shape `(batch_size, num_candidates, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ candidate_token_type_ids (`torch.LongTensor` of shape `(batch_size, num_candidates, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ candidate_inputs_embeds (`torch.FloatTensor` of shape `(batch_size * num_candidates, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `candidate_input_ids` you can choose to directly pass an embedded
+ representation. This is useful if you want more control over how to convert *candidate_input_ids* indices
+ into associated vectors than the model's internal embedding lookup matrix.
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, RealmScorer
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/realm-cc-news-pretrained-scorer")
+ >>> model = RealmScorer.from_pretrained("google/realm-cc-news-pretrained-scorer", num_candidates=2)
+
+ >>> # batch_size = 2, num_candidates = 2
+ >>> input_texts = ["How are you?", "What is the item in the picture?"]
+ >>> candidates_texts = [["Hello world!", "Nice to meet you!"], ["A cute cat.", "An adorable dog."]]
+
+ >>> inputs = tokenizer(input_texts, return_tensors="pt")
+ >>> candidates_inputs = tokenizer.batch_encode_candidates(candidates_texts, max_length=10, return_tensors="pt")
+
+ >>> outputs = model(
+ ... **inputs,
+ ... candidate_input_ids=candidates_inputs.input_ids,
+ ... candidate_attention_mask=candidates_inputs.attention_mask,
+ ... candidate_token_type_ids=candidates_inputs.token_type_ids,
+ ... )
+ >>> relevance_score = outputs.relevance_score
+ ```"""
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if input_ids is None and inputs_embeds is None:
+ raise ValueError("You have to specify either input_ids or input_embeds.")
+
+ if candidate_input_ids is None and candidate_inputs_embeds is None:
+ raise ValueError("You have to specify either candidate_input_ids or candidate_inputs_embeds.")
+
+ query_outputs = self.query_embedder(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ # [batch_size * num_candidates, candidate_seq_len]
+ (flattened_input_ids, flattened_attention_mask, flattened_token_type_ids) = self._flatten_inputs(
+ candidate_input_ids, candidate_attention_mask, candidate_token_type_ids
+ )
+
+ candidate_outputs = self.embedder(
+ flattened_input_ids,
+ attention_mask=flattened_attention_mask,
+ token_type_ids=flattened_token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=candidate_inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ # [batch_size, retriever_proj_size]
+ query_score = query_outputs[0]
+ # [batch_size * num_candidates, retriever_proj_size]
+ candidate_score = candidate_outputs[0]
+ # [batch_size, num_candidates, retriever_proj_size]
+ candidate_score = candidate_score.view(-1, self.config.num_candidates, self.config.retriever_proj_size)
+ # [batch_size, num_candidates]
+ relevance_score = torch.einsum("bd,bnd->bn", query_score, candidate_score)
+
+ if not return_dict:
+ return relevance_score, query_score, candidate_score
+
+ return RealmScorerOutput(
+ relevance_score=relevance_score, query_score=query_score, candidate_score=candidate_score
+ )
+
+
+@add_start_docstrings(
+ "The knowledge-augmented encoder of REALM outputting masked language model logits and marginal log-likelihood"
+ " loss.",
+ REALM_START_DOCSTRING,
+)
+class RealmKnowledgeAugEncoder(RealmPreTrainedModel):
+ _tied_weights_keys = ["cls.predictions.decoder"]
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.realm = RealmBertModel(self.config)
+ self.cls = RealmOnlyMLMHead(self.config)
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.realm.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.realm.embeddings.word_embeddings = value
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @add_start_docstrings_to_model_forward(
+ REALM_INPUTS_DOCSTRING.format("batch_size, num_candidates, sequence_length")
+ )
+ @replace_return_docstrings(output_type=MaskedLMOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ relevance_score: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ mlm_mask: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, MaskedLMOutput]:
+ r"""
+ relevance_score (`torch.FloatTensor` of shape `(batch_size, num_candidates)`, *optional*):
+ Relevance score derived from RealmScorer, must be specified if you want to compute the masked language
+ modeling loss.
+
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ mlm_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid calculating joint loss on certain positions. If not specified, the loss will not be masked.
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, RealmKnowledgeAugEncoder
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/realm-cc-news-pretrained-encoder")
+ >>> model = RealmKnowledgeAugEncoder.from_pretrained(
+ ... "google/realm-cc-news-pretrained-encoder", num_candidates=2
+ ... )
+
+ >>> # batch_size = 2, num_candidates = 2
+ >>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]
+
+ >>> inputs = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt")
+ >>> outputs = model(**inputs)
+ >>> logits = outputs.logits
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if labels is not None and relevance_score is None:
+ raise ValueError(
+ "You have to specify `relevance_score` when `labels` is specified in order to compute loss."
+ )
+
+ (flattened_input_ids, flattened_attention_mask, flattened_token_type_ids) = self._flatten_inputs(
+ input_ids, attention_mask, token_type_ids
+ )
+
+ joint_outputs = self.realm(
+ flattened_input_ids,
+ attention_mask=flattened_attention_mask,
+ token_type_ids=flattened_token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ # [batch_size * num_candidates, joint_seq_len, hidden_size]
+ joint_output = joint_outputs[0]
+ # [batch_size * num_candidates, joint_seq_len, vocab_size]
+ prediction_scores = self.cls(joint_output)
+ # [batch_size, num_candidates]
+ candidate_score = relevance_score
+
+ masked_lm_loss = None
+ if labels is not None:
+ batch_size, seq_length = labels.size()
+
+ if mlm_mask is None:
+ mlm_mask = torch.ones_like(labels, dtype=torch.float32)
+ else:
+ mlm_mask = mlm_mask.type(torch.float32)
+
+ # Compute marginal log-likelihood
+ loss_fct = CrossEntropyLoss(reduction="none") # -100 index = padding token
+
+ # [batch_size * num_candidates * joint_seq_len, vocab_size]
+ mlm_logits = prediction_scores.view(-1, self.config.vocab_size)
+ # [batch_size * num_candidates * joint_seq_len]
+ mlm_targets = labels.tile(1, self.config.num_candidates).view(-1)
+ # [batch_size, num_candidates, joint_seq_len]
+ masked_lm_log_prob = -loss_fct(mlm_logits, mlm_targets).view(
+ batch_size, self.config.num_candidates, seq_length
+ )
+ # [batch_size, num_candidates, 1]
+ candidate_log_prob = candidate_score.log_softmax(-1).unsqueeze(-1)
+ # [batch_size, num_candidates, joint_seq_len]
+ joint_gold_log_prob = candidate_log_prob + masked_lm_log_prob
+ # [batch_size, joint_seq_len]
+ marginal_gold_log_probs = joint_gold_log_prob.logsumexp(1)
+ # []
+ masked_lm_loss = -torch.nansum(torch.sum(marginal_gold_log_probs * mlm_mask) / torch.sum(mlm_mask))
+
+ if not return_dict:
+ output = (prediction_scores,) + joint_outputs[2:4]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=joint_outputs.hidden_states,
+ attentions=joint_outputs.attentions,
+ )
+
+
+@add_start_docstrings("The reader of REALM.", REALM_START_DOCSTRING)
+class RealmReader(RealmPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.realm = RealmBertModel(config)
+ self.cls = RealmOnlyMLMHead(config)
+ self.qa_outputs = RealmReaderProjection(config)
+
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(REALM_INPUTS_DOCSTRING.format("reader_beam_size, sequence_length"))
+ @replace_return_docstrings(output_type=RealmReaderOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ relevance_score: Optional[torch.FloatTensor] = None,
+ block_mask: Optional[torch.BoolTensor] = None,
+ start_positions: Optional[torch.LongTensor] = None,
+ end_positions: Optional[torch.LongTensor] = None,
+ has_answers: Optional[torch.BoolTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, RealmReaderOutput]:
+ r"""
+ relevance_score (`torch.FloatTensor` of shape `(searcher_beam_size,)`, *optional*):
+ Relevance score, which must be specified if you want to compute the logits and marginal log loss.
+ block_mask (`torch.BoolTensor` of shape `(searcher_beam_size, sequence_length)`, *optional*):
+ The mask of the evidence block, which must be specified if you want to compute the logits and marginal log
+ loss.
+ start_positions (`torch.LongTensor` of shape `(searcher_beam_size,)`, *optional*):
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ end_positions (`torch.LongTensor` of shape `(searcher_beam_size,)`, *optional*):
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ has_answers (`torch.BoolTensor` of shape `(searcher_beam_size,)`, *optional*):
+ Whether or not the evidence block has answer(s).
+
+ Returns:
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if relevance_score is None:
+ raise ValueError("You have to specify `relevance_score` to calculate logits and loss.")
+ if block_mask is None:
+ raise ValueError("You have to specify `block_mask` to separate question block and evidence block.")
+ if token_type_ids.size(1) < self.config.max_span_width:
+ raise ValueError("The input sequence length must be greater than or equal to config.max_span_width.")
+ outputs = self.realm(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ # [reader_beam_size, joint_seq_len, hidden_size]
+ sequence_output = outputs[0]
+
+ # [reader_beam_size, num_candidates], [num_candidates], [num_candidates]
+ reader_logits, candidate_starts, candidate_ends = self.qa_outputs(
+ sequence_output, block_mask[0 : self.config.reader_beam_size]
+ )
+ # [searcher_beam_size, 1]
+ retriever_logits = torch.unsqueeze(relevance_score[0 : self.config.reader_beam_size], -1)
+ # [reader_beam_size, num_candidates]
+ reader_logits += retriever_logits
+ # []
+ predicted_block_index = torch.argmax(torch.max(reader_logits, dim=1).values)
+ # []
+ predicted_candidate = torch.argmax(torch.max(reader_logits, dim=0).values)
+ # [1]
+ predicted_start = torch.index_select(candidate_starts, dim=0, index=predicted_candidate)
+ # [1]
+ predicted_end = torch.index_select(candidate_ends, dim=0, index=predicted_candidate)
+
+ total_loss = None
+ retriever_loss = None
+ reader_loss = None
+ retriever_correct = None
+ reader_correct = None
+ if start_positions is not None and end_positions is not None and has_answers is not None:
+
+ def compute_correct_candidates(candidate_starts, candidate_ends, gold_starts, gold_ends):
+ """Compute correct span."""
+ # [reader_beam_size, num_answers, num_candidates]
+ is_gold_start = torch.eq(
+ torch.unsqueeze(torch.unsqueeze(candidate_starts, 0), 0), torch.unsqueeze(gold_starts, -1)
+ )
+ is_gold_end = torch.eq(
+ torch.unsqueeze(torch.unsqueeze(candidate_ends, 0), 0), torch.unsqueeze(gold_ends, -1)
+ )
+
+ # [reader_beam_size, num_candidates]
+ return torch.any(torch.logical_and(is_gold_start, is_gold_end), 1)
+
+ def marginal_log_loss(logits, is_correct):
+ """Loss based on the negative marginal log-likelihood."""
+
+ def mask_to_score(mask, dtype=torch.float32):
+ return (1.0 - mask.type(dtype)) * torch.finfo(dtype).min
+
+ # []
+ log_numerator = torch.logsumexp(logits + mask_to_score(is_correct, dtype=logits.dtype), dim=-1)
+ log_denominator = torch.logsumexp(logits, dim=-1)
+ return log_denominator - log_numerator
+
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ # `-1` is reserved for no answer.
+ ignored_index = sequence_output.size(1)
+ start_positions = start_positions.clamp(-1, ignored_index)
+ end_positions = end_positions.clamp(-1, ignored_index)
+
+ retriever_correct = has_answers
+ any_retriever_correct = torch.any(retriever_correct)
+
+ reader_correct = compute_correct_candidates(
+ candidate_starts=candidate_starts,
+ candidate_ends=candidate_ends,
+ gold_starts=start_positions[0 : self.config.reader_beam_size],
+ gold_ends=end_positions[0 : self.config.reader_beam_size],
+ )
+ any_reader_correct = torch.any(reader_correct)
+
+ retriever_loss = marginal_log_loss(relevance_score, retriever_correct)
+ reader_loss = marginal_log_loss(reader_logits.view(-1), reader_correct.view(-1))
+ retriever_loss *= any_retriever_correct.type(torch.float32)
+ reader_loss *= any_reader_correct.type(torch.float32)
+
+ total_loss = (retriever_loss + reader_loss).mean()
+
+ if not return_dict:
+ output = (predicted_block_index, predicted_candidate, predicted_start, predicted_end) + outputs[2:]
+ return (
+ ((total_loss, retriever_loss, reader_loss, retriever_correct, reader_correct) + output)
+ if total_loss is not None
+ else output
+ )
+
+ return RealmReaderOutput(
+ loss=total_loss,
+ retriever_loss=retriever_loss,
+ reader_loss=reader_loss,
+ retriever_correct=retriever_correct,
+ reader_correct=reader_correct,
+ block_idx=predicted_block_index,
+ candidate=predicted_candidate,
+ start_pos=predicted_start,
+ end_pos=predicted_end,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+REALM_FOR_OPEN_QA_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token (should not be used in this model by design).
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ answer_ids (`list` of shape `(num_answers, answer_length)`, *optional*):
+ Answer ids for computing the marginal log-likelihood loss. Indices should be in `[-1, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-1` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "`RealmForOpenQA` for end-to-end open domain question answering.",
+ REALM_START_DOCSTRING,
+)
+class RealmForOpenQA(RealmPreTrainedModel):
+ def __init__(self, config, retriever=None):
+ super().__init__(config)
+ self.embedder = RealmEmbedder(config)
+ self.reader = RealmReader(config)
+ self.register_buffer(
+ "block_emb",
+ torch.zeros(()).new_empty(
+ size=(config.num_block_records, config.retriever_proj_size),
+ dtype=torch.float32,
+ device=torch.device("cpu"),
+ ),
+ )
+ self.retriever = retriever
+
+ self.post_init()
+
+ @property
+ def searcher_beam_size(self):
+ if self.training:
+ return self.config.searcher_beam_size
+ return self.config.reader_beam_size
+
+ def block_embedding_to(self, device):
+ """Send `self.block_emb` to a specific device.
+
+ Args:
+ device (`str` or `torch.device`):
+ The device to which `self.block_emb` will be sent.
+ """
+
+ self.block_emb = self.block_emb.to(device)
+
+ @add_start_docstrings_to_model_forward(REALM_FOR_OPEN_QA_DOCSTRING.format("1, sequence_length"))
+ @replace_return_docstrings(output_type=RealmForOpenQAOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor],
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ answer_ids: Optional[torch.LongTensor] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, RealmForOpenQAOutput]:
+ r"""
+ Returns:
+
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import RealmForOpenQA, RealmRetriever, AutoTokenizer
+
+ >>> retriever = RealmRetriever.from_pretrained("google/realm-orqa-nq-openqa")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/realm-orqa-nq-openqa")
+ >>> model = RealmForOpenQA.from_pretrained("google/realm-orqa-nq-openqa", retriever=retriever)
+
+ >>> question = "Who is the pioneer in modern computer science?"
+ >>> question_ids = tokenizer([question], return_tensors="pt")
+ >>> answer_ids = tokenizer(
+ ... ["alan mathison turing"],
+ ... add_special_tokens=False,
+ ... return_token_type_ids=False,
+ ... return_attention_mask=False,
+ ... ).input_ids
+
+ >>> reader_output, predicted_answer_ids = model(**question_ids, answer_ids=answer_ids, return_dict=False)
+ >>> predicted_answer = tokenizer.decode(predicted_answer_ids)
+ >>> loss = reader_output.loss
+ ```"""
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if input_ids is not None and input_ids.shape[0] != 1:
+ raise ValueError("The batch_size of the inputs must be 1.")
+
+ question_outputs = self.embedder(
+ input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask, return_dict=True
+ )
+ # [1, projection_size]
+ question_projection = question_outputs[0]
+
+ # CPU computation starts.
+ # [1, block_emb_size]
+ batch_scores = torch.einsum("BD,QD->QB", self.block_emb, question_projection.to(self.block_emb.device))
+ # [1, searcher_beam_size]
+ _, retrieved_block_ids = torch.topk(batch_scores, k=self.searcher_beam_size, dim=-1)
+ # [searcher_beam_size]
+ retrieved_block_ids = retrieved_block_ids.squeeze()
+ # [searcher_beam_size, projection_size]
+ retrieved_block_emb = torch.index_select(self.block_emb, dim=0, index=retrieved_block_ids)
+ # CPU computation ends.
+
+ # Retrieve possible answers
+ has_answers, start_pos, end_pos, concat_inputs = self.retriever(
+ retrieved_block_ids.cpu(), input_ids, answer_ids, max_length=self.config.reader_seq_len
+ )
+
+ concat_inputs = concat_inputs.to(self.reader.device)
+ block_mask = concat_inputs.special_tokens_mask.type(torch.bool).to(device=self.reader.device)
+ block_mask.logical_not_().logical_and_(concat_inputs.token_type_ids.type(torch.bool))
+
+ if has_answers is not None:
+ has_answers = torch.tensor(has_answers, dtype=torch.bool, device=self.reader.device)
+ start_pos = torch.tensor(start_pos, dtype=torch.long, device=self.reader.device)
+ end_pos = torch.tensor(end_pos, dtype=torch.long, device=self.reader.device)
+
+ # [searcher_beam_size]
+ retrieved_logits = torch.einsum(
+ "D,BD->B", question_projection.squeeze(), retrieved_block_emb.to(self.reader.device)
+ )
+
+ reader_output = self.reader(
+ input_ids=concat_inputs.input_ids[0 : self.config.reader_beam_size],
+ attention_mask=concat_inputs.attention_mask[0 : self.config.reader_beam_size],
+ token_type_ids=concat_inputs.token_type_ids[0 : self.config.reader_beam_size],
+ relevance_score=retrieved_logits,
+ block_mask=block_mask,
+ has_answers=has_answers,
+ start_positions=start_pos,
+ end_positions=end_pos,
+ return_dict=True,
+ )
+
+ predicted_block = concat_inputs.input_ids[reader_output.block_idx]
+ predicted_answer_ids = predicted_block[reader_output.start_pos : reader_output.end_pos + 1]
+
+ if not return_dict:
+ return reader_output, predicted_answer_ids
+
+ return RealmForOpenQAOutput(
+ reader_output=reader_output,
+ predicted_answer_ids=predicted_answer_ids,
+ )
+
+
+__all__ = [
+ "RealmEmbedder",
+ "RealmForOpenQA",
+ "RealmKnowledgeAugEncoder",
+ "RealmPreTrainedModel",
+ "RealmReader",
+ "RealmScorer",
+ "load_tf_weights_in_realm",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/retrieval_realm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/retrieval_realm.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5e47abb11791aedccd5621677713136a037be8c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/retrieval_realm.py
@@ -0,0 +1,176 @@
+# coding=utf-8
+# Copyright 2022 The REALM authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""REALM Retriever model implementation."""
+
+import os
+from typing import Optional, Union
+
+import numpy as np
+from huggingface_hub import hf_hub_download
+
+from transformers import AutoTokenizer
+
+from ....utils import logging, strtobool
+
+
+_REALM_BLOCK_RECORDS_FILENAME = "block_records.npy"
+
+
+logger = logging.get_logger(__name__)
+
+
+def convert_tfrecord_to_np(block_records_path: str, num_block_records: int) -> np.ndarray:
+ import tensorflow.compat.v1 as tf
+
+ blocks_dataset = tf.data.TFRecordDataset(block_records_path, buffer_size=512 * 1024 * 1024)
+ blocks_dataset = blocks_dataset.batch(num_block_records, drop_remainder=True)
+ np_record = next(blocks_dataset.take(1).as_numpy_iterator())
+
+ return np_record
+
+
+class ScaNNSearcher:
+ """Note that ScaNNSearcher cannot currently be used within the model. In future versions, it might however be included."""
+
+ def __init__(
+ self,
+ db,
+ num_neighbors,
+ dimensions_per_block=2,
+ num_leaves=1000,
+ num_leaves_to_search=100,
+ training_sample_size=100000,
+ ):
+ """Build scann searcher."""
+
+ from scann.scann_ops.py.scann_ops_pybind import builder as Builder
+
+ builder = Builder(db=db, num_neighbors=num_neighbors, distance_measure="dot_product")
+ builder = builder.tree(
+ num_leaves=num_leaves, num_leaves_to_search=num_leaves_to_search, training_sample_size=training_sample_size
+ )
+ builder = builder.score_ah(dimensions_per_block=dimensions_per_block)
+
+ self.searcher = builder.build()
+
+ def search_batched(self, question_projection):
+ retrieved_block_ids, _ = self.searcher.search_batched(question_projection.detach().cpu())
+ return retrieved_block_ids.astype("int64")
+
+
+class RealmRetriever:
+ """The retriever of REALM outputting the retrieved evidence block and whether the block has answers as well as answer
+ positions."
+
+ Parameters:
+ block_records (`np.ndarray`):
+ A numpy array which contains evidence texts.
+ tokenizer ([`RealmTokenizer`]):
+ The tokenizer to encode retrieved texts.
+ """
+
+ def __init__(self, block_records, tokenizer):
+ super().__init__()
+ self.block_records = block_records
+ self.tokenizer = tokenizer
+
+ def __call__(self, retrieved_block_ids, question_input_ids, answer_ids, max_length=None, return_tensors="pt"):
+ retrieved_blocks = np.take(self.block_records, indices=retrieved_block_ids, axis=0)
+
+ question = self.tokenizer.decode(question_input_ids[0], skip_special_tokens=True)
+
+ text = []
+ text_pair = []
+ for retrieved_block in retrieved_blocks:
+ text.append(question)
+ text_pair.append(retrieved_block.decode())
+
+ concat_inputs = self.tokenizer(
+ text, text_pair, padding=True, truncation=True, return_special_tokens_mask=True, max_length=max_length
+ )
+ concat_inputs_tensors = concat_inputs.convert_to_tensors(return_tensors)
+
+ if answer_ids is not None:
+ return self.block_has_answer(concat_inputs, answer_ids) + (concat_inputs_tensors,)
+ else:
+ return (None, None, None, concat_inputs_tensors)
+
+ @classmethod
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], *init_inputs, **kwargs):
+ if os.path.isdir(pretrained_model_name_or_path):
+ block_records_path = os.path.join(pretrained_model_name_or_path, _REALM_BLOCK_RECORDS_FILENAME)
+ else:
+ block_records_path = hf_hub_download(
+ repo_id=pretrained_model_name_or_path, filename=_REALM_BLOCK_RECORDS_FILENAME, **kwargs
+ )
+ if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
+ raise ValueError(
+ "This part uses `pickle.load` which is insecure and will execute arbitrary code that is "
+ "potentially malicious. It's recommended to never unpickle data that could have come from an "
+ "untrusted source, or that could have been tampered with. If you already verified the pickle "
+ "data and decided to use it, you can set the environment variable "
+ "`TRUST_REMOTE_CODE` to `True` to allow it."
+ )
+ block_records = np.load(block_records_path, allow_pickle=True)
+
+ tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name_or_path, *init_inputs, **kwargs)
+
+ return cls(block_records, tokenizer)
+
+ def save_pretrained(self, save_directory):
+ # save block records
+ np.save(os.path.join(save_directory, _REALM_BLOCK_RECORDS_FILENAME), self.block_records)
+ # save tokenizer
+ self.tokenizer.save_pretrained(save_directory)
+
+ def block_has_answer(self, concat_inputs, answer_ids):
+ """check if retrieved_blocks has answers."""
+ has_answers = []
+ start_pos = []
+ end_pos = []
+ max_answers = 0
+
+ for input_id in concat_inputs.input_ids:
+ input_id_list = input_id.tolist()
+ # Check answers between two [SEP] tokens
+ first_sep_idx = input_id_list.index(self.tokenizer.sep_token_id)
+ second_sep_idx = first_sep_idx + 1 + input_id_list[first_sep_idx + 1 :].index(self.tokenizer.sep_token_id)
+
+ start_pos.append([])
+ end_pos.append([])
+ for answer in answer_ids:
+ for idx in range(first_sep_idx + 1, second_sep_idx):
+ if answer[0] == input_id_list[idx]:
+ if input_id_list[idx : idx + len(answer)] == answer:
+ start_pos[-1].append(idx)
+ end_pos[-1].append(idx + len(answer) - 1)
+
+ if len(start_pos[-1]) == 0:
+ has_answers.append(False)
+ else:
+ has_answers.append(True)
+ if len(start_pos[-1]) > max_answers:
+ max_answers = len(start_pos[-1])
+
+ # Pad -1 to max_answers
+ for start_pos_, end_pos_ in zip(start_pos, end_pos):
+ if len(start_pos_) < max_answers:
+ padded = [-1] * (max_answers - len(start_pos_))
+ start_pos_ += padded
+ end_pos_ += padded
+ return has_answers, start_pos, end_pos
+
+
+__all__ = ["RealmRetriever"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/tokenization_realm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/tokenization_realm.py
new file mode 100644
index 0000000000000000000000000000000000000000..af7cdc1a5bac3afea8ed0651ae2892adcc03cbc3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/tokenization_realm.py
@@ -0,0 +1,534 @@
+# coding=utf-8
+# Copyright 2022 The REALM authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for REALM."""
+
+import collections
+import os
+import unicodedata
+from typing import Optional
+
+from ....tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
+from ....tokenization_utils_base import BatchEncoding
+from ....utils import PaddingStrategy, logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
+
+
+def load_vocab(vocab_file):
+ """Loads a vocabulary file into a dictionary."""
+ vocab = collections.OrderedDict()
+ with open(vocab_file, "r", encoding="utf-8") as reader:
+ tokens = reader.readlines()
+ for index, token in enumerate(tokens):
+ token = token.rstrip("\n")
+ vocab[token] = index
+ return vocab
+
+
+def whitespace_tokenize(text):
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
+ text = text.strip()
+ if not text:
+ return []
+ tokens = text.split()
+ return tokens
+
+
+class RealmTokenizer(PreTrainedTokenizer):
+ r"""
+ Construct a REALM tokenizer.
+
+ [`RealmTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation splitting and
+ wordpiece.
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ File containing the vocabulary.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
+ Whether or not to do basic tokenization before WordPiece.
+ never_split (`Iterable`, *optional*):
+ Collection of tokens which will never be split during tokenization. Only has an effect when
+ `do_basic_tokenize=True`
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters.
+
+ This should likely be deactivated for Japanese (see this
+ [issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+
+ def __init__(
+ self,
+ vocab_file,
+ do_lower_case=True,
+ do_basic_tokenize=True,
+ never_split=None,
+ unk_token="[UNK]",
+ sep_token="[SEP]",
+ pad_token="[PAD]",
+ cls_token="[CLS]",
+ mask_token="[MASK]",
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ **kwargs,
+ ):
+ if not os.path.isfile(vocab_file):
+ raise ValueError(
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
+ " model use `tokenizer = RealmTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
+ )
+ self.vocab = load_vocab(vocab_file)
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
+ self.do_basic_tokenize = do_basic_tokenize
+ if do_basic_tokenize:
+ self.basic_tokenizer = BasicTokenizer(
+ do_lower_case=do_lower_case,
+ never_split=never_split,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ )
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
+ super().__init__(
+ do_lower_case=do_lower_case,
+ do_basic_tokenize=do_basic_tokenize,
+ never_split=never_split,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ **kwargs,
+ )
+
+ @property
+ def do_lower_case(self):
+ return self.basic_tokenizer.do_lower_case
+
+ @property
+ def vocab_size(self):
+ return len(self.vocab)
+
+ def get_vocab(self):
+ return dict(self.vocab, **self.added_tokens_encoder)
+
+ def _tokenize(self, text):
+ split_tokens = []
+ if self.do_basic_tokenize:
+ for token in self.basic_tokenizer.tokenize(text, never_split=self.all_special_tokens):
+ # If the token is part of the never_split set
+ if token in self.basic_tokenizer.never_split:
+ split_tokens.append(token)
+ else:
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
+ else:
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
+ return split_tokens
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.ids_to_tokens.get(index, self.unk_token)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ out_string = " ".join(tokens).replace(" ##", "").strip()
+ return out_string
+
+ def batch_encode_candidates(self, text, **kwargs):
+ r"""
+ Encode a batch of text or text pair. This method is similar to regular __call__ method but has the following
+ differences:
+
+ 1. Handle additional num_candidate axis. (batch_size, num_candidates, text)
+ 2. Always pad the sequences to *max_length*.
+ 3. Must specify *max_length* in order to stack packs of candidates into a batch.
+
+ - single sequence: `[CLS] X [SEP]`
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
+
+ Args:
+ text (`List[List[str]]`):
+ The batch of sequences to be encoded. Each sequence must be in this format: (batch_size,
+ num_candidates, text).
+ text_pair (`List[List[str]]`, *optional*):
+ The batch of sequences to be encoded. Each sequence must be in this format: (batch_size,
+ num_candidates, text).
+ **kwargs:
+ Keyword arguments of the __call__ method.
+
+ Returns:
+ [`BatchEncoding`]: Encoded text or text pair.
+
+ Example:
+
+ ```python
+ >>> from transformers import RealmTokenizer
+
+ >>> # batch_size = 2, num_candidates = 2
+ >>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]
+
+ >>> tokenizer = RealmTokenizer.from_pretrained("google/realm-cc-news-pretrained-encoder")
+ >>> tokenized_text = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt")
+ ```"""
+
+ # Always using a fixed sequence length to encode in order to stack candidates into a batch.
+ kwargs["padding"] = PaddingStrategy.MAX_LENGTH
+
+ batch_text = text
+ batch_text_pair = kwargs.pop("text_pair", None)
+ return_tensors = kwargs.pop("return_tensors", None)
+
+ output_data = {
+ "input_ids": [],
+ "attention_mask": [],
+ "token_type_ids": [],
+ }
+
+ for idx, candidate_text in enumerate(batch_text):
+ if batch_text_pair is not None:
+ candidate_text_pair = batch_text_pair[idx]
+ else:
+ candidate_text_pair = None
+
+ encoded_candidates = super().__call__(candidate_text, candidate_text_pair, return_tensors=None, **kwargs)
+
+ encoded_input_ids = encoded_candidates.get("input_ids")
+ encoded_attention_mask = encoded_candidates.get("attention_mask")
+ encoded_token_type_ids = encoded_candidates.get("token_type_ids")
+
+ if encoded_input_ids is not None:
+ output_data["input_ids"].append(encoded_input_ids)
+ if encoded_attention_mask is not None:
+ output_data["attention_mask"].append(encoded_attention_mask)
+ if encoded_token_type_ids is not None:
+ output_data["token_type_ids"].append(encoded_token_type_ids)
+
+ output_data = {key: item for key, item in output_data.items() if len(item) != 0}
+
+ return BatchEncoding(output_data, tensor_type=return_tensors)
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A REALM sequence has the following format:
+
+ - single sequence: `[CLS] X [SEP]`
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ if token_ids_1 is None:
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
+ cls = [self.cls_token_id]
+ sep = [self.sep_token_id]
+ return cls + token_ids_0 + sep + token_ids_1 + sep
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is not None:
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
+ return [1] + ([0] * len(token_ids_0)) + [1]
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ index = 0
+ if os.path.isdir(save_directory):
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ else:
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
+ with open(vocab_file, "w", encoding="utf-8") as writer:
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
+ " Please check that the vocabulary is not corrupted!"
+ )
+ index = token_index
+ writer.write(token + "\n")
+ index += 1
+ return (vocab_file,)
+
+
+class BasicTokenizer:
+ """
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
+
+ Args:
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ never_split (`Iterable`, *optional*):
+ Collection of tokens which will never be split during tokenization. Only has an effect when
+ `do_basic_tokenize=True`
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters.
+
+ This should likely be deactivated for Japanese (see this
+ [issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ """
+
+ def __init__(self, do_lower_case=True, never_split=None, tokenize_chinese_chars=True, strip_accents=None):
+ if never_split is None:
+ never_split = []
+ self.do_lower_case = do_lower_case
+ self.never_split = set(never_split)
+ self.tokenize_chinese_chars = tokenize_chinese_chars
+ self.strip_accents = strip_accents
+
+ def tokenize(self, text, never_split=None):
+ """
+ Basic Tokenization of a piece of text. Split on "white spaces" only, for sub-word tokenization, see
+ WordPieceTokenizer.
+
+ Args:
+ never_split (`List[str]`, *optional*)
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
+ """
+ # union() returns a new set by concatenating the two sets.
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
+ text = self._clean_text(text)
+
+ # This was added on November 1st, 2018 for the multilingual and Chinese
+ # models. This is also applied to the English models now, but it doesn't
+ # matter since the English models were not trained on any Chinese data
+ # and generally don't have any Chinese data in them (there are Chinese
+ # characters in the vocabulary because Wikipedia does have some Chinese
+ # words in the English Wikipedia.).
+ if self.tokenize_chinese_chars:
+ text = self._tokenize_chinese_chars(text)
+ orig_tokens = whitespace_tokenize(text)
+ split_tokens = []
+ for token in orig_tokens:
+ if token not in never_split:
+ if self.do_lower_case:
+ token = token.lower()
+ if self.strip_accents is not False:
+ token = self._run_strip_accents(token)
+ elif self.strip_accents:
+ token = self._run_strip_accents(token)
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
+
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
+ return output_tokens
+
+ def _run_strip_accents(self, text):
+ """Strips accents from a piece of text."""
+ text = unicodedata.normalize("NFD", text)
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat == "Mn":
+ continue
+ output.append(char)
+ return "".join(output)
+
+ def _run_split_on_punc(self, text, never_split=None):
+ """Splits punctuation on a piece of text."""
+ if never_split is not None and text in never_split:
+ return [text]
+ chars = list(text)
+ i = 0
+ start_new_word = True
+ output = []
+ while i < len(chars):
+ char = chars[i]
+ if _is_punctuation(char):
+ output.append([char])
+ start_new_word = True
+ else:
+ if start_new_word:
+ output.append([])
+ start_new_word = False
+ output[-1].append(char)
+ i += 1
+
+ return ["".join(x) for x in output]
+
+ def _tokenize_chinese_chars(self, text):
+ """Adds whitespace around any CJK character."""
+ output = []
+ for char in text:
+ cp = ord(char)
+ if self._is_chinese_char(cp):
+ output.append(" ")
+ output.append(char)
+ output.append(" ")
+ else:
+ output.append(char)
+ return "".join(output)
+
+ def _is_chinese_char(self, cp):
+ """Checks whether CP is the codepoint of a CJK character."""
+ # This defines a "chinese character" as anything in the CJK Unicode block:
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
+ #
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
+ # despite its name. The modern Korean Hangul alphabet is a different block,
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
+ # space-separated words, so they are not treated specially and handled
+ # like the all of the other languages.
+ if (
+ (cp >= 0x4E00 and cp <= 0x9FFF)
+ or (cp >= 0x3400 and cp <= 0x4DBF)
+ or (cp >= 0x20000 and cp <= 0x2A6DF)
+ or (cp >= 0x2A700 and cp <= 0x2B73F)
+ or (cp >= 0x2B740 and cp <= 0x2B81F)
+ or (cp >= 0x2B820 and cp <= 0x2CEAF)
+ or (cp >= 0xF900 and cp <= 0xFAFF)
+ or (cp >= 0x2F800 and cp <= 0x2FA1F)
+ ):
+ return True
+
+ return False
+
+ def _clean_text(self, text):
+ """Performs invalid character removal and whitespace cleanup on text."""
+ output = []
+ for char in text:
+ cp = ord(char)
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
+ continue
+ if _is_whitespace(char):
+ output.append(" ")
+ else:
+ output.append(char)
+ return "".join(output)
+
+
+class WordpieceTokenizer:
+ """Runs WordPiece tokenization."""
+
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
+ self.vocab = vocab
+ self.unk_token = unk_token
+ self.max_input_chars_per_word = max_input_chars_per_word
+
+ def tokenize(self, text):
+ """
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
+ tokenization using the given vocabulary.
+
+ For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
+
+ Args:
+ text: A single token or whitespace separated tokens. This should have
+ already been passed through *BasicTokenizer*.
+
+ Returns:
+ A list of wordpiece tokens.
+ """
+
+ output_tokens = []
+ for token in whitespace_tokenize(text):
+ chars = list(token)
+ if len(chars) > self.max_input_chars_per_word:
+ output_tokens.append(self.unk_token)
+ continue
+
+ is_bad = False
+ start = 0
+ sub_tokens = []
+ while start < len(chars):
+ end = len(chars)
+ cur_substr = None
+ while start < end:
+ substr = "".join(chars[start:end])
+ if start > 0:
+ substr = "##" + substr
+ if substr in self.vocab:
+ cur_substr = substr
+ break
+ end -= 1
+ if cur_substr is None:
+ is_bad = True
+ break
+ sub_tokens.append(cur_substr)
+ start = end
+
+ if is_bad:
+ output_tokens.append(self.unk_token)
+ else:
+ output_tokens.extend(sub_tokens)
+ return output_tokens
+
+
+__all__ = ["RealmTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/tokenization_realm_fast.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/tokenization_realm_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..53a1d99e0ac804ae196e9c65f0e2979dcb2401c8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/realm/tokenization_realm_fast.py
@@ -0,0 +1,223 @@
+# coding=utf-8
+# Copyright 2022 The REALM authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Fast Tokenization classes for REALM."""
+
+import json
+from typing import Optional
+
+from tokenizers import normalizers
+
+from ....tokenization_utils_base import BatchEncoding
+from ....tokenization_utils_fast import PreTrainedTokenizerFast
+from ....utils import PaddingStrategy, logging
+from .tokenization_realm import RealmTokenizer
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
+
+
+class RealmTokenizerFast(PreTrainedTokenizerFast):
+ r"""
+ Construct a "fast" REALM tokenizer (backed by HuggingFace's *tokenizers* library). Based on WordPiece.
+
+ [`RealmTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization: punctuation
+ splitting and wordpiece.
+
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ File containing the vocabulary.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ clean_text (`bool`, *optional*, defaults to `True`):
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
+ whitespaces by the classic one.
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
+ issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
+ The prefix for subwords.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ slow_tokenizer_class = RealmTokenizer
+
+ def __init__(
+ self,
+ vocab_file=None,
+ tokenizer_file=None,
+ do_lower_case=True,
+ unk_token="[UNK]",
+ sep_token="[SEP]",
+ pad_token="[PAD]",
+ cls_token="[CLS]",
+ mask_token="[MASK]",
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ **kwargs,
+ ):
+ super().__init__(
+ vocab_file,
+ tokenizer_file=tokenizer_file,
+ do_lower_case=do_lower_case,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ **kwargs,
+ )
+
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
+ if (
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
+ ):
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
+ normalizer_state["lowercase"] = do_lower_case
+ normalizer_state["strip_accents"] = strip_accents
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
+
+ self.do_lower_case = do_lower_case
+
+ def batch_encode_candidates(self, text, **kwargs):
+ r"""
+ Encode a batch of text or text pair. This method is similar to regular __call__ method but has the following
+ differences:
+
+ 1. Handle additional num_candidate axis. (batch_size, num_candidates, text)
+ 2. Always pad the sequences to *max_length*.
+ 3. Must specify *max_length* in order to stack packs of candidates into a batch.
+
+ - single sequence: `[CLS] X [SEP]`
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
+
+ Args:
+ text (`List[List[str]]`):
+ The batch of sequences to be encoded. Each sequence must be in this format: (batch_size,
+ num_candidates, text).
+ text_pair (`List[List[str]]`, *optional*):
+ The batch of sequences to be encoded. Each sequence must be in this format: (batch_size,
+ num_candidates, text).
+ **kwargs:
+ Keyword arguments of the __call__ method.
+
+ Returns:
+ [`BatchEncoding`]: Encoded text or text pair.
+
+ Example:
+
+ ```python
+ >>> from transformers import RealmTokenizerFast
+
+ >>> # batch_size = 2, num_candidates = 2
+ >>> text = [["Hello world!", "Nice to meet you!"], ["The cute cat.", "The adorable dog."]]
+
+ >>> tokenizer = RealmTokenizerFast.from_pretrained("google/realm-cc-news-pretrained-encoder")
+ >>> tokenized_text = tokenizer.batch_encode_candidates(text, max_length=10, return_tensors="pt")
+ ```"""
+
+ # Always using a fixed sequence length to encode in order to stack candidates into a batch.
+ kwargs["padding"] = PaddingStrategy.MAX_LENGTH
+
+ batch_text = text
+ batch_text_pair = kwargs.pop("text_pair", None)
+ return_tensors = kwargs.pop("return_tensors", None)
+
+ output_data = {
+ "input_ids": [],
+ "attention_mask": [],
+ "token_type_ids": [],
+ }
+
+ for idx, candidate_text in enumerate(batch_text):
+ if batch_text_pair is not None:
+ candidate_text_pair = batch_text_pair[idx]
+ else:
+ candidate_text_pair = None
+
+ encoded_candidates = super().__call__(candidate_text, candidate_text_pair, return_tensors=None, **kwargs)
+
+ encoded_input_ids = encoded_candidates.get("input_ids")
+ encoded_attention_mask = encoded_candidates.get("attention_mask")
+ encoded_token_type_ids = encoded_candidates.get("token_type_ids")
+
+ if encoded_input_ids is not None:
+ output_data["input_ids"].append(encoded_input_ids)
+ if encoded_attention_mask is not None:
+ output_data["attention_mask"].append(encoded_attention_mask)
+ if encoded_token_type_ids is not None:
+ output_data["token_type_ids"].append(encoded_token_type_ids)
+
+ output_data = {key: item for key, item in output_data.items() if len(item) != 0}
+
+ return BatchEncoding(output_data, tensor_type=return_tensors)
+
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A REALM sequence has the following format:
+
+ - single sequence: `[CLS] X [SEP]`
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
+
+ if token_ids_1 is not None:
+ output += token_ids_1 + [self.sep_token_id]
+
+ return output
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
+ return tuple(files)
+
+
+__all__ = ["RealmTokenizerFast"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a875576607430c041abab01eccaf468a6cc9272e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_retribert import *
+ from .modeling_retribert import *
+ from .tokenization_retribert import *
+ from .tokenization_retribert_fast import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..28256ce16af256ccc9bdc9538226624758c375b5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/configuration_retribert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/configuration_retribert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d4604f78ce36b75e79f0721a9ea02520e6cde687
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/configuration_retribert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/modeling_retribert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/modeling_retribert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..97c68c210f5c29652a8d42f4732e51d45e6a99ac
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/modeling_retribert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/tokenization_retribert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/tokenization_retribert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ec7695e97663d25aa56f233a3f000f10ebbd2f7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/tokenization_retribert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/tokenization_retribert_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/tokenization_retribert_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43317d12d2fd1f67710fc822b170e749288b027d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/__pycache__/tokenization_retribert_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/configuration_retribert.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/configuration_retribert.py
new file mode 100644
index 0000000000000000000000000000000000000000..80d755a16961450cae783d834385e5e6873dc24e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/configuration_retribert.py
@@ -0,0 +1,108 @@
+# coding=utf-8
+# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""RetriBERT model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class RetriBertConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`RetriBertModel`]. It is used to instantiate a
+ RetriBertModel model according to the specified arguments, defining the model architecture. Instantiating a
+ configuration with the defaults will yield a similar configuration to that of the RetriBERT
+ [yjernite/retribert-base-uncased](https://huggingface.co/yjernite/retribert-base-uncased) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 30522):
+ Vocabulary size of the RetriBERT model. Defines the number of different tokens that can be represented by
+ the `inputs_ids` passed when calling [`RetriBertModel`]
+ hidden_size (`int`, *optional*, defaults to 768):
+ Dimensionality of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 3072):
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention probabilities.
+ max_position_embeddings (`int`, *optional*, defaults to 512):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ type_vocab_size (`int`, *optional*, defaults to 2):
+ The vocabulary size of the *token_type_ids* passed into [`BertModel`].
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ share_encoders (`bool`, *optional*, defaults to `True`):
+ Whether or not to use the same Bert-type encoder for the queries and document
+ projection_dim (`int`, *optional*, defaults to 128):
+ Final dimension of the query and document representation after projection
+ """
+
+ model_type = "retribert"
+
+ def __init__(
+ self,
+ vocab_size=30522,
+ hidden_size=768,
+ num_hidden_layers=8,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=512,
+ type_vocab_size=2,
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ share_encoders=True,
+ projection_dim=128,
+ pad_token_id=0,
+ **kwargs,
+ ):
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
+
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.hidden_act = hidden_act
+ self.intermediate_size = intermediate_size
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.max_position_embeddings = max_position_embeddings
+ self.type_vocab_size = type_vocab_size
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.share_encoders = share_encoders
+ self.projection_dim = projection_dim
+
+
+__all__ = ["RetriBertConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/modeling_retribert.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/modeling_retribert.py
new file mode 100644
index 0000000000000000000000000000000000000000..06806e8e6d0bb01fa31c6849ccb23f3e29bf74aa
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/modeling_retribert.py
@@ -0,0 +1,217 @@
+# coding=utf-8
+# Copyright 2019-present, the HuggingFace Inc. team, The Google AI Language Team and Facebook, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+RetriBERT model
+"""
+
+import math
+from typing import Optional
+
+import torch
+import torch.utils.checkpoint as checkpoint
+from torch import nn
+
+from ....modeling_utils import PreTrainedModel
+from ....utils import add_start_docstrings, logging
+from ...bert.modeling_bert import BertModel
+from .configuration_retribert import RetriBertConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
+class RetriBertPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: RetriBertConfig
+ load_tf_weights = None
+ base_model_prefix = "retribert"
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+RETRIBERT_START_DOCSTRING = r"""
+
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`RetriBertConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+
+@add_start_docstrings(
+ """Bert Based model to embed queries or document for document retrieval.""",
+ RETRIBERT_START_DOCSTRING,
+)
+class RetriBertModel(RetriBertPreTrainedModel):
+ def __init__(self, config: RetriBertConfig) -> None:
+ super().__init__(config)
+ self.projection_dim = config.projection_dim
+
+ self.bert_query = BertModel(config)
+ self.bert_doc = None if config.share_encoders else BertModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.project_query = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
+ self.project_doc = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
+
+ self.ce_loss = nn.CrossEntropyLoss(reduction="mean")
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def embed_sentences_checkpointed(
+ self,
+ input_ids,
+ attention_mask,
+ sent_encoder,
+ checkpoint_batch_size=-1,
+ ):
+ # reproduces BERT forward pass with checkpointing
+ if checkpoint_batch_size < 0 or input_ids.shape[0] < checkpoint_batch_size:
+ return sent_encoder(input_ids, attention_mask=attention_mask)[1]
+ else:
+ # prepare implicit variables
+ device = input_ids.device
+ input_shape = input_ids.size()
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+ head_mask = [None] * sent_encoder.config.num_hidden_layers
+ extended_attention_mask: torch.Tensor = sent_encoder.get_extended_attention_mask(
+ attention_mask, input_shape
+ )
+
+ # define function for checkpointing
+ def partial_encode(*inputs):
+ encoder_outputs = sent_encoder.encoder(
+ inputs[0],
+ attention_mask=inputs[1],
+ head_mask=head_mask,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = sent_encoder.pooler(sequence_output)
+ return pooled_output
+
+ # run embedding layer on everything at once
+ embedding_output = sent_encoder.embeddings(
+ input_ids=input_ids, position_ids=None, token_type_ids=token_type_ids, inputs_embeds=None
+ )
+ # run encoding and pooling on one mini-batch at a time
+ pooled_output_list = []
+ for b in range(math.ceil(input_ids.shape[0] / checkpoint_batch_size)):
+ b_embedding_output = embedding_output[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
+ b_attention_mask = extended_attention_mask[b * checkpoint_batch_size : (b + 1) * checkpoint_batch_size]
+ pooled_output = checkpoint.checkpoint(partial_encode, b_embedding_output, b_attention_mask)
+ pooled_output_list.append(pooled_output)
+ return torch.cat(pooled_output_list, dim=0)
+
+ def embed_questions(
+ self,
+ input_ids,
+ attention_mask=None,
+ checkpoint_batch_size=-1,
+ ):
+ q_reps = self.embed_sentences_checkpointed(
+ input_ids,
+ attention_mask,
+ self.bert_query,
+ checkpoint_batch_size,
+ )
+ return self.project_query(q_reps)
+
+ def embed_answers(
+ self,
+ input_ids,
+ attention_mask=None,
+ checkpoint_batch_size=-1,
+ ):
+ a_reps = self.embed_sentences_checkpointed(
+ input_ids,
+ attention_mask,
+ self.bert_query if self.bert_doc is None else self.bert_doc,
+ checkpoint_batch_size,
+ )
+ return self.project_doc(a_reps)
+
+ def forward(
+ self,
+ input_ids_query: torch.LongTensor,
+ attention_mask_query: Optional[torch.FloatTensor],
+ input_ids_doc: torch.LongTensor,
+ attention_mask_doc: Optional[torch.FloatTensor],
+ checkpoint_batch_size: int = -1,
+ ) -> torch.FloatTensor:
+ r"""
+ Args:
+ input_ids_query (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary for the queries in a batch.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask_query (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ input_ids_doc (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary for the documents in a batch.
+ attention_mask_doc (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on documents padding token indices.
+ checkpoint_batch_size (`int`, *optional*, defaults to `-1`):
+ If greater than 0, uses gradient checkpointing to only compute sequence representation on
+ `checkpoint_batch_size` examples at a time on the GPU. All query representations are still compared to
+ all document representations in the batch.
+
+ Return:
+ `torch.FloatTensor``: The bidirectional cross-entropy loss obtained while trying to match each query to its
+ corresponding document and each document to its corresponding query in the batch
+ """
+ device = input_ids_query.device
+ q_reps = self.embed_questions(input_ids_query, attention_mask_query, checkpoint_batch_size)
+ a_reps = self.embed_answers(input_ids_doc, attention_mask_doc, checkpoint_batch_size)
+ compare_scores = torch.mm(q_reps, a_reps.t())
+ loss_qa = self.ce_loss(compare_scores, torch.arange(compare_scores.shape[1]).to(device))
+ loss_aq = self.ce_loss(compare_scores.t(), torch.arange(compare_scores.shape[0]).to(device))
+ loss = (loss_qa + loss_aq) / 2
+ return loss
+
+
+__all__ = ["RetriBertModel", "RetriBertPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/tokenization_retribert.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/tokenization_retribert.py
new file mode 100644
index 0000000000000000000000000000000000000000..288b46e267bccb358fa86e74ac2b98dcb99e8904
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/tokenization_retribert.py
@@ -0,0 +1,475 @@
+# coding=utf-8
+# Copyright 2018 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for RetriBERT."""
+
+import collections
+import os
+import unicodedata
+from typing import Optional
+
+from ....tokenization_utils import PreTrainedTokenizer, _is_control, _is_punctuation, _is_whitespace
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt"}
+
+
+def load_vocab(vocab_file):
+ """Loads a vocabulary file into a dictionary."""
+ vocab = collections.OrderedDict()
+ with open(vocab_file, "r", encoding="utf-8") as reader:
+ tokens = reader.readlines()
+ for index, token in enumerate(tokens):
+ token = token.rstrip("\n")
+ vocab[token] = index
+ return vocab
+
+
+def whitespace_tokenize(text):
+ """Runs basic whitespace cleaning and splitting on a piece of text."""
+ text = text.strip()
+ if not text:
+ return []
+ tokens = text.split()
+ return tokens
+
+
+class RetriBertTokenizer(PreTrainedTokenizer):
+ r"""
+ Constructs a RetriBERT tokenizer.
+
+ [`RetriBertTokenizer`] is identical to [`BertTokenizer`] and runs end-to-end tokenization: punctuation splitting
+ and wordpiece.
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer
+ to: this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ File containing the vocabulary.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ do_basic_tokenize (`bool`, *optional*, defaults to `True`):
+ Whether or not to do basic tokenization before WordPiece.
+ never_split (`Iterable`, *optional*):
+ Collection of tokens which will never be split during tokenization. Only has an effect when
+ `do_basic_tokenize=True`
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see this
+ [issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ vocab_file,
+ do_lower_case=True,
+ do_basic_tokenize=True,
+ never_split=None,
+ unk_token="[UNK]",
+ sep_token="[SEP]",
+ pad_token="[PAD]",
+ cls_token="[CLS]",
+ mask_token="[MASK]",
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ **kwargs,
+ ):
+ if not os.path.isfile(vocab_file):
+ raise ValueError(
+ f"Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained"
+ " model use `tokenizer = BertTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`"
+ )
+ self.vocab = load_vocab(vocab_file)
+ self.ids_to_tokens = collections.OrderedDict([(ids, tok) for tok, ids in self.vocab.items()])
+ self.do_basic_tokenize = do_basic_tokenize
+ if do_basic_tokenize:
+ self.basic_tokenizer = BasicTokenizer(
+ do_lower_case=do_lower_case,
+ never_split=never_split,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ )
+
+ self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab, unk_token=str(unk_token))
+
+ super().__init__(
+ do_lower_case=do_lower_case,
+ do_basic_tokenize=do_basic_tokenize,
+ never_split=never_split,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ **kwargs,
+ )
+
+ @property
+ def do_lower_case(self):
+ return self.basic_tokenizer.do_lower_case
+
+ @property
+ def vocab_size(self):
+ return len(self.vocab)
+
+ def get_vocab(self):
+ return dict(self.vocab, **self.added_tokens_encoder)
+
+ def _tokenize(self, text, split_special_tokens=False):
+ split_tokens = []
+ if self.do_basic_tokenize:
+ for token in self.basic_tokenizer.tokenize(
+ text, never_split=self.all_special_tokens if not split_special_tokens else None
+ ):
+ # If the token is part of the never_split set
+ if token in self.basic_tokenizer.never_split:
+ split_tokens.append(token)
+ else:
+ split_tokens += self.wordpiece_tokenizer.tokenize(token)
+ else:
+ split_tokens = self.wordpiece_tokenizer.tokenize(text)
+ return split_tokens
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.vocab.get(token, self.vocab.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.ids_to_tokens.get(index, self.unk_token)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ out_string = " ".join(tokens).replace(" ##", "").strip()
+ return out_string
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A BERT sequence has the following format:
+
+ - single sequence: `[CLS] X [SEP]`
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ if token_ids_1 is None:
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
+ cls = [self.cls_token_id]
+ sep = [self.sep_token_id]
+ return cls + token_ids_0 + sep + token_ids_1 + sep
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is not None:
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
+ return [1] + ([0] * len(token_ids_0)) + [1]
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ index = 0
+ if os.path.isdir(save_directory):
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ else:
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
+ with open(vocab_file, "w", encoding="utf-8") as writer:
+ for token, token_index in sorted(self.vocab.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive."
+ " Please check that the vocabulary is not corrupted!"
+ )
+ index = token_index
+ writer.write(token + "\n")
+ index += 1
+ return (vocab_file,)
+
+
+class BasicTokenizer:
+ """
+ Constructs a BasicTokenizer that will run basic tokenization (punctuation splitting, lower casing, etc.).
+
+ Args:
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ never_split (`Iterable`, *optional*):
+ Collection of tokens which will never be split during tokenization. Only has an effect when
+ `do_basic_tokenize=True`
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters.
+
+ This should likely be deactivated for Japanese (see this
+ [issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ do_split_on_punc (`bool`, *optional*, defaults to `True`):
+ In some instances we want to skip the basic punctuation splitting so that later tokenization can capture
+ the full context of the words, such as contractions.
+ """
+
+ def __init__(
+ self,
+ do_lower_case=True,
+ never_split=None,
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ do_split_on_punc=True,
+ ):
+ if never_split is None:
+ never_split = []
+ self.do_lower_case = do_lower_case
+ self.never_split = set(never_split)
+ self.tokenize_chinese_chars = tokenize_chinese_chars
+ self.strip_accents = strip_accents
+ self.do_split_on_punc = do_split_on_punc
+
+ def tokenize(self, text, never_split=None):
+ """
+ Basic Tokenization of a piece of text. For sub-word tokenization, see WordPieceTokenizer.
+
+ Args:
+ never_split (`List[str]`, *optional*)
+ Kept for backward compatibility purposes. Now implemented directly at the base class level (see
+ [`PreTrainedTokenizer.tokenize`]) List of token not to split.
+ """
+ # union() returns a new set by concatenating the two sets.
+ never_split = self.never_split.union(set(never_split)) if never_split else self.never_split
+ text = self._clean_text(text)
+
+ # This was added on November 1st, 2018 for the multilingual and Chinese
+ # models. This is also applied to the English models now, but it doesn't
+ # matter since the English models were not trained on any Chinese data
+ # and generally don't have any Chinese data in them (there are Chinese
+ # characters in the vocabulary because Wikipedia does have some Chinese
+ # words in the English Wikipedia.).
+ if self.tokenize_chinese_chars:
+ text = self._tokenize_chinese_chars(text)
+ # prevents treating the same character with different unicode codepoints as different characters
+ unicode_normalized_text = unicodedata.normalize("NFC", text)
+ orig_tokens = whitespace_tokenize(unicode_normalized_text)
+ split_tokens = []
+ for token in orig_tokens:
+ if token not in never_split:
+ if self.do_lower_case:
+ token = token.lower()
+ if self.strip_accents is not False:
+ token = self._run_strip_accents(token)
+ elif self.strip_accents:
+ token = self._run_strip_accents(token)
+ split_tokens.extend(self._run_split_on_punc(token, never_split))
+
+ output_tokens = whitespace_tokenize(" ".join(split_tokens))
+ return output_tokens
+
+ def _run_strip_accents(self, text):
+ """Strips accents from a piece of text."""
+ text = unicodedata.normalize("NFD", text)
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat == "Mn":
+ continue
+ output.append(char)
+ return "".join(output)
+
+ def _run_split_on_punc(self, text, never_split=None):
+ """Splits punctuation on a piece of text."""
+ if not self.do_split_on_punc or (never_split is not None and text in never_split):
+ return [text]
+ chars = list(text)
+ i = 0
+ start_new_word = True
+ output = []
+ while i < len(chars):
+ char = chars[i]
+ if _is_punctuation(char):
+ output.append([char])
+ start_new_word = True
+ else:
+ if start_new_word:
+ output.append([])
+ start_new_word = False
+ output[-1].append(char)
+ i += 1
+
+ return ["".join(x) for x in output]
+
+ def _tokenize_chinese_chars(self, text):
+ """Adds whitespace around any CJK character."""
+ output = []
+ for char in text:
+ cp = ord(char)
+ if self._is_chinese_char(cp):
+ output.append(" ")
+ output.append(char)
+ output.append(" ")
+ else:
+ output.append(char)
+ return "".join(output)
+
+ def _is_chinese_char(self, cp):
+ """Checks whether CP is the codepoint of a CJK character."""
+ # This defines a "chinese character" as anything in the CJK Unicode block:
+ # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
+ #
+ # Note that the CJK Unicode block is NOT all Japanese and Korean characters,
+ # despite its name. The modern Korean Hangul alphabet is a different block,
+ # as is Japanese Hiragana and Katakana. Those alphabets are used to write
+ # space-separated words, so they are not treated specially and handled
+ # like the all of the other languages.
+ if (
+ (cp >= 0x4E00 and cp <= 0x9FFF)
+ or (cp >= 0x3400 and cp <= 0x4DBF)
+ or (cp >= 0x20000 and cp <= 0x2A6DF)
+ or (cp >= 0x2A700 and cp <= 0x2B73F)
+ or (cp >= 0x2B740 and cp <= 0x2B81F)
+ or (cp >= 0x2B820 and cp <= 0x2CEAF)
+ or (cp >= 0xF900 and cp <= 0xFAFF)
+ or (cp >= 0x2F800 and cp <= 0x2FA1F)
+ ):
+ return True
+
+ return False
+
+ def _clean_text(self, text):
+ """Performs invalid character removal and whitespace cleanup on text."""
+ output = []
+ for char in text:
+ cp = ord(char)
+ if cp == 0 or cp == 0xFFFD or _is_control(char):
+ continue
+ if _is_whitespace(char):
+ output.append(" ")
+ else:
+ output.append(char)
+ return "".join(output)
+
+
+class WordpieceTokenizer:
+ """Runs WordPiece tokenization."""
+
+ def __init__(self, vocab, unk_token, max_input_chars_per_word=100):
+ self.vocab = vocab
+ self.unk_token = unk_token
+ self.max_input_chars_per_word = max_input_chars_per_word
+
+ def tokenize(self, text):
+ """
+ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform
+ tokenization using the given vocabulary.
+
+ For example, `input = "unaffable"` will return as output `["un", "##aff", "##able"]`.
+
+ Args:
+ text: A single token or whitespace separated tokens. This should have
+ already been passed through *BasicTokenizer*.
+
+ Returns:
+ A list of wordpiece tokens.
+ """
+
+ output_tokens = []
+ for token in whitespace_tokenize(text):
+ chars = list(token)
+ if len(chars) > self.max_input_chars_per_word:
+ output_tokens.append(self.unk_token)
+ continue
+
+ is_bad = False
+ start = 0
+ sub_tokens = []
+ while start < len(chars):
+ end = len(chars)
+ cur_substr = None
+ while start < end:
+ substr = "".join(chars[start:end])
+ if start > 0:
+ substr = "##" + substr
+ if substr in self.vocab:
+ cur_substr = substr
+ break
+ end -= 1
+ if cur_substr is None:
+ is_bad = True
+ break
+ sub_tokens.append(cur_substr)
+ start = end
+
+ if is_bad:
+ output_tokens.append(self.unk_token)
+ else:
+ output_tokens.extend(sub_tokens)
+ return output_tokens
+
+
+__all__ = ["RetriBertTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/tokenization_retribert_fast.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/tokenization_retribert_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fcbc395a1b7ba7f659a9befae14c8ba658c27d0
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/retribert/tokenization_retribert_fast.py
@@ -0,0 +1,150 @@
+# coding=utf-8
+# Copyright 2018 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for RetriBERT."""
+
+import json
+from typing import Optional
+
+from tokenizers import normalizers
+
+from ....tokenization_utils_fast import PreTrainedTokenizerFast
+from ....utils import logging
+from .tokenization_retribert import RetriBertTokenizer
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
+
+
+class RetriBertTokenizerFast(PreTrainedTokenizerFast):
+ r"""
+ Construct a "fast" RetriBERT tokenizer (backed by HuggingFace's *tokenizers* library).
+
+ [`RetriBertTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization: punctuation
+ splitting and wordpiece.
+
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ File containing the vocabulary.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ clean_text (`bool`, *optional*, defaults to `True`):
+ Whether or not to clean the text before tokenization by removing any control characters and replacing all
+ whitespaces by the classic one.
+ tokenize_chinese_chars (`bool`, *optional*, defaults to `True`):
+ Whether or not to tokenize Chinese characters. This should likely be deactivated for Japanese (see [this
+ issue](https://github.com/huggingface/transformers/issues/328)).
+ strip_accents (`bool`, *optional*):
+ Whether or not to strip all accents. If this option is not specified, then it will be determined by the
+ value for `lowercase` (as in the original BERT).
+ wordpieces_prefix (`str`, *optional*, defaults to `"##"`):
+ The prefix for subwords.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ slow_tokenizer_class = RetriBertTokenizer
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ vocab_file=None,
+ tokenizer_file=None,
+ do_lower_case=True,
+ unk_token="[UNK]",
+ sep_token="[SEP]",
+ pad_token="[PAD]",
+ cls_token="[CLS]",
+ mask_token="[MASK]",
+ tokenize_chinese_chars=True,
+ strip_accents=None,
+ **kwargs,
+ ):
+ super().__init__(
+ vocab_file,
+ tokenizer_file=tokenizer_file,
+ do_lower_case=do_lower_case,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ tokenize_chinese_chars=tokenize_chinese_chars,
+ strip_accents=strip_accents,
+ **kwargs,
+ )
+
+ normalizer_state = json.loads(self.backend_tokenizer.normalizer.__getstate__())
+ if (
+ normalizer_state.get("lowercase", do_lower_case) != do_lower_case
+ or normalizer_state.get("strip_accents", strip_accents) != strip_accents
+ or normalizer_state.get("handle_chinese_chars", tokenize_chinese_chars) != tokenize_chinese_chars
+ ):
+ normalizer_class = getattr(normalizers, normalizer_state.pop("type"))
+ normalizer_state["lowercase"] = do_lower_case
+ normalizer_state["strip_accents"] = strip_accents
+ normalizer_state["handle_chinese_chars"] = tokenize_chinese_chars
+ self.backend_tokenizer.normalizer = normalizer_class(**normalizer_state)
+
+ self.do_lower_case = do_lower_case
+
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A BERT sequence has the following format:
+
+ - single sequence: `[CLS] X [SEP]`
+ - pair of sequences: `[CLS] A [SEP] B [SEP]`
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ output = [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
+
+ if token_ids_1 is not None:
+ output += token_ids_1 + [self.sep_token_id]
+
+ return output
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
+ return tuple(files)
+
+
+__all__ = ["RetriBertTokenizerFast"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..78c549b6e294e1ca97a718ef601472d4d400e12a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2021 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_speech_to_text_2 import *
+ from .modeling_speech_to_text_2 import *
+ from .processing_speech_to_text_2 import *
+ from .tokenization_speech_to_text_2 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab18d6ae762ef93e2ab4795fe4d6e3644d341472
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/configuration_speech_to_text_2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/configuration_speech_to_text_2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d812f1d3b242f583acd3a280d9b54f1a435876b1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/configuration_speech_to_text_2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/modeling_speech_to_text_2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/modeling_speech_to_text_2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ae3fcec98cfaa03053703ab4fd315da32023bb72
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/modeling_speech_to_text_2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/processing_speech_to_text_2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/processing_speech_to_text_2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..23ac0a5aa21acf7accb1bd1440c62a6a12d58331
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/processing_speech_to_text_2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/tokenization_speech_to_text_2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/tokenization_speech_to_text_2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96edf92a8f174bf56cf2d754d41d2c1d569e200e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/__pycache__/tokenization_speech_to_text_2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/configuration_speech_to_text_2.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/configuration_speech_to_text_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..a7cde922740a9a2173c64311aec8f6ad5496ac03
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/configuration_speech_to_text_2.py
@@ -0,0 +1,134 @@
+# coding=utf-8
+# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Speech2Text model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class Speech2Text2Config(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`Speech2Text2ForCausalLM`]. It is used to
+ instantiate an Speech2Text2 model according to the specified arguments, defining the model architecture.
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the Speech2Text2
+ [facebook/s2t-wav2vec2-large-en-de](https://huggingface.co/facebook/s2t-wav2vec2-large-en-de) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 50265):
+ Vocabulary size of the Speech2Text model. Defines the number of different tokens that can be represented by
+ the `inputs_ids` passed when calling [`Speech2TextModel`]
+ d_model (`int`, *optional*, defaults to 1024):
+ Dimensionality of the layers and the pooler layer.
+ decoder_layers (`int`, *optional*, defaults to 12):
+ Number of decoder layers.
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
+ Number of attention heads for each attention layer in the Transformer decoder.
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the pooler. If string, `"gelu"`, `"relu"`,
+ `"silu"` and `"gelu_new"` are supported.
+ dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, and pooler.
+ attention_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+ activation_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for activations inside the fully connected layer.
+ init_std (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ https://huggingface.co/papers/1909.11556>`__ for more details.
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
+ for more details.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models).
+ max_target_positions (`int`, *optional*, defaults to 1024):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+
+ Example:
+
+ ```python
+ >>> from transformers import Speech2Text2Config, Speech2Text2ForCausalLM
+
+ >>> # Initializing a Speech2Text2 s2t_transformer_s style configuration
+ >>> configuration = Speech2Text2Config()
+
+ >>> # Initializing a model (with random weights) from the s2t_transformer_s style configuration
+ >>> model = Speech2Text2ForCausalLM(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "speech_to_text_2"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {"num_attention_heads": "decoder_attention_heads", "hidden_size": "d_model"}
+
+ def __init__(
+ self,
+ vocab_size=10000,
+ decoder_layers=6,
+ decoder_ffn_dim=2048,
+ decoder_attention_heads=4,
+ decoder_layerdrop=0.0,
+ use_cache=True,
+ activation_function="relu",
+ d_model=256,
+ dropout=0.1,
+ attention_dropout=0.0,
+ activation_dropout=0.0,
+ init_std=0.02,
+ decoder_start_token_id=2,
+ scale_embedding=True,
+ pad_token_id=1,
+ bos_token_id=0,
+ eos_token_id=2,
+ max_target_positions=1024,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.d_model = d_model
+ self.decoder_ffn_dim = decoder_ffn_dim
+ self.decoder_layers = decoder_layers
+ self.decoder_attention_heads = decoder_attention_heads
+ self.dropout = dropout
+ self.attention_dropout = attention_dropout
+ self.activation_dropout = activation_dropout
+ self.activation_function = activation_function
+ self.init_std = init_std
+ self.decoder_layerdrop = decoder_layerdrop
+ self.use_cache = use_cache
+ self.num_hidden_layers = decoder_layers
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
+ self.max_target_positions = max_target_positions
+
+ super().__init__(
+ pad_token_id=pad_token_id,
+ bos_token_id=bos_token_id,
+ eos_token_id=eos_token_id,
+ decoder_start_token_id=decoder_start_token_id,
+ **kwargs,
+ )
+
+
+__all__ = ["Speech2Text2Config"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/modeling_speech_to_text_2.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/modeling_speech_to_text_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..2117526b04f836b69cc20c80c70169d012b6764a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/modeling_speech_to_text_2.py
@@ -0,0 +1,904 @@
+# coding=utf-8
+# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Speech2Text2 model."""
+
+import math
+from typing import Optional, Union
+
+import torch
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ....activations import ACT2FN
+from ....modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
+from ....modeling_utils import PreTrainedModel
+from ....utils import add_start_docstrings, logging, replace_return_docstrings
+from ....utils.deprecation import deprecate_kwarg
+from .configuration_speech_to_text_2 import Speech2Text2Config
+
+
+logger = logging.get_logger(__name__)
+
+_CONFIG_FOR_DOC = "Speech2Text2Config"
+_CHECKPOINT_FOR_DOC = "facebook/s2t-wav2vec2-large-en-de"
+
+
+class Speech2Text2SinusoidalPositionalEmbedding(nn.Module):
+ """This module produces sinusoidal positional embeddings of any length."""
+
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
+ super().__init__()
+ self.offset = 2
+ self.embedding_dim = embedding_dim
+ self.padding_idx = padding_idx
+
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
+ if hasattr(self, "weights"):
+ # in forward put the weights on the correct dtype and device of the param
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
+
+ self.weights = nn.Parameter(emb_weights)
+ self.weights.requires_grad = False
+ self.weights.detach_()
+
+ @staticmethod
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
+ """
+ Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the
+ description in Section 3.5 of "Attention Is All You Need".
+ """
+ half_dim = embedding_dim // 2
+ emb = math.log(10000) / (half_dim - 1)
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
+ if embedding_dim % 2 == 1:
+ # zero pad
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
+ if padding_idx is not None:
+ emb[padding_idx, :] = 0
+ return emb.to(torch.get_default_dtype())
+
+ @torch.no_grad()
+ def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0):
+ bsz, seq_len = input_ids.size()
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length).to(
+ input_ids.device
+ )
+
+ # expand embeddings if needed
+ max_pos = self.padding_idx + 1 + seq_len
+ if max_pos > self.weights.size(0):
+ self.make_weights(max_pos + self.offset, self.embedding_dim, self.padding_idx)
+
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, -1).detach()
+
+ def create_position_ids_from_input_ids(
+ self, input_ids: torch.Tensor, padding_idx: int, past_key_values_length: Optional[int] = 0
+ ):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
+ symbols are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+class Speech2Text2Attention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool = False,
+ bias: bool = True,
+ is_causal: bool = False,
+ config: Optional[Speech2Text2Config] = None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ self.config = config
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.is_causal = is_causal
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: Optional[torch.Tensor] = None,
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ layer_head_mask: Optional[torch.Tensor] = None,
+ output_attentions: bool = False,
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+
+ bsz, tgt_len, _ = hidden_states.size()
+
+ # get query proj
+ query_states = self.q_proj(hidden_states) * self.scaling
+ # get key, value proj
+ # `past_key_values[0].shape[2] == key_value_states.shape[1]`
+ # is checking that the `sequence_length` of the `past_key_values` is the same as
+ # the provided `key_value_states` to support prefix tuning
+ if (
+ is_cross_attention
+ and past_key_values is not None
+ and past_key_values[0].shape[2] == key_value_states.shape[1]
+ ):
+ # reuse k,v, cross_attentions
+ key_states = past_key_values[0]
+ value_states = past_key_values[1]
+ elif is_cross_attention:
+ # cross_attentions
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
+ elif past_key_values is not None:
+ # reuse k, v, self_attention
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
+ key_states = torch.cat([past_key_values[0], key_states], dim=2)
+ value_states = torch.cat([past_key_values[1], value_states], dim=2)
+ else:
+ # self_attention
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
+
+ if self.is_decoder:
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
+ # Further calls to cross_attention layer can then reuse all cross-attention
+ # key/value_states (first "if" case)
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
+ past_key_values = (key_states, value_states)
+
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
+ key_states = key_states.reshape(*proj_shape)
+ value_states = value_states.reshape(*proj_shape)
+
+ src_len = key_states.size(1)
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
+
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
+ raise ValueError(
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
+ f" {attn_weights.size()}"
+ )
+
+ if attention_mask is not None:
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
+ raise ValueError(
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
+ )
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ if layer_head_mask is not None:
+ if layer_head_mask.size() != (self.num_heads,):
+ raise ValueError(
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
+ f" {layer_head_mask.size()}"
+ )
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ if output_attentions:
+ # this operation is a bit awkward, but it's required to
+ # make sure that attn_weights keeps its gradient.
+ # In order to do so, attn_weights have to be reshaped
+ # twice and have to be reused in the following
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
+ else:
+ attn_weights_reshaped = None
+
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
+
+ attn_output = torch.bmm(attn_probs, value_states)
+
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
+ f" {attn_output.size()}"
+ )
+
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
+ attn_output = attn_output.transpose(1, 2)
+
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
+ # partitioned across GPUs when using tensor-parallelism.
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
+
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights_reshaped, past_key_values
+
+
+class Speech2Text2DecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: Speech2Text2Config):
+ super().__init__()
+ self.embed_dim = config.d_model
+
+ self.self_attn = Speech2Text2Attention(
+ embed_dim=self.embed_dim,
+ num_heads=config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ )
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ if config.is_decoder:
+ self.encoder_attn = Speech2Text2Attention(
+ self.embed_dim,
+ config.decoder_attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ )
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ layer_head_mask: Optional[torch.Tensor] = None,
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[tuple[torch.Tensor]] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = True,
+ ):
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
+ `(encoder_attention_heads,)`.
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
+ size *(decoder_attention_heads,)*.
+ past_key_values (`Tuple(torch.FloatTensor)`): cached past key and value projection states
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ """
+ residual = hidden_states
+
+ # Self Attention
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
+ self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
+ hidden_states=hidden_states,
+ past_key_values=self_attn_past_key_value,
+ attention_mask=attention_mask,
+ layer_head_mask=layer_head_mask,
+ output_attentions=output_attentions,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ # Cross-Attention Block
+ cross_attn_present_key_value = None
+ cross_attn_weights = None
+ if encoder_hidden_states is not None:
+ residual = hidden_states
+
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
+ cross_attn_past_key_value = past_key_values[-2:] if past_key_values is not None else None
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
+ hidden_states=hidden_states,
+ key_value_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ layer_head_mask=cross_attn_layer_head_mask,
+ past_key_values=cross_attn_past_key_value,
+ output_attentions=output_attentions,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ # add cross-attn to positions 3,4 of present_key_value tuple
+ present_key_value = present_key_value + cross_attn_present_key_value
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights, cross_attn_weights)
+
+ if use_cache:
+ outputs += (present_key_value,)
+
+ return outputs
+
+
+class Speech2Text2PreTrainedModel(PreTrainedModel):
+ config: Speech2Text2Config
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ std = self.config.init_std
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, Speech2Text2SinusoidalPositionalEmbedding):
+ weight = module.get_embedding(*module.weight.shape, module.padding_idx)
+ weight = nn.Parameter(weight, requires_grad=False)
+ weight.detach_()
+ module.weight = weight
+
+
+SPEECH_TO_TEXT_2_START_DOCSTRING = r"""
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`Speech2Text2Config`]):
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
+ load the weights associated with the model, only the configuration. Check out the
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+
+class Speech2Text2Decoder(Speech2Text2PreTrainedModel):
+ """
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`Speech2Text2DecoderLayer`]
+
+ Args:
+ config: Speech2Text2Config
+ embed_tokens (nn.Embedding): output embedding
+ """
+
+ def __init__(self, config: Speech2Text2Config):
+ super().__init__(config)
+ self.dropout = config.dropout
+ self.layerdrop = config.decoder_layerdrop
+ self.padding_idx = config.pad_token_id
+ self.max_target_positions = config.max_target_positions
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
+
+ self.embed_positions = Speech2Text2SinusoidalPositionalEmbedding(
+ self.max_target_positions,
+ config.d_model,
+ self.padding_idx,
+ )
+
+ self.layers = nn.ModuleList([Speech2Text2DecoderLayer(config) for _ in range(config.decoder_layers)])
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def forward(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ head_mask=None,
+ cross_attn_head_mask=None,
+ past_key_values=None,
+ inputs_embeds=None,
+ use_cache=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ ):
+ r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
+ provide it.
+
+ Indices can be obtained using [`Speech2Text2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ of the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
+ selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
+ Mask to nullify selected heads of the attention modules in encoder to avoid performing cross-attention
+ on hidden heads. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
+ than the model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # retrieve input_ids and inputs_embeds
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_shape = input_ids.size()
+ input_ids = input_ids.view(-1, input_shape[-1])
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
+
+ # past_key_values_length
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
+
+ attention_mask = _prepare_4d_causal_attention_mask(
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
+ )
+
+ # expand encoder attention mask
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
+ encoder_attention_mask = _prepare_4d_attention_mask(
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
+ )
+
+ # embed positions
+ positions = self.embed_positions(input_ids, past_key_values_length=past_key_values_length)
+
+ hidden_states = inputs_embeds + positions
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache = True` is incompatible with gradient checkpointing. Setting `use_cache = False`..."
+ )
+ use_cache = False
+
+ # decoder layers
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
+ next_decoder_cache = () if use_cache else None
+
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
+ if attn_mask is not None:
+ if attn_mask.size()[0] != (len(self.layers)):
+ raise ValueError(
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
+ f" {head_mask.size()[0]}."
+ )
+ for idx, decoder_layer in enumerate(self.layers):
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+
+ layer_outputs = decoder_layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
+ cross_attn_layer_head_mask=(cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None),
+ past_key_values=past_key_values[idx] if past_key_values is not None else None,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ )
+ hidden_states = layer_outputs[0]
+
+ if use_cache:
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
+
+ if output_attentions:
+ all_self_attns += (layer_outputs[1],)
+
+ if encoder_hidden_states is not None:
+ all_cross_attentions += (layer_outputs[2],)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ next_cache = next_decoder_cache if use_cache else None
+ if not return_dict:
+ return tuple(
+ v
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
+ if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=next_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+@add_start_docstrings(
+ "The Speech2Text2 Model with a language modeling head. Can be used for summarization.",
+ SPEECH_TO_TEXT_2_START_DOCSTRING,
+)
+class Speech2Text2DecoderWrapper(Speech2Text2PreTrainedModel):
+ """
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
+ used in combination with the [`EncoderDecoderModel`] framework.
+ """
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.decoder = Speech2Text2Decoder(config)
+
+ def forward(self, *args, **kwargs):
+ return self.decoder(*args, **kwargs)
+
+
+@add_start_docstrings(
+ "The Speech2Text2 Decoder with a language modeling head. Can be used as the decoder part of"
+ " [`EncoderDecoderModel`] and [`SpeechEncoderDecoder`].",
+ SPEECH_TO_TEXT_2_START_DOCSTRING,
+)
+class Speech2Text2ForCausalLM(Speech2Text2PreTrainedModel):
+ _tied_weights_keys = ["lm_head.weight"]
+
+ def __init__(self, config):
+ config.is_decoder = True
+ config.is_encoder_decoder = False
+ super().__init__(config)
+ self.model = Speech2Text2DecoderWrapper(config)
+
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.model.decoder.embed_tokens
+
+ def set_input_embeddings(self, value):
+ self.model.decoder.embed_tokens = value
+
+ def set_decoder(self, decoder):
+ self.model.decoder = decoder
+
+ def get_decoder(self):
+ return self.model.decoder
+
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.FloatTensor], CausalLMOutputWithCrossAttentions]:
+ r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
+ provide it.
+
+ Indices can be obtained using [`Speech2Text2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
+ if the model is configured as a decoder.
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
+ for more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import (
+ ... SpeechEncoderDecoderModel,
+ ... Speech2Text2ForCausalLM,
+ ... Wav2Vec2Model,
+ ... Speech2Text2Config,
+ ... Wav2Vec2Config,
+ ... Wav2Vec2FeatureExtractor,
+ ... Speech2Text2Tokenizer,
+ ... )
+ >>> from datasets import load_dataset
+
+ >>> feature_extractor = Wav2Vec2FeatureExtractor()
+ >>> tokenizer = Speech2Text2Tokenizer.from_pretrained("facebook/s2t-wav2vec2-large-en-de")
+
+ >>> encoder = Wav2Vec2Model(Wav2Vec2Config())
+ >>> decoder = Speech2Text2ForCausalLM(Speech2Text2Config())
+ >>> # init random speech2text model
+
+ >>> model = SpeechEncoderDecoderModel(encoder=encoder, decoder=decoder)
+ >>> model.config.pad_token_id = tokenizer.pad_token_id
+ >>> model.config.decoder_start_token_id = tokenizer.bos_token_id
+ >>> # pre-process inputs and labels
+
+ >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
+ >>> inputs = feature_extractor(
+ ... ds[0]["audio"]["array"], sampling_rate=ds[0]["audio"]["sampling_rate"], return_tensors="pt"
+ ... )
+ >>> input_values = inputs.input_values
+ >>> decoder_input_ids = tokenizer(ds[0]["text"], return_tensors="pt").input_ids
+ >>> # compute loss
+
+ >>> loss = model(inputs=input_values, labels=decoder_input_ids).loss
+ >>> # backprop loss
+
+ >>> loss.backward() # doctest: +IGNORE_RESULT
+ ```"""
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs = self.model.decoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ head_mask=head_mask,
+ cross_attn_head_mask=cross_attn_head_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ logits = self.lm_head(outputs[0])
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return (loss,) + output if loss is not None else output
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self, input_ids, past_key_values=None, attention_mask=None, use_cache=None, **kwargs
+ ):
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
+ if attention_mask is None:
+ attention_mask = input_ids.new_ones(input_ids.shape)
+
+ if past_key_values:
+ past_length = past_key_values.get_seq_length()
+
+ # Some generation methods already pass only the last input ID
+ if input_ids.shape[1] > past_length:
+ remove_prefix_length = past_length
+ else:
+ # Default to old behavior: keep only final ID
+ remove_prefix_length = input_ids.shape[1] - 1
+
+ input_ids = input_ids[:, remove_prefix_length:]
+ # first step, decoder_cached_states are empty
+ return {
+ "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
+ "attention_mask": attention_mask,
+ "past_key_values": past_key_values,
+ "use_cache": use_cache,
+ }
+
+ @staticmethod
+ def _reorder_cache(past_key_values, beam_idx):
+ reordered_past = ()
+ for layer_past in past_key_values:
+ reordered_past += (
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
+ )
+ return reordered_past
+
+
+__all__ = ["Speech2Text2ForCausalLM", "Speech2Text2PreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/processing_speech_to_text_2.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/processing_speech_to_text_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..b69420bf540cbe737d6509b79d943af9d41e6c24
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/processing_speech_to_text_2.py
@@ -0,0 +1,105 @@
+# coding=utf-8
+# Copyright 2021 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Speech processor class for Speech2Text2
+"""
+
+import warnings
+from contextlib import contextmanager
+
+from ....processing_utils import ProcessorMixin
+
+
+class Speech2Text2Processor(ProcessorMixin):
+ r"""
+ Constructs a Speech2Text2 processor which wraps a Speech2Text2 feature extractor and a Speech2Text2 tokenizer into
+ a single processor.
+
+ [`Speech2Text2Processor`] offers all the functionalities of [`AutoFeatureExtractor`] and [`Speech2Text2Tokenizer`].
+ See the [`~Speech2Text2Processor.__call__`] and [`~Speech2Text2Processor.decode`] for more information.
+
+ Args:
+ feature_extractor (`AutoFeatureExtractor`):
+ An instance of [`AutoFeatureExtractor`]. The feature extractor is a required input.
+ tokenizer (`Speech2Text2Tokenizer`):
+ An instance of [`Speech2Text2Tokenizer`]. The tokenizer is a required input.
+ """
+
+ feature_extractor_class = "AutoFeatureExtractor"
+ tokenizer_class = "Speech2Text2Tokenizer"
+
+ def __init__(self, feature_extractor, tokenizer):
+ super().__init__(feature_extractor, tokenizer)
+ self.current_processor = self.feature_extractor
+ self._in_target_context_manager = False
+
+ def __call__(self, *args, **kwargs):
+ """
+ When used in normal mode, this method forwards all its arguments to AutoFeatureExtractor's
+ [`~AutoFeatureExtractor.__call__`] and returns its output. If used in the context
+ [`~Speech2Text2Processor.as_target_processor`] this method forwards all its arguments to
+ Speech2Text2Tokenizer's [`~Speech2Text2Tokenizer.__call__`]. Please refer to the docstring of the above two
+ methods for more information.
+ """
+ # For backward compatibility
+ if self._in_target_context_manager:
+ return self.current_processor(*args, **kwargs)
+
+ if "raw_speech" in kwargs:
+ warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.")
+ audio = kwargs.pop("raw_speech")
+ else:
+ audio = kwargs.pop("audio", None)
+ sampling_rate = kwargs.pop("sampling_rate", None)
+ text = kwargs.pop("text", None)
+ if len(args) > 0:
+ audio = args[0]
+ args = args[1:]
+
+ if audio is None and text is None:
+ raise ValueError("You need to specify either an `audio` or `text` input to process.")
+
+ if audio is not None:
+ inputs = self.feature_extractor(audio, *args, sampling_rate=sampling_rate, **kwargs)
+ if text is not None:
+ encodings = self.tokenizer(text, **kwargs)
+
+ if text is None:
+ return inputs
+ elif audio is None:
+ return encodings
+ else:
+ inputs["labels"] = encodings["input_ids"]
+ return inputs
+
+ @contextmanager
+ def as_target_processor(self):
+ """
+ Temporarily sets the tokenizer for processing the input. Useful for encoding the labels when fine-tuning
+ Speech2Text2.
+ """
+ warnings.warn(
+ "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
+ "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
+ "your audio inputs, or in a separate call."
+ )
+ self._in_target_context_manager = True
+ self.current_processor = self.tokenizer
+ yield
+ self.current_processor = self.feature_extractor
+ self._in_target_context_manager = False
+
+
+__all__ = ["Speech2Text2Processor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/tokenization_speech_to_text_2.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/tokenization_speech_to_text_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..05c10080b7732601efd476a8c6e2640e74450a76
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/speech_to_text_2/tokenization_speech_to_text_2.py
@@ -0,0 +1,252 @@
+# coding=utf-8
+# Copyright 2021 The Facebook Inc. and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization class for Speech2Text2."""
+
+import json
+import os
+from typing import Optional
+
+from ....tokenization_utils import PreTrainedTokenizer
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+VOCAB_FILES_NAMES = {
+ "vocab_file": "vocab.json",
+ "tokenizer_config_file": "tokenizer_config.json",
+ "merges_file": "merges.txt",
+}
+
+
+BPE_TOKEN_MERGES = ""
+BPE_TOKEN_VOCAB = "@@ "
+
+
+def get_pairs(word):
+ """
+ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
+ strings)
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+ return pairs
+
+
+# Speech2Text2 has no max input length
+
+
+class Speech2Text2Tokenizer(PreTrainedTokenizer):
+ """
+ Constructs a Speech2Text2Tokenizer.
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains some of the main methods. Users should refer to
+ the superclass for more information regarding such methods.
+
+ Args:
+ vocab_file (`str`):
+ File containing the vocabulary.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sentence token.
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sentence token.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+
+ **kwargs
+ Additional keyword arguments passed along to [`PreTrainedTokenizer`]
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ vocab_file,
+ bos_token="",
+ pad_token="",
+ eos_token="",
+ unk_token="",
+ do_lower_case=False,
+ merges_file=None,
+ **kwargs,
+ ):
+ self.do_lower_case = do_lower_case
+
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
+ self.encoder = json.load(vocab_handle)
+ self.decoder = {v: k for k, v in self.encoder.items()}
+
+ if merges_file is None:
+ logger.info(f"No merges files provided. {self.__class__.__name__} can only be used for decoding.")
+
+ self.bpe_ranks = None
+ self.cache = None
+ else:
+ with open(merges_file, encoding="utf-8") as merges_handle:
+ merges = merges_handle.read().split("\n")[:-1]
+
+ merges = [tuple(merge.split()[:2]) for merge in merges]
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
+ self.cache = {}
+ super().__init__(
+ unk_token=unk_token,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ pad_token=pad_token,
+ do_lower_case=do_lower_case,
+ **kwargs,
+ )
+
+ @property
+ def vocab_size(self) -> int:
+ return len(self.decoder)
+
+ def get_vocab(self) -> dict:
+ return dict(self.encoder, **self.added_tokens_encoder)
+
+ def bpe(self, token):
+ word = tuple(token[:-1]) + (token[-1] + BPE_TOKEN_MERGES,)
+ if token in self.cache:
+ return self.cache[token]
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token
+
+ while True:
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ except ValueError:
+ new_word.extend(word[i:])
+ break
+ else:
+ new_word.extend(word[i:j])
+ i = j
+
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
+ new_word.append(first + second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = " ".join(word)
+ if word == "\n " + BPE_TOKEN_MERGES:
+ word = "\n" + BPE_TOKEN_MERGES
+
+ if word.endswith(BPE_TOKEN_MERGES):
+ word = word.replace(BPE_TOKEN_MERGES, "")
+
+ word = word.replace(" ", BPE_TOKEN_VOCAB)
+ self.cache[token] = word
+ return word
+
+ def _tokenize(self, text):
+ """Tokenize a string."""
+
+ if self.bpe_ranks is None:
+ raise ValueError(
+ "This tokenizer was instantiated without a `merges.txt` file, so"
+ " that it can only be used for decoding, not for encoding. "
+ "Make sure to provide `merges.txt` file at instantiation to enable "
+ "encoding."
+ )
+
+ if self.do_lower_case:
+ text = text.lower()
+
+ text = text.split()
+
+ split_tokens = []
+ for token in text:
+ if token:
+ split_tokens.extend(list(self.bpe(token).split(" ")))
+
+ return split_tokens
+
+ def _convert_token_to_id(self, token: str) -> int:
+ """Converts a token (str) in an index (integer) using the vocab."""
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
+
+ def _convert_id_to_token(self, index: int) -> str:
+ """Converts an index (integer) in a token (str) using the vocab."""
+ result = self.decoder.get(index, self.unk_token)
+ return result
+
+ def convert_tokens_to_string(self, tokens: list[str]) -> str:
+ """
+ Converts a list of output tokens into a single string.
+ """
+ # combine tokens
+ string = " ".join(tokens)
+
+ # make sure @@ tokens are concatenated
+ string = "".join(string.split(BPE_TOKEN_VOCAB))
+
+ return string
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ merges_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
+ )
+
+ with open(vocab_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
+
+ index = 0
+ if self.bpe_ranks is None:
+ return (vocab_file,)
+
+ with open(merges_file, "w", encoding="utf-8") as writer:
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {merges_file}: BPE merge indices are not consecutive."
+ " Please check that the tokenizer is not corrupted!"
+ )
+ index = token_index
+ writer.write(" ".join(bpe_tokens) + "\n")
+ index += 1
+
+ return (vocab_file, merges_file)
+
+
+__all__ = ["Speech2Text2Tokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b535eb1df2c40a7680bbf8d57fc70b78e23437f4
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/__init__.py
@@ -0,0 +1,26 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .tokenization_tapex import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5b26d61b7f4703ebd400852cc4378bcb12d1490
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/__pycache__/tokenization_tapex.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/__pycache__/tokenization_tapex.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9fd4c6aea0fb1dbb64029095b490769ee186f563
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/__pycache__/tokenization_tapex.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/tokenization_tapex.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/tokenization_tapex.py
new file mode 100644
index 0000000000000000000000000000000000000000..b32383ddd497828b6a429d39c5d4069a21154b9f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tapex/tokenization_tapex.py
@@ -0,0 +1,1470 @@
+# coding=utf-8
+# Copyright 2022 Microsoft Research and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for TAPEX."""
+
+import json
+import os
+import random
+from functools import lru_cache
+from typing import Optional, Union
+
+import regex as re
+
+from ....file_utils import ExplicitEnum, PaddingStrategy, TensorType, add_end_docstrings, is_pandas_available
+from ....tokenization_utils import AddedToken, PreTrainedTokenizer
+from ....tokenization_utils_base import ENCODE_KWARGS_DOCSTRING, BatchEncoding, TextInput, TruncationStrategy
+from ....utils import logging
+
+
+if is_pandas_available():
+ import pandas as pd
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt"}
+
+
+class TapexTruncationStrategy(ExplicitEnum):
+ """
+ Possible values for the `truncation` argument in [`~TapasTokenizer.__call__`]. Useful for tab-completion in an IDE.
+ """
+
+ DROP_ROWS_TO_FIT = "drop_rows_to_fit"
+
+
+TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING = r"""
+ add_special_tokens (`bool`, *optional*, defaults to `True`):
+ Whether or not to encode the sequences with the special tokens relative to their model.
+ padding (`bool`, `str` or [`~file_utils.PaddingStrategy`], *optional*, defaults to `False`):
+ Activates and controls padding. Accepts the following values:
+
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
+ sequence if provided).
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
+ acceptable input length for the model if that argument is not provided.
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
+ lengths).
+ truncation (`bool`, `str`, [`TapexTruncationStrategy`] or [`~tokenization_utils_base.TruncationStrategy`],
+ *optional*, defaults to `False`):
+
+ Activates and controls truncation. Accepts the following values:
+
+ - `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length` or to the
+ maximum acceptable input length for the model if that argument is not provided. This will truncate
+ row by row, removing rows from the table.
+ - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or
+ to the maximum acceptable input length for the model if that argument is not provided. This will
+ truncate token by token, removing a token from the longest sequence in the pair if a pair of
+ sequences (or a batch of pairs) is provided.
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the
+ maximum acceptable input length for the model if that argument is not provided. This will only
+ truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the
+ maximum acceptable input length for the model if that argument is not provided. This will only
+ truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
+ greater than the model maximum admissible input size).
+ max_length (`int`, *optional*):
+ Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to
+ `None`, this will use the predefined model maximum length if a maximum length is required by one of the
+ truncation/padding parameters. If the model has no specific maximum input length (like XLNet)
+ truncation/padding to a maximum length will be deactivated.
+ stride (`int`, *optional*, defaults to 0):
+ If set to a number along with `max_length`, the overflowing tokens returned when
+ `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence
+ returned to provide some overlap between truncated and overflowing sequences. The value of this
+ argument defines the number of overlapping tokens.
+ pad_to_multiple_of (`int`, *optional*):
+ If set will pad the sequence to a multiple of the provided value. This is especially useful to enable
+ the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta).
+ return_tensors (`str` or [`~file_utils.TensorType`], *optional*):
+ If set, will return tensors instead of list of python integers. Acceptable values are:
+
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return Numpy `np.ndarray` objects.
+"""
+
+
+@lru_cache
+def bytes_to_unicode():
+ """
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
+ characters the bpe code barfs on. The reversible bpe codes work on unicode strings. This means you need a large #
+ of unicode characters in your vocab if you want to avoid UNKs. When you're at something like a 10B token dataset
+ you end up needing around 5K for decent coverage. This is a significant percentage of your normal, say, 32K bpe
+ vocab. To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
+ """
+ bs = (
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
+ )
+ cs = bs[:]
+ n = 0
+ for b in range(2**8):
+ if b not in bs:
+ bs.append(b)
+ cs.append(2**8 + n)
+ n += 1
+ cs = [chr(n) for n in cs]
+ return dict(zip(bs, cs))
+
+
+def get_pairs(word):
+ """
+ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length
+ strings).
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+ return pairs
+
+
+class IndexedRowTableLinearize:
+ """
+ FORMAT: col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
+ """
+
+ def process_table(self, table_content: dict):
+ """
+ Given a table, TableLinearize aims at converting it into a flatten sequence with special symbols.
+ """
+ assert "header" in table_content and "rows" in table_content, self.PROMPT_MESSAGE
+ # process header
+ table_str = self.process_header(table_content["header"]) + " "
+ # process rows
+ for i, row_example in enumerate(table_content["rows"]):
+ # NOTE: the row should start from row 1 instead of 0
+ table_str += self.process_row(row_example, row_index=i + 1) + " "
+ return table_str.strip()
+
+ def process_header(self, headers: list):
+ """
+ Given a list of headers, TableLinearize aims at converting it into a flatten sequence with special symbols.
+ """
+ return "col : " + " | ".join(headers)
+
+ def process_row(self, row: list, row_index: int):
+ """
+ Given a row, TableLinearize aims at converting it into a flatten sequence with special symbols.
+ """
+ row_str = ""
+ row_cell_values = []
+ for cell_value in row:
+ if isinstance(cell_value, int):
+ row_cell_values.append(str(cell_value))
+ else:
+ row_cell_values.append(cell_value)
+ row_str += " | ".join(row_cell_values)
+ return "row " + str(row_index) + " : " + row_str
+
+
+class TapexTokenizer(PreTrainedTokenizer):
+ r"""
+ Construct a TAPEX tokenizer. Based on byte-level Byte-Pair-Encoding (BPE).
+
+ This tokenizer can be used to flatten one or more table(s) and concatenate them with one or more related sentences
+ to be used by TAPEX models. The format that the TAPEX tokenizer creates is the following:
+
+ sentence col: col1 | col2 | col 3 row 1 : val1 | val2 | val3 row 2 : ...
+
+ The tokenizer supports a single table + single query, a single table and multiple queries (in which case the table
+ will be duplicated for every query), a single query and multiple tables (in which case the query will be duplicated
+ for every table), and multiple tables and queries. In other words, you can provide a batch of tables + questions to
+ the tokenizer for instance to prepare them for the model.
+
+ Tokenization itself is based on the BPE algorithm. It is identical to the one used by BART, RoBERTa and GPT-2.
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Path to the vocabulary file.
+ merges_file (`str`):
+ Path to the merges file.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether or not to lowercase the input when tokenizing.
+ errors (`str`, *optional*, defaults to `"replace"`):
+ Paradigm to follow when decoding bytes to UTF-8. See
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
+ other word. (BART tokenizer detect beginning of words by the preceding space).
+ max_cell_length (`int`, *optional*, defaults to 15):
+ Maximum number of characters per cell when linearizing a table. If this number is exceeded, truncation
+ takes place.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ vocab_file,
+ merges_file,
+ do_lower_case=True,
+ errors="replace",
+ bos_token="",
+ eos_token="",
+ sep_token="",
+ cls_token="",
+ unk_token="",
+ pad_token="",
+ mask_token="",
+ add_prefix_space=False,
+ max_cell_length=15,
+ **kwargs,
+ ):
+ bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
+ eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
+ sep_token = AddedToken(sep_token, lstrip=False, rstrip=False) if isinstance(sep_token, str) else sep_token
+ cls_token = AddedToken(cls_token, lstrip=False, rstrip=False) if isinstance(cls_token, str) else cls_token
+ unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
+ pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
+
+ # Mask token behave like a normal word, i.e. include the space before it
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
+
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
+ self.encoder = json.load(vocab_handle)
+ self.decoder = {v: k for k, v in self.encoder.items()}
+ self.errors = errors # how to handle errors in decoding
+ self.byte_encoder = bytes_to_unicode()
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
+ with open(merges_file, encoding="utf-8") as merges_handle:
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
+ self.cache = {}
+ self.add_prefix_space = add_prefix_space
+ self.do_lower_case = do_lower_case
+
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
+
+ # additional properties
+
+ super().__init__(
+ vocab_file=vocab_file,
+ merges_file=merges_file,
+ do_lower_case=do_lower_case,
+ errors=errors,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ pad_token=pad_token,
+ mask_token=mask_token,
+ add_prefix_space=add_prefix_space,
+ max_cell_length=max_cell_length,
+ **kwargs,
+ )
+
+ self.max_cell_length = max_cell_length
+ self.table_linearize = IndexedRowTableLinearize()
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A TAPEX sequence has the following format:
+ - single sequence: ` X `
+ - pair of sequences: ` A B `
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ Returns:
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ if token_ids_1 is None:
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
+ cls = [self.cls_token_id]
+ sep = [self.sep_token_id]
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Args:
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+ Returns:
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is None:
+ return [1] + ([0] * len(token_ids_0)) + [1]
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Args:
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. TAPEX does not:
+ make use of token type ids, therefore a list of zeros is returned.
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ Returns:
+ `list[int]`: List of zeros.
+ """
+ sep = [self.sep_token_id]
+ cls = [self.cls_token_id]
+
+ if token_ids_1 is None:
+ return len(cls + token_ids_0 + sep) * [0]
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
+
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
+ if (is_split_into_words or add_prefix_space) and (len(text) > 0 and not text[0].isspace()):
+ text = " " + text
+ return (text, kwargs)
+
+ @property
+ def vocab_size(self):
+ return len(self.encoder)
+
+ def get_vocab(self):
+ return dict(self.encoder, **self.added_tokens_encoder)
+
+ def bpe(self, token):
+ if token in self.cache:
+ return self.cache[token]
+ word = tuple(token)
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token
+
+ while True:
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ except ValueError:
+ new_word.extend(word[i:])
+ break
+ else:
+ new_word.extend(word[i:j])
+ i = j
+
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
+ new_word.append(first + second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = " ".join(word)
+ self.cache[token] = word
+ return word
+
+ def _tokenize(self, text):
+ """Tokenize a string."""
+ bpe_tokens = []
+ for token in re.findall(self.pat, text):
+ token = "".join(
+ self.byte_encoder[b] for b in token.encode("utf-8")
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
+ return bpe_tokens
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.decoder.get(index)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ text = "".join(tokens)
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
+ return text
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ merge_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
+ )
+
+ with open(vocab_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
+
+ index = 0
+ with open(merge_file, "w", encoding="utf-8") as writer:
+ writer.write("#version: 0.2\n")
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
+ " Please check that the tokenizer is not corrupted!"
+ )
+ index = token_index
+ writer.write(" ".join(bpe_tokens) + "\n")
+ index += 1
+
+ return vocab_file, merge_file
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def __call__(
+ self,
+ table: Union["pd.DataFrame", list["pd.DataFrame"]] = None,
+ query: Optional[Union[TextInput, list[TextInput]]] = None,
+ answer: Optional[Union[str, list[str]]] = None,
+ add_special_tokens: bool = True,
+ padding: Union[bool, str, PaddingStrategy] = False,
+ truncation: Union[bool, str, TruncationStrategy] = None,
+ max_length: Optional[int] = None,
+ stride: int = 0,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ Main method to tokenize and prepare for the model one or several table-sequence pair(s).
+
+ Args:
+ table (`pd.DataFrame`, `list[pd.DataFrame]`):
+ Table(s) containing tabular data.
+ query (`str` or `list[str]`, *optional*):
+ Sentence or batch of sentences related to one or more table(s) to be encoded. Note that the number of
+ sentences must match the number of tables.
+ answer (`str` or `list[str]`, *optional*):
+ Optionally, the corresponding answer to the questions as supervision.
+ """
+
+ if table is not None:
+ return self.source_call_func(
+ table=table,
+ query=query,
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+ elif answer is not None:
+ return self.target_call_func(
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+ else:
+ raise ValueError("You need to provide either a `table` or an `answer`.")
+
+ def source_call_func(
+ self,
+ table: Union["pd.DataFrame", list["pd.DataFrame"]],
+ query: Optional[Union[TextInput, list[TextInput]]] = None,
+ answer: Optional[Union[str, list[str]]] = None,
+ add_special_tokens: bool = True,
+ padding: Union[bool, str, PaddingStrategy] = False,
+ truncation: Union[bool, str, TruncationStrategy] = None,
+ max_length: Optional[int] = None,
+ stride: int = 0,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ # Input type checking for clearer error
+ valid_table = False
+ valid_query = False
+
+ # Check that table have a valid type
+ if isinstance(table, pd.DataFrame):
+ valid_table = True
+ elif isinstance(table, (list, tuple)) and isinstance(table[0], pd.DataFrame):
+ valid_table = True
+
+ # Check that query have a valid type
+ if query is None or isinstance(query, str):
+ valid_query = True
+ elif isinstance(query, (list, tuple)):
+ if len(query) == 0 or isinstance(query[0], str):
+ valid_query = True
+
+ if not valid_table:
+ raise ValueError(
+ "table input must of type `pd.DataFrame` (single example), `list[pd.DataFrame]` (batch of examples). "
+ )
+ if not valid_query:
+ raise ValueError("query input must of type `str` (single example), `list[str]` (batch of examples). ")
+ is_batched = isinstance(table, (list, tuple)) or isinstance(query, (list, tuple))
+
+ if is_batched:
+ return self.batch_encode_plus(
+ table=table,
+ query=query,
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+ else:
+ return self.encode_plus(
+ table=table,
+ query=query,
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def batch_encode_plus(
+ self,
+ table: Union["pd.DataFrame", list["pd.DataFrame"]],
+ query: Optional[list[TextInput]] = None,
+ answer: Optional[list[str]] = None,
+ add_special_tokens: bool = True,
+ padding: Union[bool, str, PaddingStrategy] = False,
+ truncation: Optional[Union[bool, str]] = None,
+ max_length: Optional[int] = None,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+
+
+ This method is deprecated, `__call__` should be used instead.
+
+
+ """
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ return self._batch_encode_plus(
+ table=table,
+ query=query,
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def _batch_encode_plus(
+ self,
+ table: Union["pd.DataFrame", list["pd.DataFrame"]],
+ query: Optional[list[TextInput]] = None,
+ answer: Optional[list[str]] = None,
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: Optional[int] = None,
+ stride: int = 0,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ if return_offsets_mapping:
+ raise NotImplementedError(
+ "return_offset_mapping is not available when using Python tokenizers. "
+ "To use this feature, change your tokenizer to one deriving from "
+ "transformers.PreTrainedTokenizerFast."
+ )
+
+ if isinstance(table, pd.DataFrame) and isinstance(query, (list, tuple)):
+ # single table, many queries case
+ # duplicate table for every query
+ table = [table] * len(query)
+ if isinstance(table, (list, tuple)) and isinstance(query, str):
+ # many tables, single query case
+ # duplicate query for every table
+ query = [query] * len(table)
+
+ batch_outputs = self._batch_prepare_for_model(
+ table=table,
+ query=query,
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_attention_mask=return_attention_mask,
+ return_token_type_ids=return_token_type_ids,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ return_tensors=return_tensors,
+ verbose=verbose,
+ )
+
+ return BatchEncoding(batch_outputs)
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def _batch_prepare_for_model(
+ self,
+ table: Union["pd.DataFrame", list["pd.DataFrame"]],
+ query: Optional[Union[TextInput, list[TextInput]]] = None,
+ answer: Optional[Union[str, list[str]]] = None,
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: Optional[int] = None,
+ stride: int = 0,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[str] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ ) -> BatchEncoding:
+ """
+ This method adds special tokens, truncates sequences if overflowing while taking into account the special
+ tokens and manages a moving window (with user defined stride) for overflowing tokens.
+ """
+ batch_outputs = {}
+ if answer is None:
+ answer = [None] * len(table)
+ for _table, _query, _answer in zip(table, query, answer):
+ text = self.prepare_table_query(
+ _table, _query, _answer, truncation_strategy=truncation_strategy, max_length=max_length
+ )
+
+ if self.do_lower_case:
+ text = text.lower()
+
+ tokens = self.tokenize(text)
+ outputs = self.prepare_for_model(
+ ids=self.convert_tokens_to_ids(tokens),
+ add_special_tokens=add_special_tokens,
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
+ truncation=truncation_strategy.value,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=None, # we pad in batch afterwards
+ return_attention_mask=False, # we pad in batch afterwards
+ return_token_type_ids=return_token_type_ids,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ return_tensors=None, # We convert the whole batch to tensors at the end
+ prepend_batch_axis=False,
+ verbose=verbose,
+ )
+
+ for key, value in outputs.items():
+ if key not in batch_outputs:
+ batch_outputs[key] = []
+ batch_outputs[key].append(value)
+
+ batch_outputs = self.pad(
+ batch_outputs,
+ padding=padding_strategy.value,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_attention_mask=return_attention_mask,
+ )
+
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
+
+ return batch_outputs
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING)
+ def encode(
+ self,
+ table: "pd.DataFrame",
+ query: Optional[TextInput] = None,
+ answer: Optional[str] = None,
+ add_special_tokens: bool = True,
+ padding: Union[bool, str, PaddingStrategy] = False,
+ truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
+ max_length: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ **kwargs,
+ ) -> list[int]:
+ """
+ Prepare a table, a string and possible answer for the model. This method does not return token type IDs,
+ attention masks, etc. which are necessary for the model to work correctly. Use this method if you want to build
+ your processing on your own, otherwise refer to `__call__`.
+ """
+ encoded_inputs = self.encode_plus(
+ table,
+ query=query,
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ return_tensors=return_tensors,
+ **kwargs,
+ )
+
+ return encoded_inputs["input_ids"]
+
+ @add_end_docstrings(ENCODE_KWARGS_DOCSTRING, TAPEX_ENCODE_PLUS_ADDITIONAL_KWARGS_DOCSTRING)
+ def encode_plus(
+ self,
+ table: "pd.DataFrame",
+ query: Optional[TextInput] = None,
+ answer: Optional[str] = None,
+ add_special_tokens: bool = True,
+ padding: Union[bool, str, PaddingStrategy] = False,
+ truncation: Optional[Union[bool, str]] = None,
+ max_length: Optional[int] = None,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ return self._encode_plus(
+ table=table,
+ query=query,
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def _encode_plus(
+ self,
+ table: "pd.DataFrame",
+ query: Optional[TextInput] = None,
+ answer: Optional[str] = None,
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: Optional[int] = None,
+ stride: int = 0,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ if return_offsets_mapping:
+ raise NotImplementedError(
+ "return_offset_mapping is not available when using Python tokenizers. "
+ "To use this feature, change your tokenizer to one deriving from "
+ "transformers.PreTrainedTokenizerFast. "
+ "More information on available tokenizers at "
+ "https://github.com/huggingface/transformers/pull/2674"
+ )
+
+ text = self.prepare_table_query(
+ table, query, answer, truncation_strategy=truncation_strategy, max_length=max_length
+ )
+
+ # if necessary, perform lower case
+ if self.do_lower_case:
+ text = text.lower()
+
+ tokens = self.tokenize(text)
+
+ return self.prepare_for_model(
+ ids=self.convert_tokens_to_ids(tokens),
+ add_special_tokens=add_special_tokens,
+ padding=padding_strategy.value,
+ truncation=truncation_strategy.value,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ prepend_batch_axis=True,
+ return_attention_mask=return_attention_mask,
+ return_token_type_ids=return_token_type_ids,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ verbose=verbose,
+ )
+
+ def target_call_func(
+ self,
+ answer: Union[str, list[str]],
+ add_special_tokens: bool = True,
+ padding: Union[bool, str, PaddingStrategy] = False,
+ truncation: Union[bool, str, TruncationStrategy] = None,
+ max_length: Optional[int] = None,
+ stride: int = 0,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ The method tokenizes and prepares the answer label for the model.
+
+ Args:
+ answer (`str` or `list[str]`):
+ Corresponding answer supervision to the queries for training the model.
+ """
+ is_batched = isinstance(answer, (list, tuple))
+
+ if is_batched:
+ return self.target_batch_encode_plus(
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+ else:
+ return self.target_encode_plus(
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def target_batch_encode_plus(
+ self,
+ answer: list[str],
+ add_special_tokens: bool = True,
+ padding: Union[bool, str, PaddingStrategy] = False,
+ truncation: Optional[Union[bool, str]] = None,
+ max_length: Optional[int] = None,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ Prepare answer strings for the model.
+
+ Args:
+ answer `list[str]`:
+ Corresponding answer supervision to the queries for training the model.
+ """
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ return self._target_batch_encode_plus(
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def _target_batch_encode_plus(
+ self,
+ answer: list[str],
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: Optional[int] = None,
+ stride: int = 0,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ batch_outputs = {}
+ for text in answer:
+ if self.do_lower_case:
+ text = text.lower()
+
+ tokens = self.tokenize(text)
+ outputs = self.prepare_for_model(
+ ids=self.convert_tokens_to_ids(tokens),
+ add_special_tokens=add_special_tokens,
+ padding=PaddingStrategy.DO_NOT_PAD.value, # we pad in batch afterwards
+ truncation=truncation_strategy.value,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=None, # we pad in batch afterwards
+ return_attention_mask=False, # we pad in batch afterwards
+ return_token_type_ids=return_token_type_ids,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ return_tensors=None, # We convert the whole batch to tensors at the end
+ prepend_batch_axis=False,
+ verbose=verbose,
+ )
+
+ for key, value in outputs.items():
+ if key not in batch_outputs:
+ batch_outputs[key] = []
+ batch_outputs[key].append(value)
+
+ batch_outputs = self.pad(
+ batch_outputs,
+ padding=padding_strategy.value,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_attention_mask=return_attention_mask,
+ )
+
+ batch_outputs = BatchEncoding(batch_outputs, tensor_type=return_tensors)
+
+ return BatchEncoding(batch_outputs)
+
+ def target_encode(
+ self,
+ answer: str,
+ add_special_tokens: bool = True,
+ padding: Union[bool, str, PaddingStrategy] = False,
+ truncation: Union[bool, str, TruncationStrategy, TapexTruncationStrategy] = None,
+ max_length: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ **kwargs,
+ ) -> list[int]:
+ """
+ Prepare the answer string for the model. This method does not return token type IDs, attention masks, etc.
+ which are necessary for the model to work correctly. Use this method if you want to build your processing on
+ your own, otherwise refer to `__call__`.
+
+ Args:
+ answer `str`:
+ Corresponding answer supervision to the queries for training the model
+ """
+ encoded_outputs = self.target_encode_plus(
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ return_tensors=return_tensors,
+ **kwargs,
+ )
+
+ return encoded_outputs["input_ids"]
+
+ def target_encode_plus(
+ self,
+ answer: str,
+ add_special_tokens: bool = True,
+ padding: Union[bool, str, PaddingStrategy] = False,
+ truncation: Optional[Union[bool, str]] = None,
+ max_length: Optional[int] = None,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ """
+ Prepare a answer string for the model.
+
+ Args:
+ answer `str`:
+ Corresponding answer supervision to the queries for training the model.
+ """
+ # Backward compatibility for 'truncation_strategy', 'pad_to_max_length'
+ padding_strategy, truncation_strategy, max_length, kwargs = self._get_padding_truncation_strategies(
+ padding=padding,
+ truncation=truncation,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ return self._target_encode_plus(
+ answer=answer,
+ add_special_tokens=add_special_tokens,
+ padding_strategy=padding_strategy,
+ truncation_strategy=truncation_strategy,
+ max_length=max_length,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ return_token_type_ids=return_token_type_ids,
+ return_attention_mask=return_attention_mask,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_offsets_mapping=return_offsets_mapping,
+ return_length=return_length,
+ verbose=verbose,
+ **kwargs,
+ )
+
+ def _target_encode_plus(
+ self,
+ answer: str,
+ add_special_tokens: bool = True,
+ padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD,
+ truncation_strategy: TruncationStrategy = TruncationStrategy.DO_NOT_TRUNCATE,
+ max_length: Optional[int] = None,
+ stride: int = 0,
+ pad_to_multiple_of: Optional[int] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_token_type_ids: Optional[bool] = None,
+ return_attention_mask: Optional[bool] = None,
+ return_overflowing_tokens: bool = False,
+ return_special_tokens_mask: bool = False,
+ return_offsets_mapping: bool = False,
+ return_length: bool = False,
+ verbose: bool = True,
+ **kwargs,
+ ) -> BatchEncoding:
+ if return_offsets_mapping:
+ raise NotImplementedError(
+ "return_offset_mapping is not available when using Python tokenizers. "
+ "To use this feature, change your tokenizer to one deriving from "
+ "transformers.PreTrainedTokenizerFast. "
+ "More information on available tokenizers at "
+ "https://github.com/huggingface/transformers/pull/2674"
+ )
+
+ text = answer
+
+ # if necessary, perform lower case
+ if self.do_lower_case:
+ text = text.lower()
+
+ tokens = self.tokenize(text)
+
+ return self.prepare_for_model(
+ ids=self.convert_tokens_to_ids(tokens),
+ add_special_tokens=add_special_tokens,
+ padding=padding_strategy.value,
+ truncation=truncation_strategy.value,
+ max_length=max_length,
+ stride=stride,
+ pad_to_multiple_of=pad_to_multiple_of,
+ return_tensors=return_tensors,
+ prepend_batch_axis=True,
+ return_attention_mask=return_attention_mask,
+ return_token_type_ids=return_token_type_ids,
+ return_overflowing_tokens=return_overflowing_tokens,
+ return_special_tokens_mask=return_special_tokens_mask,
+ return_length=return_length,
+ verbose=verbose,
+ )
+
+ def prepare_table_query(
+ self,
+ table,
+ query,
+ answer=None,
+ truncation_strategy=Union[str, TruncationStrategy, TapexTruncationStrategy],
+ max_length=None,
+ ):
+ """
+ This method can be used to linearize a table and add a corresponding query.
+
+ Optionally, it also handles truncation of the table (cells).
+
+ An answer can be provided for more precise truncation.
+ """
+ if not table.empty:
+ # step 1: create table dictionary
+ table_content = {"header": list(table.columns), "rows": [list(row.values) for i, row in table.iterrows()]}
+
+ # step 2: modify table internally
+ # always truncate table cells based on self.max_cell_length
+ # optionally truncate rows if truncation_strategy is set to it
+ self.truncate_table_cells(table_content, query, answer)
+ if truncation_strategy == TapexTruncationStrategy.DROP_ROWS_TO_FIT:
+ self.truncate_table_rows(table_content, query, answer, max_length=max_length)
+
+ # step 3: linearize table
+ linear_table = self.table_linearize.process_table(table_content)
+ else:
+ linear_table = ""
+
+ if linear_table == "":
+ logger.warning(
+ "You provide an empty table, or all cells contain much tokens (e.g., >= 1024 tokens). "
+ + f"Please carefully check the corresponding table with the query : {query}."
+ )
+ if query == "":
+ logger.warning("You provide nothing to query with respect to the table.")
+ # step 4: concatenate query with linear_table
+ separator = " " if query and linear_table else ""
+ joint_input = (query + separator + linear_table) if query else linear_table
+
+ return joint_input
+
+ def truncate_table_cells(self, table_content: dict, question: str, answer: list):
+ # TODO (Qian): is it possible to revert the original cell if it is in the final answer?
+ cell_mapping = {}
+ for row in table_content["rows"]:
+ for i, cell in enumerate(row):
+ truncate_cell = self.truncate_cell(cell)
+ if truncate_cell is not None:
+ cell_mapping[cell] = truncate_cell
+ row[i] = truncate_cell
+
+ # modify the answer list
+ if answer is not None:
+ for i, case in enumerate(answer):
+ if case in cell_mapping:
+ answer[i] = cell_mapping[case]
+
+ def truncate_cell(self, cell_value):
+ # do not process on these cases
+ if isinstance(cell_value, (int, float)):
+ return cell_value
+ if cell_value.strip() != "":
+ try_tokens = self.tokenize(cell_value)
+ if len(try_tokens) >= self.max_cell_length:
+ retain_tokens = try_tokens[: self.max_cell_length]
+ retain_cell_value = self.convert_tokens_to_string(retain_tokens)
+ return retain_cell_value
+ else:
+ return None
+ else:
+ return cell_value
+
+ def truncate_table_rows(
+ self, table_content: dict, question: str, answer: Optional[Union[str, list[str]]] = None, max_length=None
+ ):
+ """
+ Args:
+ table_content:
+ {"header": xxx, "rows": xxx, "id" (Optionally): xxx}
+
+ question:
+ natural language sentence
+
+ answer:
+ if for training, is the supervision; otherwise will be empty
+ """
+ delete_ratio, remain_token_len = self.estimate_delete_ratio(table_content, question, max_length)
+ # randomly delete unrelated rows
+ self.delete_unrelated_rows(table_content, question, answer, delete_ratio)
+ # guarantee the result < max_length
+ maximum_keep_rows = 0
+ for ind, row_example in enumerate(table_content["rows"]):
+ value_string = self.table_linearize.process_row(row_example, ind + 1)
+ value_token_len = len(self.tokenize(value_string))
+ # over the size limit, and take action
+ if value_token_len > remain_token_len:
+ break
+ remain_token_len -= value_token_len
+ maximum_keep_rows += 1
+ del table_content["rows"][maximum_keep_rows:]
+
+ def estimate_delete_ratio(self, table_content: dict, question: str, max_length=None):
+ if "header" not in table_content or "rows" not in table_content:
+ raise ValueError("The table content should contain both 'header' and 'rows' keys.")
+ # calculate the tokens of header, special tokens will only be pre-prepended into question
+ question_tokens = self.tokenize(question, add_special_tokens=True)
+ # calculate the tokens of header
+ header_string = self.table_linearize.process_header(table_content["header"])
+ header_tokens = self.tokenize(header_string, add_special_tokens=False)
+ # split all cell values into tokens and see how many can be accommodated
+ used_token_len = len(question_tokens) + len(header_tokens)
+ # remaining token space for rows
+ remain_token_len = max_length - used_token_len
+
+ value_string = ""
+ for _, row_example in enumerate(table_content["rows"]):
+ # use a general index to roughly estimate the overall token len
+ value_string += self.table_linearize.process_row(row_example, 100) + " "
+ value_token_len = len(self.tokenize(value_string))
+
+ if value_token_len < remain_token_len:
+ # no row will be deleted
+ return 0.0, remain_token_len
+ else:
+ # calc a roughly delete rate
+ return 1.0 - remain_token_len / value_token_len, remain_token_len
+
+ def delete_unrelated_rows(self, table_content: dict, question: str, answer: list, delete_ratio: float):
+ """
+ The argument answer is used only during training.
+ """
+ truncated_unrelated_indices = []
+ related_indices = []
+ if answer is None or len(answer) == 0:
+ answer_set = set()
+ else:
+ answer_set = {ans_ex.lower() for ans_ex in answer}
+ # add question key words into answer set
+ if question is not None:
+ answer_set.update(question.split())
+ question_set = set(question.strip("?!.,").split(" "))
+ row_max_len = len(table_content["rows"])
+ for _row_idx, row in enumerate(table_content["rows"]):
+ lower_row = {str(cell).lower() for cell in row}
+ if len(lower_row & answer_set) == 0 and len(lower_row & question_set) == 0:
+ truncated_unrelated_indices.append(_row_idx)
+ else:
+ # add neighbours to preserve information aggressively
+ related_indices.extend([_row_idx - 2, _row_idx - 1, _row_idx, _row_idx + 1, _row_idx + 2])
+
+ # remove the neighbours
+ truncated_unrelated_indices = [
+ _row_idx for _row_idx in truncated_unrelated_indices if _row_idx not in related_indices
+ ]
+ # select some cases to drop
+ drop_items = min(len(truncated_unrelated_indices), int(len(table_content["rows"]) * delete_ratio))
+ drop_row_indices = random.choices(truncated_unrelated_indices, k=drop_items)
+
+ for _row_idx in reversed(range(row_max_len)):
+ if _row_idx in drop_row_indices:
+ del table_content["rows"][_row_idx]
+
+ # only when the drop ratio is too large, logging for warning.
+ if "id" in table_content and len(drop_row_indices) > 0:
+ logger.warning("Delete {:.2f} rows in table {}".format(len(drop_row_indices), table_content["id"]))
+
+
+__all__ = ["TapexTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4bccdd12c9703313951e223d0ac1955f9ca1581
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_trajectory_transformer import *
+ from .modeling_trajectory_transformer import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe2732b125fc386b98bc497051adbf3de5ea6e66
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__pycache__/configuration_trajectory_transformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__pycache__/configuration_trajectory_transformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e88576c8d0fbbdf396e7f22c26c3c9a6c753d4fd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__pycache__/configuration_trajectory_transformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__pycache__/modeling_trajectory_transformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__pycache__/modeling_trajectory_transformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..626630834db9da647e008ba92bb17481c5767f9e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/__pycache__/modeling_trajectory_transformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a267cc4c4b82c6703eaa3a732d3fca1606a60d7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py
@@ -0,0 +1,155 @@
+# coding=utf-8
+# Copyright 2022 The Trajectory Transformers paper authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""TrajectoryTransformer model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class TrajectoryTransformerConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`TrajectoryTransformerModel`]. It is used to
+ instantiate an TrajectoryTransformer model according to the specified arguments, defining the model architecture.
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the
+ TrajectoryTransformer
+ [CarlCochet/trajectory-transformer-halfcheetah-medium-v2](https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2)
+ architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 100):
+ Vocabulary size of the TrajectoryTransformer model. Defines the number of different tokens that can be
+ represented by the `trajectories` passed when calling [`TrajectoryTransformerModel`]
+ action_weight (`int`, *optional*, defaults to 5):
+ Weight of the action in the loss function
+ reward_weight (`int`, *optional*, defaults to 1):
+ Weight of the reward in the loss function
+ value_weight (`int`, *optional*, defaults to 1):
+ Weight of the value in the loss function
+ block_size (`int`, *optional*, defaults to 249):
+ Size of the blocks in the trajectory transformer.
+ action_dim (`int`, *optional*, defaults to 6):
+ Dimension of the action space.
+ observation_dim (`int`, *optional*, defaults to 17):
+ Dimension of the observation space.
+ transition_dim (`int`, *optional*, defaults to 25):
+ Dimension of the transition space.
+ n_layer (`int`, *optional*, defaults to 4):
+ Number of hidden layers in the Transformer encoder.
+ n_head (`int`, *optional*, defaults to 4):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ n_embd (`int`, *optional*, defaults to 128):
+ Dimensionality of the embeddings and hidden states.
+ resid_pdrop (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ embd_pdrop (`int`, *optional*, defaults to 0.1):
+ The dropout ratio for the embeddings.
+ attn_pdrop (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ max_position_embeddings (`int`, *optional*, defaults to 512):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ kaiming_initializer_range (`float, *optional*, defaults to 1):
+ A coefficient scaling the negative slope of the kaiming initializer rectifier for EinLinear layers.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+ Example:
+
+ ```python
+ >>> from transformers import TrajectoryTransformerConfig, TrajectoryTransformerModel
+
+ >>> # Initializing a TrajectoryTransformer CarlCochet/trajectory-transformer-halfcheetah-medium-v2 style configuration
+ >>> configuration = TrajectoryTransformerConfig()
+
+ >>> # Initializing a model (with random weights) from the CarlCochet/trajectory-transformer-halfcheetah-medium-v2 style configuration
+ >>> model = TrajectoryTransformerModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "trajectory_transformer"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "hidden_size": "n_embd",
+ "num_attention_heads": "n_head",
+ "num_hidden_layers": "n_layer",
+ }
+
+ def __init__(
+ self,
+ vocab_size=100,
+ action_weight=5,
+ reward_weight=1,
+ value_weight=1,
+ block_size=249,
+ action_dim=6,
+ observation_dim=17,
+ transition_dim=25,
+ n_layer=4,
+ n_head=4,
+ n_embd=128,
+ embd_pdrop=0.1,
+ attn_pdrop=0.1,
+ resid_pdrop=0.1,
+ learning_rate=0.0006,
+ max_position_embeddings=512,
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ kaiming_initializer_range=1,
+ use_cache=True,
+ pad_token_id=1,
+ bos_token_id=50256,
+ eos_token_id=50256,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.action_weight = action_weight
+ self.reward_weight = reward_weight
+ self.value_weight = value_weight
+ self.max_position_embeddings = max_position_embeddings
+ self.block_size = block_size
+ self.action_dim = action_dim
+ self.observation_dim = observation_dim
+ self.transition_dim = transition_dim
+ self.learning_rate = learning_rate
+ self.n_layer = n_layer
+ self.n_head = n_head
+ self.n_embd = n_embd
+ self.embd_pdrop = embd_pdrop
+ self.attn_pdrop = attn_pdrop
+ self.resid_pdrop = resid_pdrop
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.kaiming_initializer_range = kaiming_initializer_range
+ self.use_cache = use_cache
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
+
+
+__all__ = ["TrajectoryTransformerConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf49223b8b5d2c2341e99da87148a09540e492f2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py
@@ -0,0 +1,602 @@
+# coding=utf-8
+# Copyright 2022 The Trajectory Transformers paper authors and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch TrajectoryTransformer model."""
+
+import math
+import os
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import numpy as np
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import functional as F
+
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_utils import PreTrainedModel
+from ....utils import (
+ ModelOutput,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+ replace_return_docstrings,
+)
+from .configuration_trajectory_transformer import TrajectoryTransformerConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "CarlCochet/trajectory-transformer-halfcheetah-medium-v2"
+_CONFIG_FOR_DOC = "TrajectoryTransformerConfig"
+
+
+def load_tf_weights_in_trajectory_transformer(model, config, tf_checkpoint_path):
+ """Load tf checkpoints in a pytorch model."""
+ try:
+ import re
+
+ import numpy as np
+ import tensorflow as tf
+ except ImportError:
+ logger.error(
+ "Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
+ "https://www.tensorflow.org/install/ for installation instructions."
+ )
+ raise
+ tf_path = os.path.abspath(tf_checkpoint_path)
+ logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
+ # Load weights from TF model
+ init_vars = tf.train.list_variables(tf_path)
+ names = []
+ arrays = []
+ for name, shape in init_vars:
+ logger.info(f"Loading TF weight {name} with shape {shape}")
+ array = tf.train.load_variable(tf_path, name)
+ names.append(name)
+ arrays.append(array)
+
+ for name, array in zip(names, arrays):
+ name = name.split("/")
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
+ # which are not required for using pretrained model
+ if any(
+ n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"]
+ for n in name
+ ):
+ logger.info(f"Skipping {'/'.join(name)}")
+ continue
+ pointer = model
+ for m_name in name:
+ if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
+ scope_names = re.split(r"_(\d+)", m_name)
+ else:
+ scope_names = [m_name]
+ if scope_names[0] == "kernel" or scope_names[0] == "gamma":
+ pointer = getattr(pointer, "weight")
+ elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
+ pointer = getattr(pointer, "bias")
+ elif scope_names[0] == "output_weights":
+ pointer = getattr(pointer, "weight")
+ elif scope_names[0] == "squad":
+ pointer = getattr(pointer, "classifier")
+ else:
+ try:
+ pointer = getattr(pointer, scope_names[0])
+ except AttributeError:
+ logger.info(f"Skipping {'/'.join(name)}")
+ continue
+ if len(scope_names) >= 2:
+ num = int(scope_names[1])
+ pointer = pointer[num]
+ if m_name[-11:] == "_embeddings":
+ pointer = getattr(pointer, "weight")
+ elif m_name == "kernel":
+ array = np.transpose(array)
+ try:
+ if pointer.shape != array.shape:
+ raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
+ except AssertionError as e:
+ e.args += (pointer.shape, array.shape)
+ raise
+ logger.info(f"Initialize PyTorch weight {name}")
+ pointer.data = torch.from_numpy(array)
+ return model
+
+
+@dataclass
+class TrajectoryTransformerOutput(ModelOutput):
+ """
+ Base class for model's outputs that also contains a pooling of the last hidden states.
+
+ Args:
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ past_key_values (`tuple[tuple[torch.Tensor]]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ Tuple of length `config.n_layers`, containing tuples of tensors of shape `(batch_size, num_heads,
+ sequence_length, embed_size_per_head)`). Contains pre-computed hidden-states (key and values in the
+ attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
+ plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. GPT2Attentions weights after the attention softmax, used to compute the weighted average
+ in the self-attention heads.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+class TrajectoryTransformerPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: TrajectoryTransformerConfig
+ load_tf_weights = load_tf_weights_in_trajectory_transformer
+ base_model_prefix = "trajectory_transformer"
+ main_input_name = "trajectories"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ if isinstance(module, (nn.Linear, nn.Embedding)):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if isinstance(module, nn.Linear) and module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ elif isinstance(module, EinLinear):
+ for i in range(module.n_models):
+ nn.init.kaiming_uniform_(module.weight[i], a=math.sqrt(5) / self.config.kaiming_initializer_range)
+ if module.bias is not None:
+ fan_in, _ = nn.init._calculate_fan_in_and_fan_out(module.weight[i])
+ bound = (1 / math.sqrt(fan_in)) * self.config.initializer_range
+ nn.init.uniform_(module.bias[i], -bound, bound)
+
+
+TRAJECTORY_TRANSFORMER_START_DOCSTRING = r"""
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
+ behavior.
+
+ Parameters:
+ config ([`TrajectoryTransformerConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+TRAJECTORY_TRANSFORMER_INPUTS_DOCSTRING = r"""
+ Args:
+ trajectories (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Batch of trajectories, where a trajectory is a sequence of states, actions and rewards.
+ past_key_values (`tuple[tuple[torch.Tensor]]` of length `config.n_layers`, *optional*):
+ Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
+ `past_key_values` output below). Can be used to speed up sequential decoding. The `input_ids` which have
+ their past given to this model should not be passed as `input_ids` as they have already been computed.
+ targets (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Desired targets used to compute the loss.
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+class EinLinear(nn.Module):
+ def __init__(self, n_models, in_features, out_features, bias):
+ super().__init__()
+ self.n_models = n_models
+ self.out_features = out_features
+ self.in_features = in_features
+ self.weight = nn.Parameter(torch.Tensor(n_models, out_features, in_features))
+ if bias:
+ self.bias = nn.Parameter(torch.Tensor(n_models, out_features))
+ else:
+ self.register_parameter("bias", None)
+
+ def reset_parameters(self):
+ for i in range(self.n_models):
+ nn.init.kaiming_uniform_(self.weight[i], a=math.sqrt(5))
+ if self.bias is not None:
+ fan_in, _ = nn.init._calculate_fan_in_and_fan_out(self.weight[i])
+ bound = 1 / math.sqrt(fan_in)
+ nn.init.uniform_(self.bias[i], -bound, bound)
+
+ def forward(self, input):
+ """
+ Args:
+ input (`torch.FloatTensor` of shape `(B, n_models, input_dim)`):
+ The input to the layer.
+ """
+ # [ batch_size x n_models x output_dim ]
+ output = torch.einsum("eoi,bei->beo", self.weight, input)
+ if self.bias is not None:
+ raise RuntimeError()
+ return output
+
+
+class CausalSelfAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ if config.n_embd % config.n_head != 0:
+ raise ValueError(f"n_head ({config.n_head}) should be a divisor of n_embd ({config.n_embd})")
+
+ # key, query, value projections for all heads
+ self.key = nn.Linear(config.n_embd, config.n_embd)
+ self.query = nn.Linear(config.n_embd, config.n_embd)
+ self.value = nn.Linear(config.n_embd, config.n_embd)
+
+ # regularization
+ self.attn_drop = nn.Dropout(config.attn_pdrop)
+ self.resid_drop = nn.Dropout(config.resid_pdrop)
+
+ # output projection
+ self.proj = nn.Linear(config.n_embd, config.n_embd)
+
+ # causal mask to ensure that attention is only applied to the left in the input sequence
+ self.register_buffer(
+ "mask",
+ torch.tril(torch.ones(config.block_size, config.block_size)).view(
+ 1, 1, config.block_size, config.block_size
+ ),
+ persistent=False,
+ )
+
+ # mask previous value estimates
+ joined_dim = config.observation_dim + config.action_dim + 2
+ self.mask.squeeze()[:, joined_dim - 1 :: joined_dim] = 0
+
+ self.n_head = config.n_head
+
+ def forward(
+ self,
+ hidden_states: Optional[tuple[torch.FloatTensor]],
+ layer_past: Optional[tuple[torch.Tensor]] = None,
+ use_cache: Optional[bool] = False,
+ output_attentions: Optional[bool] = False,
+ ):
+ batch_size, sequence_length, embedding_dim = hidden_states.size()
+
+ # calculate query, key, values for all heads in batch and move head forward to be the batch dim
+ # [ batch_size x n_heads x sequence_length x head_dim ]
+ key = (
+ self.key(hidden_states)
+ .view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
+ .transpose(1, 2)
+ )
+ query = (
+ self.query(hidden_states)
+ .view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
+ .transpose(1, 2)
+ )
+ value = (
+ self.value(hidden_states)
+ .view(batch_size, sequence_length, self.n_head, embedding_dim // self.n_head)
+ .transpose(1, 2)
+ )
+
+ if layer_past is not None:
+ past_key, past_value = layer_past
+ key = torch.cat((past_key, key), dim=-2)
+ value = torch.cat((past_value, value), dim=-2)
+
+ if use_cache is True:
+ present = (key, value)
+ else:
+ present = None
+
+ # causal self-attention
+ # [ batch_size x n_heads x sequence_length x sequence_length ]
+ attn_weights = (torch.matmul(query, key.transpose(-2, -1))) * (1.0 / math.sqrt(key.size(-1)))
+ attn_weights = attn_weights.masked_fill(
+ self.mask[:, :, :sequence_length, :sequence_length] == 0, torch.finfo(attn_weights.dtype).min
+ )
+ attn_weights = F.softmax(attn_weights, dim=-1)
+ self._attn_map = attn_weights.clone()
+ attn_weights = self.attn_drop(attn_weights)
+
+ output = torch.matmul(attn_weights, value)
+ # [ batch_size x sequence_length x embedding_dim ]
+ # re-assemble all head outputs side by side
+ output = output.transpose(1, 2).contiguous().view(batch_size, sequence_length, embedding_dim)
+
+ # output projection
+ output = self.resid_drop(self.proj(output))
+
+ outputs = (output, present)
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+class Block(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.ln1 = nn.LayerNorm(config.n_embd)
+ self.ln2 = nn.LayerNorm(config.n_embd)
+ self.attn = CausalSelfAttention(config)
+
+ # MLP
+ self.l1 = nn.Linear(config.n_embd, 4 * config.n_embd)
+ self.act = nn.GELU()
+ self.l2 = nn.Linear(4 * config.n_embd, config.n_embd)
+ self.drop = nn.Dropout(config.resid_pdrop)
+
+ def forward(
+ self,
+ hidden_states: Optional[tuple[torch.FloatTensor]],
+ layer_past: Optional[tuple[torch.Tensor]] = None,
+ use_cache: Optional[bool] = False,
+ output_attentions: Optional[bool] = False,
+ ):
+ residual = hidden_states
+ hidden_states = self.ln1(hidden_states)
+
+ attn_outputs = self.attn(
+ hidden_states, layer_past=layer_past, use_cache=use_cache, output_attentions=output_attentions
+ )
+ attn_output = attn_outputs[0]
+ outputs = attn_outputs[1:]
+ hidden_states = attn_output + residual
+
+ residual = hidden_states
+ hidden_states = self.ln2(hidden_states)
+ hidden_states = self.l1(hidden_states)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.l2(hidden_states)
+ hidden_states = residual + self.drop(hidden_states)
+
+ if use_cache:
+ outputs = (hidden_states,) + outputs
+ else:
+ outputs = (hidden_states,) + outputs[1:]
+
+ return outputs
+
+
+@add_start_docstrings(
+ "The bare TrajectoryTransformer Model transformer outputting raw hidden-states without any specific head on top.",
+ TRAJECTORY_TRANSFORMER_START_DOCSTRING,
+)
+class TrajectoryTransformerModel(TrajectoryTransformerPreTrainedModel):
+ """the full GPT language model, with a context size of block_size"""
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ # input embedding stem (+1 for stop token)
+ self.tok_emb = nn.Embedding(config.vocab_size * config.transition_dim + 1, config.n_embd)
+
+ self.pos_emb = nn.Parameter(torch.zeros(1, config.block_size, config.n_embd))
+ self.drop = nn.Dropout(config.embd_pdrop)
+ # transformer
+ self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)])
+ # decoder head
+ self.ln_f = nn.LayerNorm(config.n_embd)
+ self.head = EinLinear(config.transition_dim, config.n_embd, config.vocab_size + 1, bias=False)
+
+ self.vocab_size = config.vocab_size
+ self.stop_token = config.vocab_size * config.transition_dim
+ self.block_size = config.block_size
+
+ self.observation_dim = config.observation_dim
+ self.action_dim = config.action_dim
+ self.transition_dim = config.transition_dim
+ self.embedding_dim = config.n_embd
+
+ self.action_weight = config.action_weight
+ self.reward_weight = config.reward_weight
+ self.value_weight = config.value_weight
+
+ self.gradient_checkpointing = False
+
+ self.post_init()
+
+ def get_block_size(self):
+ return self.block_size
+
+ def offset_tokens(self, trajectories):
+ _, sequence_length = trajectories.shape
+
+ n_states = int(np.ceil(sequence_length / self.transition_dim))
+
+ offsets = torch.arange(self.transition_dim) * self.vocab_size
+ offsets = offsets.repeat(n_states).to(trajectories.device)
+
+ offset_trajectories = trajectories + offsets[:sequence_length]
+ offset_trajectories[trajectories == self.vocab_size] = self.stop_token
+ return offset_trajectories
+
+ def pad_to_full_observation(self, hidden_states):
+ batch_size, sequence_length, _ = hidden_states.shape
+
+ n_pad = (self.transition_dim - sequence_length % self.transition_dim) % self.transition_dim
+ padding = torch.zeros(batch_size, n_pad, self.embedding_dim, device=hidden_states.device)
+
+ # [ batch_size x padded_sequence_length' x embedding_dim ]
+ hidden_states_pad = torch.cat([hidden_states, padding], dim=1)
+ hidden_states_pad = hidden_states_pad.view(-1, self.transition_dim, self.embedding_dim)
+
+ return hidden_states_pad, n_pad
+
+ @add_start_docstrings_to_model_forward(
+ TRAJECTORY_TRANSFORMER_INPUTS_DOCSTRING.format("batch_size, sequence_length")
+ )
+ @replace_return_docstrings(output_type=TrajectoryTransformerOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ trajectories: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.Tensor]]] = None,
+ targets: Optional[torch.FloatTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], TrajectoryTransformerOutput]:
+ r"""
+ Returns:
+
+ Examples:
+
+ ```python
+ >>> from transformers import TrajectoryTransformerModel
+ >>> import torch
+
+ >>> model = TrajectoryTransformerModel.from_pretrained(
+ ... "CarlCochet/trajectory-transformer-halfcheetah-medium-v2"
+ ... )
+ >>> model.to(device)
+ >>> model.eval()
+
+ >>> observations_dim, action_dim, batch_size = 17, 6, 256
+ >>> seq_length = observations_dim + action_dim + 1
+
+ >>> trajectories = torch.LongTensor([np.random.permutation(self.seq_length) for _ in range(batch_size)]).to(
+ ... device
+ ... )
+ >>> targets = torch.LongTensor([np.random.permutation(self.seq_length) for _ in range(batch_size)]).to(device)
+
+ >>> outputs = model(
+ ... trajectories,
+ ... targets=targets,
+ ... use_cache=True,
+ ... output_attentions=True,
+ ... output_hidden_states=True,
+ ... return_dict=True,
+ ... )
+ ```
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+
+ if past_key_values is None:
+ past_key_values = tuple([None] * len(self.blocks))
+
+ batch_size, sequence_length = trajectories.size()
+
+ if sequence_length > self.block_size:
+ raise ValueError("Cannot forward, model block size is exhausted.")
+
+ offset_trajectories = self.offset_tokens(trajectories)
+ # [ batch_size x sequence_length x embedding_dim ]
+ # forward the GPT model
+ token_embeddings = self.tok_emb(offset_trajectories) # each index maps to a (learnable) vector
+ position_embeddings = self.pos_emb[:, :sequence_length, :] # each position maps to a (learnable) vector
+
+ hidden_states = self.drop(token_embeddings + position_embeddings)
+
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ presents = () if use_cache else None
+ all_self_attentions = () if output_attentions else None
+ all_hidden_states = () if output_hidden_states else None
+
+ for i, (block, layer_past) in enumerate(zip(self.blocks, past_key_values)):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ outputs = block(hidden_states, layer_past, use_cache, output_attentions)
+
+ hidden_states = outputs[0]
+ if use_cache is True:
+ presents = presents + (outputs[1],)
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
+
+ # [ batch_size x sequence_length x embedding_dim ]
+ hidden_state = self.ln_f(hidden_states)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ hidden_states_pad, n_pad = self.pad_to_full_observation(hidden_state)
+
+ logits = self.head(hidden_states_pad)
+ logits = logits.reshape(batch_size, sequence_length + n_pad, self.vocab_size + 1)
+ logits = logits[:, :sequence_length]
+
+ # if we are given some desired targets also calculate the loss
+ if targets is not None:
+ loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)), targets.view(-1), reduction="none")
+ if self.action_weight != 1 or self.reward_weight != 1 or self.value_weight != 1:
+ # make weights
+ n_states = int(np.ceil(sequence_length / self.transition_dim))
+ weights = torch.cat(
+ [
+ torch.ones(self.observation_dim, device=trajectories.device),
+ torch.ones(self.action_dim, device=trajectories.device) * self.action_weight,
+ torch.ones(1, device=trajectories.device) * self.reward_weight,
+ torch.ones(1, device=trajectories.device) * self.value_weight,
+ ]
+ )
+ weights = weights.repeat(n_states)
+ weights = weights[1:].repeat(batch_size, 1)
+ loss = loss * weights.view(-1)
+ loss = (loss * attention_mask.view(-1)).mean()
+ else:
+ loss = None
+
+ if not return_dict:
+ return tuple(v for v in [loss, logits, presents, all_hidden_states, all_self_attentions] if v is not None)
+
+ return TrajectoryTransformerOutput(
+ loss=loss,
+ logits=logits,
+ past_key_values=presents,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+__all__ = [
+ "TrajectoryTransformerModel",
+ "TrajectoryTransformerPreTrainedModel",
+ "load_tf_weights_in_trajectory_transformer",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ac9a2cbf4766bd187d90fdaf46505db3e92b68f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_transfo_xl import *
+ from .modeling_tf_transfo_xl import *
+ from .modeling_transfo_xl import *
+ from .tokenization_transfo_xl import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3c66924851d55d6a546b6884d2b24d40ac47037
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/configuration_transfo_xl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/configuration_transfo_xl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a6bfec513b7875c05a9f8a6c6597472067f6a36
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/configuration_transfo_xl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_tf_transfo_xl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_tf_transfo_xl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ee98e91c60ef414569e0af80ff380644044fd64
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_tf_transfo_xl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_tf_transfo_xl_utilities.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_tf_transfo_xl_utilities.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..49c2054c724f0e587d6ce57649628a657fdb318d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_tf_transfo_xl_utilities.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_transfo_xl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_transfo_xl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4caa8cf120f12b6327bdc068dd4fcbc53b31a733
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_transfo_xl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_transfo_xl_utilities.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_transfo_xl_utilities.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6aa3bc3087866c547be9ebb67da9dd46ef0f3b4a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/modeling_transfo_xl_utilities.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/tokenization_transfo_xl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/tokenization_transfo_xl.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eaf85e7490ff4e27fc64d0c1981cad51d5a98836
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/__pycache__/tokenization_transfo_xl.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/configuration_transfo_xl.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/configuration_transfo_xl.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7926246c4cbb37904fb3044507f4831bb7d9bb9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/configuration_transfo_xl.py
@@ -0,0 +1,189 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Transformer XL configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class TransfoXLConfig(PretrainedConfig):
+ """
+ This is the configuration class to store the configuration of a [`TransfoXLModel`] or a [`TFTransfoXLModel`]. It is
+ used to instantiate a Transformer-XL model according to the specified arguments, defining the model architecture.
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the TransfoXL
+ [transfo-xl/transfo-xl-wt103](https://huggingface.co/transfo-xl/transfo-xl-wt103) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 267735):
+ Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`TransfoXLModel`] or [`TFTransfoXLModel`].
+ cutoffs (`list[int]`, *optional*, defaults to `[20000, 40000, 200000]`):
+ Cutoffs for the adaptive softmax.
+ d_model (`int`, *optional*, defaults to 1024):
+ Dimensionality of the model's hidden states.
+ d_embed (`int`, *optional*, defaults to 1024):
+ Dimensionality of the embeddings
+ n_head (`int`, *optional*, defaults to 16):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ d_head (`int`, *optional*, defaults to 64):
+ Dimensionality of the model's heads.
+ d_inner (`int`, *optional*, defaults to 4096):
+ Inner dimension in FF
+ div_val (`int`, *optional*, defaults to 4):
+ Divident value for adaptive input and softmax
+ pre_lnorm (`boolean`, *optional*, defaults to `False`):
+ Whether or not to apply LayerNorm to the input instead of the output in the blocks.
+ n_layer (`int`, *optional*, defaults to 18):
+ Number of hidden layers in the Transformer encoder.
+ mem_len (`int`, *optional*, defaults to 1600):
+ Length of the retained previous heads.
+ clamp_len (`int`, *optional*, defaults to 1000):
+ Use the same pos embeddings after clamp_len.
+ same_length (`boolean`, *optional*, defaults to `True`):
+ Whether or not to use the same attn length for all tokens
+ proj_share_all_but_first (`boolean`, *optional*, defaults to `True`):
+ True to share all but first projs, False not to share.
+ attn_type (`int`, *optional*, defaults to 0):
+ Attention type. 0 for Transformer-XL, 1 for Shaw et al, 2 for Vaswani et al, 3 for Al Rfou et al.
+ sample_softmax (`int`, *optional*, defaults to -1):
+ Number of samples in the sampled softmax.
+ adaptive (`boolean`, *optional*, defaults to `True`):
+ Whether or not to use adaptive softmax.
+ dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ dropatt (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+ untie_r (`boolean`, *optional*, defaults to `True`):
+ Whether ot not to untie relative position biases.
+ init (`str`, *optional*, defaults to `"normal"`):
+ Parameter initializer to use.
+ init_range (`float`, *optional*, defaults to 0.01):
+ Parameters initialized by U(-init_range, init_range).
+ proj_init_std (`float`, *optional*, defaults to 0.01):
+ Parameters initialized by N(0, init_std)
+ init_std (`float`, *optional*, defaults to 0.02):
+ Parameters initialized by N(0, init_std)
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
+ The epsilon to use in the layer normalization layers
+ eos_token_id (`int`, *optional*, defaults to 0):
+ End of stream token id.
+
+ Examples:
+
+ ```python
+ >>> from transformers import TransfoXLConfig, TransfoXLModel
+
+ >>> # Initializing a Transformer XL configuration
+ >>> configuration = TransfoXLConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = TransfoXLModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "transfo-xl"
+ keys_to_ignore_at_inference = ["mems"]
+ attribute_map = {
+ "n_token": "vocab_size",
+ "hidden_size": "d_model",
+ "num_attention_heads": "n_head",
+ "num_hidden_layers": "n_layer",
+ }
+
+ def __init__(
+ self,
+ vocab_size=267735,
+ cutoffs=[20000, 40000, 200000],
+ d_model=1024,
+ d_embed=1024,
+ n_head=16,
+ d_head=64,
+ d_inner=4096,
+ div_val=4,
+ pre_lnorm=False,
+ n_layer=18,
+ mem_len=1600,
+ clamp_len=1000,
+ same_length=True,
+ proj_share_all_but_first=True,
+ attn_type=0,
+ sample_softmax=-1,
+ adaptive=True,
+ dropout=0.1,
+ dropatt=0.0,
+ untie_r=True,
+ init="normal",
+ init_range=0.01,
+ proj_init_std=0.01,
+ init_std=0.02,
+ layer_norm_epsilon=1e-5,
+ eos_token_id=0,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.cutoffs = []
+ self.cutoffs.extend(cutoffs)
+ if proj_share_all_but_first:
+ self.tie_projs = [False] + [True] * len(self.cutoffs)
+ else:
+ self.tie_projs = [False] + [False] * len(self.cutoffs)
+ self.d_model = d_model
+ self.d_embed = d_embed
+ self.d_head = d_head
+ self.d_inner = d_inner
+ self.div_val = div_val
+ self.pre_lnorm = pre_lnorm
+ self.n_layer = n_layer
+ self.n_head = n_head
+ self.mem_len = mem_len
+ self.same_length = same_length
+ self.attn_type = attn_type
+ self.clamp_len = clamp_len
+ self.sample_softmax = sample_softmax
+ self.adaptive = adaptive
+ self.dropout = dropout
+ self.dropatt = dropatt
+ self.untie_r = untie_r
+ self.init = init
+ self.init_range = init_range
+ self.proj_init_std = proj_init_std
+ self.init_std = init_std
+ self.layer_norm_epsilon = layer_norm_epsilon
+ super().__init__(eos_token_id=eos_token_id, **kwargs)
+
+ @property
+ def max_position_embeddings(self):
+ # Message copied from Transformer-XL documentation
+ logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit.")
+ return -1
+
+ @max_position_embeddings.setter
+ def max_position_embeddings(self, value):
+ # Message copied from Transformer-XL documentation
+ raise NotImplementedError(
+ f"The model {self.model_type} is one of the few models that has no sequence length limit."
+ )
+
+
+__all__ = ["TransfoXLConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c7830d633448bde3b8a420f0d84cdd070498882
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py
@@ -0,0 +1,1128 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+TF 2.0 Transformer XL model.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import numpy as np
+import tensorflow as tf
+
+from ....modeling_tf_utils import (
+ TFModelInputType,
+ TFPreTrainedModel,
+ TFSequenceClassificationLoss,
+ get_initializer,
+ keras,
+ keras_serializable,
+ unpack_inputs,
+)
+from ....tf_utils import shape_list, stable_softmax
+from ....utils import (
+ ModelOutput,
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+)
+from .configuration_transfo_xl import TransfoXLConfig
+from .modeling_tf_transfo_xl_utilities import TFAdaptiveSoftmaxMask
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "transfo-xl/transfo-xl-wt103"
+_CONFIG_FOR_DOC = "TransfoXLConfig"
+
+
+class TFPositionalEmbedding(keras.layers.Layer):
+ def __init__(self, demb, **kwargs):
+ super().__init__(**kwargs)
+
+ self.inv_freq = 1 / (10000 ** (tf.range(0, demb, 2.0) / demb))
+
+ def call(self, pos_seq, bsz=None):
+ self.inv_freq = tf.cast(self.inv_freq, dtype=pos_seq.dtype)
+ sinusoid_inp = tf.einsum("i,j->ij", pos_seq, self.inv_freq)
+ pos_emb = tf.concat([tf.sin(sinusoid_inp), tf.cos(sinusoid_inp)], -1)
+
+ if bsz is not None:
+ return tf.tile(pos_emb[:, None, :], [1, bsz, 1])
+ else:
+ return pos_emb[:, None, :]
+
+
+class TFPositionwiseFF(keras.layers.Layer):
+ def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5, init_std=0.02, **kwargs):
+ super().__init__(**kwargs)
+
+ self.d_model = d_model
+ self.d_inner = d_inner
+ self.dropout = dropout
+
+ self.layer_1 = keras.layers.Dense(
+ d_inner, kernel_initializer=get_initializer(init_std), activation=tf.nn.relu, name="CoreNet_._0"
+ )
+ self.drop_1 = keras.layers.Dropout(dropout)
+ self.layer_2 = keras.layers.Dense(d_model, kernel_initializer=get_initializer(init_std), name="CoreNet_._3")
+ self.drop_2 = keras.layers.Dropout(dropout)
+
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layer_norm")
+
+ self.pre_lnorm = pre_lnorm
+
+ def call(self, inp, training=False):
+ if self.pre_lnorm:
+ # layer normalization + positionwise feed-forward
+ core_out = self.layer_norm(inp)
+ core_out = self.layer_1(core_out)
+ core_out = self.drop_1(core_out, training=training)
+ core_out = self.layer_2(core_out)
+ core_out = self.drop_2(core_out, training=training)
+
+ # residual connection
+ output = core_out + inp
+ else:
+ # positionwise feed-forward
+ core_out = self.layer_1(inp)
+ core_out = self.drop_1(core_out, training=training)
+ core_out = self.layer_2(core_out)
+ core_out = self.drop_2(core_out, training=training)
+
+ # residual connection + layer normalization
+ output = self.layer_norm(inp + core_out)
+
+ return output
+
+
+class TFRelPartialLearnableMultiHeadAttn(keras.layers.Layer):
+ def __init__(
+ self,
+ n_head,
+ d_model,
+ d_head,
+ dropout,
+ dropatt=0.0,
+ pre_lnorm=False,
+ r_r_bias=None,
+ r_w_bias=None,
+ layer_norm_epsilon=1e-5,
+ init_std=0.02,
+ output_attentions=False,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.n_head = n_head
+ self.d_model = d_model
+ self.d_head = d_head
+ self.dropout = dropout
+ self.output_attentions = output_attentions
+
+ self.qkv_net = keras.layers.Dense(
+ 3 * n_head * d_head, kernel_initializer=get_initializer(init_std), use_bias=False, name="qkv_net"
+ )
+
+ self.drop = keras.layers.Dropout(dropout)
+ self.dropatt = keras.layers.Dropout(dropatt)
+ self.o_net = keras.layers.Dense(
+ d_model, kernel_initializer=get_initializer(init_std), use_bias=False, name="o_net"
+ )
+
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=layer_norm_epsilon, name="layer_norm")
+
+ self.scale = 1 / (d_head**0.5)
+
+ self.pre_lnorm = pre_lnorm
+
+ if r_r_bias is not None and r_w_bias is not None: # Biases are shared
+ self.r_r_bias = r_r_bias
+ self.r_w_bias = r_w_bias
+ else:
+ self.r_r_bias = None
+ self.r_w_bias = None
+
+ self.r_net = keras.layers.Dense(
+ self.n_head * self.d_head, kernel_initializer=get_initializer(init_std), use_bias=False, name="r_net"
+ )
+
+ def build(self, input_shape):
+ if self.r_r_bias is None or self.r_w_bias is None: # Biases are not shared
+ self.r_r_bias = self.add_weight(
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias"
+ )
+ self.r_w_bias = self.add_weight(
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias"
+ )
+ super().build(input_shape)
+
+ def _rel_shift(self, x):
+ x_size = shape_list(x)
+
+ x = tf.pad(x, [[0, 0], [1, 0], [0, 0], [0, 0]])
+ x = tf.reshape(x, [x_size[1] + 1, x_size[0], x_size[2], x_size[3]])
+ x = tf.slice(x, [1, 0, 0, 0], [-1, -1, -1, -1])
+ x = tf.reshape(x, x_size)
+
+ return x
+
+ def call(self, w, r, attn_mask, mems, head_mask, output_attentions, training=False):
+ qlen, rlen, bsz = shape_list(w)[0], shape_list(r)[0], shape_list(w)[1]
+
+ if mems is not None:
+ mems = tf.cast(mems, dtype=w.dtype)
+ cat = tf.concat([mems, w], 0)
+ if self.pre_lnorm:
+ w_heads = self.qkv_net(self.layer_norm(cat))
+ else:
+ w_heads = self.qkv_net(cat)
+ r_head_k = self.r_net(r)
+
+ w_head_q, w_head_k, w_head_v = tf.split(w_heads, 3, axis=-1)
+ w_head_q = w_head_q[-qlen:]
+ else:
+ if self.pre_lnorm:
+ w_heads = self.qkv_net(self.layer_norm(w))
+ else:
+ w_heads = self.qkv_net(w)
+ r_head_k = self.r_net(r)
+
+ w_head_q, w_head_k, w_head_v = tf.split(w_heads, 3, axis=-1)
+
+ klen = shape_list(w_head_k)[0]
+
+ w_head_q = tf.reshape(w_head_q, (qlen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
+ w_head_k = tf.reshape(w_head_k, (klen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
+ w_head_v = tf.reshape(w_head_v, (klen, bsz, self.n_head, self.d_head)) # qlen x bsz x n_head x d_head
+
+ r_head_k = tf.reshape(r_head_k, (rlen, self.n_head, self.d_head)) # qlen x n_head x d_head
+
+ # compute attention score
+ rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head
+ AC = tf.einsum("ibnd,jbnd->ijbn", rw_head_q, w_head_k) # qlen x klen x bsz x n_head
+
+ rr_head_q = w_head_q + self.r_r_bias
+ BD = tf.einsum("ibnd,jnd->ijbn", rr_head_q, r_head_k) # qlen x klen x bsz x n_head
+ BD = self._rel_shift(BD)
+
+ # [qlen x klen x bsz x n_head]
+ attn_score = AC + BD
+ attn_score = attn_score * self.scale
+
+ # compute attention probability
+ if attn_mask is not None:
+ attn_mask_t = attn_mask[:, :, None, None]
+ attn_mask_t = tf.cast(attn_mask_t, dtype=attn_score.dtype)
+ attn_score = attn_score * (1.0 - attn_mask_t) - 1e30 * attn_mask_t
+
+ # [qlen x klen x bsz x n_head]
+ attn_prob = stable_softmax(attn_score, axis=1)
+ attn_prob = self.dropatt(attn_prob, training=training)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attn_prob = attn_prob * head_mask
+
+ # compute attention vector
+ attn_vec = tf.einsum("ijbn,jbnd->ibnd", attn_prob, w_head_v)
+
+ # [qlen x bsz x n_head x d_head]
+ attn_vec_sizes = shape_list(attn_vec)
+ attn_vec = tf.reshape(attn_vec, (attn_vec_sizes[0], attn_vec_sizes[1], self.n_head * self.d_head))
+
+ # linear projection
+ attn_out = self.o_net(attn_vec)
+ attn_out = self.drop(attn_out, training=training)
+
+ if self.pre_lnorm:
+ # residual connection
+ outputs = [w + attn_out]
+ else:
+ # residual connection + layer normalization
+ outputs = [self.layer_norm(w + attn_out)]
+
+ if output_attentions:
+ outputs.append(attn_prob)
+
+ return outputs
+
+
+class TFRelPartialLearnableDecoderLayer(keras.layers.Layer):
+ def __init__(
+ self,
+ n_head,
+ d_model,
+ d_head,
+ d_inner,
+ dropout,
+ dropatt=0.0,
+ pre_lnorm=False,
+ r_w_bias=None,
+ r_r_bias=None,
+ layer_norm_epsilon=1e-5,
+ init_std=0.02,
+ output_attentions=False,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.dec_attn = TFRelPartialLearnableMultiHeadAttn(
+ n_head,
+ d_model,
+ d_head,
+ dropout,
+ dropatt=dropatt,
+ pre_lnorm=pre_lnorm,
+ r_w_bias=r_w_bias,
+ r_r_bias=r_r_bias,
+ init_std=init_std,
+ layer_norm_epsilon=layer_norm_epsilon,
+ output_attentions=output_attentions,
+ name="dec_attn",
+ )
+ self.pos_ff = TFPositionwiseFF(
+ d_model,
+ d_inner,
+ dropout,
+ pre_lnorm=pre_lnorm,
+ init_std=init_std,
+ layer_norm_epsilon=layer_norm_epsilon,
+ name="pos_ff",
+ )
+
+ def call(self, dec_inp, r, dec_attn_mask, mems, head_mask, output_attentions, training=False):
+ attn_outputs = self.dec_attn(dec_inp, r, dec_attn_mask, mems, head_mask, output_attentions, training=training)
+ ff_output = self.pos_ff(attn_outputs[0], training=training)
+
+ outputs = [ff_output] + attn_outputs[1:]
+
+ return outputs
+
+
+class TFTransfoEmbeddings(keras.layers.Layer):
+ def __init__(self, vocab_size, emb_size, init_std, **kwargs):
+ super().__init__(**kwargs)
+
+ self.vocab_size = vocab_size
+ self.emb_size = emb_size
+ self.init_std = init_std
+
+ def build(self, input_shape):
+ self.weight = self.add_weight(
+ shape=(self.vocab_size, self.emb_size),
+ initializer=get_initializer(self.init_std),
+ name="embeddings",
+ )
+
+ super().build(input_shape)
+
+ def call(self, inputs):
+ return tf.gather(self.weight, inputs)
+
+
+class TFAdaptiveEmbedding(keras.layers.Layer):
+ def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, init_std=0.02, sample_softmax=False, **kwargs):
+ super().__init__(**kwargs)
+
+ self.n_token = n_token
+ self.d_embed = d_embed
+ self.init_std = init_std
+
+ self.cutoffs = cutoffs + [n_token]
+ self.div_val = div_val
+ self.d_proj = d_proj
+
+ self.emb_scale = d_proj**0.5
+
+ self.cutoff_ends = [0] + self.cutoffs
+
+ self.emb_layers = []
+ self.emb_projs = []
+
+ if div_val == 1:
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
+ else:
+ for i in range(len(self.cutoffs)):
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
+ d_emb_i = d_embed // (div_val**i)
+ self.emb_layers.append(
+ TFTransfoEmbeddings(
+ r_idx - l_idx,
+ d_emb_i,
+ init_std,
+ name=f"emb_layers_._{i}",
+ )
+ )
+
+ def build(self, input_shape):
+ for i in range(len(self.cutoffs)):
+ d_emb_i = self.d_embed // (self.div_val**i)
+ self.emb_projs.append(
+ self.add_weight(
+ shape=(d_emb_i, self.d_proj),
+ initializer=get_initializer(self.init_std),
+ trainable=True,
+ name=f"emb_projs_._{i}",
+ )
+ )
+
+ super().build(input_shape)
+
+ def call(self, inp):
+ if self.div_val == 1:
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
+ else:
+ inp_flat = tf.reshape(inp, (-1,))
+ emb_flat = tf.zeros([shape_list(inp_flat)[0], self.d_proj])
+ for i in range(len(self.cutoffs)):
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
+
+ mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx)
+
+ inp_i = tf.boolean_mask(inp_flat, mask_i) - l_idx
+ emb_i = self.emb_layers[i](inp_i)
+ emb_i = tf.einsum("id,de->ie", emb_i, self.emb_projs[i])
+
+ mask_idx = tf.where(mask_i)
+ scatter = tf.scatter_nd(mask_idx, emb_i, shape_list(emb_flat))
+ emb_flat = tf.cast(emb_flat, dtype=scatter.dtype)
+ emb_flat += scatter
+
+ embed_shape = shape_list(inp) + [self.d_proj]
+ embed = tf.reshape(emb_flat, embed_shape)
+
+ embed *= self.emb_scale
+
+ return embed
+
+
+@keras_serializable
+class TFTransfoXLMainLayer(keras.layers.Layer):
+ config_class = TransfoXLConfig
+
+ def __init__(self, config, **kwargs):
+ super().__init__(**kwargs)
+
+ self.config = config
+ self.output_hidden_states = config.output_hidden_states
+ self.output_attentions = config.output_attentions
+ self.return_dict = config.use_return_dict
+
+ self.n_token = config.vocab_size
+
+ self.d_embed = config.d_embed
+ self.d_model = config.d_model
+ self.n_head = config.n_head
+ self.d_head = config.d_head
+ self.untie_r = config.untie_r
+
+ self.word_emb = TFAdaptiveEmbedding(
+ config.vocab_size,
+ config.d_embed,
+ config.d_model,
+ config.cutoffs,
+ div_val=config.div_val,
+ init_std=config.init_std,
+ name="word_emb",
+ )
+
+ self.drop = keras.layers.Dropout(config.dropout)
+
+ self.n_layer = config.n_layer
+ self.mem_len = config.mem_len
+ self.attn_type = config.attn_type
+
+ self.layers = []
+ if config.attn_type == 0: # the default attention
+ for i in range(config.n_layer):
+ self.layers.append(
+ TFRelPartialLearnableDecoderLayer(
+ config.n_head,
+ config.d_model,
+ config.d_head,
+ config.d_inner,
+ config.dropout,
+ dropatt=config.dropatt,
+ pre_lnorm=config.pre_lnorm,
+ r_w_bias=None if self.untie_r else self.r_w_bias,
+ r_r_bias=None if self.untie_r else self.r_r_bias,
+ layer_norm_epsilon=config.layer_norm_epsilon,
+ init_std=config.init_std,
+ output_attentions=self.output_attentions,
+ name=f"layers_._{i}",
+ )
+ )
+ else: # learnable embeddings and absolute embeddings
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
+
+ self.same_length = config.same_length
+ self.clamp_len = config.clamp_len
+
+ if self.attn_type == 0: # default attention
+ self.pos_emb = TFPositionalEmbedding(self.d_model, name="pos_emb")
+ else: # learnable embeddings and absolute embeddings
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
+
+ def build(self, input_shape):
+ if not self.untie_r:
+ self.r_w_bias = self.add_weight(
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias"
+ )
+ self.r_r_bias = self.add_weight(
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias"
+ )
+ super().build(input_shape)
+
+ def get_input_embeddings(self):
+ return self.word_emb
+
+ def set_input_embeddings(self, value):
+ raise NotImplementedError
+
+ def backward_compatible(self):
+ self.sample_softmax = -1
+
+ def reset_memory_length(self, mem_len):
+ self.mem_len = mem_len
+
+ def _prune_heads(self, heads):
+ raise NotImplementedError
+
+ def init_mems(self, bsz):
+ if self.mem_len > 0:
+ mems = []
+ for i in range(self.n_layer):
+ empty = tf.zeros([self.mem_len, bsz, self.d_model])
+ mems.append(empty)
+
+ return mems
+ else:
+ return None
+
+ def _update_mems(self, hids, mems, mlen, qlen):
+ # does not deal with None
+ if mems is None:
+ return None
+
+ # mems is not None
+ assert len(hids) == len(mems), "len(hids) != len(mems)"
+
+ # There are `mlen + qlen` steps that can be cached into mems
+ new_mems = []
+ end_idx = mlen + tf.math.maximum(0, qlen)
+ beg_idx = tf.math.maximum(0, end_idx - tf.convert_to_tensor(self.mem_len))
+ for i in range(len(hids)):
+ mems[i] = tf.cast(mems[i], dtype=hids[i].dtype)
+ cat = tf.concat([mems[i], hids[i]], axis=0)
+ tf.stop_gradient(cat)
+ new_mems.append(cat[beg_idx:end_idx])
+
+ return new_mems
+
+ @unpack_inputs
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ mems: list[tf.Tensor] | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ):
+ # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library
+ # so we transpose here from shape [bsz, len] to shape [len, bsz]
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_ids = tf.transpose(input_ids, perm=(1, 0))
+ qlen, bsz = shape_list(input_ids)
+ elif inputs_embeds is not None:
+ inputs_embeds = tf.transpose(inputs_embeds, perm=(1, 0, 2))
+ qlen, bsz = shape_list(inputs_embeds)[:2]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ if mems is None:
+ mems = self.init_mems(bsz)
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
+ # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
+ if head_mask is not None:
+ raise NotImplementedError
+ else:
+ head_mask = [None] * self.n_layer
+
+ if inputs_embeds is not None:
+ word_emb = inputs_embeds
+ else:
+ word_emb = self.word_emb(input_ids)
+
+ mlen = shape_list(mems[0])[0] if mems is not None else 0
+ klen = mlen + qlen
+
+ # Compute decoder attention mask
+ all_ones = tf.ones([qlen, klen], dtype=tf.int32)
+ upper_mask = 1 - tf.linalg.band_part(tf.ones([qlen, klen], dtype=tf.int32), -1, mlen)
+ if self.same_length:
+ mask_len = klen - self.mem_len
+ mask_shift_len = qlen - tf.nn.relu(mask_len) # Lazy clamping of negatives to zero
+
+ # Use an indicator variable instead of a conditional to keep the compiler happy
+ lower_mask = tf.linalg.band_part(all_ones, -1, 0) - (
+ tf.linalg.band_part(all_ones, mask_shift_len - 1, 0) * tf.cast(mask_shift_len != 0, tf.int32)
+ )
+ dec_attn_mask = upper_mask + lower_mask
+ else:
+ dec_attn_mask = upper_mask
+
+ hids = []
+ attentions = [] if output_attentions else None
+ if self.attn_type == 0: # default
+ pos_seq = tf.range(klen - 1, -1, -1.0)
+ if self.clamp_len > 0:
+ pos_seq = tf.minimum(pos_seq, self.clamp_len)
+ pos_emb = self.pos_emb(pos_seq)
+
+ core_out = self.drop(word_emb, training=training)
+ pos_emb = self.drop(pos_emb, training=training)
+
+ for i, layer in enumerate(self.layers):
+ hids.append(core_out)
+ mems_i = None if mems is None else mems[i]
+ layer_outputs = layer(
+ core_out,
+ pos_emb,
+ dec_attn_mask,
+ mems_i,
+ head_mask[i],
+ output_attentions,
+ training=training,
+ )
+ core_out = layer_outputs[0]
+ if output_attentions:
+ attentions.append(layer_outputs[1])
+ else: # learnable embeddings and absolute embeddings
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
+
+ core_out = self.drop(core_out, training=training)
+
+ new_mems = self._update_mems(hids, mems, mlen, qlen)
+
+ # We transpose back here to shape [bsz, len, hidden_dim]
+ core_out = tf.transpose(core_out, perm=(1, 0, 2))
+
+ if output_hidden_states:
+ # Transpose to library standard shape [bsz, len, hidden_dim] and add last layer
+ hids = tuple(tf.transpose(t, perm=(1, 0, 2)) for t in hids)
+ hids = hids + (core_out,)
+ else:
+ hids = None
+ if output_attentions:
+ # Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len]
+ attentions = tuple(tf.transpose(t, perm=(2, 3, 0, 1)) for t in attentions)
+
+ if not return_dict:
+ return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None)
+
+ return TFTransfoXLModelOutput(
+ last_hidden_state=core_out,
+ mems=new_mems,
+ hidden_states=hids,
+ attentions=attentions,
+ )
+
+
+class TFTransfoXLPreTrainedModel(TFPreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config_class = TransfoXLConfig
+ base_model_prefix = "transformer"
+
+
+@dataclass
+class TFTransfoXLModelOutput(ModelOutput):
+ """
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
+
+ Args:
+ last_hidden_state (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the model.
+ mems (`list[tf.Tensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
+ be passed as input ids as they have already been computed.
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ last_hidden_state: tf.Tensor | None = None
+ mems: list[tf.Tensor] = None
+ hidden_states: tuple[tf.Tensor] | None = None
+ attentions: tuple[tf.Tensor] | None = None
+
+
+@dataclass
+class TFTransfoXLLMHeadModelOutput(ModelOutput):
+ """
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
+
+ Args:
+ losses (`tf.Tensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided):
+ Language modeling losses (not reduced).
+ prediction_scores (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax).
+ mems (`list[tf.Tensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
+ be passed as input ids as they have already been computed.
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ prediction_scores: tf.Tensor | None = None
+ mems: list[tf.Tensor] = None
+ hidden_states: tuple[tf.Tensor] | None = None
+ attentions: tuple[tf.Tensor] | None = None
+
+
+@dataclass
+class TFTransfoXLSequenceClassifierOutputWithPast(ModelOutput):
+ """
+ Base class for outputs of sentence classification models.
+
+ Args:
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
+ mems (`list[tf.Tensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
+ be passed as input ids as they have already been computed.
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: tf.Tensor | None = None
+ logits: tf.Tensor | None = None
+ mems: list[tf.Tensor] = None
+ hidden_states: tuple[tf.Tensor] | None = None
+ attentions: tuple[tf.Tensor] | None = None
+
+
+TRANSFO_XL_START_DOCSTRING = r"""
+
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
+ behavior.
+
+
+
+ TensorFlow models and layers in `transformers` accept two formats as input:
+
+ - having all inputs as keyword arguments (like PyTorch models), or
+ - having all inputs as a list, tuple or dict in the first positional argument.
+
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
+ positional argument:
+
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
+
+ Note that when creating models and layers with
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
+ about any of this, as you can just pass inputs like you would to any other Python function!
+
+
+
+ Parameters:
+ config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+TRANSFO_XL_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
+ [`PreTrainedTokenizer.encode`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ mems (`list[tf.Tensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
+ `mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems
+ given to this model should not be passed as `input_ids` as they have already been computed.
+ head_mask (`tf.Tensor` or `Numpy array` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+ inputs_embeds (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
+ config will be used instead.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
+ used instead.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
+ eager mode, in graph mode the value will always be set to True.
+ training (`bool`, *optional*, defaults to `False`):
+ Whether or not to use the model in training mode (some modules like dropout modules have different
+ behaviors between training and evaluation).
+"""
+
+
+@add_start_docstrings(
+ "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
+ TRANSFO_XL_START_DOCSTRING,
+)
+class TFTransfoXLModel(TFTransfoXLPreTrainedModel):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.transformer = TFTransfoXLMainLayer(config, name="transformer")
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFTransfoXLModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ mems: list[tf.Tensor] | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ training: bool = False,
+ ) -> TFTransfoXLModelOutput | tuple[tf.Tensor]:
+ outputs = self.transformer(
+ input_ids=input_ids,
+ mems=mems,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ return outputs
+
+
+@add_start_docstrings(
+ """
+ The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive
+ input embeddings)
+ """,
+ TRANSFO_XL_START_DOCSTRING,
+)
+class TFTransfoXLLMHeadModel(TFTransfoXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.transformer = TFTransfoXLMainLayer(config, name="transformer")
+ self.sample_softmax = config.sample_softmax
+ assert self.sample_softmax <= 0, (
+ "Sampling from the softmax is not implemented yet. Please look at issue: #3310:"
+ " https://github.com/huggingface/transformers/issues/3310"
+ )
+
+ self.crit = TFAdaptiveSoftmaxMask(
+ config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val, name="crit"
+ )
+
+ def _resize_token_embeddings(self, new_num_tokens):
+ raise NotImplementedError()
+
+ def get_output_embeddings(self):
+ """Double-check if you are using adaptive softmax."""
+ if len(self.crit.out_layers) > 0:
+ return self.crit.out_layers[-1]
+ return None
+
+ def reset_memory_length(self, mem_len):
+ self.transformer.reset_memory_length(mem_len)
+
+ def init_mems(self, bsz):
+ return self.transformer.init_mems(bsz)
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFTransfoXLLMHeadModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ mems: list[tf.Tensor] | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ) -> TFTransfoXLLMHeadModelOutput | tuple[tf.Tensor]:
+ if input_ids is not None:
+ bsz, tgt_len = shape_list(input_ids)[:2]
+ else:
+ bsz, tgt_len = shape_list(inputs_embeds)[:2]
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ mems,
+ head_mask,
+ inputs_embeds,
+ output_attentions,
+ output_hidden_states,
+ return_dict,
+ training=training,
+ )
+
+ last_hidden = transformer_outputs[0]
+ pred_hid = last_hidden[:, -tgt_len:]
+
+ softmax_output = self.crit(pred_hid, labels, training=training)
+ prediction_scores = softmax_output if labels is None else ()
+
+ if not return_dict:
+ return (prediction_scores,) + transformer_outputs[1:]
+
+ return TFTransfoXLLMHeadModelOutput(
+ prediction_scores=prediction_scores,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **model_kwargs):
+ inputs = {}
+
+ # if past is defined in model kwargs then use it for faster decoding
+ if past_key_values:
+ input_ids = tf.expand_dims(input_ids[:, -1], axis=-1)
+ else:
+ input_ids = input_ids
+
+ return inputs
+
+ # Adapted from the torch tie_weights function
+ def tf_to_pt_weight_rename(self, tf_weight):
+ if self.config.tie_word_embeddings and "crit.out_layers" in tf_weight:
+ return tf_weight, tf_weight.replace("crit.out_layers", "transformer.word_emb.emb_layers")
+ elif self.config.tie_projs and "crit.out_projs" in tf_weight:
+ for i, tie_proj in enumerate(self.config.tie_projs):
+ if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed:
+ # self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0]
+ return tf_weight, tf_weight.replace(f"crit.out_projs.{i}", "transformer.word_emb.emb_projs.0")
+ elif tie_proj and self.config.div_val != 1:
+ # self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i]
+ return tf_weight, tf_weight.replace("crit.out_projs", "transformer.word_emb.emb_projs")
+ else:
+ return (tf_weight,)
+
+
+@add_start_docstrings(
+ """
+ The Transfo XL Model transformer with a sequence classification head on top (linear layer).
+
+ [`TFTransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal
+ models (e.g. GPT-1,GPT-2) do.
+
+ Since it does classification on the last token, it requires to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """,
+ TRANSFO_XL_START_DOCSTRING,
+)
+class TFTransfoXLForSequenceClassification(TFTransfoXLPreTrainedModel, TFSequenceClassificationLoss):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.num_labels = config.num_labels
+ self.score = keras.layers.Dense(
+ config.num_labels,
+ kernel_initializer=get_initializer(config.init_range),
+ name="score",
+ use_bias=False,
+ )
+ self.transformer = TFTransfoXLMainLayer(config, name="transformer")
+
+ def get_output_embeddings(self):
+ # Remove after transformers v4.32. Fix this model's `test_model_common_attributes` test too.
+ logger.warning(
+ "Sequence classification models do not have output embeddings. `.get_output_embeddings` will be removed "
+ "in transformers v4.32."
+ )
+ return self.transformer.word_emb
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFTransfoXLSequenceClassifierOutputWithPast,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ mems: list[tf.Tensor] | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool | None = False,
+ ) -> tuple | TFTransfoXLSequenceClassifierOutputWithPast:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
+ config.vocab_size - 1]`.
+ """
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ mems=mems,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ hidden_states = transformer_outputs[0]
+ logits = self.score(hidden_states)
+ in_logits = None
+ if self.config.pad_token_id is None:
+ sequence_lengths = -1
+ else:
+ if input_ids is not None:
+ sequence_lengths = (
+ tf.argmax(tf.cast(tf.math.equal(input_ids, self.config.pad_token_id), input_ids.dtype), axis=-1)
+ - 1
+ )
+ sequence_lengths = tf.where(sequence_lengths >= 0, sequence_lengths, input_ids.shape[-1] - 1)
+ in_logits = tf.gather(logits, sequence_lengths, batch_dims=1, axis=1)
+ else:
+ sequence_lengths = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+ loss = None
+
+ if labels is not None:
+ if input_ids is not None:
+ batch_size, sequence_length = shape_list(input_ids)[:2]
+ else:
+ batch_size, sequence_length = shape_list(inputs_embeds)[:2]
+ assert self.config.pad_token_id is not None or batch_size == 1, (
+ "Cannot handle batch sizes > 1 if no padding token is defined."
+ )
+
+ if not tf.is_tensor(sequence_lengths):
+ in_logits = logits[0:batch_size, sequence_lengths]
+
+ loss = self.hf_compute_loss(tf.reshape(labels, [-1, 1]), tf.reshape(in_logits, [-1, self.num_labels]))
+
+ pooled_logits = in_logits if in_logits is not None else logits
+
+ if not return_dict:
+ output = (pooled_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFTransfoXLSequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = [
+ "TFAdaptiveEmbedding",
+ "TFTransfoXLForSequenceClassification",
+ "TFTransfoXLLMHeadModel",
+ "TFTransfoXLMainLayer",
+ "TFTransfoXLModel",
+ "TFTransfoXLPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py
new file mode 100644
index 0000000000000000000000000000000000000000..48205e06fb20a473959544db4971dff0d3e58cbf
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py
@@ -0,0 +1,178 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+A TF 2.0 Adaptive Softmax for Transformer XL model.
+"""
+
+import tensorflow as tf
+
+from ....modeling_tf_utils import keras
+from ....tf_utils import shape_list
+
+
+class TFAdaptiveSoftmaxMask(keras.layers.Layer):
+ def __init__(self, vocab_size, d_embed, d_proj, cutoffs, div_val=1, keep_order=False, **kwargs):
+ super().__init__(**kwargs)
+
+ self.vocab_size = vocab_size
+ self.d_embed = d_embed
+ self.d_proj = d_proj
+
+ self.cutoffs = cutoffs + [vocab_size]
+ self.cutoff_ends = [0] + self.cutoffs
+ self.div_val = div_val
+
+ self.shortlist_size = self.cutoffs[0]
+ self.n_clusters = len(self.cutoffs) - 1
+ self.head_size = self.shortlist_size + self.n_clusters
+ self.keep_order = keep_order
+
+ self.out_layers = []
+ self.out_projs = []
+
+ def build(self, input_shape):
+ if self.n_clusters > 0:
+ self.cluster_weight = self.add_weight(
+ shape=(self.n_clusters, self.d_embed), initializer="zeros", trainable=True, name="cluster_weight"
+ )
+ self.cluster_bias = self.add_weight(
+ shape=(self.n_clusters,), initializer="zeros", trainable=True, name="cluster_bias"
+ )
+
+ if self.div_val == 1:
+ for i in range(len(self.cutoffs)):
+ if self.d_proj != self.d_embed:
+ weight = self.add_weight(
+ shape=(self.d_embed, self.d_proj),
+ initializer="zeros",
+ trainable=True,
+ name=f"out_projs_._{i}",
+ )
+ self.out_projs.append(weight)
+ else:
+ self.out_projs.append(None)
+ weight = self.add_weight(
+ shape=(self.vocab_size, self.d_embed),
+ initializer="zeros",
+ trainable=True,
+ name=f"out_layers_._{i}_._weight",
+ )
+ bias = self.add_weight(
+ shape=(self.vocab_size,),
+ initializer="zeros",
+ trainable=True,
+ name=f"out_layers_._{i}_._bias",
+ )
+ self.out_layers.append((weight, bias))
+ else:
+ for i in range(len(self.cutoffs)):
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
+ d_emb_i = self.d_embed // (self.div_val**i)
+
+ weight = self.add_weight(
+ shape=(d_emb_i, self.d_proj), initializer="zeros", trainable=True, name=f"out_projs_._{i}"
+ )
+ self.out_projs.append(weight)
+ weight = self.add_weight(
+ shape=(r_idx - l_idx, d_emb_i),
+ initializer="zeros",
+ trainable=True,
+ name=f"out_layers_._{i}_._weight",
+ )
+ bias = self.add_weight(
+ shape=(r_idx - l_idx,),
+ initializer="zeros",
+ trainable=True,
+ name=f"out_layers_._{i}_._bias",
+ )
+ self.out_layers.append((weight, bias))
+ super().build(input_shape)
+
+ @staticmethod
+ def _logit(x, W, b, proj=None):
+ y = x
+ if proj is not None:
+ y = tf.einsum("ibd,ed->ibe", y, proj)
+ return tf.einsum("ibd,nd->ibn", y, W) + b
+
+ @staticmethod
+ def _gather_logprob(logprob, target):
+ lp_size = shape_list(logprob)
+ r = tf.range(lp_size[0], dtype=target.dtype)
+ idx = tf.stack([r, target], 1)
+ return tf.gather_nd(logprob, idx)
+
+ def call(self, hidden, target, return_mean=True, training=False):
+ head_logprob = 0
+ if self.n_clusters == 0:
+ output = self._logit(hidden, self.out_layers[0][0], self.out_layers[0][1], self.out_projs[0])
+ if target is not None:
+ loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=target, logits=output)
+ out = tf.nn.log_softmax(output, axis=-1)
+ else:
+ hidden_sizes = shape_list(hidden)
+ out = []
+ loss = tf.zeros(hidden_sizes[:2])
+ for i in range(len(self.cutoffs)):
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
+ if target is not None:
+ mask = (target >= l_idx) & (target < r_idx)
+ mask_idx = tf.where(mask)
+ cur_target = tf.boolean_mask(target, mask) - l_idx
+
+ if self.div_val == 1:
+ cur_W = self.out_layers[0][0][l_idx:r_idx]
+ cur_b = self.out_layers[0][1][l_idx:r_idx]
+ else:
+ cur_W = self.out_layers[i][0]
+ cur_b = self.out_layers[i][1]
+
+ if i == 0:
+ cur_W = tf.concat([cur_W, self.cluster_weight], 0)
+ cur_b = tf.concat([cur_b, self.cluster_bias], 0)
+
+ head_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[0])
+ head_logprob = tf.nn.log_softmax(head_logit)
+ out.append(head_logprob[..., : self.cutoffs[0]])
+ if target is not None:
+ cur_head_logprob = tf.boolean_mask(head_logprob, mask)
+ cur_logprob = self._gather_logprob(cur_head_logprob, cur_target)
+ else:
+ tail_logit = self._logit(hidden, cur_W, cur_b, self.out_projs[i])
+ tail_logprob = tf.nn.log_softmax(tail_logit)
+ cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster
+ logprob_i = head_logprob[..., cluster_prob_idx, None] + tail_logprob
+ out.append(logprob_i)
+ if target is not None:
+ cur_head_logprob = tf.boolean_mask(head_logprob, mask)
+ cur_tail_logprob = tf.boolean_mask(tail_logprob, mask)
+ cur_logprob = self._gather_logprob(cur_tail_logprob, cur_target)
+ cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
+ if target is not None:
+ loss += tf.scatter_nd(mask_idx, -cur_logprob, shape_list(loss))
+ out = tf.concat(out, axis=-1)
+
+ if target is not None:
+ if return_mean:
+ loss = tf.reduce_mean(loss)
+ # Add the training-time loss value to the layer using `self.add_loss()`.
+ self.add_loss(loss)
+
+ # Log the loss as a metric (we could log arbitrary metrics,
+ # including different metrics for training and inference.
+ self.add_metric(loss, name=self.name, aggregation="mean" if return_mean else "")
+
+ return out
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c469036f23251f5a29078c95799f6bc802a7c4f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py
@@ -0,0 +1,1303 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+PyTorch Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl. In particular
+https://github.com/kimiyoung/transformer-xl/blob/master/pytorch/mem_transformer.py
+"""
+
+import warnings
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....modeling_utils import PreTrainedModel
+from ....utils import (
+ ModelOutput,
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+)
+from .configuration_transfo_xl import TransfoXLConfig
+from .modeling_transfo_xl_utilities import ProjectedAdaptiveLogSoftmax
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "transfo-xl/transfo-xl-wt103"
+_CONFIG_FOR_DOC = "TransfoXLConfig"
+
+
+def build_tf_to_pytorch_map(model, config):
+ """
+ A map of modules from TF to PyTorch. This time I use a map to keep the PyTorch model as identical to the original
+ PyTorch model as possible.
+ """
+ tf_to_pt_map = {}
+
+ if hasattr(model, "transformer"):
+ # We are loading in a TransfoXLLMHeadModel => we will load also the Adaptive Softmax
+ tf_to_pt_map.update(
+ {
+ "transformer/adaptive_softmax/cutoff_0/cluster_W": model.crit.cluster_weight,
+ "transformer/adaptive_softmax/cutoff_0/cluster_b": model.crit.cluster_bias,
+ }
+ )
+ for i, (out_l, proj_l, tie_proj) in enumerate(
+ zip(model.crit.out_layers, model.crit.out_projs, config.tie_projs)
+ ):
+ layer_str = f"transformer/adaptive_softmax/cutoff_{i}/"
+ if config.tie_word_embeddings:
+ tf_to_pt_map.update({layer_str + "b": out_l.bias})
+ else:
+ raise NotImplementedError
+ # I don't think this is implemented in the TF code
+ tf_to_pt_map.update({layer_str + "lookup_table": out_l.weight, layer_str + "b": out_l.bias})
+ if not tie_proj:
+ tf_to_pt_map.update({layer_str + "proj": proj_l})
+ # Now load the rest of the transformer
+ model = model.transformer
+
+ # Embeddings
+ for i, (embed_l, proj_l) in enumerate(zip(model.word_emb.emb_layers, model.word_emb.emb_projs)):
+ layer_str = f"transformer/adaptive_embed/cutoff_{i}/"
+ tf_to_pt_map.update({layer_str + "lookup_table": embed_l.weight, layer_str + "proj_W": proj_l})
+
+ # Transformer blocks
+ for i, b in enumerate(model.layers):
+ layer_str = f"transformer/layer_{i}/"
+ tf_to_pt_map.update(
+ {
+ layer_str + "rel_attn/LayerNorm/gamma": b.dec_attn.layer_norm.weight,
+ layer_str + "rel_attn/LayerNorm/beta": b.dec_attn.layer_norm.bias,
+ layer_str + "rel_attn/o/kernel": b.dec_attn.o_net.weight,
+ layer_str + "rel_attn/qkv/kernel": b.dec_attn.qkv_net.weight,
+ layer_str + "rel_attn/r/kernel": b.dec_attn.r_net.weight,
+ layer_str + "ff/LayerNorm/gamma": b.pos_ff.layer_norm.weight,
+ layer_str + "ff/LayerNorm/beta": b.pos_ff.layer_norm.bias,
+ layer_str + "ff/layer_1/kernel": b.pos_ff.CoreNet[0].weight,
+ layer_str + "ff/layer_1/bias": b.pos_ff.CoreNet[0].bias,
+ layer_str + "ff/layer_2/kernel": b.pos_ff.CoreNet[3].weight,
+ layer_str + "ff/layer_2/bias": b.pos_ff.CoreNet[3].bias,
+ }
+ )
+
+ # Relative positioning biases
+ if config.untie_r:
+ r_r_list = []
+ r_w_list = []
+ for b in model.layers:
+ r_r_list.append(b.dec_attn.r_r_bias)
+ r_w_list.append(b.dec_attn.r_w_bias)
+ else:
+ r_r_list = [model.r_r_bias]
+ r_w_list = [model.r_w_bias]
+ tf_to_pt_map.update({"transformer/r_r_bias": r_r_list, "transformer/r_w_bias": r_w_list})
+ return tf_to_pt_map
+
+
+def load_tf_weights_in_transfo_xl(model, config, tf_path):
+ """Load tf checkpoints in a pytorch model"""
+ try:
+ import numpy as np
+ import tensorflow as tf
+ except ImportError:
+ logger.error(
+ "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
+ "https://www.tensorflow.org/install/ for installation instructions."
+ )
+ raise
+ # Build TF to PyTorch weights loading map
+ tf_to_pt_map = build_tf_to_pytorch_map(model, config)
+
+ # Load weights from TF model
+ init_vars = tf.train.list_variables(tf_path)
+ tf_weights = {}
+ for name, shape in init_vars:
+ logger.info(f"Loading TF weight {name} with shape {shape}")
+ array = tf.train.load_variable(tf_path, name)
+ tf_weights[name] = array
+
+ for name, pointer in tf_to_pt_map.items():
+ assert name in tf_weights
+ array = tf_weights[name]
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
+ # which are not required for using pretrained model
+ if "kernel" in name or "proj" in name:
+ array = np.transpose(array)
+ if ("r_r_bias" in name or "r_w_bias" in name) and len(pointer) > 1:
+ # Here we will split the TF weights
+ assert len(pointer) == array.shape[0]
+ for i, p_i in enumerate(pointer):
+ arr_i = array[i, ...]
+ try:
+ assert p_i.shape == arr_i.shape
+ except AssertionError as e:
+ e.args += (p_i.shape, arr_i.shape)
+ raise
+ logger.info(f"Initialize PyTorch weight {name} for layer {i}")
+ p_i.data = torch.from_numpy(arr_i)
+ else:
+ try:
+ assert pointer.shape == array.shape, (
+ f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
+ )
+ except AssertionError as e:
+ e.args += (pointer.shape, array.shape)
+ raise
+ logger.info(f"Initialize PyTorch weight {name}")
+ pointer.data = torch.from_numpy(array)
+ tf_weights.pop(name, None)
+ tf_weights.pop(name + "/Adam", None)
+ tf_weights.pop(name + "/Adam_1", None)
+
+ logger.info(f"Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}")
+ return model
+
+
+class PositionalEmbedding(nn.Module):
+ def __init__(self, demb):
+ super().__init__()
+
+ self.demb = demb
+
+ inv_freq = 1 / (10000 ** (torch.arange(0.0, demb, 2.0) / demb))
+ self.register_buffer("inv_freq", inv_freq)
+
+ def forward(self, pos_seq, bsz=None):
+ sinusoid_inp = torch.outer(pos_seq, self.inv_freq)
+ pos_emb = torch.cat([sinusoid_inp.sin(), sinusoid_inp.cos()], dim=-1)
+
+ if bsz is not None:
+ return pos_emb[:, None, :].expand(-1, bsz, -1)
+ else:
+ return pos_emb[:, None, :]
+
+
+class PositionwiseFF(nn.Module):
+ def __init__(self, d_model, d_inner, dropout, pre_lnorm=False, layer_norm_epsilon=1e-5):
+ super().__init__()
+
+ self.d_model = d_model
+ self.d_inner = d_inner
+ self.dropout = dropout
+
+ self.CoreNet = nn.Sequential(
+ nn.Linear(d_model, d_inner),
+ nn.ReLU(inplace=True),
+ nn.Dropout(dropout),
+ nn.Linear(d_inner, d_model),
+ nn.Dropout(dropout),
+ )
+
+ self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon)
+
+ self.pre_lnorm = pre_lnorm
+
+ def forward(self, inp):
+ if self.pre_lnorm:
+ # layer normalization + positionwise feed-forward
+ core_out = self.CoreNet(self.layer_norm(inp))
+
+ # residual connection
+ output = core_out + inp
+ else:
+ # positionwise feed-forward
+ core_out = self.CoreNet(inp)
+
+ # residual connection + layer normalization
+ output = self.layer_norm(inp + core_out)
+
+ return output
+
+
+class RelPartialLearnableMultiHeadAttn(nn.Module):
+ def __init__(
+ self,
+ n_head,
+ d_model,
+ d_head,
+ dropout,
+ dropatt=0,
+ pre_lnorm=False,
+ r_r_bias=None,
+ r_w_bias=None,
+ layer_norm_epsilon=1e-5,
+ ):
+ super().__init__()
+
+ self.n_head = n_head
+ self.d_model = d_model
+ self.d_head = d_head
+ self.dropout = dropout
+
+ self.qkv_net = nn.Linear(d_model, 3 * n_head * d_head, bias=False)
+
+ self.drop = nn.Dropout(dropout)
+ self.dropatt = nn.Dropout(dropatt)
+ self.o_net = nn.Linear(n_head * d_head, d_model, bias=False)
+
+ self.layer_norm = nn.LayerNorm(d_model, eps=layer_norm_epsilon)
+
+ self.scale = 1 / (d_head**0.5)
+
+ self.pre_lnorm = pre_lnorm
+
+ if r_r_bias is None or r_w_bias is None: # Biases are not shared
+ self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
+ self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
+ else:
+ self.r_r_bias = r_r_bias
+ self.r_w_bias = r_w_bias
+
+ self.r_net = nn.Linear(self.d_model, self.n_head * self.d_head, bias=False)
+
+ def _rel_shift(self, x):
+ zero_pad_shape = (x.size(0), 1) + x.size()[2:]
+ zero_pad = torch.zeros(zero_pad_shape, device=x.device, dtype=x.dtype)
+ x_padded = torch.cat([zero_pad, x], dim=1)
+
+ x_padded_shape = (x.size(1) + 1, x.size(0)) + x.size()[2:]
+ x_padded = x_padded.view(*x_padded_shape)
+
+ x = x_padded[1:].view_as(x)
+
+ return x
+
+ def forward(self, w, r, attn_mask=None, mems=None, head_mask=None, output_attentions=False):
+ qlen, rlen, bsz = w.size(0), r.size(0), w.size(1)
+
+ if mems is not None:
+ cat = torch.cat([mems, w], 0)
+ if self.pre_lnorm:
+ w_heads = self.qkv_net(self.layer_norm(cat))
+ else:
+ w_heads = self.qkv_net(cat)
+ r_head_k = self.r_net(r)
+
+ w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
+ w_head_q = w_head_q[-qlen:]
+ else:
+ if self.pre_lnorm:
+ w_heads = self.qkv_net(self.layer_norm(w))
+ else:
+ w_heads = self.qkv_net(w)
+ r_head_k = self.r_net(r)
+
+ w_head_q, w_head_k, w_head_v = torch.chunk(w_heads, 3, dim=-1)
+
+ klen = w_head_k.size(0)
+
+ w_head_q = w_head_q.view(qlen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
+ w_head_k = w_head_k.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
+ w_head_v = w_head_v.view(klen, bsz, self.n_head, self.d_head) # qlen x bsz x n_head x d_head
+
+ r_head_k = r_head_k.view(rlen, self.n_head, self.d_head) # qlen x n_head x d_head
+
+ # compute attention score
+ rw_head_q = w_head_q + self.r_w_bias # qlen x bsz x n_head x d_head
+ AC = torch.einsum("ibnd,jbnd->ijbn", (rw_head_q, w_head_k)) # qlen x klen x bsz x n_head
+
+ rr_head_q = w_head_q + self.r_r_bias
+ BD = torch.einsum("ibnd,jnd->ijbn", (rr_head_q, r_head_k)) # qlen x klen x bsz x n_head
+ BD = self._rel_shift(BD)
+
+ # [qlen x klen x bsz x n_head]
+ attn_score = AC + BD
+ attn_score.mul_(self.scale)
+
+ mask_value = torch.finfo(attn_score.dtype).min
+
+ # compute attention probability
+ if attn_mask is not None and torch.sum(attn_mask).item():
+ attn_mask = attn_mask == 1 # Switch to bool
+ if attn_mask.dim() == 2:
+ attn_score = (
+ attn_score.float().masked_fill(attn_mask[None, :, :, None], mask_value).type_as(attn_score)
+ )
+ elif attn_mask.dim() == 3:
+ attn_score = attn_score.float().masked_fill(attn_mask[:, :, :, None], mask_value).type_as(attn_score)
+
+ # [qlen x klen x bsz x n_head]
+ attn_prob = nn.functional.softmax(attn_score, dim=1)
+ attn_prob = self.dropatt(attn_prob)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attn_prob = attn_prob * head_mask
+
+ # compute attention vector
+ attn_vec = torch.einsum("ijbn,jbnd->ibnd", (attn_prob, w_head_v))
+
+ # [qlen x bsz x n_head x d_head]
+ attn_vec = attn_vec.contiguous().view(attn_vec.size(0), attn_vec.size(1), self.n_head * self.d_head)
+
+ # linear projection
+ attn_out = self.o_net(attn_vec)
+ attn_out = self.drop(attn_out)
+
+ if self.pre_lnorm:
+ # residual connection
+ outputs = [w + attn_out]
+ else:
+ # residual connection + layer normalization
+ outputs = [self.layer_norm(w + attn_out)]
+
+ if output_attentions:
+ outputs.append(attn_prob)
+
+ return outputs
+
+
+class RelPartialLearnableDecoderLayer(nn.Module):
+ def __init__(self, n_head, d_model, d_head, d_inner, dropout, layer_norm_epsilon=1e-5, **kwargs):
+ super().__init__()
+
+ self.dec_attn = RelPartialLearnableMultiHeadAttn(
+ n_head, d_model, d_head, dropout, layer_norm_epsilon=layer_norm_epsilon, **kwargs
+ )
+ self.pos_ff = PositionwiseFF(
+ d_model, d_inner, dropout, pre_lnorm=kwargs.get("pre_lnorm"), layer_norm_epsilon=layer_norm_epsilon
+ )
+
+ def forward(self, dec_inp, r, dec_attn_mask=None, mems=None, head_mask=None, output_attentions=False):
+ attn_outputs = self.dec_attn(
+ dec_inp,
+ r,
+ attn_mask=dec_attn_mask,
+ mems=mems,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ )
+ ff_output = self.pos_ff(attn_outputs[0])
+
+ outputs = [ff_output] + attn_outputs[1:]
+
+ return outputs
+
+
+class AdaptiveEmbedding(nn.Module):
+ def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, sample_softmax=False):
+ super().__init__()
+
+ self.n_token = n_token
+ self.d_embed = d_embed
+
+ self.cutoffs = cutoffs + [n_token]
+ self.div_val = div_val
+ self.d_proj = d_proj
+
+ self.emb_scale = d_proj**0.5
+
+ self.cutoff_ends = [0] + self.cutoffs
+
+ self.emb_layers = nn.ModuleList()
+ self.emb_projs = nn.ParameterList()
+ if div_val == 1:
+ self.emb_layers.append(nn.Embedding(n_token, d_embed, sparse=sample_softmax > 0))
+ if d_proj != d_embed:
+ self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed)))
+ else:
+ for i in range(len(self.cutoffs)):
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
+ d_emb_i = d_embed // (div_val**i)
+ self.emb_layers.append(nn.Embedding(r_idx - l_idx, d_emb_i))
+ self.emb_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i)))
+
+ def forward(self, inp):
+ if self.div_val == 1:
+ embed = self.emb_layers[0](inp)
+ if self.d_proj != self.d_embed:
+ embed = nn.functional.linear(embed, self.emb_projs[0])
+ else:
+ param = next(self.parameters())
+ inp_flat = inp.view(-1)
+ emb_flat = torch.zeros([inp_flat.size(0), self.d_proj], dtype=param.dtype, device=param.device)
+ for i in range(len(self.cutoffs)):
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
+
+ mask_i = (inp_flat >= l_idx) & (inp_flat < r_idx)
+ indices_i = mask_i.nonzero().squeeze()
+
+ if indices_i.numel() == 0:
+ continue
+
+ inp_i = inp_flat.index_select(0, indices_i) - l_idx
+ emb_i = self.emb_layers[i](inp_i)
+ emb_i = nn.functional.linear(emb_i, self.emb_projs[i])
+
+ emb_flat.index_copy_(0, indices_i, emb_i)
+
+ embed_shape = inp.size() + (self.d_proj,)
+ embed = emb_flat.view(embed_shape)
+
+ embed.mul_(self.emb_scale)
+
+ return embed
+
+
+class TransfoXLPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: TransfoXLConfig
+ load_tf_weights = load_tf_weights_in_transfo_xl
+ base_model_prefix = "transformer"
+
+ def _init_weight(self, weight):
+ if self.config.init == "uniform":
+ nn.init.uniform_(weight, -self.config.init_range, self.config.init_range)
+ elif self.config.init == "normal":
+ nn.init.normal_(weight, 0.0, self.config.init_std)
+
+ def _init_bias(self, bias):
+ nn.init.constant_(bias, 0.0)
+
+ def _init_weights(self, m):
+ """Initialize the weights."""
+ classname = m.__class__.__name__
+ if classname.find("Linear") != -1:
+ if hasattr(m, "weight") and m.weight is not None:
+ self._init_weight(m.weight)
+ if hasattr(m, "bias") and m.bias is not None:
+ self._init_bias(m.bias)
+ elif classname.find("AdaptiveEmbedding") != -1:
+ if hasattr(m, "emb_projs"):
+ for i in range(len(m.emb_projs)):
+ if m.emb_projs[i] is not None:
+ nn.init.normal_(m.emb_projs[i], 0.0, self.config.proj_init_std)
+ elif classname.find("Embedding") != -1:
+ if hasattr(m, "weight"):
+ self._init_weight(m.weight)
+ elif classname.find("ProjectedAdaptiveLogSoftmax") != -1:
+ if hasattr(m, "cluster_weight") and m.cluster_weight is not None:
+ self._init_weight(m.cluster_weight)
+ if hasattr(m, "cluster_bias") and m.cluster_bias is not None:
+ self._init_bias(m.cluster_bias)
+ if hasattr(m, "out_projs"):
+ for i in range(len(m.out_projs)):
+ if m.out_projs[i] is not None:
+ nn.init.normal_(m.out_projs[i], 0.0, self.config.proj_init_std)
+ elif classname.find("LayerNorm") != -1:
+ if hasattr(m, "weight"):
+ nn.init.normal_(m.weight, 1.0, self.config.init_std)
+ if hasattr(m, "bias") and m.bias is not None:
+ self._init_bias(m.bias)
+ else:
+ if hasattr(m, "r_emb"):
+ self._init_weight(m.r_emb)
+ if hasattr(m, "r_w_bias"):
+ self._init_weight(m.r_w_bias)
+ if hasattr(m, "r_r_bias"):
+ self._init_weight(m.r_r_bias)
+ if hasattr(m, "r_bias"):
+ self._init_bias(m.r_bias)
+
+ def resize_token_embeddings(self, new_num_tokens: Optional[int] = None, layer: Optional[int] = -1):
+ """
+ Resize input token embeddings matrix of the model if new_num_tokens != config.vocab_size. Take care of tying
+ weights embeddings afterwards if the model class has a *tie_weights()* method.
+
+ Arguments:
+ new_num_tokens: (*optional*) int:
+ New number of tokens in the embedding matrix. Increasing the size will add newly initialized vectors at
+ the end. Reducing the size will remove vectors from the end. If not provided or None: does nothing and
+ just returns a pointer to the input tokens `torch.nn.Embeddings` Module of the model.
+ layer: (*optional*) int:
+ Layer of the *AdaptiveEmbedding* where the resizing should be done. Per default the last layer will be
+ resized. Be aware that when resizing other than the last layer, you have to ensure that the new
+ token(s) in the tokenizer are at the corresponding position.
+
+ Return: `torch.nn.Embeddings` Pointer to the input tokens Embeddings Module of the model
+ """
+ base_model = getattr(self, self.base_model_prefix, self) # get the base model if needed
+
+ if new_num_tokens is None:
+ return self.get_input_embeddings()
+
+ new_num_tokens_layer, layer = self._get_new_num_tokens_layer(new_num_tokens, layer)
+ assert new_num_tokens_layer > 0, "The size of the new embedding layer cannot be 0 or less"
+ model_embeds = base_model._resize_token_embeddings(new_num_tokens_layer, layer)
+
+ # Update base model and current model config
+ self.config.vocab_size = new_num_tokens
+ base_model.vocab_size = new_num_tokens
+ base_model.n_token = new_num_tokens
+
+ new_embedding_shapes = self._get_embedding_shapes()
+ self._resize_cutoffs(new_num_tokens, new_num_tokens_layer, new_embedding_shapes, layer)
+
+ # Tie weights again if needed
+ self.tie_weights()
+
+ return model_embeds
+
+ def _get_new_num_tokens_layer(self, new_num_tokens, layer):
+ embeddings = self.get_input_embeddings()
+ if layer == -1:
+ layer = len(embeddings.emb_layers) - 1
+ assert 0 <= layer <= len(embeddings.emb_layers) - 1
+
+ new_num_tokens_layer = (
+ new_num_tokens
+ - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[:layer]])
+ - sum([emb.weight.shape[0] for emb in embeddings.emb_layers[layer + 1 :]])
+ )
+ return new_num_tokens_layer, layer
+
+ def _get_embedding_shapes(self):
+ embeddings = self.get_input_embeddings()
+ return [emb.weight.shape[0] for emb in embeddings.emb_layers]
+
+ def _resize_token_embeddings(self, new_num_tokens, layer=-1):
+ embeddings = self.get_input_embeddings()
+ if new_num_tokens is None:
+ return embeddings
+ new_embeddings_layer = self._get_resized_embeddings(embeddings.emb_layers[layer], new_num_tokens)
+ embeddings.emb_layers[layer] = new_embeddings_layer
+
+ self.set_input_embeddings(embeddings)
+
+ return self.get_input_embeddings()
+
+ def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer):
+ embeddings = self.get_input_embeddings()
+
+ for i in range(layer, len(embeddings.cutoffs)):
+ embeddings.cutoffs[i] = sum(new_embedding_shapes[: i + 1])
+
+ embeddings.cutoff_ends = [0] + embeddings.cutoffs
+ embeddings.n_token = new_num_tokens
+
+ self.config.cutoffs = embeddings.cutoffs[:-1]
+
+ return embeddings.cutoffs
+
+
+@dataclass
+class TransfoXLModelOutput(ModelOutput):
+ """
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
+
+ Args:
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the model.
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
+ be passed as input ids as they have already been computed.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ last_hidden_state: torch.FloatTensor
+ mems: list[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+@dataclass
+class TransfoXLSequenceClassifierOutputWithPast(ModelOutput):
+ """
+ Base class for outputs of sentence classification models.
+
+ Args:
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
+ be passed as input ids as they have already been computed.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ mems: list[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+@dataclass
+class TransfoXLLMHeadModelOutput(ModelOutput):
+ """
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
+
+ Args:
+ losses (`torch.FloatTensor` of shape *(batch_size, sequence_length-1)*, *optional*, returned when `labels` is provided):
+ Language modeling losses (not reduced).
+ prediction_scores (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token after SoftMax).
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (key and values in the attention blocks). Can be used (see `mems`
+ input) to speed up sequential decoding. The token ids which have their past given to this model should not
+ be passed as input ids as they have already been computed.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ loss (`torch.FloatTensor` of shape `()`, *optional*, returned when `labels` is provided)
+ Reduced language modeling loss.
+ """
+
+ losses: Optional[torch.FloatTensor] = None
+ prediction_scores: Optional[torch.FloatTensor] = None
+ mems: list[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+ loss: Optional[torch.FloatTensor] = None
+
+ @property
+ def logits(self):
+ # prediction scores are the output of the adaptive softmax, see
+ # the file `modeling_transfo_xl_utilities`. Since the adaptive
+ # softmax returns the log softmax value, `self.prediction_scores`
+ # are strictly speaking not exactly `logits`, but behave the same
+ # way logits do.
+ return self.prediction_scores
+
+
+TRANSFO_XL_START_DOCSTRING = r"""
+
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
+ and behavior.
+
+ Parameters:
+ config ([`TransfoXLConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+TRANSFO_XL_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see
+ `mems` output below). Can be used to speed up sequential decoding. The token ids which have their mems
+ given to this model should not be passed as `input_ids` as they have already been computed.
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
+ TRANSFO_XL_START_DOCSTRING,
+)
+class TransfoXLModel(TransfoXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.n_token = config.vocab_size
+
+ self.d_embed = config.d_embed
+ self.d_model = config.d_model
+ self.n_head = config.n_head
+ self.d_head = config.d_head
+
+ self.word_emb = AdaptiveEmbedding(
+ config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val
+ )
+
+ self.drop = nn.Dropout(config.dropout)
+
+ self.n_layer = config.n_layer
+ self.mem_len = config.mem_len
+ self.attn_type = config.attn_type
+
+ if not config.untie_r:
+ self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
+ self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
+
+ self.layers = nn.ModuleList()
+ if config.attn_type == 0: # the default attention
+ for i in range(config.n_layer):
+ self.layers.append(
+ RelPartialLearnableDecoderLayer(
+ config.n_head,
+ config.d_model,
+ config.d_head,
+ config.d_inner,
+ config.dropout,
+ dropatt=config.dropatt,
+ pre_lnorm=config.pre_lnorm,
+ r_w_bias=None if config.untie_r else self.r_w_bias,
+ r_r_bias=None if config.untie_r else self.r_r_bias,
+ layer_norm_epsilon=config.layer_norm_epsilon,
+ )
+ )
+ else: # learnable embeddings and absolute embeddings are not used in our pretrained checkpoints
+ raise NotImplementedError # Removed them to avoid maintaining dead code
+
+ self.same_length = config.same_length
+ self.clamp_len = config.clamp_len
+
+ if self.attn_type == 0: # default attention
+ self.pos_emb = PositionalEmbedding(self.d_model)
+ else: # learnable embeddings and absolute embeddings
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.word_emb
+
+ def set_input_embeddings(self, new_embeddings):
+ self.word_emb = new_embeddings
+
+ def backward_compatible(self):
+ self.sample_softmax = -1
+
+ def reset_memory_length(self, mem_len):
+ self.mem_len = mem_len
+
+ def _prune_heads(self, heads):
+ logger.info("Head pruning is not implemented for Transformer-XL model")
+ pass
+
+ def init_mems(self, bsz):
+ if self.mem_len > 0:
+ mems = []
+ param = next(self.parameters())
+ for i in range(self.n_layer):
+ empty = torch.zeros(self.mem_len, bsz, self.config.d_model, dtype=param.dtype, device=param.device)
+ mems.append(empty)
+
+ return mems
+ else:
+ return None
+
+ def _update_mems(self, hids, mems, mlen, qlen):
+ # does not deal with None
+ if mems is None:
+ return None
+
+ # mems is not None
+ assert len(hids) == len(mems), "len(hids) != len(mems)"
+
+ # There are `mlen + qlen` steps that can be cached into mems
+ with torch.no_grad():
+ new_mems = []
+ end_idx = mlen + max(0, qlen)
+ beg_idx = max(0, end_idx - self.mem_len)
+ for i in range(len(hids)):
+ cat = torch.cat([mems[i], hids[i]], dim=0)
+ new_mems.append(cat[beg_idx:end_idx].detach())
+
+ return new_mems
+
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TransfoXLModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ mems: Optional[list[torch.FloatTensor]] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, TransfoXLModelOutput]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # the original code for Transformer-XL used shapes [len, bsz] but we want a unified interface in the library
+ # so we transpose here from shape [bsz, len] to shape [len, bsz]
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_ids = input_ids.transpose(0, 1).contiguous()
+ qlen, bsz = input_ids.size()
+ elif inputs_embeds is not None:
+ inputs_embeds = inputs_embeds.transpose(0, 1).contiguous()
+ qlen, bsz = inputs_embeds.shape[0], inputs_embeds.shape[1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ if mems is None:
+ mems = self.init_mems(bsz)
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
+ # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
+ if head_mask is not None:
+ if head_mask.dim() == 1:
+ head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0)
+ head_mask = head_mask.expand(self.n_layer, -1, -1, -1, -1)
+ elif head_mask.dim() == 2:
+ head_mask = head_mask.unsqueeze(1).unsqueeze(1).unsqueeze(1)
+ head_mask = head_mask.to(
+ dtype=next(self.parameters()).dtype
+ ) # switch to float if need + fp16 compatibility
+ else:
+ head_mask = [None] * self.n_layer
+
+ if inputs_embeds is not None:
+ word_emb = inputs_embeds
+ else:
+ word_emb = self.word_emb(input_ids)
+
+ mlen = mems[0].size(0) if mems is not None else 0
+ klen = mlen + qlen
+ if self.same_length:
+ all_ones = word_emb.new_ones((qlen, klen), dtype=torch.bool)
+ mask_len = klen - self.mem_len
+ if mask_len > 0:
+ mask_shift_len = qlen - mask_len
+ else:
+ mask_shift_len = qlen
+ dec_attn_mask = (torch.triu(all_ones, 1 + mlen) + torch.tril(all_ones, -mask_shift_len))[:, :, None] # -1
+ else:
+ dec_attn_mask = torch.triu(word_emb.new_ones((qlen, klen), dtype=torch.bool), diagonal=1 + mlen)[
+ :, :, None
+ ]
+
+ hids = []
+ attentions = [] if output_attentions else None
+ if self.attn_type == 0: # default
+ pos_seq = torch.arange(klen - 1, -1, -1.0, device=word_emb.device, dtype=torch.int64).type_as(
+ dtype=word_emb.dtype
+ )
+ if self.clamp_len > 0:
+ pos_seq.clamp_(max=self.clamp_len)
+ pos_emb = self.pos_emb(pos_seq)
+
+ core_out = self.drop(word_emb)
+ pos_emb = self.drop(pos_emb)
+
+ for i, layer in enumerate(self.layers):
+ hids.append(core_out)
+ mems_i = None if mems is None else mems[i]
+ layer_outputs = layer(
+ core_out,
+ pos_emb,
+ dec_attn_mask=dec_attn_mask,
+ mems=mems_i,
+ head_mask=head_mask[i],
+ output_attentions=output_attentions,
+ )
+ core_out = layer_outputs[0]
+ if output_attentions:
+ attentions.append(layer_outputs[1])
+ else: # learnable embeddings and absolute embeddings
+ raise NotImplementedError # Removed these to avoid maintaining dead code - They are not used in our pretrained checkpoint
+
+ core_out = self.drop(core_out)
+
+ new_mems = self._update_mems(hids, mems, mlen, qlen)
+
+ if output_hidden_states:
+ # Add last layer and transpose to library standard shape [bsz, len, hidden_dim]
+ hids.append(core_out)
+ hids = tuple(t.transpose(0, 1).contiguous() for t in hids)
+ else:
+ hids = None
+ if output_attentions:
+ # Transpose to library standard shape [bsz, n_heads, query_seq_len, key_seq_len]
+ attentions = tuple(t.permute(2, 3, 0, 1).contiguous() for t in attentions)
+ # We transpose back here to shape [bsz, len, hidden_dim]
+ core_out = core_out.transpose(0, 1).contiguous()
+
+ if not return_dict:
+ return tuple(v for v in [core_out, new_mems, hids, attentions] if v is not None)
+
+ return TransfoXLModelOutput(
+ last_hidden_state=core_out,
+ mems=new_mems,
+ hidden_states=hids,
+ attentions=attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ The Transformer-XL Model with a language modeling head on top (adaptive softmax with weights tied to the adaptive
+ input embeddings)
+ """,
+ TRANSFO_XL_START_DOCSTRING,
+)
+class TransfoXLLMHeadModel(TransfoXLPreTrainedModel):
+ _tied_weights_keys = [r"crit\.out_projs\.\d+", r"crit\.out_layers\.\d+\.weight"]
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.transformer = TransfoXLModel(config)
+ self.sample_softmax = config.sample_softmax
+ self.trainer_compatible = getattr(config, "trainer_compatible", False)
+
+ if not self.trainer_compatible:
+ warnings.warn(
+ "The output of TransfoXL will be updated in v5 to support a single loss as first argument. In order "
+ "to use that updated output, please specify `trainer_compatible=True` as your configuration"
+ " attribute.",
+ DeprecationWarning,
+ )
+
+ assert self.sample_softmax <= 0, (
+ "Sampling from the softmax is not implemented yet. Please look at issue: #3310:"
+ " https://github.com/huggingface/transformers/issues/3310"
+ )
+
+ self.crit = ProjectedAdaptiveLogSoftmax(
+ config.vocab_size, config.d_embed, config.d_model, config.cutoffs, div_val=config.div_val
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def tie_weights(self):
+ """
+ Run this to be sure output and input (adaptive) softmax weights are tied
+ """
+
+ if self.config.tie_word_embeddings:
+ for i in range(len(self.crit.out_layers)):
+ self._tie_or_clone_weights(self.crit.out_layers[i], self.transformer.word_emb.emb_layers[i])
+ if self.config.tie_projs:
+ for i, tie_proj in enumerate(self.config.tie_projs):
+ if tie_proj and self.config.div_val == 1 and self.config.d_model != self.config.d_embed:
+ if self.config.torchscript:
+ self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[0].clone())
+ else:
+ self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[0]
+ elif tie_proj and self.config.div_val != 1:
+ if self.config.torchscript:
+ self.crit.out_projs[i] = nn.Parameter(self.transformer.word_emb.emb_projs[i].clone())
+ else:
+ self.crit.out_projs[i] = self.transformer.word_emb.emb_projs[i]
+
+ def reset_memory_length(self, mem_len):
+ self.transformer.reset_memory_length(mem_len)
+
+ def init_mems(self, bsz):
+ return self.transformer.init_mems(bsz)
+
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TransfoXLLMHeadModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ mems: Optional[list[torch.FloatTensor]] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, TransfoXLLMHeadModelOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ if input_ids is not None:
+ bsz, tgt_len = input_ids.size(0), input_ids.size(1)
+ elif inputs_embeds is not None:
+ bsz, tgt_len = inputs_embeds.size(0), inputs_embeds.size(1)
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ mems=mems,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ last_hidden = transformer_outputs[0]
+ pred_hid = last_hidden[:, -tgt_len:]
+
+ if labels is not None:
+ # Prevents all labels being -100 and throwing an error
+ # when backwarding the loss
+ miss_valid_label = labels[0, 1:].sum() == (labels.size(1) - 1) * -100
+ if miss_valid_label:
+ # Sets an token, just to prevent loss from being NaN
+ labels[0, 1] = self.config.eos_token_id
+
+ softmax_output = self.crit(pred_hid, labels)
+ prediction_scores = softmax_output.view(bsz, tgt_len, -1) if labels is None else ()
+
+ if labels is not None:
+ losses = softmax_output.view(bsz, tgt_len - 1)
+ # Avoids from incorporating padding (-100) tokens into loss value
+ loss = losses[losses != 0].mean()
+ else:
+ losses, loss = None, None
+
+ if not return_dict:
+ if self.trainer_compatible:
+ output = (prediction_scores, losses) if losses is not None else (prediction_scores,)
+ output += transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+ else:
+ output = (prediction_scores, *transformer_outputs[1:])
+ output = ((losses,) + output) if losses is not None else output
+ return (output + (loss,)) if loss is not None else output
+
+ return TransfoXLLMHeadModelOutput(
+ loss=loss,
+ prediction_scores=prediction_scores,
+ losses=losses,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def get_output_embeddings(self):
+ """Double-check if you are using adaptive softmax."""
+ if self.sample_softmax > 0:
+ return self.out_layer
+ else:
+ return self.crit.out_layers[-1]
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **model_kwargs):
+ inputs = {}
+
+ # if past is defined in model kwargs then use it for faster decoding
+ if past_key_values:
+ inputs["mems"] = past_key_values
+ inputs["input_ids"] = input_ids[:, -1].unsqueeze(-1)
+ else:
+ inputs["input_ids"] = input_ids
+
+ return inputs
+
+ def _resize_cutoffs(self, new_num_tokens, new_emb_size, new_embedding_shapes, layer):
+ new_cutoffs = super()._resize_cutoffs(new_num_tokens, new_emb_size, new_embedding_shapes, layer)
+
+ self.crit.cutoffs = new_cutoffs
+ self.crit.cutoff_ends = [0] + new_cutoffs
+ self.crit.n_token = new_num_tokens
+
+ @staticmethod
+ def _reorder_cache(mems: list[torch.Tensor], beam_idx: torch.Tensor) -> list[torch.Tensor]:
+ """
+ This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every
+ generation step.
+ """
+ return [layer_past.index_select(1, beam_idx.to(layer_past.device)) for layer_past in mems]
+
+
+@add_start_docstrings(
+ """
+ The Transformer-XL Model transformer with a sequence classification head on top (linear layer).
+
+ [`TransfoXLForSequenceClassification`] uses the last token in order to do the classification, as other causal
+ models (e.g. GPT-1) do.
+
+ Since it does classification on the last token, it requires to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """,
+ TRANSFO_XL_START_DOCSTRING,
+)
+class TransfoXLForSequenceClassification(TransfoXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.transformer = TransfoXLModel(config)
+ self.score = nn.Linear(config.d_embed, self.num_labels, bias=False)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(TRANSFO_XL_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TransfoXLSequenceClassifierOutputWithPast,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ mems: Optional[list[torch.FloatTensor]] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, TransfoXLSequenceClassifierOutputWithPast]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ mems=mems,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ hidden_states = transformer_outputs[0]
+ logits = self.score(hidden_states)
+
+ if input_ids is not None:
+ batch_size, sequence_length = input_ids.shape[:2]
+ else:
+ batch_size, sequence_length = inputs_embeds.shape[:2]
+
+ assert self.config.pad_token_id is not None or batch_size == 1, (
+ "Cannot handle batch sizes > 1 if no padding token is defined."
+ )
+ if self.config.pad_token_id is None:
+ sequence_lengths = -1
+ else:
+ if input_ids is not None:
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
+ sequence_lengths = sequence_lengths.to(logits.device)
+ else:
+ sequence_lengths = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+
+ pooled_logits = logits[range(batch_size), sequence_lengths]
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(pooled_logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(pooled_logits, labels)
+ if not return_dict:
+ output = (pooled_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TransfoXLSequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = [
+ "AdaptiveEmbedding",
+ "TransfoXLForSequenceClassification",
+ "TransfoXLLMHeadModel",
+ "TransfoXLModel",
+ "TransfoXLPreTrainedModel",
+ "load_tf_weights_in_transfo_xl",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py
new file mode 100644
index 0000000000000000000000000000000000000000..f76f3ccc6259fcb033b44eb43dd98be23482221c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py
@@ -0,0 +1,251 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Utilities for PyTorch Transformer XL model. Directly adapted from https://github.com/kimiyoung/transformer-xl.
+"""
+
+import torch
+from torch import nn
+
+
+# CUDA_MAJOR = int(torch.version.cuda.split('.')[0])
+# CUDA_MINOR = int(torch.version.cuda.split('.')[1])
+
+
+class ProjectedAdaptiveLogSoftmax(nn.Module):
+ def __init__(self, n_token, d_embed, d_proj, cutoffs, div_val=1, keep_order=False):
+ super().__init__()
+
+ self.n_token = n_token
+ self.d_embed = d_embed
+ self.d_proj = d_proj
+
+ self.cutoffs = cutoffs + [n_token]
+ self.cutoff_ends = [0] + self.cutoffs
+ self.div_val = div_val
+
+ self.shortlist_size = self.cutoffs[0]
+ self.n_clusters = len(self.cutoffs) - 1
+ self.head_size = self.shortlist_size + self.n_clusters
+
+ if self.n_clusters > 0:
+ self.cluster_weight = nn.Parameter(torch.zeros(self.n_clusters, self.d_embed))
+ self.cluster_bias = nn.Parameter(torch.zeros(self.n_clusters))
+
+ self.out_layers = nn.ModuleList()
+ self.out_projs = nn.ParameterList()
+
+ if div_val == 1:
+ for i in range(len(self.cutoffs)):
+ if d_proj != d_embed:
+ self.out_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_embed)))
+ else:
+ self.out_projs.append(None)
+
+ self.out_layers.append(nn.Linear(d_embed, n_token))
+ else:
+ for i in range(len(self.cutoffs)):
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
+ d_emb_i = d_embed // (div_val**i)
+
+ self.out_projs.append(nn.Parameter(torch.FloatTensor(d_proj, d_emb_i)))
+
+ self.out_layers.append(nn.Linear(d_emb_i, r_idx - l_idx))
+
+ self.keep_order = keep_order
+
+ def _compute_logit(self, hidden, weight, bias, proj):
+ if proj is None:
+ logit = nn.functional.linear(hidden, weight, bias=bias)
+ else:
+ # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
+ proj_hid = nn.functional.linear(hidden, proj.t().contiguous())
+ logit = nn.functional.linear(proj_hid, weight, bias=bias)
+ # else:
+ # logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
+ # if bias is not None:
+ # logit = logit + bias
+
+ return logit
+
+ def forward(self, hidden, labels=None, keep_order=False):
+ """
+ Params:
+ hidden :: [len*bsz x d_proj]
+ labels :: [len*bsz]
+
+ Return:
+ if labels is None: out :: [len*bsz x n_tokens] log probabilities of tokens over the vocabulary else: out ::
+ [(len-1)*bsz] Negative log likelihood. We could replace this implementation by the native PyTorch one if
+ theirs had an option to set bias on all clusters in the native one. here:
+ https://github.com/pytorch/pytorch/blob/dbe6a7a9ff1a364a8706bf5df58a1ca96d2fd9da/torch/nn/modules/adaptive.py#L138
+ """
+
+ if labels is not None:
+ # Shift so that tokens < n predict n
+ hidden = hidden[..., :-1, :].contiguous()
+ labels = labels[..., 1:].contiguous()
+ hidden = hidden.view(-1, hidden.size(-1))
+ labels = labels.view(-1)
+ if hidden.size(0) != labels.size(0):
+ raise RuntimeError("Input and labels should have the same size in the batch dimension.")
+ else:
+ hidden = hidden.view(-1, hidden.size(-1))
+
+ if self.n_clusters == 0:
+ logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0])
+ if labels is not None:
+ mask = labels != -100
+ out = torch.zeros_like(labels, dtype=hidden.dtype, device=hidden.device)
+ out[mask] = (
+ -nn.functional.log_softmax(logit, dim=-1)[mask].gather(1, labels[mask].unsqueeze(1)).squeeze(1)
+ )
+ else:
+ out = nn.functional.log_softmax(logit, dim=-1)
+ else:
+ # construct weights and biases
+ weights, biases = [], []
+ for i in range(len(self.cutoffs)):
+ if self.div_val == 1:
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
+ weight_i = self.out_layers[0].weight[l_idx:r_idx]
+ bias_i = self.out_layers[0].bias[l_idx:r_idx]
+ else:
+ weight_i = self.out_layers[i].weight
+ bias_i = self.out_layers[i].bias
+
+ if i == 0:
+ weight_i = torch.cat([weight_i, self.cluster_weight], dim=0)
+ bias_i = torch.cat([bias_i, self.cluster_bias], dim=0)
+
+ weights.append(weight_i)
+ biases.append(bias_i)
+
+ head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0]
+
+ head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj)
+ head_logprob = nn.functional.log_softmax(head_logit, dim=1)
+
+ if labels is None:
+ out = hidden.new_empty((head_logit.size(0), self.n_token))
+ else:
+ out = torch.zeros_like(labels, dtype=hidden.dtype, device=hidden.device)
+
+ offset = 0
+ cutoff_values = [0] + self.cutoffs
+ for i in range(len(cutoff_values) - 1):
+ l_idx, r_idx = cutoff_values[i], cutoff_values[i + 1]
+
+ if labels is not None:
+ mask_i = (labels >= l_idx) & (labels < r_idx)
+ indices_i = mask_i.nonzero().squeeze()
+
+ if indices_i.numel() == 0:
+ continue
+
+ target_i = labels.index_select(0, indices_i) - l_idx
+ head_logprob_i = head_logprob.index_select(0, indices_i)
+ hidden_i = hidden.index_select(0, indices_i)
+ else:
+ hidden_i = hidden
+
+ if i == 0:
+ if labels is not None:
+ logprob_i = head_logprob_i.gather(1, target_i[:, None]).squeeze(1)
+ else:
+ out[:, : self.cutoffs[0]] = head_logprob[:, : self.cutoffs[0]]
+ else:
+ weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i]
+
+ tail_logit_i = self._compute_logit(hidden_i, weight_i, bias_i, proj_i)
+ tail_logprob_i = nn.functional.log_softmax(tail_logit_i, dim=1)
+ cluster_prob_idx = self.cutoffs[0] + i - 1 # No probability for the head cluster
+ if labels is not None:
+ logprob_i = head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
+ 1, target_i[:, None]
+ ).squeeze(1)
+ else:
+ logprob_i = head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
+ out[:, l_idx:r_idx] = logprob_i
+
+ if labels is not None:
+ if (hasattr(self, "keep_order") and self.keep_order) or keep_order:
+ out.index_copy_(0, indices_i, -logprob_i)
+ else:
+ out[offset : offset + logprob_i.size(0)].copy_(-logprob_i)
+ offset += logprob_i.size(0)
+
+ return out
+
+ def log_prob(self, hidden):
+ r"""
+ Computes log probabilities for all \\(n\_classes\\) From:
+ https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/adaptive.p
+
+ Args:
+ hidden (Tensor): a minibatch of example
+
+ Returns:
+ log-probabilities of for each class \\(c\\) in range \\(0 <= c <= n\_classes\\), where \\(n\_classes\\) is
+ a parameter passed to `AdaptiveLogSoftmaxWithLoss` constructor. Shape:
+
+ - Input: \\((N, in\_features)\\)
+ - Output: \\((N, n\_classes)\\)
+ """
+ if self.n_clusters == 0:
+ logit = self._compute_logit(hidden, self.out_layers[0].weight, self.out_layers[0].bias, self.out_projs[0])
+ return nn.functional.log_softmax(logit, dim=-1)
+ else:
+ # construct weights and biases
+ weights, biases = [], []
+ for i in range(len(self.cutoffs)):
+ if self.div_val == 1:
+ l_idx, r_idx = self.cutoff_ends[i], self.cutoff_ends[i + 1]
+ weight_i = self.out_layers[0].weight[l_idx:r_idx]
+ bias_i = self.out_layers[0].bias[l_idx:r_idx]
+ else:
+ weight_i = self.out_layers[i].weight
+ bias_i = self.out_layers[i].bias
+
+ if i == 0:
+ weight_i = torch.cat([weight_i, self.cluster_weight], dim=0)
+ bias_i = torch.cat([bias_i, self.cluster_bias], dim=0)
+
+ weights.append(weight_i)
+ biases.append(bias_i)
+
+ head_weight, head_bias, head_proj = weights[0], biases[0], self.out_projs[0]
+ head_logit = self._compute_logit(hidden, head_weight, head_bias, head_proj)
+
+ out = hidden.new_empty((head_logit.size(0), self.n_token))
+ head_logprob = nn.functional.log_softmax(head_logit, dim=1)
+
+ cutoff_values = [0] + self.cutoffs
+ for i in range(len(cutoff_values) - 1):
+ start_idx, stop_idx = cutoff_values[i], cutoff_values[i + 1]
+
+ if i == 0:
+ out[:, : self.cutoffs[0]] = head_logprob[:, : self.cutoffs[0]]
+ else:
+ weight_i, bias_i, proj_i = weights[i], biases[i], self.out_projs[i]
+
+ tail_logit_i = self._compute_logit(hidden, weight_i, bias_i, proj_i)
+ tail_logprob_i = nn.functional.log_softmax(tail_logit_i, dim=1)
+
+ logprob_i = head_logprob[:, -i] + tail_logprob_i
+ out[:, start_idx, stop_idx] = logprob_i
+
+ return out
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/tokenization_transfo_xl.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/tokenization_transfo_xl.py
new file mode 100644
index 0000000000000000000000000000000000000000..70e2da0185563d4115748266474a935ffddef059
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/transfo_xl/tokenization_transfo_xl.py
@@ -0,0 +1,825 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Tokenization classes for Transformer XL model. Adapted from https://github.com/kimiyoung/transformer-xl.
+"""
+
+import glob
+import os
+import pickle
+import re
+from collections import Counter, OrderedDict
+from typing import Optional
+
+import numpy as np
+
+from ....tokenization_utils import PreTrainedTokenizer
+from ....utils import (
+ cached_file,
+ check_torch_load_is_safe,
+ is_sacremoses_available,
+ is_torch_available,
+ logging,
+ requires_backends,
+ strtobool,
+ torch_only_method,
+)
+
+
+if is_sacremoses_available():
+ import sacremoses as sm
+
+
+if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {
+ "pretrained_vocab_file": "vocab.pkl",
+ "pretrained_vocab_file_torch": "vocab.bin",
+ "vocab_file": "vocab.txt",
+}
+
+
+PRETRAINED_CORPUS_ARCHIVE_MAP = {
+ "transfo-xl/transfo-xl-wt103": "https://huggingface.co/transfo-xl/transfo-xl-wt103/resolve/main/corpus.bin",
+}
+CORPUS_NAME = "corpus.bin"
+
+MATCH_NUMBERS = r"(?<=\d)[,.](?=\d)", r" @\g<0>@ "
+DETOKENIZE_NUMBERS = [(r" @\,@ ", r","), (r" @\.@ ", r".")]
+
+
+def tokenize_numbers(text_array: list[str]) -> list[str]:
+ """
+ Splits large comma-separated numbers and floating point values. This is done by replacing commas with ' @,@ ' and
+ dots with ' @.@ '.
+
+ Args:
+ text_array: An already tokenized text as list.
+
+ Returns:
+ A list of strings with tokenized numbers.
+
+ Example:
+
+ ```python
+ >>> tokenize_numbers(["$", "5,000", "1.73", "m"])
+ ['$', '5', '@,@', '000', '1', '@.@', '73', 'm']
+ ```"""
+ tokenized = []
+ for i in range(len(text_array)):
+ reg, sub = MATCH_NUMBERS
+ replaced = re.sub(reg, sub, text_array[i]).split()
+ tokenized.extend(replaced)
+
+ return tokenized
+
+
+def detokenize_numbers(text: str) -> str:
+ """
+ Inverts the operation of *tokenize_numbers*. This is replacing ' @,@ ' and ' @.@' by ',' and '.'.
+
+ Args:
+ text: A string where the number should be detokenized.
+
+ Returns:
+ A detokenized string.
+
+ Example:
+
+ ```python
+ >>> detokenize_numbers("$ 5 @,@ 000 1 @.@ 73 m")
+ '$ 5,000 1.73 m'
+ ```"""
+ for reg, sub in DETOKENIZE_NUMBERS:
+ text = re.sub(reg, sub, text)
+ return text
+
+
+class TransfoXLTokenizer(PreTrainedTokenizer):
+ """
+ Construct a Transformer-XL tokenizer adapted from Vocab class in [the original
+ code](https://github.com/kimiyoung/transformer-xl). The Transformer-XL tokenizer is a word-level tokenizer (no
+ sub-word tokenization).
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ special (`list[str]`, *optional*):
+ A list of special tokens (to be treated by the original implementation of this tokenizer).
+ min_freq (`int`, *optional*, defaults to 0):
+ The minimum number of times a token has to be present in order to be kept in the vocabulary (otherwise it
+ will be mapped to `unk_token`).
+ max_size (`int`, *optional*):
+ The maximum size of the vocabulary. If left unset, it will default to the size of the vocabulary found
+ after excluding the tokens according to the `min_freq` rule.
+ lower_case (`bool`, *optional*, defaults to `False`):
+ Whether or not to lowercase the input when tokenizing.
+ delimiter (`str`, *optional*):
+ The delimiter used between tokens.
+ vocab_file (`str`, *optional*):
+ File containing the vocabulary (from the original implementation).
+ pretrained_vocab_file (`str`, *optional*):
+ File containing the vocabulary as saved with the `save_pretrained()` method.
+ never_split (`list[str]`, *optional*):
+ List of tokens that should never be split. If no list is specified, will simply use the existing special
+ tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+ additional_special_tokens (`list[str]`, *optional*, defaults to `['']`):
+ A list of additional special tokens (for the HuggingFace functionality).
+ language (`str`, *optional*, defaults to `"en"`):
+ The language of this tokenizer (used for mose preprocessing).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids"]
+
+ def __init__(
+ self,
+ special=None,
+ min_freq=0,
+ max_size=None,
+ lower_case=False,
+ delimiter=None,
+ vocab_file=None,
+ pretrained_vocab_file: Optional[str] = None,
+ never_split=None,
+ unk_token="",
+ eos_token="",
+ additional_special_tokens=[""],
+ language="en",
+ **kwargs,
+ ):
+ logger.error(
+ "`TransfoXL` was deprecated due to security issues linked to `pickle.load` in `TransfoXLTokenizer`. "
+ "See more details on this model's documentation page: "
+ "`https://github.com/huggingface/transformers/blob/main/docs/source/en/model_doc/transfo-xl.md`."
+ )
+
+ requires_backends(self, "sacremoses")
+ if special is None:
+ special = []
+ self.counter = Counter()
+ self.special = special
+ self.min_freq = min_freq
+ self.max_size = max_size
+ self.lower_case = lower_case
+ self.delimiter = delimiter
+ self.vocab_file = vocab_file
+ self.punctuation_symbols = '!"#$%&()*+,-./\\:;<=>?@[\\]^_`{|}~'
+ self.punction_without_space_before_pattern = re.compile(rf"[^\s][{self.punctuation_symbols}]")
+ self.punctuation_with_space_around_pattern = self._compile_space_around_punctuation_pattern()
+ self.language = language
+ self.moses_punct_normalizer = sm.MosesPunctNormalizer(language)
+ self.moses_tokenizer = sm.MosesTokenizer(language)
+ self.moses_detokenizer = sm.MosesDetokenizer(language)
+ self.idx2sym = []
+ self.sym2idx = OrderedDict()
+ # This try... catch... is not beautiful but honestly this tokenizer was not made to be used
+ # in a library like ours, at all.
+ try:
+ vocab_dict = None
+ if pretrained_vocab_file is not None:
+ # Priority on pickle files (support PyTorch and TF)
+ if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
+ raise ValueError(
+ "This part uses `pickle.load` which is insecure and will execute arbitrary code that is "
+ "potentially malicious. It's recommended to never unpickle data that could have come from an "
+ "untrusted source, or that could have been tampered with. If you already verified the pickle "
+ "data and decided to use it, you can set the environment variable "
+ "`TRUST_REMOTE_CODE` to `True` to allow it."
+ )
+ with open(pretrained_vocab_file, "rb") as f:
+ vocab_dict = pickle.load(f)
+
+ # Loading a torch-saved transfo-xl vocab dict with pickle results in an integer
+ # Entering this if statement means that we tried to load a torch-saved file with pickle, and we failed.
+ # We therefore load it with torch, if it's available.
+ if isinstance(vocab_dict, int):
+ if not is_torch_available():
+ raise ImportError(
+ "Not trying to load dict with PyTorch as you need to install pytorch to load "
+ "from a PyTorch pretrained vocabulary, "
+ "or activate it with environment variables USE_TORCH=1 and USE_TF=0."
+ )
+ check_torch_load_is_safe()
+ vocab_dict = torch.load(pretrained_vocab_file, weights_only=True)
+
+ if vocab_dict is not None:
+ for key, value in vocab_dict.items():
+ if key not in self.__dict__ or key in ["sym2idx", "idx2sym"]:
+ self.__dict__[key] = value
+ elif vocab_file is not None:
+ self.build_vocab()
+
+ except Exception as e:
+ raise ValueError(
+ f"Unable to parse file {pretrained_vocab_file}. Unknown format. "
+ "If you tried to load a model saved through TransfoXLTokenizerFast, "
+ "please note they are not compatible."
+ ) from e
+
+ if vocab_file is not None:
+ self.build_vocab()
+
+ super().__init__(
+ special=special,
+ min_freq=min_freq,
+ max_size=max_size,
+ lower_case=lower_case,
+ delimiter=delimiter,
+ vocab_file=vocab_file,
+ pretrained_vocab_file=pretrained_vocab_file,
+ never_split=never_split,
+ unk_token=unk_token,
+ eos_token=eos_token,
+ additional_special_tokens=additional_special_tokens,
+ language=language,
+ **kwargs,
+ )
+
+ # these are not required to initialize the parent class as only used when tokenizing.
+ if never_split is None:
+ never_split = self.all_special_tokens
+ self.never_split = never_split
+
+ @property
+ def do_lower_case(self):
+ return self.lower_case
+
+ def _compile_space_around_punctuation_pattern(self):
+ look_ahead_for_special_token = f"(?=[{self.punctuation_symbols}])"
+ look_ahead_to_match_all_except_space = r"(?=[^\s])"
+ return re.compile(r"" + look_ahead_for_special_token + look_ahead_to_match_all_except_space)
+
+ def count_file(self, path, verbose=False, add_eos=False):
+ if verbose:
+ logger.info(f"counting file {path} ...")
+ assert os.path.exists(path), f"Input file {path} not found"
+
+ sents = []
+ with open(path, "r", encoding="utf-8") as f:
+ for idx, line in enumerate(f):
+ if verbose and idx > 0 and idx % 500000 == 0:
+ logger.info(f" line {idx}")
+ symbols = self.tokenize(line, add_eos=add_eos)
+ self.counter.update(symbols)
+ sents.append(symbols)
+
+ return sents
+
+ def count_sents(self, sents, verbose=False):
+ """
+ sents : a list of sentences, each a list of tokenized symbols
+ """
+ if verbose:
+ logger.info(f"counting {len(sents)} sents ...")
+ for idx, symbols in enumerate(sents):
+ if verbose and idx > 0 and idx % 500000 == 0:
+ logger.info(f" line {idx}")
+ self.counter.update(symbols)
+
+ def _build_from_file(self, vocab_file):
+ self.idx2sym = []
+ self.sym2idx = OrderedDict()
+
+ with open(vocab_file, "r", encoding="utf-8") as f:
+ for line in f:
+ symb = line.strip().split()[0]
+ self.add_symbol(symb)
+ if "" in self.sym2idx:
+ self.unk_idx = self.sym2idx[""]
+ elif "" in self.sym2idx:
+ self.unk_idx = self.sym2idx[""]
+ else:
+ raise ValueError("Token not in vocabulary and no token in vocabulary for replacement.")
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if os.path.isdir(save_directory):
+ vocab_file = os.path.join(
+ save_directory,
+ (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["pretrained_vocab_file"],
+ )
+ else:
+ vocab_file = (filename_prefix + "-" if filename_prefix else "") + save_directory
+ with open(vocab_file, "wb") as f:
+ pickle.dump(self.__dict__, f)
+ return (vocab_file,)
+
+ def build_vocab(self):
+ if self.vocab_file:
+ logger.info(f"building vocab from {self.vocab_file}")
+ self._build_from_file(self.vocab_file)
+ logger.info(f"Final vocab size {len(self.sym2idx)}")
+ else:
+ logger.info(f"building vocab with min_freq={self.min_freq}, max_size={self.max_size}")
+ self.idx2sym = []
+ self.sym2idx = OrderedDict()
+
+ for sym in self.special:
+ self.add_special(sym)
+
+ for sym, cnt in self.counter.most_common(self.max_size):
+ if cnt < self.min_freq:
+ break
+ self.add_symbol(sym)
+
+ logger.info(f"Final vocab size {len(self.sym2idx)} from {len(self.counter)} unique tokens")
+
+ @torch_only_method
+ def encode_file(self, path, ordered=False, verbose=False, add_eos=True, add_double_eos=False):
+ if verbose:
+ logger.info(f"encoding file {path} ...")
+ assert os.path.exists(path), f"Output file {path} not found"
+ encoded = []
+ with open(path, "r", encoding="utf-8") as f:
+ for idx, line in enumerate(f):
+ if verbose and idx > 0 and idx % 500000 == 0:
+ logger.info(f" line {idx}")
+ symbols = self.tokenize(line, add_eos=add_eos, add_double_eos=add_double_eos)
+ encoded.append(self.convert_to_tensor(symbols))
+
+ if ordered:
+ encoded = torch.cat(encoded)
+
+ return encoded
+
+ @torch_only_method
+ def encode_sents(self, sents, ordered=False, verbose=False):
+ if verbose:
+ logger.info(f"encoding {len(sents)} sents ...")
+ encoded = []
+ for idx, symbols in enumerate(sents):
+ if verbose and idx > 0 and idx % 500000 == 0:
+ logger.info(f" line {idx}")
+ encoded.append(self.convert_to_tensor(symbols))
+
+ if ordered:
+ encoded = torch.cat(encoded)
+
+ return encoded
+
+ def add_special(self, sym):
+ if sym not in self.sym2idx:
+ self.idx2sym.append(sym)
+ self.sym2idx[sym] = len(self.idx2sym) - 1
+ setattr(self, f"{sym.strip('<>')}_idx", self.sym2idx[sym])
+
+ def add_symbol(self, sym):
+ if sym not in self.sym2idx:
+ self.idx2sym.append(sym)
+ self.sym2idx[sym] = len(self.idx2sym) - 1
+
+ def move_added_token(self, token: str, target_idx: int):
+ """
+ Moves an added token to a specific position in the vocab. This method should be used when resizing an embedding
+ layer other than the last one in the `AdaptiveEmbedding` in order to move the token in the tokenizer from the
+ default position (at the very end) to the desired one.
+
+ Args:
+ token: The token to move to a specific position in the vocab.
+ target_idx: The position where the token should be moved to.
+ """
+ assert token in self.added_tokens_encoder, "Token which should be moved has to be an added token"
+ assert token not in self.idx2sym, "Token which should be moved is already in vocab"
+
+ # Insert sym into vocab
+ self.idx2sym.insert(target_idx, token)
+ self.sym2idx[token] = target_idx
+
+ # Shift following indices in sym2idx
+ for idx in range(target_idx + 1, len(self.idx2sym)):
+ current_sym = self.idx2sym[idx]
+ self.sym2idx[current_sym] = idx
+
+ # Delete token from added_tokens
+ old_index = self._added_tokens_encoder.pop(token)
+ self._added_tokens_decoder.pop(old_index)
+
+ def moses_punct_norm(self, text):
+ return self.moses_punct_normalizer.normalize(text)
+
+ def moses_tokenize(self, text):
+ return self.moses_tokenizer.tokenize(
+ text, aggressive_dash_splits=True, return_str=False, escape=False, protected_patterns=self.never_split
+ )
+
+ def moses_pipeline(self, text: str) -> list[str]:
+ """
+ Does basic tokenization using [`sacremoses.MosesPunctNormalizer`] and [`sacremoses.MosesTokenizer`] with
+ *aggressive_dash_splits=True* (see [`sacremoses.tokenize.MosesTokenizer.tokenize`]). Additionally, large
+ comma-separated numbers and floating point values are split. E.g. "23,000 people are 1.80m tall" -> "23 @,@ 000
+ people are 1 @.@ 80m tall"
+
+ Args:
+ text: Text to be tokenize
+
+ Returns:
+ A list of tokenized string
+
+ Example:
+
+ ```python
+ >>> tokenizer = TransfoXLTokenizer.from_pretrained("transfo-xl/transfo-xl-wt103")
+ >>> tokenizer.moses_pipeline("23,000 people are 1.80 m tall")
+ ['23', '@,@', '000', 'people', 'are', '1', '@.@', '80', 'm', 'tall']
+ ```"""
+ text = self.moses_punct_norm(text)
+ text = self.moses_tokenize(text)
+ text = tokenize_numbers(text)
+ return text
+
+ def _convert_id_to_token(self, idx):
+ """Converts an id in a token (BPE) using the vocab."""
+ assert 0 <= idx < len(self), f"Index {idx} out of vocabulary range"
+ return self.idx2sym[idx]
+
+ def _convert_token_to_id(self, sym):
+ """Converts a token (str) in an id using the vocab."""
+ if sym in self.sym2idx:
+ return self.sym2idx[sym]
+ else:
+ # logger.info(f'encounter unk {sym}')
+ # assert '' not in sym
+ if hasattr(self, "unk_idx"):
+ return self.sym2idx.get(sym, self.unk_idx)
+ # Backward compatibility with pre-trained models
+ elif "" in self.sym2idx:
+ return self.sym2idx[""]
+ elif "" in self.sym2idx:
+ return self.sym2idx[""]
+ else:
+ raise ValueError("Token not in vocabulary and no token in vocabulary for replacement.")
+
+ def convert_tokens_to_string(self, tokens):
+ """
+ Converts a sequence of tokens (string) in a single string. Additionally, the split numbers are converted back
+ into it's original form.
+ """
+ out_string = self.moses_detokenizer.detokenize(tokens)
+ return detokenize_numbers(out_string).strip()
+
+ @torch_only_method
+ def convert_to_tensor(self, symbols):
+ return torch.LongTensor(self.convert_tokens_to_ids(symbols))
+
+ @property
+ def vocab_size(self):
+ return len(self.idx2sym)
+
+ def get_vocab(self):
+ vocab = self.sym2idx.copy()
+ vocab.update(self.added_tokens_encoder)
+ return vocab
+
+ def _tokenize(self, line, add_eos=False, add_double_eos=False):
+ line = line.strip()
+ # convert to lower case
+ if self.lower_case:
+ line = line.lower()
+
+ # empty delimiter '' will evaluate False
+ if self.delimiter == "":
+ symbols = line
+ else:
+ symbols = self.moses_pipeline(line)
+
+ if add_double_eos: # lm1b
+ return [""] + symbols + [""]
+ elif add_eos:
+ return symbols + [""]
+ else:
+ return symbols
+
+
+class LMOrderedIterator:
+ def __init__(self, data, bsz, bptt, device="cpu", ext_len=None):
+ """
+ data -- LongTensor -- the LongTensor is strictly ordered
+ """
+ self.bsz = bsz
+ self.bptt = bptt
+ self.ext_len = ext_len if ext_len is not None else 0
+
+ self.device = device
+
+ # Work out how cleanly we can divide the dataset into bsz parts.
+ self.n_step = data.size(0) // bsz
+
+ # Trim off any extra elements that wouldn't cleanly fit (remainders).
+ data = data.narrow(0, 0, self.n_step * bsz)
+
+ # Evenly divide the data across the bsz batches.
+ self.data = data.view(bsz, -1).t().contiguous().to(device)
+
+ # Number of mini-batches
+ self.n_batch = (self.n_step + self.bptt - 1) // self.bptt
+
+ def get_batch(self, i, bptt=None):
+ if bptt is None:
+ bptt = self.bptt
+ seq_len = min(bptt, self.data.size(0) - 1 - i)
+
+ end_idx = i + seq_len
+ beg_idx = max(0, i - self.ext_len)
+
+ data = self.data[beg_idx:end_idx]
+ target = self.data[i + 1 : i + 1 + seq_len]
+
+ data_out = data.transpose(0, 1).contiguous().to(self.device)
+ target_out = target.transpose(0, 1).contiguous().to(self.device)
+
+ return data_out, target_out, seq_len
+
+ def get_fixlen_iter(self, start=0):
+ for i in range(start, self.data.size(0) - 1, self.bptt):
+ yield self.get_batch(i)
+
+ def get_varlen_iter(self, start=0, std=5, min_len=5, max_deviation=3):
+ max_len = self.bptt + max_deviation * std
+ i = start
+ while True:
+ bptt = self.bptt if np.random.random() < 0.95 else self.bptt / 2.0
+ bptt = min(max_len, max(min_len, int(np.random.normal(bptt, std))))
+ data, target, seq_len = self.get_batch(i, bptt)
+ i += seq_len
+ yield data, target, seq_len
+ if i >= self.data.size(0) - 2:
+ break
+
+ def __iter__(self):
+ return self.get_fixlen_iter()
+
+
+class LMShuffledIterator:
+ def __init__(self, data, bsz, bptt, device="cpu", ext_len=None, shuffle=False):
+ """
+ data -- list[LongTensor] -- there is no order among the LongTensors
+ """
+ self.data = data
+
+ self.bsz = bsz
+ self.bptt = bptt
+ self.ext_len = ext_len if ext_len is not None else 0
+
+ self.device = device
+ self.shuffle = shuffle
+
+ def get_sent_stream(self):
+ # index iterator
+ epoch_indices = np.random.permutation(len(self.data)) if self.shuffle else np.array(range(len(self.data)))
+
+ # sentence iterator
+ for idx in epoch_indices:
+ yield self.data[idx]
+
+ @torch_only_method
+ def stream_iterator(self, sent_stream):
+ # streams for each data in the batch
+ streams = [None] * self.bsz
+
+ data = torch.LongTensor(self.bptt, self.bsz)
+ target = torch.LongTensor(self.bptt, self.bsz)
+
+ n_retain = 0
+
+ while True:
+ # data : [n_retain+bptt x bsz]
+ # target : [bptt x bsz]
+ data[n_retain:].fill_(-1)
+ target.fill_(-1)
+
+ valid_batch = True
+
+ for i in range(self.bsz):
+ n_filled = 0
+ try:
+ while n_filled < self.bptt:
+ if streams[i] is None or len(streams[i]) <= 1:
+ streams[i] = next(sent_stream)
+ # number of new tokens to fill in
+ n_new = min(len(streams[i]) - 1, self.bptt - n_filled)
+ # first n_retain tokens are retained from last batch
+ data[n_retain + n_filled : n_retain + n_filled + n_new, i] = streams[i][:n_new]
+ target[n_filled : n_filled + n_new, i] = streams[i][1 : n_new + 1]
+ streams[i] = streams[i][n_new:]
+ n_filled += n_new
+ except StopIteration:
+ valid_batch = False
+ break
+
+ if not valid_batch:
+ return
+
+ data_out = data.transpose(0, 1).contiguous().to(self.device)
+ target_out = target.transpose(0, 1).contiguous().to(self.device)
+
+ yield data_out, target_out, self.bptt
+
+ n_retain = min(data.size(0), self.ext_len)
+ if n_retain > 0:
+ data[:n_retain] = data[-n_retain:]
+ data.resize_(n_retain + self.bptt, data.size(1))
+
+ def __iter__(self):
+ # sent_stream is an iterator
+ sent_stream = self.get_sent_stream()
+
+ for batch in self.stream_iterator(sent_stream):
+ yield batch
+
+
+class LMMultiFileIterator(LMShuffledIterator):
+ def __init__(self, paths, vocab, bsz, bptt, device="cpu", ext_len=None, shuffle=False):
+ self.paths = paths
+ self.vocab = vocab
+
+ self.bsz = bsz
+ self.bptt = bptt
+ self.ext_len = ext_len if ext_len is not None else 0
+
+ self.device = device
+ self.shuffle = shuffle
+
+ def get_sent_stream(self, path):
+ sents = self.vocab.encode_file(path, add_double_eos=True)
+ if self.shuffle:
+ np.random.shuffle(sents)
+ sent_stream = iter(sents)
+
+ return sent_stream
+
+ def __iter__(self):
+ if self.shuffle:
+ np.random.shuffle(self.paths)
+
+ for path in self.paths:
+ # sent_stream is an iterator
+ sent_stream = self.get_sent_stream(path)
+ for batch in self.stream_iterator(sent_stream):
+ yield batch
+
+
+class TransfoXLCorpus:
+ @classmethod
+ @torch_only_method
+ def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs):
+ """
+ Instantiate a pre-processed corpus.
+ """
+ vocab = TransfoXLTokenizer.from_pretrained(pretrained_model_name_or_path, *inputs, **kwargs)
+ is_local = os.path.isdir(pretrained_model_name_or_path)
+ # redirect to the cache, if necessary
+ try:
+ resolved_corpus_file = cached_file(pretrained_model_name_or_path, CORPUS_NAME, cache_dir=cache_dir)
+ except OSError:
+ logger.error(
+ f"Corpus '{pretrained_model_name_or_path}' was not found in corpus list"
+ f" ({', '.join(PRETRAINED_CORPUS_ARCHIVE_MAP.keys())}. We assumed '{pretrained_model_name_or_path}'"
+ f" was a path or url but couldn't find files {CORPUS_NAME} at this path or url."
+ )
+ return None
+ if is_local:
+ logger.info(f"loading corpus file {resolved_corpus_file}")
+ else:
+ logger.info(f"loading corpus file {CORPUS_NAME} from cache at {resolved_corpus_file}")
+
+ # Instantiate tokenizer.
+ corpus = cls(*inputs, **kwargs)
+ check_torch_load_is_safe()
+ corpus_dict = torch.load(resolved_corpus_file, weights_only=True)
+ for key, value in corpus_dict.items():
+ corpus.__dict__[key] = value
+ corpus.vocab = vocab
+ if corpus.train is not None:
+ corpus.train = torch.tensor(corpus.train, dtype=torch.long)
+ if corpus.valid is not None:
+ corpus.valid = torch.tensor(corpus.valid, dtype=torch.long)
+ if corpus.test is not None:
+ corpus.test = torch.tensor(corpus.test, dtype=torch.long)
+ return corpus
+
+ def __init__(self, *args, **kwargs):
+ self.vocab = TransfoXLTokenizer(*args, **kwargs)
+ self.dataset = None
+ self.train = None
+ self.valid = None
+ self.test = None
+
+ def build_corpus(self, path, dataset):
+ self.dataset = dataset
+
+ if self.dataset in ["ptb", "wt2", "enwik8", "text8"]:
+ self.vocab.count_file(os.path.join(path, "train.txt"))
+ self.vocab.count_file(os.path.join(path, "valid.txt"))
+ self.vocab.count_file(os.path.join(path, "test.txt"))
+ elif self.dataset == "wt103":
+ self.vocab.count_file(os.path.join(path, "train.txt"))
+ elif self.dataset == "lm1b":
+ train_path_pattern = os.path.join(
+ path,
+ "1-billion-word-language-modeling-benchmark-r13output",
+ "training-monolingual.tokenized.shuffled",
+ "news.en-*",
+ )
+ train_paths = glob.glob(train_path_pattern)
+ # the vocab will load from file when build_vocab() is called
+
+ self.vocab.build_vocab()
+
+ if self.dataset in ["ptb", "wt2", "wt103"]:
+ self.train = self.vocab.encode_file(os.path.join(path, "train.txt"), ordered=True)
+ self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=True)
+ self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=True)
+ elif self.dataset in ["enwik8", "text8"]:
+ self.train = self.vocab.encode_file(os.path.join(path, "train.txt"), ordered=True, add_eos=False)
+ self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=True, add_eos=False)
+ self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=True, add_eos=False)
+ elif self.dataset == "lm1b":
+ self.train = train_paths
+ self.valid = self.vocab.encode_file(os.path.join(path, "valid.txt"), ordered=False, add_double_eos=True)
+ self.test = self.vocab.encode_file(os.path.join(path, "test.txt"), ordered=False, add_double_eos=True)
+
+ def get_iterator(self, split, *args, **kwargs):
+ if split == "train":
+ if self.dataset in ["ptb", "wt2", "wt103", "enwik8", "text8"]:
+ data_iter = LMOrderedIterator(self.train, *args, **kwargs)
+ elif self.dataset == "lm1b":
+ kwargs["shuffle"] = True
+ data_iter = LMMultiFileIterator(self.train, self.vocab, *args, **kwargs)
+ elif split in ["valid", "test"]:
+ data = self.valid if split == "valid" else self.test
+ if self.dataset in ["ptb", "wt2", "wt103", "enwik8", "text8"]:
+ data_iter = LMOrderedIterator(data, *args, **kwargs)
+ elif self.dataset == "lm1b":
+ data_iter = LMShuffledIterator(data, *args, **kwargs)
+ else:
+ data_iter = None
+ raise ValueError(f"Split not recognized: {split}")
+
+ return data_iter
+
+
+@torch_only_method
+def get_lm_corpus(datadir, dataset):
+ fn = os.path.join(datadir, "cache.pt")
+ fn_pickle = os.path.join(datadir, "cache.pkl")
+ if os.path.exists(fn):
+ logger.info("Loading cached dataset...")
+ check_torch_load_is_safe()
+ corpus = torch.load(fn_pickle, weights_only=True)
+ elif os.path.exists(fn):
+ logger.info("Loading cached dataset from pickle...")
+ if not strtobool(os.environ.get("TRUST_REMOTE_CODE", "False")):
+ raise ValueError(
+ "This part uses `pickle.load` which is insecure and will execute arbitrary code that is potentially "
+ "malicious. It's recommended to never unpickle data that could have come from an untrusted source, or "
+ "that could have been tampered with. If you already verified the pickle data and decided to use it, "
+ "you can set the environment variable `TRUST_REMOTE_CODE` to `True` to allow it."
+ )
+ with open(fn, "rb") as fp:
+ corpus = pickle.load(fp)
+ else:
+ logger.info(f"Producing dataset {dataset}...")
+ kwargs = {}
+ if dataset in ["wt103", "wt2"]:
+ kwargs["special"] = [""]
+ kwargs["lower_case"] = False
+ elif dataset == "ptb":
+ kwargs["special"] = [""]
+ kwargs["lower_case"] = True
+ elif dataset == "lm1b":
+ kwargs["special"] = []
+ kwargs["lower_case"] = False
+ kwargs["vocab_file"] = os.path.join(datadir, "1b_word_vocab.txt")
+ elif dataset in ["enwik8", "text8"]:
+ pass
+
+ corpus = TransfoXLCorpus(datadir, dataset, **kwargs)
+ torch.save(corpus, fn)
+
+ return corpus
+
+
+__all__ = ["TransfoXLCorpus", "TransfoXLTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..941db2f6ac5fefe66e06d598e1adbe0db1cf1769
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__init__.py
@@ -0,0 +1,20 @@
+# flake8: noqa
+# There's no way to ignore "F401 '...' imported but unused" warnings in this
+# module, but to preserve other warnings. So, don't check this module at all.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_tvlt import *
+ from .feature_extraction_tvlt import *
+ from .processing_tvlt import *
+ from .modeling_tvlt import *
+ from .image_processing_tvlt import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..958083d6ad00eb08eeee22dedfd71bd81de76786
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/configuration_tvlt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/configuration_tvlt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af025cfbc0ebc37a8c7c30a53a0b879095150ade
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/configuration_tvlt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/feature_extraction_tvlt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/feature_extraction_tvlt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e6db032d3366640e96e34656a60f3e3900480877
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/feature_extraction_tvlt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/image_processing_tvlt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/image_processing_tvlt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b46bf0fbbf840bb5c53d9926264069ef74562f22
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/image_processing_tvlt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/modeling_tvlt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/modeling_tvlt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40784e9f236905ea4846d0dd712c130c5d8ffa86
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/modeling_tvlt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/processing_tvlt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/processing_tvlt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..836d4a085548311967724989ae2c877295631560
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/__pycache__/processing_tvlt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/configuration_tvlt.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/configuration_tvlt.py
new file mode 100644
index 0000000000000000000000000000000000000000..57144e349f5bcb244b4f9eeeefebd0312c4770aa
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/configuration_tvlt.py
@@ -0,0 +1,187 @@
+# coding=utf-8
+# Copyright 2023 MURGe-Lab and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""TVLT model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class TvltConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`TvltModel`]. It is used to instantiate a TVLT
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the TVLT
+ [ZinengTang/tvlt-base](https://huggingface.co/ZinengTang/tvlt-base) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ image_size (`int`, *optional*, defaults to 224):
+ The size (resolution) of each image.
+ spectrogram_length (`int`, *optional*, defaults to 2048):
+ The time length of each audio spectrogram.
+ frequency_length (`int`, *optional*, defaults to 128):
+ The frequency length of audio spectrogram.
+ image_patch_size (`list[int]`, *optional*, defaults to `[16, 16]`):
+ The size (resolution) of each image patch.
+ audio_patch_size (`list[int]`, *optional*, defaults to `[16, 16]`):
+ The size (resolution) of each audio patch.
+ num_image_channels (`int`, *optional*, defaults to 3):
+ The number of input image channels.
+ num_audio_channels (`int`, *optional*, defaults to 1):
+ The number of input audio channels.
+ num_frames (`int`, *optional*, defaults to 8):
+ The maximum number of frames for an input video.
+ hidden_size (`int`, *optional*, defaults to 768):
+ Dimensionality of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 3072):
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
+ The epsilon used by the layer normalization layers.
+ qkv_bias (`bool`, *optional*, defaults to `True`):
+ Whether to add a bias to the queries, keys and values.
+ use_mean_pooling (`bool`, *optional*, defaults to `False`):
+ Whether to mean pool the final hidden states instead of using the final hidden state of the [CLS] token.
+ decoder_num_attention_heads (`int`, *optional*, defaults to 16):
+ Number of attention heads for each attention layer in the decoder.
+ decoder_hidden_size (`int`, *optional*, defaults to 512):
+ Dimensionality of the decoder.
+ decoder_num_hidden_layers (`int`, *optional*, defaults to 8):
+ Number of hidden layers in the decoder.
+ decoder_intermediate_size (`int`, *optional*, defaults to 2048):
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the decoder.
+ pixel_mask_ratio (`float`, *optional*, defaults to 0.75):
+ Image patch masking ratio.
+ audio_mask_ratio (`float`, *optional*, defaults to 0.15):
+ Audio patch masking ratio.
+ audio_mask_type (`str`, *optional*, defaults to `"frame-level"`):
+ Audio patch masking type, choose between "frame-level" and "patch-level".
+ task_matching (`bool`, *optional*, defaults to `True`):
+ Whether to use vision audio matching task in pretraining.
+ task_mae (`bool`, *optional*, defaults to `True`):
+ Whether to use the masked auto-encoder (MAE) in pretraining.
+ loss_type (`str`, *optional*, defaults to `"classification"`):
+ Loss types including regression and classification.
+
+ Example:
+
+ ```python
+ >>> from transformers import TvltConfig, TvltModel
+
+ >>> # # Initializing a TVLT ZinengTang/tvlt-base style configuration
+ >>> configuration = TvltConfig()
+
+ >>> # # Initializing a model (with random weights) from the ZinengTang/tvlt-base style configuration
+ >>> model = TvltModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "tvlt"
+
+ def __init__(
+ self,
+ image_size=224,
+ spectrogram_length=2048,
+ frequency_length=128,
+ image_patch_size=[16, 16],
+ audio_patch_size=[16, 16],
+ num_image_channels=3,
+ num_audio_channels=1,
+ num_frames=8,
+ hidden_size=768,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.0,
+ attention_probs_dropout_prob=0.0,
+ initializer_range=0.02,
+ layer_norm_eps=1e-6,
+ qkv_bias=True,
+ use_mean_pooling=False,
+ decoder_num_attention_heads=16,
+ decoder_hidden_size=512,
+ decoder_num_hidden_layers=8,
+ decoder_intermediate_size=2048,
+ pixel_mask_ratio=0.75,
+ audio_mask_ratio=0.15,
+ audio_mask_type="frame-level",
+ task_matching=True,
+ task_mae=True,
+ loss_type="classification",
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ if audio_mask_type not in ("frame-level", "patch_level"):
+ raise ValueError(
+ "audio_mask_type must be one of two acceptable strategies - {'frame_level', 'patch-level') "
+ f"got {audio_mask_type}"
+ )
+
+ self.image_size = image_size
+ self.spectrogram_length = spectrogram_length
+ self.frequency_length = frequency_length
+ self.image_patch_size = image_patch_size
+ self.audio_patch_size = audio_patch_size
+ self.num_image_channels = num_image_channels
+ self.num_audio_channels = num_audio_channels
+ self.num_frames = num_frames
+
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.qkv_bias = qkv_bias
+ self.use_mean_pooling = use_mean_pooling
+
+ self.decoder_num_attention_heads = decoder_num_attention_heads
+ self.decoder_hidden_size = decoder_hidden_size
+ self.decoder_num_hidden_layers = decoder_num_hidden_layers
+ self.decoder_intermediate_size = decoder_intermediate_size
+ self.pixel_mask_ratio = pixel_mask_ratio
+ self.audio_mask_ratio = audio_mask_ratio
+ self.audio_mask_type = audio_mask_type
+
+ self.task_matching = task_matching
+ self.task_mae = task_mae
+ self.loss_type = loss_type
+
+
+__all__ = ["TvltConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/feature_extraction_tvlt.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/feature_extraction_tvlt.py
new file mode 100644
index 0000000000000000000000000000000000000000..086c411feb0b62c8f86722e94c147764b4e3f110
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/feature_extraction_tvlt.py
@@ -0,0 +1,233 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Feature extractor class for TVLT."""
+
+from math import ceil
+from typing import Optional, Union
+
+import numpy as np
+
+from ....audio_utils import mel_filter_bank, spectrogram, window_function
+from ....feature_extraction_sequence_utils import BatchFeature, SequenceFeatureExtractor
+from ....utils import TensorType, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class TvltFeatureExtractor(SequenceFeatureExtractor):
+ r"""
+ Constructs a TVLT audio feature extractor. This feature extractor can be used to prepare audios for the model.
+
+ This feature extractor inherits from [`FeatureExtractionMixin`] which contains most of the main methods. Users
+ should refer to this superclass for more information regarding those methods.
+
+ Args:
+ spectrogram_length (`dict[str, int]` *optional*, defaults to 2048):
+ The time length of each audio spectrogram.
+ num_channels (`int` *optional*, defaults to 1):
+ Number of audio channels.
+ patch_size (`list[int]` *optional*, defaults to `[16, 16]`):
+ The patch size of audio patch embedding.
+ feature_size (`int`, *optional*, defaults to 128):
+ The frequency length of audio spectrogram.
+ sampling_rate (`int`, *optional*, defaults to 44100):
+ The sampling rate at which the audio files should be digitalized expressed in Hertz (Hz).
+ hop_length_to_sampling_rate (`int`, *optional*, defaults to 86):
+ Hop length is length of the overlapping windows for the STFT used to obtain the Mel Frequency coefficients.
+ For example, with sampling rate 44100, the hop length is 512, with 44100 / 512 = 86
+ n_fft (`int`, *optional*, defaults to 2048):
+ Size of the Fourier transform.
+ padding_value (`float`, *optional*, defaults to 0.0):
+ Padding value used to pad the audio. Should correspond to silences.
+ """
+
+ model_input_names = ["audio_values", "audio_mask"]
+
+ def __init__(
+ self,
+ spectrogram_length=2048,
+ num_channels=1,
+ patch_size=[16, 16],
+ feature_size=128,
+ sampling_rate=44100,
+ hop_length_to_sampling_rate=86,
+ n_fft=2048,
+ padding_value=0.0,
+ **kwargs,
+ ):
+ super().__init__(
+ feature_size=feature_size,
+ sampling_rate=sampling_rate,
+ padding_value=padding_value,
+ **kwargs,
+ )
+
+ self.spectrogram_length = spectrogram_length
+ self.num_channels = num_channels
+ self.patch_size = patch_size
+ self.freq_len = feature_size // self.patch_size[1]
+ self.n_fft = n_fft
+ self.hop_length = sampling_rate // hop_length_to_sampling_rate
+ self.sampling_rate = sampling_rate
+ self.padding_value = padding_value
+ self.mel_filters = mel_filter_bank(
+ num_frequency_bins=1 + n_fft // 2,
+ num_mel_filters=feature_size,
+ min_frequency=0.0,
+ max_frequency=22050.0,
+ sampling_rate=sampling_rate,
+ norm="slaney",
+ mel_scale="slaney",
+ ).T
+
+ def _np_extract_fbank_features(self, waveform: np.array) -> np.ndarray:
+ """
+ Compute the log-mel spectrogram of the provided audio, gives similar results to Whisper's original torch
+ implementation with 1e-5 tolerance.
+ """
+ log_spec = spectrogram(
+ waveform,
+ window_function(self.n_fft, "hann"),
+ frame_length=self.n_fft,
+ hop_length=self.hop_length,
+ power=2.0,
+ mel_filters=self.mel_filters.T,
+ log_mel="dB",
+ db_range=80.0,
+ )
+ log_spec = log_spec[:, :-1]
+ log_spec = log_spec - 20.0
+ log_spec = np.clip(log_spec / 40.0, -2.0, 0.0) + 1.0
+ return log_spec
+
+ def __call__(
+ self,
+ raw_speech: Union[np.ndarray, list[float], list[np.ndarray], list[list[float]]],
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ return_attention_mask: Optional[bool] = True,
+ sampling_rate: Optional[int] = None,
+ resample: bool = False,
+ mask_audio: bool = False,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Main method to prepare one or several audio(s) for the model.
+
+ Args:
+ raw_speech (`np.ndarray`, `list[float]`, `list[np.ndarray]`, `list[list[float]]`):
+ The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
+ values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
+ stereo, i.e. single float per timestep.
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
+ If set, will return tensors instead of list of python integers. Acceptable values are:
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return Numpy `np.ndarray` objects.
+ return_attention_mask (`bool`, *optional*, default to `True`):
+ Whether to return the attention mask. If left to the default, will return the attention mask according
+ to the specific feature_extractor's default. [What are attention masks?](../glossary#attention-mask)
+
+
+
+ For TvltTransformer models, `attention_mask` should always be passed for batched inference, to avoid
+ subtle bugs.
+
+
+
+ sampling_rate (`int`, *optional*):
+ The sampling rate at which the `raw_speech` input was sampled. It is strongly recommended to pass
+ `sampling_rate` at the forward call to prevent silent errors and allow automatic speech recognition
+ pipeline. Current model supports sampling rate 16000 and 44100.
+ resample (`bool`, *optional*, defaults to `False`):
+ If the sampling rate is not matched, resample the input audio to match.
+ mask_audio (`bool`, *optional*, defaults to `False`):
+ Whether or not to mask input audio for MAE task.
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **audio_values** -- Audio values to be fed to a model, of shape (batch_size, num_channels, height,
+ width).
+
+ - **audio_mask** -- Audio masks to be fed to a model, of shape (batch_size, num_audio_patches).
+ """
+
+ if sampling_rate is not None:
+ if sampling_rate != self.sampling_rate:
+ raise ValueError(
+ "This feature extractor is set to support sampling rate"
+ f" of {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled"
+ f" with {self.sampling_rate} and not {sampling_rate}."
+ )
+ else:
+ logger.warning(
+ "It is strongly recommended to pass the `sampling_rate` argument to this function. "
+ "Failing to do so can result in silent errors that might be hard to debug."
+ )
+
+ is_batched_numpy = isinstance(raw_speech, np.ndarray) and len(raw_speech.shape) > 1
+ if is_batched_numpy and len(raw_speech.shape) > 2:
+ raise ValueError(f"Only mono-channel audio is supported for input to {self}")
+ is_batched = is_batched_numpy or (
+ isinstance(raw_speech, (list, tuple)) and (isinstance(raw_speech[0], (np.ndarray, tuple, list)))
+ )
+ if is_batched:
+ raw_speech = [np.asarray([speech], dtype=np.float32).T for speech in raw_speech]
+ elif not is_batched and not isinstance(raw_speech, np.ndarray):
+ raw_speech = np.asarray(raw_speech, dtype=np.float32)
+ elif isinstance(raw_speech, np.ndarray) and raw_speech.dtype is np.dtype(np.float64):
+ raw_speech = raw_speech.astype(np.float32)
+ # always return batch
+ if not is_batched:
+ raw_speech = [np.asarray([raw_speech]).T]
+
+ # Convert audio signals to log mel spectrograms, truncate by time axis
+ audio_features = [
+ self._np_extract_fbank_features(waveform.squeeze()).T[: self.spectrogram_length] for waveform in raw_speech
+ ]
+ if isinstance(audio_features[0], list):
+ audio_features = [np.asarray(feature, dtype=np.float32) for feature in audio_features]
+
+ # Create audio attention mask
+ max_patch_len = max(
+ [ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len for feature in audio_features]
+ ) # The maximum number of audio patches in a batch
+ if return_attention_mask:
+ audio_mask = [
+ (ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [1]
+ + (max_patch_len - ceil(feature.shape[0] / self.patch_size[0]) * self.freq_len) * [0]
+ for feature in audio_features
+ ]
+ audio_mask = np.array(audio_mask).astype(np.float32)
+
+ # convert into correct format for padding
+ max_time_len = max_patch_len // self.freq_len * self.patch_size[0] # The maximum audio size in a batch
+ padded_audio_features = np.ones([len(audio_features), 1, max_time_len, self.feature_size]).astype(np.float32)
+ padded_audio_features = padded_audio_features * self.padding_value
+ for i in range(len(audio_features)):
+ feature = audio_features[i]
+ padded_audio_features[i, :, : feature.shape[0], :] = feature
+
+ # return as BatchFeature
+ if return_attention_mask:
+ data = {"audio_values": padded_audio_features, "audio_mask": audio_mask}
+ else:
+ data = {"audio_values": padded_audio_features}
+
+ encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
+ return encoded_inputs
+
+
+__all__ = ["TvltFeatureExtractor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/image_processing_tvlt.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/image_processing_tvlt.py
new file mode 100644
index 0000000000000000000000000000000000000000..d142939ee394127f9f29d40f988458205770ac22
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/image_processing_tvlt.py
@@ -0,0 +1,438 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for TVLT."""
+
+from typing import Optional, Union
+
+import numpy as np
+
+from ....image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
+from ....image_transforms import (
+ get_resize_output_image_size,
+ resize,
+ to_channel_dimension_format,
+)
+from ....image_utils import (
+ IMAGENET_STANDARD_MEAN,
+ IMAGENET_STANDARD_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ infer_channel_dimension_format,
+ is_scaled_image,
+ is_valid_image,
+ to_numpy_array,
+ valid_images,
+ validate_kwargs,
+ validate_preprocess_arguments,
+)
+from ....utils import TensorType, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+def make_batched(videos) -> list[list[ImageInput]]:
+ if isinstance(videos, (list, tuple)) and isinstance(videos[0], (list, tuple)):
+ return videos
+
+ elif isinstance(videos, (list, tuple)) and is_valid_image(videos[0]):
+ videos_dim = np.array(videos[0]).ndim
+ if videos_dim == 3:
+ return [videos]
+ elif videos_dim == 4:
+ return videos
+
+ elif is_valid_image(videos):
+ videos_dim = np.array(videos).ndim
+ if videos_dim == 3:
+ return [[videos]]
+ elif videos_dim == 4:
+ return [videos]
+ elif videos_dim == 5:
+ return videos
+
+ raise ValueError(f"Could not make batched video from {videos}")
+
+
+class TvltImageProcessor(BaseImageProcessor):
+ r"""
+ Constructs a TVLT image processor.
+
+ This processor can be used to prepare either videos or images for the model by converting images to 1-frame videos.
+
+ Args:
+ do_resize (`bool`, *optional*, defaults to `True`):
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by the
+ `do_resize` parameter in the `preprocess` method.
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
+ Size of the output image after resizing. The shortest edge of the image will be resized to
+ `size["shortest_edge"]` while maintaining the aspect ratio of the original image. Can be overridden by
+ `size` in the `preprocess` method.
+ patch_size (`list[int]` *optional*, defaults to [16,16]):
+ The patch size of image patch embedding.
+ num_frames (`int` *optional*, defaults to 8):
+ The maximum number of video frames.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
+ `preprocess` method.
+ do_center_crop (`bool`, *optional*, defaults to `True`):
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by the `do_center_crop`
+ parameter in the `preprocess` method.
+ crop_size (`dict[str, int]`, *optional*, defaults to `{"height": 224, "width": 224}`):
+ Size of the image after applying the center crop. Can be overridden by the `crop_size` parameter in the
+ `preprocess` method.
+ do_rescale (`bool`, *optional*, defaults to `True`):
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
+ parameter in the `preprocess` method.
+ rescale_factor (`int` or `float`, *optional*, defaults to 1/255):
+ Defines the scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter
+ in the `preprocess` method.
+ do_normalize (`bool`, *optional*, defaults to `True`):
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
+ method.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
+ """
+
+ model_input_names = [
+ "pixel_values",
+ "pixel_mask",
+ "pixel_values_mixed",
+ "pixel_mask_mixed",
+ ]
+
+ def __init__(
+ self,
+ do_resize: bool = True,
+ size: Optional[dict[str, int]] = None,
+ patch_size: list[int] = [16, 16],
+ num_frames: int = 8,
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
+ do_center_crop: bool = True,
+ crop_size: Optional[dict[str, int]] = None,
+ do_rescale: bool = True,
+ rescale_factor: Union[int, float] = 1 / 255,
+ do_normalize: bool = True,
+ image_mean: Optional[Union[float, list[float]]] = IMAGENET_STANDARD_MEAN,
+ image_std: Optional[Union[float, list[float]]] = IMAGENET_STANDARD_STD,
+ init_mask_generator=False,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ size = size if size is not None else {"shortest_edge": 224}
+ size = get_size_dict(size, default_to_square=False)
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
+
+ self.do_resize = do_resize
+ self.size = size
+ self.patch_size = patch_size
+ self.num_frames = num_frames
+ self.do_center_crop = do_center_crop
+ self.crop_size = crop_size
+ self.resample = resample
+ self.do_rescale = do_rescale
+ self.rescale_factor = rescale_factor
+ self.do_normalize = do_normalize
+ self.image_mean = image_mean
+ self.image_std = image_std
+ self._valid_processor_keys = [
+ "videos",
+ "do_resize",
+ "size",
+ "patch_size",
+ "num_frames",
+ "resample",
+ "do_center_crop",
+ "crop_size",
+ "do_rescale",
+ "rescale_factor",
+ "do_normalize",
+ "image_mean",
+ "image_std",
+ "is_mixed",
+ "return_tensors",
+ "data_format",
+ "input_data_format",
+ ]
+
+ def resize(
+ self,
+ image: np.ndarray,
+ size: dict[str, int],
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Resize an image.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`dict[str, int]`):
+ Size of the output image. If `size` is of the form `{"height": h, "width": w}`, the output image will
+ have the size `(h, w)`. If `size` is of the form `{"shortest_edge": s}`, the output image will have its
+ shortest edge of length `s` while keeping the aspect ratio of the original image.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use when resiizing the image.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
+ input_data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred.
+ """
+ size = get_size_dict(size, default_to_square=False)
+ if "shortest_edge" in size:
+ output_size = get_resize_output_image_size(
+ image, size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
+ )
+ elif "height" in size and "width" in size:
+ output_size = (size["height"], size["width"])
+ else:
+ raise ValueError(f"Size must have 'height' and 'width' or 'shortest_edge' as keys. Got {size.keys()}")
+ return resize(
+ image,
+ size=output_size,
+ resample=resample,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ **kwargs,
+ )
+
+ def _preprocess_image(
+ self,
+ image: ImageInput,
+ do_resize: Optional[bool] = None,
+ size: Optional[dict[str, int]] = None,
+ resample: PILImageResampling = None,
+ do_center_crop: Optional[bool] = None,
+ crop_size: Optional[dict[str, int]] = None,
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ ) -> np.ndarray:
+ """Preprocesses a single image."""
+
+ validate_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_center_crop=do_center_crop,
+ crop_size=crop_size,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ )
+
+ # All transformations expect numpy arrays.
+ image = to_numpy_array(image)
+
+ if do_rescale and is_scaled_image(image):
+ logger.warning_once(
+ "It looks like you are trying to rescale already rescaled images. If the input"
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
+ )
+
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+
+ if do_resize:
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
+
+ if do_center_crop:
+ image = self.center_crop(image, size=crop_size, input_data_format=input_data_format)
+
+ if do_rescale:
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
+
+ if do_normalize:
+ image = self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
+ image = to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
+ return image
+
+ def preprocess(
+ self,
+ videos: ImageInput,
+ do_resize: Optional[bool] = None,
+ size: Optional[dict[str, int]] = None,
+ patch_size: Optional[list[int]] = None,
+ num_frames: Optional[int] = None,
+ resample: PILImageResampling = None,
+ do_center_crop: Optional[bool] = None,
+ crop_size: Optional[dict[str, int]] = None,
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ is_mixed: bool = False,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ data_format: ChannelDimension = ChannelDimension.FIRST,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an videos or image or batch of videos or images.
+
+ Args:
+ videos (`ImageInput`):
+ Images or videos to preprocess. Expects a single or batch of frames with pixel values ranging from 0 to
+ 255. If passing in frames with pixel values between 0 and 1, set `do_rescale=False`.
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
+ Whether to resize the image.
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
+ Size of the image after applying resize.
+ patch_size (`list[int]` *optional*, defaults to self.patch_size):
+ The patch size of image patch embedding.
+ num_frames (`int` *optional*, defaults to self.num_frames):
+ The maximum number of video frames.
+ resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
+ has an effect if `do_resize` is set to `True`.
+ do_center_crop (`bool`, *optional*, defaults to `self.do_centre_crop`):
+ Whether to centre crop the image.
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
+ Size of the image after applying the centre crop.
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
+ Whether to rescale the image values between [0 - 1].
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
+ Whether to normalize the image.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
+ Image mean.
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
+ Image standard deviation.
+ is_mixed (`bool`, *optional*):
+ If the input video has negative samples.
+ return_tensors (`str` or `TensorType`, *optional*):
+ The type of tensors to return. Can be one of:
+ - Unset: Return a list of `np.ndarray`.
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
+ The channel dimension format for the output image. Can be one of:
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - Unset: Use the inferred channel dimension format of the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+
+ Returns:
+ [`BatchFeature`]: A [`BatchFeature`] with the following fields:
+
+ - **pixel_values** -- Pixel values to be fed to a model, of shape (batch_size, num_channels, height,
+ width).
+
+ - **pixel_mask** -- Pixel masks to be fed to a model, of shape (batch_size, num_pixel_patches).
+
+ - **pixel_values_mixed** -- Pixel values with both positive or negative to be fed to a model, of shape
+ (batch_size, num_channels, height, width).
+
+ - **pixel_mask_mixed** -- Pixel masks with both positive or negative to be fed to a model, of shape
+ (batch_size, num_pixel_patches).
+ """
+ do_resize = do_resize if do_resize is not None else self.do_resize
+ resample = resample if resample is not None else self.resample
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
+ image_mean = image_mean if image_mean is not None else self.image_mean
+ image_std = image_std if image_std is not None else self.image_std
+
+ size = size if size is not None else self.size
+ size = get_size_dict(size, default_to_square=False)
+ crop_size = crop_size if crop_size is not None else self.crop_size
+ crop_size = get_size_dict(crop_size, param_name="crop_size")
+ patch_size = patch_size if patch_size is not None else self.patch_size
+ num_frames = num_frames if patch_size is not None else self.num_frames
+
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
+
+ if not valid_images(videos):
+ raise ValueError(
+ "Invalid image or video type. Must be of type PIL.Image.Image, numpy.ndarray, "
+ "torch.Tensor, tf.Tensor or jax.ndarray."
+ )
+
+ videos = make_batched(videos)
+
+ # Check number of frames is fewer than maximum frames
+ for video in videos:
+ if len(video) > self.num_frames:
+ raise ValueError(
+ f"number of frames must not be greater than the maximum frames of the model {self.num_frames}."
+ )
+
+ max_num_frames = max([len(video) for video in videos])
+ num_patches_per_image = (size["shortest_edge"] // patch_size[0]) ** 2
+ video_masks = np.array(
+ [
+ len(video) * num_patches_per_image * [1] + (max_num_frames - len(video)) * num_patches_per_image * [0]
+ for video in videos
+ ]
+ )
+
+ videos = [
+ [
+ self._preprocess_image(
+ image=img,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ do_center_crop=do_center_crop,
+ crop_size=crop_size,
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ )
+ for img in video
+ ]
+ for video in videos
+ ]
+
+ # If videos contain both positive/negative, use mixed key for video-audio matching task
+ if is_mixed:
+ data = {"pixel_values_mixed": videos, "pixel_mask_mixed": video_masks}
+ else:
+ data = {"pixel_values": videos, "pixel_mask": video_masks}
+
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+
+__all__ = ["TvltImageProcessor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/modeling_tvlt.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/modeling_tvlt.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f34083ac2ff5401fb417e556ee5892b879861ac
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/modeling_tvlt.py
@@ -0,0 +1,1275 @@
+# coding=utf-8
+# Copyright 2023 MURGe-Lab and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch TVLT model."""
+
+import collections.abc
+import math
+from copy import deepcopy
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_outputs import BaseModelOutput, SequenceClassifierOutput
+from ....modeling_utils import PreTrainedModel
+from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
+from ....utils import (
+ ModelOutput,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+ replace_return_docstrings,
+)
+from .configuration_tvlt import TvltConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CONFIG_FOR_DOC = "TvltConfig"
+_CHECKPOINT_FOR_DOC = "ZinengTang/tvlt-base"
+
+
+@dataclass
+class TvltModelOutput(ModelOutput):
+ """
+ Class for TvltModel's outputs, with potential hidden states and attentions.
+
+ Args:
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the model.
+ last_pixel_hidden_state (`torch.FloatTensor` of shape `(batch_size, pixel_sequence_length, hidden_size)`):
+ Pixel sequence of hidden-states at the output of the last layer of the model.
+ last_audio_hidden_state (`torch.FloatTensor` of shape `(batch_size, audio_sequence_length, hidden_size)`):
+ Audio sequence of hidden-states at the output of the last layer of the model.
+ pixel_label_masks (`torch.FloatTensor` of shape `(batch_size, pixel_patch_length)`):
+ Tensor indicating which pixel patches are masked (1) and which are not (0).
+ audio_label_masks (`torch.FloatTensor` of shape `(batch_size, audio_patch_length)`):
+ Tensor indicating which audio patches are masked (1) and which are not (0).
+ pixel_ids_restore (`torch.LongTensor` of shape `(batch_size, pixel_patch_length)`):
+ Tensor containing the ids permutation of pixel masking.
+ audio_ids_restore (`torch.LongTensor` of shape `(batch_size, audio_patch_length)`):
+ Tensor containing the ids permutation of audio masking.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
+ plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
+ the self-attention heads.
+ """
+
+ last_hidden_state: Optional[torch.FloatTensor] = None
+ last_pixel_hidden_state: Optional[torch.FloatTensor] = None
+ last_audio_hidden_state: Optional[torch.FloatTensor] = None
+ pixel_label_masks: Optional[torch.LongTensor] = None
+ audio_label_masks: Optional[torch.LongTensor] = None
+ pixel_ids_restore: Optional[torch.LongTensor] = None
+ audio_ids_restore: Optional[torch.LongTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+class TvltDecoderOutput(ModelOutput):
+ """
+ Class for TvltDecoder's outputs, with potential hidden states and attentions.
+
+ Args:
+ logits (`torch.FloatTensor` of shape `(batch_size, patch_size ** 2 * num_channels)`):
+ Pixel reconstruction logits.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
+ plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
+ the self-attention heads.
+ """
+
+ logits: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+class TvltForPreTrainingOutput(ModelOutput):
+ """
+ Class for TvltForPreTraining's outputs, with potential hidden states and attentions.
+
+ Args:
+ loss (`torch.FloatTensor` of shape `(1,)`):
+ Pixel reconstruction loss.
+ matching_logits (`torch.FloatTensor` of shape `(batch_size, 1)`):
+ Matching objective logits.
+ pixel_logits (`torch.FloatTensor` of shape
+ `(batch_size, pixel_patch_length, image_patch_size ** 3 * pixel_num_channels)`): Pixel reconstruction
+ logits.
+ audio_logits (`torch.FloatTensor` of shape
+ `(batch_size, audio_patch_length, image_patch_size[0] * image_patch_size[1])`): Audio reconstruction
+ logits.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings and one for the output of each layer) of
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
+ plus the initial embedding outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
+ the self-attention heads.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ matching_logits: Optional[torch.FloatTensor] = None
+ pixel_logits: Optional[torch.FloatTensor] = None
+ audio_logits: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+def generate_pixel_mask_noise(pixel_values, pixel_mask=None, mask_ratio=0.75):
+ """Generate noise for audio masking."""
+
+ batch_size, seq_len = pixel_values.shape[:2]
+ noise = torch.rand((batch_size, seq_len), device=pixel_values.device) # noise in [0, 1]
+ len_keep = int(seq_len * (1 - mask_ratio))
+ return noise, len_keep
+
+
+def generate_audio_mask_noise(audio_values, audio_mask=None, mask_ratio=0.75, mask_type="patch-level", freq_len=8):
+ """Generate noise for audio masking."""
+
+ batch_size, seq_len = audio_values.shape[:2]
+ if mask_type == "frame-level":
+ num_time_patches = seq_len // freq_len
+ noise = (
+ torch.rand(batch_size, num_time_patches, device=audio_values.device)
+ .unsqueeze(-1)
+ .repeat(1, 1, freq_len)
+ .view(batch_size, seq_len)
+ ) # noise in [0, 1]
+ elif mask_type == "patch-level":
+ noise = torch.rand(batch_size, seq_len, device=audio_values.device) # noise in [0, 1]
+ len_keep = int(seq_len * (1 - mask_ratio))
+ return noise, len_keep
+
+
+def random_masking(sequence, noise, len_keep, attention_masks=None):
+ """
+ Perform random masking by per-sample shuffling on frame-level. Per-sample shuffling is done by argsort random
+ noise. sequence: [batch_size, seq_len, hidden_dim], sequence
+ """
+
+ batch_size, seq_len, hidden_dim = sequence.shape
+
+ # sort noise for each sample
+ ids_shuffle = torch.argsort(noise, dim=1) # ascend: small is keep, large is remove
+ ids_restore = torch.argsort(ids_shuffle, dim=1)
+
+ # keep the first subset
+ ids_keep = ids_shuffle[:, :len_keep]
+ sequence_masked = torch.gather(sequence, dim=1, index=ids_keep.unsqueeze(-1).repeat(1, 1, hidden_dim))
+
+ # generate the binary mask: 0 is keep, 1 is remove
+ label_masks = torch.ones([batch_size, seq_len], device=sequence.device)
+ label_masks[:, :len_keep] = 0
+ # unshuffle to get the binary mask
+ label_masks = torch.gather(label_masks, dim=1, index=ids_restore)
+
+ if attention_masks is not None:
+ label_masks *= attention_masks
+ attention_masks = torch.gather(attention_masks, dim=1, index=ids_keep)
+
+ return sequence_masked, attention_masks, label_masks, ids_restore
+
+
+class TvltPixelEmbeddings(nn.Module):
+ """Construct the patch and position embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.patch_embeddings = TvltPixelPatchEmbeddings(config)
+ self.num_patches_per_image = self.patch_embeddings.num_patches_per_image
+
+ self.type_embed_v = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
+ self.temporal_embed = nn.Parameter(torch.zeros(1, config.num_frames, config.hidden_size))
+ self.pos_embed_v = nn.Parameter(torch.zeros(1, self.num_patches_per_image, config.hidden_size))
+
+ self.config = config
+
+ def forward(self, pixel_values, attention_masks=None):
+ # create patch embeddings
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
+
+ embeddings = self.patch_embeddings(pixel_values)
+ embeddings += self.pos_embed_v.repeat(1, num_frames, 1)
+ embeddings += torch.repeat_interleave(self.temporal_embed[:, :num_frames], self.num_patches_per_image, dim=1)
+ embeddings += self.type_embed_v
+
+ return embeddings, attention_masks
+
+
+class TvltAudioEmbeddings(nn.Module):
+ """Construct the patch and position embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.patch_embeddings = TvltAudioPatchEmbeddings(config)
+ self.num_patches = self.patch_embeddings.num_patches
+
+ self.type_embed_a = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
+ self.num_freq_patches = config.frequency_length // config.audio_patch_size[1]
+ self.pos_embed_a = nn.Parameter(torch.zeros(1, self.num_patches // self.num_freq_patches, config.hidden_size))
+ self.freq_embed = nn.Parameter(torch.zeros(1, self.num_freq_patches, config.hidden_size))
+
+ self.num_freq_patches = config.frequency_length // config.audio_patch_size[1]
+ self.config = config
+
+ def forward(self, audio_values, attention_masks=None):
+ # create patch embeddings
+ embeddings = self.patch_embeddings(audio_values)
+
+ num_time_patches = embeddings.size(1) // self.num_freq_patches
+ embeddings += self.freq_embed.repeat(1, num_time_patches, 1)
+ embeddings += torch.repeat_interleave(self.pos_embed_a[:, :num_time_patches], self.num_freq_patches, dim=1)
+ embeddings += self.type_embed_a
+
+ return embeddings, attention_masks
+
+
+class TvltPixelPatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ image_size, patch_size = config.image_size, config.image_patch_size
+ num_channels, hidden_size = config.num_image_channels, config.hidden_size
+
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches_per_image = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.num_patches_per_image = num_patches_per_image
+ self.hidden_size = hidden_size
+
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+ if height != self.image_size[0] or width != self.image_size[1]:
+ raise ValueError(
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size[0]}*{self.image_size[1]})."
+ )
+
+ pixel_values = pixel_values.reshape(batch_size * num_frames, num_channels, height, width)
+ embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
+ embeddings = embeddings.reshape(batch_size, num_frames * self.num_patches_per_image, self.hidden_size)
+
+ return embeddings
+
+
+class TvltAudioPatchEmbeddings(nn.Module):
+ """
+ This class turns `audio_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ spectrogram_length, frequency_length, patch_size = (
+ config.spectrogram_length,
+ config.frequency_length,
+ config.audio_patch_size,
+ )
+ num_channels, hidden_size = config.num_audio_channels, config.hidden_size
+
+ spectrogram_size = (spectrogram_length, frequency_length)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches = (spectrogram_size[1] // patch_size[1]) * (spectrogram_size[0] // patch_size[0])
+ patch_shape = (spectrogram_size[0] // patch_size[0], spectrogram_size[1] // patch_size[1])
+ self.spectrogram_size = spectrogram_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.num_patches = num_patches
+ self.patch_shape = patch_shape
+
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, audio_values: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, height, width = audio_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+ if height > self.spectrogram_size[0] or width != self.spectrogram_size[1]:
+ raise ValueError(
+ f"Input audio size ({height}*{width}) doesn't match model"
+ f" ({self.spectrogram_size[0]}*{self.spectrogram_size[1]})."
+ )
+ embeddings = self.projection(audio_values).flatten(2).transpose(1, 2)
+
+ return embeddings
+
+
+class TvltSelfAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
+ f"heads {config.num_attention_heads}."
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ def transpose_for_scores(self, x):
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
+ x = x.view(*new_x_shape)
+ return x.permute(0, 2, 1, 3)
+
+ def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
+ mixed_query_layer = self.query(hidden_states)
+
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.Softmax(dim=-1)(attention_scores)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = attention_probs * head_mask
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+class TvltSelfOutput(nn.Module):
+ """
+ The residual connection is defined in TvltLayer instead of here (as is the case with other models), due to the
+ layernorm applied before each block.
+ """
+
+ def __init__(self, config: TvltConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ return hidden_states
+
+
+class TvltAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.attention = TvltSelfAttention(config)
+ self.output = TvltSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.attention.query = prune_linear_layer(self.attention.query, index)
+ self.attention.key = prune_linear_layer(self.attention.key, index)
+ self.attention.value = prune_linear_layer(self.attention.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
+ self_outputs = self.attention(hidden_states, attention_mask, head_mask, output_attentions)
+
+ attention_output = self.output(self_outputs[0], hidden_states)
+
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+class TvltIntermediate(nn.Module):
+ def __init__(self, config: TvltConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+
+ return hidden_states
+
+
+class TvltOutput(nn.Module):
+ def __init__(self, config: TvltConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ hidden_states = hidden_states + input_tensor
+
+ return hidden_states
+
+
+class TvltLayer(GradientCheckpointingLayer):
+ """This corresponds to the Block class in the timm implementation."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = TvltAttention(config)
+ self.intermediate = TvltIntermediate(config)
+ self.output = TvltOutput(config)
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states, attention_mask=None, head_mask=None, output_attentions=False):
+ self_attention_outputs = self.attention(
+ self.layernorm_before(hidden_states), # in ViLT, layernorm is applied before self-attention
+ attention_mask,
+ head_mask,
+ output_attentions=output_attentions,
+ )
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ # first residual connection
+ hidden_states = attention_output + hidden_states.to(attention_output.device)
+
+ # in ViLT, layernorm is also applied after self-attention
+ layer_output = self.layernorm_after(hidden_states)
+ layer_output = self.intermediate(layer_output)
+
+ # second residual connection is done here
+ layer_output = self.output(layer_output, hidden_states)
+
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+
+class TvltEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([TvltLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+
+ layer_outputs = layer_module(hidden_states, attention_mask, layer_head_mask, output_attentions)
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class TvltPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: TvltConfig
+ base_model_prefix = "tvlt"
+ main_input_name = "pixel_values"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+TVLT_START_DOCSTRING = r"""
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
+ behavior.
+
+ Parameters:
+ config ([`TvltConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+TVLT_INPUTS_DOCSTRING = r"""
+ Args:
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
+ Pixel values. Pixel values can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
+ details.
+
+ audio_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Audio values. Audio values can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
+ details.
+
+ pixel_mask (`torch.FloatTensor` of shape `(batch_size, num_pixel_patches)`):
+ Pixel masks. Pixel masks can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
+ details.
+
+ audio_mask (`torch.FloatTensor` of shape `(batch_size, num_audio_patches)`):
+ Audio masks. Audio masks can be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for
+ details.
+
+ pixel_values_mixed (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
+ Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Pixel values mixed can
+ be obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for details.
+
+ pixel_mask_mixed (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Pixel masks of pixel_values_mixed. Pixel masks mixed can be obtained using [`TvltProcessor`]. See
+ [`TvltProcessor.__call__`] for details.
+
+ mask_pixel (`bool`, *optional*):
+ Whether to mask pixel for MAE tasks. Only set to True in TvltForPreTraining.
+
+ mask_audio (`bool`, *optional*):
+ Whether to mask audio for MAE tasks. Only set to True in TvltForPreTraining.
+
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare TVLT Model transformer outputting raw hidden-states without any specific head on top.",
+ TVLT_START_DOCSTRING,
+)
+class TvltModel(TvltPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+
+ self.pixel_embeddings = TvltPixelEmbeddings(config)
+ self.audio_embeddings = TvltAudioEmbeddings(config)
+ self.encoder = TvltEncoder(config)
+
+ self.cls_embedding = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
+
+ if config.use_mean_pooling:
+ self.layernorm = None
+ else:
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.pixel_embeddings.patch_embeddings, self.audio_embeddings.patch_embeddings
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ @add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=TvltModelOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ audio_values: torch.FloatTensor,
+ pixel_mask: Optional[torch.FloatTensor] = None,
+ audio_mask: Optional[torch.FloatTensor] = None,
+ mask_pixel: bool = False,
+ mask_audio: bool = False,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.FloatTensor], TvltModelOutput]:
+ r"""
+ Returns:
+
+ Examples:
+
+ ```python
+ >>> from transformers import TvltProcessor, TvltModel
+ >>> import numpy as np
+ >>> import torch
+
+ >>> num_frames = 8
+ >>> images = list(np.random.randn(num_frames, 3, 224, 224))
+ >>> audio = list(np.random.randn(10000))
+
+ >>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
+ >>> model = TvltModel.from_pretrained("ZinengTang/tvlt-base")
+
+ >>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors="pt")
+
+ >>> outputs = model(**input_dict)
+ >>> loss = outputs.loss
+ ```"""
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ pixel_embedding_output, pixel_mask = self.pixel_embeddings(pixel_values, pixel_mask)
+
+ audio_embedding_output, audio_mask = self.audio_embeddings(audio_values, audio_mask)
+
+ # Mask pixel if mask_pixel is True
+ pixel_label_masks = None
+ pixel_ids_restore = None
+ if mask_pixel:
+ pixel_mask_noise, pixel_len_keep = generate_pixel_mask_noise(
+ pixel_embedding_output, pixel_mask=pixel_mask, mask_ratio=self.config.pixel_mask_ratio
+ )
+ pixel_embedding_output, pixel_mask, pixel_label_masks, pixel_ids_restore = random_masking(
+ pixel_embedding_output,
+ pixel_mask_noise,
+ pixel_len_keep,
+ attention_masks=pixel_mask,
+ )
+
+ # Mask audio if mask_audio is True
+ audio_label_masks = None
+ audio_ids_restore = None
+ if mask_audio:
+ num_freq_patches = self.config.frequency_length // self.config.audio_patch_size[1]
+ audio_mask_noise, audio_len_keep = generate_audio_mask_noise(
+ audio_embedding_output,
+ audio_mask=audio_mask,
+ mask_ratio=self.config.audio_mask_ratio,
+ mask_type=self.config.audio_mask_type,
+ freq_len=num_freq_patches,
+ )
+ audio_embedding_output, audio_mask, audio_label_masks, audio_ids_restore = random_masking(
+ audio_embedding_output,
+ audio_mask_noise,
+ audio_len_keep,
+ attention_masks=audio_mask,
+ )
+
+ # Prepare for encoder inputs and attention masks
+ batch_size = pixel_values.size(0)
+ embedding_output = torch.cat(
+ [self.cls_embedding.repeat(batch_size, 1, 1), pixel_embedding_output, audio_embedding_output], 1
+ )
+ masked_pixel_len = pixel_embedding_output.size(1)
+
+ attention_mask = None
+ if pixel_mask is not None and audio_mask is not None:
+ attention_mask = torch.cat([pixel_mask[:, :1], pixel_mask, audio_mask], 1)
+
+ input_shape = embedding_output.size()
+ extended_attention_mask = None
+ if attention_mask is not None:
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+ if self.layernorm is not None:
+ sequence_output = self.layernorm(sequence_output)
+
+ pixel_sequence_output = sequence_output[:, 1 : 1 + masked_pixel_len]
+ audio_sequence_output = sequence_output[:, 1 + masked_pixel_len :]
+ if not return_dict:
+ return (
+ sequence_output,
+ pixel_sequence_output,
+ audio_sequence_output,
+ pixel_label_masks,
+ audio_label_masks,
+ pixel_ids_restore,
+ audio_ids_restore,
+ ) + encoder_outputs[1:]
+
+ return TvltModelOutput(
+ last_hidden_state=sequence_output,
+ last_pixel_hidden_state=pixel_sequence_output,
+ last_audio_hidden_state=audio_sequence_output,
+ pixel_label_masks=pixel_label_masks,
+ audio_label_masks=audio_label_masks,
+ pixel_ids_restore=pixel_ids_restore,
+ audio_ids_restore=audio_ids_restore,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+class TvltDecoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ decoder_config = deepcopy(config)
+ decoder_config.hidden_size = config.decoder_hidden_size
+ decoder_config.num_hidden_layers = config.decoder_num_hidden_layers
+ decoder_config.num_attention_heads = config.decoder_num_attention_heads
+ decoder_config.intermediate_size = config.decoder_intermediate_size
+ self.decoder_layers = nn.ModuleList(
+ [TvltLayer(decoder_config) for _ in range(config.decoder_num_hidden_layers)]
+ )
+
+ self.layernorm = nn.LayerNorm(config.decoder_hidden_size, eps=config.layer_norm_eps)
+
+ self.gradient_checkpointing = False
+ self.config = config
+
+ def forward(
+ self,
+ hidden_states,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ # apply Transformer layers (blocks)
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+ for i, layer_module in enumerate(self.decoder_layers):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_outputs = layer_module(hidden_states, output_attentions=output_attentions)
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ # predictor projection
+ logits = self.layernorm(hidden_states)
+
+ if not return_dict:
+ return tuple(v for v in [logits, all_hidden_states, all_self_attentions] if v is not None)
+ return TvltDecoderOutput(logits=logits, hidden_states=all_hidden_states, attentions=all_self_attentions)
+
+
+@add_start_docstrings(
+ "The TVLT Model transformer with the decoder on top for self-supervised pre-training.",
+ TVLT_START_DOCSTRING,
+)
+class TvltForPreTraining(TvltPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+
+ self.task_matching = config.task_matching
+ self.task_mae = config.task_mae
+ if not (self.task_matching or self.task_mae):
+ raise ValueError("Must set at least one of matching task and MAE task to true")
+
+ self.tvlt = TvltModel(config)
+
+ if self.task_matching:
+ self.matching_head = TvltMatchingHead(config)
+
+ if self.task_mae:
+ self.encoder_to_decoder = nn.Linear(config.hidden_size, config.decoder_hidden_size, bias=True)
+
+ self.pixel_mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
+ self.audio_mask_token = nn.Parameter(torch.zeros(1, 1, config.decoder_hidden_size))
+
+ self.decoder = TvltDecoder(config)
+
+ decoder_hidden_size = config.decoder_hidden_size
+
+ num_frames = config.num_frames
+ num_patches_per_image = self.tvlt.pixel_embeddings.num_patches_per_image
+ self.decoder_pixel_pos_embed = nn.Parameter(torch.zeros(1, num_patches_per_image, decoder_hidden_size))
+ self.decoder_temporal_embed = nn.Parameter(torch.zeros(1, config.num_frames, decoder_hidden_size))
+ self.decoder_pixel_type_embed = nn.Parameter(torch.zeros(1, 1, decoder_hidden_size))
+
+ num_audio_patches = self.tvlt.audio_embeddings.num_patches
+ num_freq_patches = config.frequency_length // config.audio_patch_size[1]
+ self.decoder_audio_pos_embed = nn.Parameter(
+ torch.zeros(1, num_audio_patches // num_freq_patches, decoder_hidden_size)
+ )
+ self.decoder_freq_embed = nn.Parameter(torch.zeros(1, num_freq_patches, decoder_hidden_size))
+ self.decoder_audio_type_embed = nn.Parameter(torch.zeros(1, 1, decoder_hidden_size))
+
+ pixel_mae_output_dim = self.config.image_patch_size[0] ** 2 * self.config.num_image_channels
+ self.pixel_mae_head = TvltMAEHead(config, pixel_mae_output_dim)
+ audio_mae_output_dim = (
+ self.config.audio_patch_size[0] * self.config.audio_patch_size[1] * self.config.num_audio_channels
+ )
+ self.audio_mae_head = TvltMAEHead(config, audio_mae_output_dim)
+
+ self.num_frames = num_frames
+ self.num_patches_per_image = num_patches_per_image
+ self.num_freq_patches = num_freq_patches
+ self.image_patch_size = config.image_patch_size
+ self.audio_patch_size = config.audio_patch_size
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def patchify_pixel(self, pixel_values):
+ """
+ pixel_values: [batch_size, num_frames, 3, height, width]
+ """
+ batch_size, num_frames, num_channels, height, width = pixel_values.shape
+ num_patches_height = pixel_values.shape[3] // self.image_patch_size[0]
+ num_patches_width = pixel_values.shape[4] // self.image_patch_size[1]
+ patchified_pixel_values = pixel_values.reshape(
+ shape=(
+ batch_size,
+ num_frames,
+ num_channels,
+ num_patches_height,
+ self.image_patch_size[0],
+ num_patches_width,
+ self.image_patch_size[1],
+ )
+ )
+ patchified_pixel_values = torch.einsum("ntchpwq->nthwpqc", patchified_pixel_values)
+ patchified_pixel_values = patchified_pixel_values.reshape(
+ shape=(
+ batch_size,
+ num_patches_height * num_patches_width * num_frames,
+ self.image_patch_size[0] * self.image_patch_size[1] * num_channels,
+ )
+ )
+ return patchified_pixel_values
+
+ def patchify_audio(self, audio_values):
+ """
+ audio_values: [batch_size, 1, height, width]
+ """
+ batch_size, num_channels, height, width = audio_values.shape
+ num_patches_height = height // self.audio_patch_size[0]
+ num_patches_width = width // self.audio_patch_size[1]
+ patchified_audio_values = audio_values.reshape(
+ shape=(
+ batch_size,
+ num_channels,
+ num_patches_height,
+ self.audio_patch_size[0],
+ num_patches_width,
+ self.audio_patch_size[1],
+ )
+ )
+ patchified_audio_values = torch.einsum("nchpwq->nhwpqc", patchified_audio_values)
+ patchified_audio_values = patchified_audio_values.reshape(
+ shape=(
+ batch_size,
+ num_patches_height * num_patches_width,
+ self.audio_patch_size[0] * self.audio_patch_size[1] * num_channels,
+ )
+ )
+ return patchified_audio_values
+
+ def pixel_mae_loss(self, pixel_values, pixel_predictions, mask):
+ patchified_pixel_values = self.patchify_pixel(pixel_values)
+ loss = (pixel_predictions - patchified_pixel_values) ** 2
+ loss = loss.mean(dim=-1) # [batch_size, pixel_pixel_length], mean loss per patch
+ loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches
+ return loss
+
+ def audio_mae_loss(self, audio_values, audio_predictions, mask):
+ patchified_audio_values = self.patchify_audio(audio_values)
+ loss = (audio_predictions - patchified_audio_values) ** 2
+ loss = loss.mean(dim=-1) # [batch_size, audio_pixel_length], mean loss per patch
+ loss = (loss * mask).sum() / mask.sum() # mean loss on removed patches
+ return loss
+
+ def concatenate_mask(self, mask_token, sequence, ids_restore):
+ batch_size, seq_length, dim = sequence.shape
+ mask_tokens = mask_token.repeat(batch_size, ids_restore.shape[1] - seq_length, 1)
+ padded_sequence = torch.cat([sequence, mask_tokens], dim=1)
+ padded_sequence = torch.gather(
+ padded_sequence, dim=1, index=ids_restore.unsqueeze(-1).repeat(1, 1, dim)
+ ) # unshuffle
+ return padded_sequence
+
+ @add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=TvltForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ audio_values: torch.FloatTensor,
+ pixel_mask: Optional[torch.FloatTensor] = None,
+ audio_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ pixel_values_mixed: Optional[torch.FloatTensor] = None,
+ pixel_mask_mixed: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.FloatTensor], TvltForPreTrainingOutput]:
+ r"""
+ pixel_values_mixed (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
+ Pixel values that mix positive and negative samples in Tvlt vision-audio matching. Audio values can be
+ obtained using [`TvltProcessor`]. See [`TvltProcessor.__call__`] for details.
+
+ pixel_mask_mixed (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Pixel masks of pixel_values_mixed. Pixel values mixed can be obtained using [`TvltProcessor`]. See
+ [`TvltProcessor.__call__`] for details.
+
+ labels (`torch.LongTensor` of shape `(batch_size, num_labels)`, *optional*):
+ Labels for computing the vision audio matching loss. Indices should be in `[0, 1]`. num_labels has to be 1.
+
+ Return:
+
+ Examples:
+
+ ```python
+ >>> from transformers import TvltProcessor, TvltForPreTraining
+ >>> import numpy as np
+ >>> import torch
+
+ >>> num_frames = 8
+ >>> images = list(np.random.randn(num_frames, 3, 224, 224))
+ >>> images_mixed = list(np.random.randn(num_frames, 3, 224, 224))
+ >>> audio = list(np.random.randn(10000))
+ >>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
+ >>> model = TvltForPreTraining.from_pretrained("ZinengTang/tvlt-base")
+ >>> input_dict = processor(
+ ... images, audio, images_mixed, sampling_rate=44100, mask_pixel=True, mask_audio=True, return_tensors="pt"
+ ... )
+
+ >>> outputs = model(**input_dict)
+ >>> loss = outputs.loss
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ total_loss = 0.0
+
+ if self.task_matching:
+ if labels is None:
+ raise ValueError("Matching task requires labels")
+ if pixel_values_mixed is None:
+ raise ValueError("Matching task requires pixel_values_mixed")
+
+ outputs = self.tvlt(
+ pixel_values_mixed,
+ audio_values,
+ pixel_mask=pixel_mask_mixed,
+ audio_mask=audio_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ matching_logits = self.matching_head(sequence_output)
+
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(matching_logits.view(-1), labels.view(-1))
+ total_loss += loss
+
+ pixel_logits = None
+ audio_logits = None
+ if self.task_mae and self.training:
+ outputs = self.tvlt(
+ pixel_values,
+ audio_values,
+ pixel_mask=pixel_mask,
+ audio_mask=audio_mask,
+ mask_pixel=True,
+ mask_audio=True,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ pixel_sequence_output = outputs.last_pixel_hidden_state if return_dict else outputs[1]
+ audio_sequence_output = outputs.last_audio_hidden_state if return_dict else outputs[2]
+ pixel_label_masks = outputs.pixel_label_masks if return_dict else outputs[3]
+ audio_label_masks = outputs.audio_label_masks if return_dict else outputs[4]
+ pixel_ids_restore = outputs.pixel_ids_restore if return_dict else outputs[5]
+ audio_ids_restore = outputs.audio_ids_restore if return_dict else outputs[6]
+
+ pixel_decoder_input = self.encoder_to_decoder(
+ pixel_sequence_output
+ ) # [batch_size, num_masked_pixel_patches, decoder_hidden_size]
+ audio_decoder_input = self.encoder_to_decoder(
+ audio_sequence_output
+ ) # [batch_size, num_masked_audio_patches, decoder_hidden_size]
+ num_frames = pixel_values.size(1)
+ pixel_decoder_input = self.concatenate_mask(self.pixel_mask_token, pixel_decoder_input, pixel_ids_restore)
+ pixel_decoder_input = pixel_decoder_input + self.decoder_pixel_pos_embed.repeat(1, num_frames, 1)
+ pixel_decoder_input = pixel_decoder_input + torch.repeat_interleave(
+ self.decoder_temporal_embed[:, :num_frames], self.num_patches_per_image, dim=1
+ )
+ pixel_decoder_input = pixel_decoder_input + self.decoder_pixel_type_embed
+ pixel_decoder_outputs = self.decoder(pixel_decoder_input)
+ pixel_logits = self.pixel_mae_head(pixel_decoder_outputs.logits)
+
+ audio_decoder_input = self.concatenate_mask(self.audio_mask_token, audio_decoder_input, audio_ids_restore)
+ num_time_patches = audio_decoder_input.size(1) // self.num_freq_patches
+ audio_decoder_input = audio_decoder_input + self.decoder_freq_embed.repeat(1, num_time_patches, 1)
+ audio_decoder_input = audio_decoder_input + torch.repeat_interleave(
+ self.decoder_audio_pos_embed[:, :num_time_patches], self.num_freq_patches, dim=1
+ )
+ audio_decoder_input = audio_decoder_input + self.decoder_audio_type_embed
+ audio_decoder_outputs = self.decoder(audio_decoder_input)
+ audio_logits = self.audio_mae_head(audio_decoder_outputs.logits)
+
+ loss = self.pixel_mae_loss(pixel_values, pixel_logits, pixel_label_masks) + self.audio_mae_loss(
+ audio_values, audio_logits, audio_label_masks
+ )
+ total_loss += loss
+
+ if not return_dict:
+ output = (matching_logits, pixel_logits, audio_logits) + outputs[7:]
+ return ((total_loss,) + output) if loss is not None else output
+
+ return TvltForPreTrainingOutput(
+ loss=total_loss,
+ matching_logits=matching_logits,
+ pixel_logits=pixel_logits,
+ audio_logits=audio_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class TvltPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states):
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+class TvltMatchingHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.pooler = TvltPooler(config)
+ self.fc = nn.Linear(config.hidden_size, 1)
+
+ def forward(self, hidden_states):
+ hidden_states = self.fc(self.pooler(hidden_states))
+ return hidden_states
+
+
+class TvltMAEHead(nn.Module):
+ def __init__(self, config, output_dim=None):
+ super().__init__()
+ self.config = config
+ self.decoder = nn.Linear(config.decoder_hidden_size, output_dim)
+
+ def forward(self, hidden_states):
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+@add_start_docstrings(
+ """
+ Tvlt Model transformer with a classifier head on top (an MLP on top of the final hidden state of the [CLS] token)
+ for audiovisual classification tasks, e.g. CMU-MOSEI Sentiment Analysis and Audio to Video Retrieval.
+ """,
+ TVLT_START_DOCSTRING,
+)
+class TvltForAudioVisualClassification(TvltPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.tvlt = TvltModel(config)
+
+ # Classifier head
+ self.classifier = nn.Sequential(
+ nn.Linear(config.hidden_size, config.hidden_size * 2),
+ nn.LayerNorm(config.hidden_size * 2, eps=config.layer_norm_eps),
+ nn.GELU(),
+ nn.Linear(config.hidden_size * 2, config.num_labels),
+ )
+ self.config = config
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(TVLT_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=SequenceClassifierOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ audio_values: torch.FloatTensor,
+ pixel_mask: Optional[torch.FloatTensor] = None,
+ audio_mask: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ labels: Optional[torch.LongTensor] = None,
+ ) -> Union[tuple[torch.FloatTensor], SequenceClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, num_labels)`, *optional*):
+ Labels for computing the audiovisual loss. Indices should be in `[0, ..., num_classes-1]` where num_classes
+ refers to the number of classes in audiovisual tasks.
+
+ Return:
+
+ Examples:
+ ```python
+ >>> from transformers import TvltProcessor, TvltForAudioVisualClassification
+ >>> import numpy as np
+ >>> import torch
+
+ >>> num_frames = 8
+ >>> images = list(np.random.randn(num_frames, 3, 224, 224))
+ >>> audio = list(np.random.randn(10000))
+ >>> processor = TvltProcessor.from_pretrained("ZinengTang/tvlt-base")
+ >>> model = TvltForAudioVisualClassification.from_pretrained("ZinengTang/tvlt-base")
+ >>> input_dict = processor(images, audio, sampling_rate=44100, return_tensors="pt")
+
+ >>> outputs = model(**input_dict)
+ >>> loss = outputs.loss
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.tvlt(
+ pixel_values,
+ audio_values,
+ pixel_mask=pixel_mask,
+ audio_mask=audio_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0][:, 0]
+ logits = self.classifier(sequence_output) # rank value
+
+ loss = None
+ if labels is not None:
+ if self.config.loss_type == "regression":
+ loss_fct = MSELoss()
+ loss = loss_fct(logits, labels)
+ elif self.config.loss_type == "classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[4:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["TvltModel", "TvltForPreTraining", "TvltForAudioVisualClassification", "TvltPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/processing_tvlt.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/processing_tvlt.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ecbac0dfa16f7c2cf70d07775bba2beeb456973
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/tvlt/processing_tvlt.py
@@ -0,0 +1,86 @@
+# coding=utf-8
+# Copyright 2023 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+Processor class for TVLT.
+"""
+
+from ....processing_utils import ProcessorMixin
+
+
+class TvltProcessor(ProcessorMixin):
+ r"""
+ Constructs a TVLT processor which wraps a TVLT image processor and TVLT feature extractor into a single processor.
+
+ [`TvltProcessor`] offers all the functionalities of [`TvltImageProcessor`] and [`TvltFeatureExtractor`]. See the
+ docstring of [`~TvltProcessor.__call__`] for more information.
+
+ Args:
+ image_processor (`TvltImageProcessor`):
+ An instance of [`TvltImageProcessor`]. The image processor is a required input.
+ feature_extractor (`TvltFeatureExtractor`):
+ An instance of [`TvltFeatureExtractor`]. The feature extractor is a required input.
+ """
+
+ attributes = ["image_processor", "feature_extractor"]
+ image_processor_class = "TvltImageProcessor"
+ feature_extractor_class = "TvltFeatureExtractor"
+
+ def __init__(self, image_processor, feature_extractor):
+ super().__init__(image_processor=image_processor, feature_extractor=feature_extractor)
+
+ self.image_processor = image_processor
+ self.feature_extractor = feature_extractor
+
+ def __call__(
+ self,
+ images=None,
+ audio=None,
+ images_mixed=None,
+ sampling_rate=None,
+ mask_audio=False,
+ mask_pixel=False,
+ *args,
+ **kwargs,
+ ):
+ """
+ Forwards the `images` argument to TvltImageProcessor's [`~TvltImageProcessor.preprocess`] and the `audio`
+ argument to TvltFeatureExtractor's [`~TvltFeatureExtractor.__call__`]. Please refer to the docstring of the
+ above two methods for more information.
+ """
+
+ if images is None and audio is None:
+ raise ValueError("You need to specify either an `images` or `audio` input to process.")
+
+ images_mixed_dict = None
+ if images is not None:
+ images_dict = self.image_processor(images, mask_pixel=mask_pixel, *args, **kwargs)
+ if images_mixed is not None:
+ images_mixed_dict = self.image_processor(images_mixed, is_mixed=True, *args, **kwargs)
+ if audio is not None:
+ audio_dict = self.feature_extractor(
+ audio, *args, sampling_rate=sampling_rate, mask_audio=mask_audio, **kwargs
+ )
+
+ output_dict = {}
+ if audio is not None:
+ output_dict.update(audio_dict)
+ if images is not None:
+ output_dict.update(images_dict)
+ if images_mixed_dict is not None:
+ output_dict.update(images_mixed_dict)
+ return output_dict
+
+
+__all__ = ["TvltProcessor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9552c827365d3913539be3eafaf822146ada5829
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_van import *
+ from .modeling_van import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cef8de3b7ca9a51eb40acc46293d121a25dfd182
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__pycache__/configuration_van.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__pycache__/configuration_van.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2b8834d288277dd9fc9bbfce606ee2e9b8b409f5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__pycache__/configuration_van.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__pycache__/modeling_van.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__pycache__/modeling_van.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52c8c9cb229fb1d31f6d76848600ca180375990f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/__pycache__/modeling_van.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/configuration_van.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/configuration_van.py
new file mode 100644
index 0000000000000000000000000000000000000000..be94e45ec63d9516584c320c98e0b1157c092c2c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/configuration_van.py
@@ -0,0 +1,110 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""VAN model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class VanConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`VanModel`]. It is used to instantiate a VAN model
+ according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the VAN
+ [Visual-Attention-Network/van-base](https://huggingface.co/Visual-Attention-Network/van-base) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ image_size (`int`, *optional*, defaults to 224):
+ The size (resolution) of each image.
+ num_channels (`int`, *optional*, defaults to 3):
+ The number of input channels.
+ patch_sizes (`list[int]`, *optional*, defaults to `[7, 3, 3, 3]`):
+ Patch size to use in each stage's embedding layer.
+ strides (`list[int]`, *optional*, defaults to `[4, 2, 2, 2]`):
+ Stride size to use in each stage's embedding layer to downsample the input.
+ hidden_sizes (`list[int]`, *optional*, defaults to `[64, 128, 320, 512]`):
+ Dimensionality (hidden size) at each stage.
+ depths (`list[int]`, *optional*, defaults to `[3, 3, 12, 3]`):
+ Depth (number of layers) for each stage.
+ mlp_ratios (`list[int]`, *optional*, defaults to `[8, 8, 4, 4]`):
+ The expansion ratio for mlp layer at each stage.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in each layer. If string, `"gelu"`, `"relu"`,
+ `"selu"` and `"gelu_new"` are supported.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-06):
+ The epsilon used by the layer normalization layers.
+ layer_scale_init_value (`float`, *optional*, defaults to 0.01):
+ The initial value for layer scaling.
+ drop_path_rate (`float`, *optional*, defaults to 0.0):
+ The dropout probability for stochastic depth.
+ dropout_rate (`float`, *optional*, defaults to 0.0):
+ The dropout probability for dropout.
+
+ Example:
+ ```python
+ >>> from transformers import VanModel, VanConfig
+
+ >>> # Initializing a VAN van-base style configuration
+ >>> configuration = VanConfig()
+ >>> # Initializing a model from the van-base style configuration
+ >>> model = VanModel(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "van"
+
+ def __init__(
+ self,
+ image_size=224,
+ num_channels=3,
+ patch_sizes=[7, 3, 3, 3],
+ strides=[4, 2, 2, 2],
+ hidden_sizes=[64, 128, 320, 512],
+ depths=[3, 3, 12, 3],
+ mlp_ratios=[8, 8, 4, 4],
+ hidden_act="gelu",
+ initializer_range=0.02,
+ layer_norm_eps=1e-6,
+ layer_scale_init_value=1e-2,
+ drop_path_rate=0.0,
+ dropout_rate=0.0,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.image_size = image_size
+ self.num_channels = num_channels
+ self.patch_sizes = patch_sizes
+ self.strides = strides
+ self.hidden_sizes = hidden_sizes
+ self.depths = depths
+ self.mlp_ratios = mlp_ratios
+ self.hidden_act = hidden_act
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.layer_scale_init_value = layer_scale_init_value
+ self.drop_path_rate = drop_path_rate
+ self.dropout_rate = dropout_rate
+
+
+__all__ = ["VanConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/modeling_van.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/modeling_van.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bbae4edb1a259682222004997b96734ab8db2ef
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/van/modeling_van.py
@@ -0,0 +1,541 @@
+# coding=utf-8
+# Copyright 2022 BNRist (Tsinghua University), TKLNDST (Nankai University) and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Visual Attention Network (VAN) model."""
+
+import math
+from collections import OrderedDict
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_outputs import (
+ BaseModelOutputWithNoAttention,
+ BaseModelOutputWithPoolingAndNoAttention,
+ ImageClassifierOutputWithNoAttention,
+)
+from ....modeling_utils import PreTrainedModel
+from ....utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
+from .configuration_van import VanConfig
+
+
+logger = logging.get_logger(__name__)
+
+# General docstring
+_CONFIG_FOR_DOC = "VanConfig"
+
+# Base docstring
+_CHECKPOINT_FOR_DOC = "Visual-Attention-Network/van-base"
+_EXPECTED_OUTPUT_SHAPE = [1, 512, 7, 7]
+
+# Image classification docstring
+_IMAGE_CLASS_CHECKPOINT = "Visual-Attention-Network/van-base"
+_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
+
+
+def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
+ """
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
+
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
+ argument.
+ """
+ if drop_prob == 0.0 or not training:
+ return input
+ keep_prob = 1 - drop_prob
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
+ random_tensor.floor_() # binarize
+ output = input.div(keep_prob) * random_tensor
+ return output
+
+
+class VanDropPath(nn.Module):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
+
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
+ super().__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ return drop_path(hidden_states, self.drop_prob, self.training)
+
+ def extra_repr(self) -> str:
+ return f"p={self.drop_prob}"
+
+
+class VanOverlappingPatchEmbedder(nn.Module):
+ """
+ Downsamples the input using a patchify operation with a `stride` of 4 by default making adjacent windows overlap by
+ half of the area. From [PVTv2: Improved Baselines with Pyramid Vision
+ Transformer](https://huggingface.co/papers/2106.13797).
+ """
+
+ def __init__(self, in_channels: int, hidden_size: int, patch_size: int = 7, stride: int = 4):
+ super().__init__()
+ self.convolution = nn.Conv2d(
+ in_channels, hidden_size, kernel_size=patch_size, stride=stride, padding=patch_size // 2
+ )
+ self.normalization = nn.BatchNorm2d(hidden_size)
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.convolution(input)
+ hidden_state = self.normalization(hidden_state)
+ return hidden_state
+
+
+class VanMlpLayer(nn.Module):
+ """
+ MLP with depth-wise convolution, from [PVTv2: Improved Baselines with Pyramid Vision
+ Transformer](https://huggingface.co/papers/2106.13797).
+ """
+
+ def __init__(
+ self,
+ in_channels: int,
+ hidden_size: int,
+ out_channels: int,
+ hidden_act: str = "gelu",
+ dropout_rate: float = 0.5,
+ ):
+ super().__init__()
+ self.in_dense = nn.Conv2d(in_channels, hidden_size, kernel_size=1)
+ self.depth_wise = nn.Conv2d(hidden_size, hidden_size, kernel_size=3, padding=1, groups=hidden_size)
+ self.activation = ACT2FN[hidden_act]
+ self.dropout1 = nn.Dropout(dropout_rate)
+ self.out_dense = nn.Conv2d(hidden_size, out_channels, kernel_size=1)
+ self.dropout2 = nn.Dropout(dropout_rate)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.in_dense(hidden_state)
+ hidden_state = self.depth_wise(hidden_state)
+ hidden_state = self.activation(hidden_state)
+ hidden_state = self.dropout1(hidden_state)
+ hidden_state = self.out_dense(hidden_state)
+ hidden_state = self.dropout2(hidden_state)
+ return hidden_state
+
+
+class VanLargeKernelAttention(nn.Module):
+ """
+ Basic Large Kernel Attention (LKA).
+ """
+
+ def __init__(self, hidden_size: int):
+ super().__init__()
+ self.depth_wise = nn.Conv2d(hidden_size, hidden_size, kernel_size=5, padding=2, groups=hidden_size)
+ self.depth_wise_dilated = nn.Conv2d(
+ hidden_size, hidden_size, kernel_size=7, dilation=3, padding=9, groups=hidden_size
+ )
+ self.point_wise = nn.Conv2d(hidden_size, hidden_size, kernel_size=1)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.depth_wise(hidden_state)
+ hidden_state = self.depth_wise_dilated(hidden_state)
+ hidden_state = self.point_wise(hidden_state)
+ return hidden_state
+
+
+class VanLargeKernelAttentionLayer(nn.Module):
+ """
+ Computes attention using Large Kernel Attention (LKA) and attends the input.
+ """
+
+ def __init__(self, hidden_size: int):
+ super().__init__()
+ self.attention = VanLargeKernelAttention(hidden_size)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ attention = self.attention(hidden_state)
+ attended = hidden_state * attention
+ return attended
+
+
+class VanSpatialAttentionLayer(nn.Module):
+ """
+ Van spatial attention layer composed by projection (via conv) -> act -> Large Kernel Attention (LKA) attention ->
+ projection (via conv) + residual connection.
+ """
+
+ def __init__(self, hidden_size: int, hidden_act: str = "gelu"):
+ super().__init__()
+ self.pre_projection = nn.Sequential(
+ OrderedDict(
+ [
+ ("conv", nn.Conv2d(hidden_size, hidden_size, kernel_size=1)),
+ ("act", ACT2FN[hidden_act]),
+ ]
+ )
+ )
+ self.attention_layer = VanLargeKernelAttentionLayer(hidden_size)
+ self.post_projection = nn.Conv2d(hidden_size, hidden_size, kernel_size=1)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ residual = hidden_state
+ hidden_state = self.pre_projection(hidden_state)
+ hidden_state = self.attention_layer(hidden_state)
+ hidden_state = self.post_projection(hidden_state)
+ hidden_state = hidden_state + residual
+ return hidden_state
+
+
+class VanLayerScaling(nn.Module):
+ """
+ Scales the inputs by a learnable parameter initialized by `initial_value`.
+ """
+
+ def __init__(self, hidden_size: int, initial_value: float = 1e-2):
+ super().__init__()
+ self.weight = nn.Parameter(initial_value * torch.ones(hidden_size), requires_grad=True)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ # unsqueezing for broadcasting
+ hidden_state = self.weight.unsqueeze(-1).unsqueeze(-1) * hidden_state
+ return hidden_state
+
+
+class VanLayer(nn.Module):
+ """
+ Van layer composed by normalization layers, large kernel attention (LKA) and a multi layer perceptron (MLP).
+ """
+
+ def __init__(
+ self,
+ config: VanConfig,
+ hidden_size: int,
+ mlp_ratio: int = 4,
+ drop_path_rate: float = 0.5,
+ ):
+ super().__init__()
+ self.drop_path = VanDropPath(drop_path_rate) if drop_path_rate > 0.0 else nn.Identity()
+ self.pre_normomalization = nn.BatchNorm2d(hidden_size)
+ self.attention = VanSpatialAttentionLayer(hidden_size, config.hidden_act)
+ self.attention_scaling = VanLayerScaling(hidden_size, config.layer_scale_init_value)
+ self.post_normalization = nn.BatchNorm2d(hidden_size)
+ self.mlp = VanMlpLayer(
+ hidden_size, hidden_size * mlp_ratio, hidden_size, config.hidden_act, config.dropout_rate
+ )
+ self.mlp_scaling = VanLayerScaling(hidden_size, config.layer_scale_init_value)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ residual = hidden_state
+ # attention
+ hidden_state = self.pre_normomalization(hidden_state)
+ hidden_state = self.attention(hidden_state)
+ hidden_state = self.attention_scaling(hidden_state)
+ hidden_state = self.drop_path(hidden_state)
+ # residual connection
+ hidden_state = residual + hidden_state
+ residual = hidden_state
+ # mlp
+ hidden_state = self.post_normalization(hidden_state)
+ hidden_state = self.mlp(hidden_state)
+ hidden_state = self.mlp_scaling(hidden_state)
+ hidden_state = self.drop_path(hidden_state)
+ # residual connection
+ hidden_state = residual + hidden_state
+ return hidden_state
+
+
+class VanStage(nn.Module):
+ """
+ VanStage, consisting of multiple layers.
+ """
+
+ def __init__(
+ self,
+ config: VanConfig,
+ in_channels: int,
+ hidden_size: int,
+ patch_size: int,
+ stride: int,
+ depth: int,
+ mlp_ratio: int = 4,
+ drop_path_rate: float = 0.0,
+ ):
+ super().__init__()
+ self.embeddings = VanOverlappingPatchEmbedder(in_channels, hidden_size, patch_size, stride)
+ self.layers = nn.Sequential(
+ *[
+ VanLayer(
+ config,
+ hidden_size,
+ mlp_ratio=mlp_ratio,
+ drop_path_rate=drop_path_rate,
+ )
+ for _ in range(depth)
+ ]
+ )
+ self.normalization = nn.LayerNorm(hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.embeddings(hidden_state)
+ hidden_state = self.layers(hidden_state)
+ # rearrange b c h w -> b (h w) c
+ batch_size, hidden_size, height, width = hidden_state.shape
+ hidden_state = hidden_state.flatten(2).transpose(1, 2)
+ hidden_state = self.normalization(hidden_state)
+ # rearrange b (h w) c- > b c h w
+ hidden_state = hidden_state.view(batch_size, height, width, hidden_size).permute(0, 3, 1, 2)
+ return hidden_state
+
+
+class VanEncoder(nn.Module):
+ """
+ VanEncoder, consisting of multiple stages.
+ """
+
+ def __init__(self, config: VanConfig):
+ super().__init__()
+ self.stages = nn.ModuleList([])
+ patch_sizes = config.patch_sizes
+ strides = config.strides
+ hidden_sizes = config.hidden_sizes
+ depths = config.depths
+ mlp_ratios = config.mlp_ratios
+ drop_path_rates = [
+ x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths), device="cpu")
+ ]
+
+ for num_stage, (patch_size, stride, hidden_size, depth, mlp_expantion, drop_path_rate) in enumerate(
+ zip(patch_sizes, strides, hidden_sizes, depths, mlp_ratios, drop_path_rates)
+ ):
+ is_first_stage = num_stage == 0
+ in_channels = hidden_sizes[num_stage - 1]
+ if is_first_stage:
+ in_channels = config.num_channels
+ self.stages.append(
+ VanStage(
+ config,
+ in_channels,
+ hidden_size,
+ patch_size=patch_size,
+ stride=stride,
+ depth=depth,
+ mlp_ratio=mlp_expantion,
+ drop_path_rate=drop_path_rate,
+ )
+ )
+
+ def forward(
+ self,
+ hidden_state: torch.Tensor,
+ output_hidden_states: Optional[bool] = False,
+ return_dict: Optional[bool] = True,
+ ) -> Union[tuple, BaseModelOutputWithNoAttention]:
+ all_hidden_states = () if output_hidden_states else None
+
+ for _, stage_module in enumerate(self.stages):
+ hidden_state = stage_module(hidden_state)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_state,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_state, all_hidden_states] if v is not None)
+
+ return BaseModelOutputWithNoAttention(last_hidden_state=hidden_state, hidden_states=all_hidden_states)
+
+
+class VanPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: VanConfig
+ base_model_prefix = "van"
+ main_input_name = "pixel_values"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ nn.init.trunc_normal_(module.weight, std=self.config.initializer_range)
+ if isinstance(module, nn.Linear) and module.bias is not None:
+ nn.init.constant_(module.bias, 0)
+ elif isinstance(module, nn.LayerNorm):
+ nn.init.constant_(module.bias, 0)
+ nn.init.constant_(module.weight, 1.0)
+ elif isinstance(module, nn.Conv2d):
+ fan_out = module.kernel_size[0] * module.kernel_size[1] * module.out_channels
+ fan_out //= module.groups
+ module.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
+ if module.bias is not None:
+ module.bias.data.zero_()
+
+
+VAN_START_DOCSTRING = r"""
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
+ behavior.
+
+ Parameters:
+ config ([`VanConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+VAN_INPUTS_DOCSTRING = r"""
+ Args:
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
+ [`ConvNextImageProcessor.__call__`] for details.
+
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all stages. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare VAN model outputting raw features without any specific head on top. Note, VAN does not have an embedding"
+ " layer.",
+ VAN_START_DOCSTRING,
+)
+class VanModel(VanPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+ self.encoder = VanEncoder(config)
+ # final layernorm layer
+ self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(VAN_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=BaseModelOutputWithPoolingAndNoAttention,
+ config_class=_CONFIG_FOR_DOC,
+ modality="vision",
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
+ )
+ def forward(
+ self,
+ pixel_values: Optional[torch.FloatTensor],
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ encoder_outputs = self.encoder(
+ pixel_values,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ last_hidden_state = encoder_outputs[0]
+ # global average pooling, n c w h -> n c
+ pooled_output = last_hidden_state.mean(dim=[-2, -1])
+
+ if not return_dict:
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndNoAttention(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ )
+
+
+@add_start_docstrings(
+ """
+ VAN Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
+ ImageNet.
+ """,
+ VAN_START_DOCSTRING,
+)
+class VanForImageClassification(VanPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.van = VanModel(config)
+ # Classifier head
+ self.classifier = (
+ nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(VAN_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
+ output_type=ImageClassifierOutputWithNoAttention,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
+ )
+ def forward(
+ self,
+ pixel_values: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, ImageClassifierOutputWithNoAttention]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.van(pixel_values, output_hidden_states=output_hidden_states, return_dict=return_dict)
+
+ pooled_output = outputs.pooler_output if return_dict else outputs[1]
+
+ logits = self.classifier(pooled_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.config.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.config.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return ImageClassifierOutputWithNoAttention(loss=loss, logits=logits, hidden_states=outputs.hidden_states)
+
+
+__all__ = ["VanForImageClassification", "VanModel", "VanPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5bd93aa4dabea9b2adbc54eeeb3664de589f43a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2022 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_vit_hybrid import *
+ from .image_processing_vit_hybrid import *
+ from .modeling_vit_hybrid import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..15924a516a7226c30830a4ed8011669b6dd879b8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/configuration_vit_hybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/configuration_vit_hybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63d3992344d9d3d40b58ddf6f93f23361afbf4cd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/configuration_vit_hybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/image_processing_vit_hybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/image_processing_vit_hybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c36d8b0cb28e5b4b8a747fbcf394f53590c1d772
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/image_processing_vit_hybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/modeling_vit_hybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/modeling_vit_hybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b7a1c9ab39deecde3ba1e38486e7fe6fd90e9c0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/__pycache__/modeling_vit_hybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/configuration_vit_hybrid.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/configuration_vit_hybrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..e96c6c4a1b58cd40e86dfac71dfcb9c0eb19f57c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/configuration_vit_hybrid.py
@@ -0,0 +1,180 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""ViT Hybrid model configuration"""
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+from ...auto.configuration_auto import CONFIG_MAPPING
+from ...bit import BitConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class ViTHybridConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`ViTHybridModel`]. It is used to instantiate a ViT
+ Hybrid model according to the specified arguments, defining the model architecture. Instantiating a configuration
+ with the defaults will yield a similar configuration to that of the ViT Hybrid
+ [google/vit-hybrid-base-bit-384](https://huggingface.co/google/vit-hybrid-base-bit-384) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ backbone_config (`Union[dict[str, Any], PretrainedConfig]`, *optional*):
+ The configuration of the backbone in a dictionary or the config object of the backbone.
+ backbone (`str`, *optional*):
+ Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
+ will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
+ is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
+ use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
+ Whether to use pretrained weights for the backbone.
+ use_timm_backbone (`bool`, *optional*, defaults to `False`):
+ Whether to load `backbone` from the timm library. If `False`, the backbone is loaded from the transformers
+ library.
+ backbone_kwargs (`dict`, *optional*):
+ Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
+ e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
+ hidden_size (`int`, *optional*, defaults to 768):
+ Dimensionality of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 3072):
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ image_size (`int`, *optional*, defaults to 224):
+ The size (resolution) of each image.
+ patch_size (`int`, *optional*, defaults to 1):
+ The size (resolution) of each patch.
+ num_channels (`int`, *optional*, defaults to 3):
+ The number of input channels.
+ backbone_featmap_shape (`list[int]`, *optional*, defaults to `[1, 1024, 24, 24]`):
+ Used only for the `hybrid` embedding type. The shape of the feature maps of the backbone.
+ qkv_bias (`bool`, *optional*, defaults to `True`):
+ Whether to add a bias to the queries, keys and values.
+
+ Example:
+
+ ```python
+ >>> from transformers import ViTHybridConfig, ViTHybridModel
+
+ >>> # Initializing a ViT Hybrid vit-hybrid-base-bit-384 style configuration
+ >>> configuration = ViTHybridConfig()
+
+ >>> # Initializing a model (with random weights) from the vit-hybrid-base-bit-384 style configuration
+ >>> model = ViTHybridModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "vit-hybrid"
+
+ def __init__(
+ self,
+ backbone_config=None,
+ backbone=None,
+ use_pretrained_backbone=False,
+ use_timm_backbone=False,
+ backbone_kwargs=None,
+ hidden_size=768,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.0,
+ attention_probs_dropout_prob=0.0,
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ image_size=224,
+ patch_size=1,
+ num_channels=3,
+ backbone_featmap_shape=[1, 1024, 24, 24],
+ qkv_bias=True,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ if use_pretrained_backbone:
+ raise ValueError("Pretrained backbones are not supported yet.")
+
+ if backbone_config is not None and backbone is not None:
+ raise ValueError("You can't specify both `backbone` and `backbone_config`.")
+
+ if backbone_config is None and backbone is None:
+ logger.info("`backbone_config` is `None`. Initializing the config with a `BiT` backbone.")
+ backbone_config = {
+ "global_padding": "same",
+ "layer_type": "bottleneck",
+ "depths": [3, 4, 9],
+ "out_features": ["stage3"],
+ "embedding_dynamic_padding": True,
+ }
+
+ if backbone_kwargs is not None and backbone_kwargs and backbone_config is not None:
+ raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.")
+
+ if isinstance(backbone_config, dict):
+ if "model_type" in backbone_config:
+ backbone_config_class = CONFIG_MAPPING[backbone_config["model_type"]]
+ else:
+ logger.info(
+ "`model_type` is not found in `backbone_config`. Use `Bit` as the backbone configuration class."
+ )
+ backbone_config_class = BitConfig
+ backbone_config = backbone_config_class(**backbone_config)
+
+ self.backbone_featmap_shape = backbone_featmap_shape
+ self.backbone_config = backbone_config
+ self.backbone = backbone
+ self.use_pretrained_backbone = use_pretrained_backbone
+ self.use_timm_backbone = use_timm_backbone
+ self.backbone_kwargs = backbone_kwargs
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.qkv_bias = qkv_bias
+
+ @property
+ def sub_configs(self):
+ return (
+ {"backbone_config": type(self.backbone_config)}
+ if getattr(self, "backbone_config", None) is not None
+ else {}
+ )
+
+
+__all__ = ["ViTHybridConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/image_processing_vit_hybrid.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/image_processing_vit_hybrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1e5a9c8e6d982a017b4990ab7d5d2ae473af994
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/image_processing_vit_hybrid.py
@@ -0,0 +1,341 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for ViT hybrid."""
+
+from typing import Optional, Union
+
+import numpy as np
+
+from ....image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
+from ....image_transforms import (
+ convert_to_rgb,
+ get_resize_output_image_size,
+ resize,
+ to_channel_dimension_format,
+)
+from ....image_utils import (
+ OPENAI_CLIP_MEAN,
+ OPENAI_CLIP_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ infer_channel_dimension_format,
+ is_scaled_image,
+ make_list_of_images,
+ to_numpy_array,
+ valid_images,
+ validate_kwargs,
+ validate_preprocess_arguments,
+)
+from ....utils import TensorType, is_vision_available, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+if is_vision_available():
+ import PIL
+
+
+class ViTHybridImageProcessor(BaseImageProcessor):
+ r"""
+ Constructs a ViT Hybrid image processor.
+
+ Args:
+ do_resize (`bool`, *optional*, defaults to `True`):
+ Whether to resize the image's (height, width) dimensions to the specified `size`. Can be overridden by
+ `do_resize` in the `preprocess` method.
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 224}`):
+ Size of the image after resizing. The shortest edge of the image is resized to size["shortest_edge"], with
+ the longest edge resized to keep the input aspect ratio. Can be overridden by `size` in the `preprocess`
+ method.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
+ Resampling filter to use if resizing the image. Can be overridden by `resample` in the `preprocess` method.
+ do_center_crop (`bool`, *optional*, defaults to `True`):
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
+ `preprocess` method.
+ crop_size (`dict[str, int]` *optional*, defaults to 224):
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
+ method.
+ do_rescale (`bool`, *optional*, defaults to `True`):
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
+ the `preprocess` method.
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in the `preprocess`
+ method.
+ do_normalize:
+ Whether to normalize the image. Can be overridden by `do_normalize` in the `preprocess` method.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
+ Can be overridden by the `image_std` parameter in the `preprocess` method.
+ do_convert_rgb (`bool`, *optional*, defaults to `True`):
+ Whether to convert the image to RGB.
+ """
+
+ model_input_names = ["pixel_values"]
+
+ def __init__(
+ self,
+ do_resize: bool = True,
+ size: Optional[dict[str, int]] = None,
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
+ do_center_crop: bool = True,
+ crop_size: Optional[dict[str, int]] = None,
+ do_rescale: bool = True,
+ rescale_factor: Union[int, float] = 1 / 255,
+ do_normalize: bool = True,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ do_convert_rgb: bool = True,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ size = size if size is not None else {"shortest_edge": 224}
+ size = get_size_dict(size, default_to_square=False)
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
+
+ self.do_resize = do_resize
+ self.size = size
+ self.resample = resample
+ self.do_center_crop = do_center_crop
+ self.crop_size = crop_size
+ self.do_rescale = do_rescale
+ self.rescale_factor = rescale_factor
+ self.do_normalize = do_normalize
+ self.image_mean = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
+ self.image_std = image_std if image_std is not None else OPENAI_CLIP_STD
+ self.do_convert_rgb = do_convert_rgb
+ self._valid_processor_keys = [
+ "images",
+ "do_resize",
+ "size",
+ "resample",
+ "do_center_crop",
+ "crop_size",
+ "do_rescale",
+ "rescale_factor",
+ "do_normalize",
+ "image_mean",
+ "image_std",
+ "do_convert_rgb",
+ "return_tensors",
+ "data_format",
+ "input_data_format",
+ ]
+
+ def resize(
+ self,
+ image: np.ndarray,
+ size: dict[str, int],
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge
+ resized to keep the input aspect ratio.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`dict[str, int]`):
+ Size of the output image.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
+ Resampling filter to use when resiizing the image.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred.
+ """
+ default_to_square = True
+ if "shortest_edge" in size:
+ size = size["shortest_edge"]
+ default_to_square = False
+ elif "height" in size and "width" in size:
+ size = (size["height"], size["width"])
+ else:
+ raise ValueError("Size must contain either 'shortest_edge' or 'height' and 'width'.")
+
+ output_size = get_resize_output_image_size(
+ image,
+ size=size,
+ default_to_square=default_to_square,
+ input_data_format=input_data_format,
+ )
+ return resize(
+ image,
+ size=output_size,
+ resample=resample,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ **kwargs,
+ )
+
+ def preprocess(
+ self,
+ images: ImageInput,
+ do_resize: Optional[bool] = None,
+ size: Optional[dict[str, int]] = None,
+ resample: PILImageResampling = None,
+ do_center_crop: Optional[bool] = None,
+ crop_size: Optional[int] = None,
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ do_convert_rgb: Optional[bool] = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ data_format: Optional[ChannelDimension] = ChannelDimension.FIRST,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> PIL.Image.Image:
+ """
+ Preprocess an image or batch of images.
+
+ Args:
+ images (`ImageInput`):
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
+ Whether to resize the image.
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
+ Size of the image after resizing. Shortest edge of the image is resized to size["shortest_edge"], with
+ the longest edge resized to keep the input aspect ratio.
+ resample (`int`, *optional*, defaults to `self.resample`):
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only
+ has an effect if `do_resize` is set to `True`.
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
+ Whether to center crop the image.
+ crop_size (`dict[str, int]`, *optional*, defaults to `self.crop_size`):
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
+ Whether to rescale the image.
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
+ Whether to normalize the image.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
+ `True`.
+ do_convert_rgb (`bool`, *optional*, defaults to `self.do_convert_rgb`):
+ Whether to convert the image to RGB.
+ return_tensors (`str` or `TensorType`, *optional*):
+ The type of tensors to return. Can be one of:
+ - Unset: Return a list of `np.ndarray`.
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
+ The channel dimension format for the output image. Can be one of:
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - Unset: defaults to the channel dimension format of the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+ """
+ do_resize = do_resize if do_resize is not None else self.do_resize
+ size = size if size is not None else self.size
+ size = get_size_dict(size, param_name="size", default_to_square=False)
+ resample = resample if resample is not None else self.resample
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
+ crop_size = crop_size if crop_size is not None else self.crop_size
+ crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
+ image_mean = image_mean if image_mean is not None else self.image_mean
+ image_std = image_std if image_std is not None else self.image_std
+ do_convert_rgb = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
+
+ images = make_list_of_images(images)
+
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
+
+ if not valid_images(images):
+ raise ValueError(
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
+ "torch.Tensor, tf.Tensor or jax.ndarray."
+ )
+ validate_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_center_crop=do_center_crop,
+ crop_size=crop_size,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ )
+
+ # PIL RGBA images are converted to RGB
+ if do_convert_rgb:
+ images = [convert_to_rgb(image) for image in images]
+
+ # All transformations expect numpy arrays.
+ images = [to_numpy_array(image) for image in images]
+
+ if do_rescale and is_scaled_image(images[0]):
+ logger.warning_once(
+ "It looks like you are trying to rescale already rescaled images. If the input"
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
+ )
+
+ if input_data_format is None:
+ # We assume that all images have the same channel dimension format.
+ input_data_format = infer_channel_dimension_format(images[0])
+
+ all_images = []
+ for image in images:
+ if do_resize:
+ image = self.resize(image=image, size=size, resample=resample, input_data_format=input_data_format)
+
+ if do_center_crop:
+ image = self.center_crop(image=image, size=crop_size, input_data_format=input_data_format)
+
+ if do_rescale:
+ image = self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
+
+ if do_normalize:
+ image = self.normalize(
+ image=image, mean=image_mean, std=image_std, input_data_format=input_data_format
+ )
+
+ all_images.append(image)
+ images = [
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
+ for image in all_images
+ ]
+
+ data = {"pixel_values": images}
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+
+__all__ = ["ViTHybridImageProcessor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/modeling_vit_hybrid.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/modeling_vit_hybrid.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d1c22301defaafe9f0428f616ed3fa482a9a072
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/vit_hybrid/modeling_vit_hybrid.py
@@ -0,0 +1,763 @@
+# coding=utf-8
+# Copyright 2022 Google AI, Ross Wightman, The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch ViT Hybrid model."""
+
+import collections.abc
+import math
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ....activations import ACT2FN
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
+from ....modeling_utils import PreTrainedModel
+from ....pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
+from ....utils import (
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+ torch_int,
+)
+from ....utils.backbone_utils import load_backbone
+from .configuration_vit_hybrid import ViTHybridConfig
+
+
+logger = logging.get_logger(__name__)
+
+# General docstring
+_CONFIG_FOR_DOC = "ViTHybridConfig"
+
+# Base docstring
+_CHECKPOINT_FOR_DOC = "google/vit-hybrid-base-bit-384"
+_EXPECTED_OUTPUT_SHAPE = [1, 197, 768]
+
+# Image classification docstring
+_IMAGE_CLASS_CHECKPOINT = "google/vit-hybrid-base-bit-384"
+_IMAGE_CLASS_EXPECTED_OUTPUT = "tabby, tabby cat"
+
+
+class ViTHybridEmbeddings(nn.Module):
+ """
+ Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
+ """
+
+ def __init__(self, config: ViTHybridConfig, use_mask_token: bool = False) -> None:
+ super().__init__()
+
+ self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
+ self.patch_embeddings = ViTHybridPatchEmbeddings(config)
+ num_patches = self.patch_embeddings.num_patches
+ self.position_embeddings = nn.Parameter(torch.randn(1, num_patches + 1, config.hidden_size))
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.patch_size = config.patch_size
+ self.config = config
+
+ # Copied from transformers.models.vit.modeling_vit.ViTEmbeddings.interpolate_pos_encoding
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
+ """
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
+ images. This method is also adapted to support torch.jit tracing.
+
+ Adapted from:
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
+ """
+
+ num_patches = embeddings.shape[1] - 1
+ num_positions = self.position_embeddings.shape[1] - 1
+
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
+ return self.position_embeddings
+
+ class_pos_embed = self.position_embeddings[:, :1]
+ patch_pos_embed = self.position_embeddings[:, 1:]
+
+ dim = embeddings.shape[-1]
+
+ new_height = height // self.patch_size
+ new_width = width // self.patch_size
+
+ sqrt_num_positions = torch_int(num_positions**0.5)
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
+
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed,
+ size=(new_height, new_width),
+ mode="bicubic",
+ align_corners=False,
+ )
+
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
+
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
+
+ def forward(
+ self,
+ pixel_values: torch.Tensor,
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
+ interpolate_pos_encoding: bool = False,
+ ) -> torch.Tensor:
+ batch_size, num_channels, height, width = pixel_values.shape
+ embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
+
+ if bool_masked_pos is not None:
+ seq_length = embeddings.shape[1]
+ mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
+ # replace the masked visual tokens by mask_tokens
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
+
+ # add the [CLS] token to the embedded patch tokens
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
+
+ # add positional encoding to each token
+ if interpolate_pos_encoding:
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
+ else:
+ embeddings = embeddings + self.position_embeddings
+
+ embeddings = self.dropout(embeddings)
+
+ return embeddings
+
+
+class ViTHybridPatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config, feature_size=None):
+ super().__init__()
+ image_size, patch_size = config.image_size, config.patch_size
+ num_channels, hidden_size = config.num_channels, config.hidden_size
+
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+
+ self.backbone = load_backbone(config)
+ if self.backbone.config.model_type != "bit":
+ raise ValueError(f"Backbone model type {self.backbone.model_type} is not supported.")
+ feature_dim = self.backbone.channels[-1]
+
+ if feature_size is None:
+ feature_map = config.backbone_featmap_shape
+
+ feature_size = feature_map[-2:]
+ feature_dim = feature_map[1]
+ else:
+ feature_size = (
+ feature_size if isinstance(feature_size, collections.abc.Iterable) else (feature_size, feature_size)
+ )
+ feature_dim = self.backbone.channels[-1]
+
+ self.grid_size = (feature_size[0] // patch_size[0], feature_size[1] // patch_size[1])
+ self.num_patches = self.grid_size[0] * self.grid_size[1]
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+
+ self.projection = nn.Conv2d(feature_dim, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
+ _, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+ if not interpolate_pos_encoding:
+ if height != self.image_size[0] or width != self.image_size[1]:
+ raise ValueError(
+ f"Input image size ({height}*{width}) doesn't match model"
+ f" ({self.image_size[0]}*{self.image_size[1]})."
+ )
+
+ features = self.backbone(pixel_values).feature_maps[-1]
+ embeddings = self.projection(features).flatten(2).transpose(1, 2)
+
+ return embeddings
+
+
+class ViTHybridSelfAttention(nn.Module):
+ def __init__(self, config: ViTHybridConfig) -> None:
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
+ f"heads {config.num_attention_heads}."
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
+ x = x.view(new_x_shape)
+ return x.permute(0, 2, 1, 3)
+
+ def forward(
+ self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
+ ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
+ mixed_query_layer = self.query(hidden_states)
+
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = attention_probs * head_mask
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+class ViTHybridSdpaSelfAttention(ViTHybridSelfAttention):
+ def __init__(self, config: ViTHybridConfig) -> None:
+ super().__init__(config)
+ self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
+
+ def forward(
+ self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
+ ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
+ mixed_query_layer = self.query(hidden_states)
+
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
+ query_layer = self.transpose_for_scores(mixed_query_layer)
+
+ context_layer = torch.nn.functional.scaled_dot_product_attention(
+ query_layer,
+ key_layer,
+ value_layer,
+ head_mask,
+ self.attention_probs_dropout_prob if self.training else 0.0,
+ is_causal=False,
+ scale=None,
+ )
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ return context_layer, None
+
+
+class ViTHybridSelfOutput(nn.Module):
+ """
+ The residual connection is defined in ViTHybridLayer instead of here (as is the case with other models), due to the
+ layernorm applied before each block.
+ """
+
+ def __init__(self, config: ViTHybridConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ return hidden_states
+
+
+class ViTHybridAttention(nn.Module):
+ def __init__(self, config: ViTHybridConfig) -> None:
+ super().__init__()
+ self.attention = ViTHybridSelfAttention(config)
+ self.output = ViTHybridSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads: set[int]) -> None:
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.attention.query = prune_linear_layer(self.attention.query, index)
+ self.attention.key = prune_linear_layer(self.attention.key, index)
+ self.attention.value = prune_linear_layer(self.attention.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ head_mask: Optional[torch.Tensor] = None,
+ output_attentions: bool = False,
+ ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
+ self_outputs = self.attention(hidden_states, head_mask, output_attentions)
+
+ attention_output = self.output(self_outputs[0], hidden_states)
+
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+class ViTHybridSdpaAttention(ViTHybridAttention):
+ def __init__(self, config: ViTHybridConfig) -> None:
+ super().__init__(config)
+ self.attention = ViTHybridSdpaSelfAttention(config)
+
+
+class ViTHybridIntermediate(nn.Module):
+ def __init__(self, config: ViTHybridConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+
+ return hidden_states
+
+
+class ViTHybridOutput(nn.Module):
+ def __init__(self, config: ViTHybridConfig) -> None:
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+
+ hidden_states = hidden_states + input_tensor
+
+ return hidden_states
+
+
+VIT_HYBRID_ATTENTION_CLASSES = {
+ "eager": ViTHybridAttention,
+ "sdpa": ViTHybridSdpaAttention,
+}
+
+
+class ViTHybridLayer(GradientCheckpointingLayer):
+ """This corresponds to the Block class in the timm implementation."""
+
+ def __init__(self, config: ViTHybridConfig) -> None:
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = VIT_HYBRID_ATTENTION_CLASSES[config._attn_implementation](config)
+ self.intermediate = ViTHybridIntermediate(config)
+ self.output = ViTHybridOutput(config)
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ head_mask: Optional[torch.Tensor] = None,
+ output_attentions: bool = False,
+ ) -> Union[tuple[torch.Tensor, torch.Tensor], tuple[torch.Tensor]]:
+ self_attention_outputs = self.attention(
+ self.layernorm_before(hidden_states), # in ViTHybrid, layernorm is applied before self-attention
+ head_mask,
+ output_attentions=output_attentions,
+ )
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ # first residual connection
+ # We assign to correct device for `accelerate`, check: https://github.com/huggingface/transformers/pull/20705/
+ hidden_states = attention_output + hidden_states.to(attention_output.device)
+
+ # in ViTHybrid, layernorm is also applied after self-attention
+ layer_output = self.layernorm_after(hidden_states)
+ layer_output = self.intermediate(layer_output)
+
+ # second residual connection is done here
+ layer_output = self.output(layer_output, hidden_states)
+
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+
+class ViTHybridEncoder(nn.Module):
+ def __init__(self, config: ViTHybridConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([ViTHybridLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ head_mask: Optional[torch.Tensor] = None,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ) -> Union[tuple, BaseModelOutput]:
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+
+ layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class ViTHybridPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config: ViTHybridConfig
+ base_model_prefix = "vit"
+ main_input_name = "pixel_values"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["ViTHybridEmbeddings", "ViTHybridLayer"]
+ _supports_sdpa = True
+
+ def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
+ """Initialize the weights"""
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ # Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
+ # `trunc_normal_cpu` not implemented in `half` issues
+ module.weight.data = nn.init.trunc_normal_(
+ module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
+ ).to(module.weight.dtype)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ elif isinstance(module, ViTHybridEmbeddings):
+ module.position_embeddings.data = nn.init.trunc_normal_(
+ module.position_embeddings.data.to(torch.float32),
+ mean=0.0,
+ std=self.config.initializer_range,
+ ).to(module.position_embeddings.dtype)
+ module.cls_token.data = nn.init.trunc_normal_(
+ module.cls_token.data.to(torch.float32),
+ mean=0.0,
+ std=self.config.initializer_range,
+ ).to(module.cls_token.dtype)
+ module.mask_token.data.zero_()
+
+
+VIT_START_DOCSTRING = r"""
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
+ behavior.
+
+ Parameters:
+ config ([`ViTHybridConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+VIT_INPUTS_DOCSTRING = r"""
+ Args:
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
+ [`ViTHybridImageProcessor.__call__`] for details.
+
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare ViT Hybrid Model transformer outputting raw hidden-states without any specific head on top.",
+ VIT_START_DOCSTRING,
+)
+class ViTHybridModel(ViTHybridPreTrainedModel):
+ def __init__(self, config: ViTHybridConfig, add_pooling_layer: bool = True, use_mask_token: bool = False):
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = ViTHybridEmbeddings(config, use_mask_token=use_mask_token)
+ self.encoder = ViTHybridEncoder(config)
+
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.pooler = ViTHybridPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> ViTHybridPatchEmbeddings:
+ return self.embeddings.patch_embeddings
+
+ def _prune_heads(self, heads_to_prune: dict[int, list[int]]) -> None:
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ @add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=BaseModelOutputWithPooling,
+ config_class=_CONFIG_FOR_DOC,
+ modality="vision",
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
+ )
+ def forward(
+ self,
+ pixel_values: Optional[torch.Tensor] = None,
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ interpolate_pos_encoding: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, BaseModelOutputWithPooling]:
+ r"""
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ # TODO: maybe have a cleaner way to cast the input (from `ImageProcessor` side?)
+ expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype
+ if pixel_values.dtype != expected_dtype:
+ pixel_values = pixel_values.to(expected_dtype)
+
+ embedding_output = self.embeddings(
+ pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+ sequence_output = self.layernorm(sequence_output)
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
+ return head_outputs + encoder_outputs[1:]
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ )
+
+
+class ViTHybridPooler(nn.Module):
+ def __init__(self, config: ViTHybridConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states):
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@add_start_docstrings(
+ """
+ ViT Hybrid Model transformer with an image classification head on top (a linear layer on top of the final hidden
+ state of the [CLS] token) e.g. for ImageNet.
+ """,
+ VIT_START_DOCSTRING,
+)
+class ViTHybridForImageClassification(ViTHybridPreTrainedModel):
+ def __init__(self, config: ViTHybridConfig) -> None:
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.vit = ViTHybridModel(config, add_pooling_layer=False)
+
+ # Classifier head
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
+ output_type=ImageClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
+ )
+ def forward(
+ self,
+ pixel_values: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ interpolate_pos_encoding: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, ImageClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.vit(
+ pixel_values,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.classifier(sequence_output[:, 0, :])
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device to enable model parallelism
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return ImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["ViTHybridForImageClassification", "ViTHybridModel", "ViTHybridPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c13c67012fa157a94bae21734a1f59b26c78588d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__init__.py
@@ -0,0 +1,28 @@
+# Copyright 2020 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ....utils import _LazyModule
+from ....utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xlm_prophetnet import *
+ from .modeling_xlm_prophetnet import *
+ from .tokenization_xlm_prophetnet import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..569f23867b331cc452e1c080497cde37404a9827
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/configuration_xlm_prophetnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/configuration_xlm_prophetnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94d32776e97ed589f4645343540c5b47d6e9761b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/configuration_xlm_prophetnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/modeling_xlm_prophetnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/modeling_xlm_prophetnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d5a88034bb80ca6af73c98008135f79e06be1d9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/modeling_xlm_prophetnet.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:13e9c411014fd65d25132958b3caef28e70020f2be4d82317e9296ef75571845
+size 114476
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/tokenization_xlm_prophetnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/tokenization_xlm_prophetnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d9c922d2fb71359b8b5c490f24f97adcdcf6b8ac
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/__pycache__/tokenization_xlm_prophetnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/configuration_xlm_prophetnet.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/configuration_xlm_prophetnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..59f42577c59f19d9d379eaaec15029eaed6967c3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/configuration_xlm_prophetnet.py
@@ -0,0 +1,181 @@
+# coding=utf-8
+# Copyright 2020 The Microsoft Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""XLM-ProphetNet model configuration"""
+
+from typing import Callable, Optional, Union
+
+from ....configuration_utils import PretrainedConfig
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class XLMProphetNetConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`XLMProphetNetModel`]. It is used to instantiate a
+ XLMProphetNet model according to the specified arguments, defining the model architecture. Instantiating a
+ configuration with the defaults will yield a similar configuration to that of the XLMProphetNet
+ [microsoft/xprophetnet-large-wiki100-cased](https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased)
+ architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ activation_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for activations inside the fully connected layer.
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ vocab_size (`int`, *optional*, defaults to 30522):
+ Vocabulary size of the ProphetNET model. Defines the number of different tokens that can be represented by
+ the `inputs_ids` passed when calling [`XLMProphetNetModel`].
+ hidden_size (`int`, *optional*, defaults to 1024):
+ Dimensionality of the layers and the pooler layer.
+ encoder_ffn_dim (`int`, *optional*, defaults to 4096):
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
+ num_encoder_layers (`int`, *optional*, defaults to 12):
+ Number of encoder layers.
+ num_encoder_attention_heads (`int`, *optional*, defaults to 16):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ decoder_ffn_dim (`int`, *optional*, defaults to 4096):
+ Dimensionality of the `intermediate` (often named feed-forward) layer in decoder.
+ num_decoder_layers (`int`, *optional*, defaults to 12):
+ Number of decoder layers.
+ num_decoder_attention_heads (`int`, *optional*, defaults to 16):
+ Number of attention heads for each attention layer in the Transformer decoder.
+ attention_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention probabilities.
+ dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ max_position_embeddings (`int`, *optional*, defaults to 512):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ init_std (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ add_cross_attention (`bool`, *optional*, defaults to `True`):
+ Whether cross-attention layers should be added to the model.
+ is_encoder_decoder (`bool`, *optional*, defaults to `True`):
+ Whether this is an encoder/decoder model.
+ pad_token_id (`int`, *optional*, defaults to 1)
+ Padding token id.
+ bos_token_id (`int`, *optional*, defaults to 0)
+ Beginning of stream token id.
+ eos_token_id (`int`, *optional*, defaults to 2)
+ End of stream token id.
+ ngram (`int`, *optional*, defaults to 2)
+ Number of future tokens to predict. Set to 1 to be same as traditional Language model to predict next first
+ token.
+ num_buckets (`int`, *optional*, defaults to 32)
+ The number of buckets to use for each attention layer. This is for relative position calculation. See the
+ [T5 paper](see https://huggingface.co/papers/1910.10683) for more details.
+ relative_max_distance (`int`, *optional*, defaults to 128)
+ Relative distances greater than this number will be put into the last same bucket. This is for relative
+ position calculation. See the [T5 paper](see https://huggingface.co/papers/1910.10683) for more details.
+ disable_ngram_loss (`bool`, *optional*, defaults to `False`):
+ Whether be trained predicting only the next first token.
+ eps (`float`, *optional*, defaults to 0.0):
+ Controls the `epsilon` parameter value for label smoothing in the loss calculation. If set to 0, no label
+ smoothing is performed.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models).
+ """
+
+ model_type = "xlm-prophetnet"
+ keys_to_ignore_at_inference = ["past_key_values"]
+ attribute_map = {
+ "num_attention_heads": "num_encoder_attention_heads",
+ }
+
+ def __init__(
+ self,
+ activation_dropout: Optional[float] = 0.1,
+ activation_function: Optional[Union[str, Callable]] = "gelu",
+ vocab_size: Optional[int] = 30522,
+ hidden_size: Optional[int] = 1024,
+ encoder_ffn_dim: Optional[int] = 4096,
+ num_encoder_layers: Optional[int] = 12,
+ num_encoder_attention_heads: Optional[int] = 16,
+ decoder_ffn_dim: Optional[int] = 4096,
+ num_decoder_layers: Optional[int] = 12,
+ num_decoder_attention_heads: Optional[int] = 16,
+ attention_dropout: Optional[float] = 0.1,
+ dropout: Optional[float] = 0.1,
+ max_position_embeddings: Optional[int] = 512,
+ init_std: Optional[float] = 0.02,
+ is_encoder_decoder: Optional[bool] = True,
+ add_cross_attention: Optional[bool] = True,
+ decoder_start_token_id: Optional[int] = 0,
+ ngram: Optional[int] = 2,
+ num_buckets: Optional[int] = 32,
+ relative_max_distance: Optional[int] = 128,
+ disable_ngram_loss: Optional[bool] = False,
+ eps: Optional[float] = 0.0,
+ use_cache: Optional[bool] = True,
+ pad_token_id: Optional[int] = 0,
+ bos_token_id: Optional[int] = 1,
+ eos_token_id: Optional[int] = 2,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.encoder_ffn_dim = encoder_ffn_dim
+ self.num_encoder_layers = num_encoder_layers
+ self.num_encoder_attention_heads = num_encoder_attention_heads
+ self.decoder_ffn_dim = decoder_ffn_dim
+ self.num_decoder_layers = num_decoder_layers
+ self.num_decoder_attention_heads = num_decoder_attention_heads
+ self.max_position_embeddings = max_position_embeddings
+ self.init_std = init_std # Normal(0, this parameter)
+ self.activation_function = activation_function
+
+ # parameters for xlmprophetnet
+ self.ngram = ngram
+ self.num_buckets = num_buckets
+ self.relative_max_distance = relative_max_distance
+ self.disable_ngram_loss = disable_ngram_loss
+ self.eps = eps
+
+ # 3 Types of Dropout
+ self.attention_dropout = attention_dropout
+ self.activation_dropout = activation_dropout
+ self.dropout = dropout
+
+ self.use_cache = use_cache
+
+ super().__init__(
+ pad_token_id=pad_token_id,
+ bos_token_id=bos_token_id,
+ eos_token_id=eos_token_id,
+ is_encoder_decoder=is_encoder_decoder,
+ add_cross_attention=add_cross_attention,
+ decoder_start_token_id=decoder_start_token_id,
+ **kwargs,
+ )
+
+ @property
+ def num_hidden_layers(self) -> int:
+ return self.num_encoder_layers + self.num_decoder_layers
+
+ @num_hidden_layers.setter
+ def num_hidden_layers(self, value):
+ raise NotImplementedError(
+ "This model does not support the setting of `num_hidden_layers`. Please set `num_encoder_layers` and"
+ " `num_decoder_layers`."
+ )
+
+
+__all__ = ["XLMProphetNetConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/modeling_xlm_prophetnet.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/modeling_xlm_prophetnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..d526b7d6504858dfb831b65533c6be64ba45908e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/modeling_xlm_prophetnet.py
@@ -0,0 +1,2305 @@
+# coding=utf-8
+# Copyright 2020 The Microsoft Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch XLM-ProphetNet model."""
+
+import copy
+import math
+import warnings
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import Tensor, nn
+from torch.nn import LayerNorm
+
+from ....activations import ACT2FN
+from ....modeling_layers import GradientCheckpointingLayer
+from ....modeling_outputs import BaseModelOutput
+from ....modeling_utils import PreTrainedModel
+from ....utils import (
+ ModelOutput,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+ replace_return_docstrings,
+)
+from ....utils.deprecation import deprecate_kwarg
+from .configuration_xlm_prophetnet import XLMProphetNetConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+_CONFIG_FOR_DOC = "XLMProphetNetConfig"
+
+
+XLM_PROPHETNET_START_DOCSTRING = r"""
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ Original ProphetNet code can be found [here](https://github.com/microsoft/ProphetNet). Checkpoints were converted
+ from original Fairseq checkpoints. For more information on the checkpoint conversion, please take a look at the
+ file `convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py`.
+
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matters related to general usage and
+ behavior.
+
+ Parameters:
+ config ([`XLMProphetNetConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+XLM_PROPHETNET_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
+ it.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Indices of decoder input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
+
+ XLMProphetNet uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
+ `past_key_values`).
+
+ decoder_attention_mask (`torch.BoolTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
+ be used by default.
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+XLM_PROPHETNET_STANDALONE_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
+ it.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+def softmax(hidden_state, dim, onnx_trace=False):
+ if onnx_trace:
+ return nn.functional.softmax(hidden_state.float(), dim=dim)
+ else:
+ return nn.functional.softmax(hidden_state, dim=dim, dtype=torch.float32)
+
+
+def ngram_attention_bias(sequence_length, ngram, device, dtype):
+ """
+ This function computes the bias for the predict stream
+ """
+ left_block = (
+ torch.ones((ngram, sequence_length, sequence_length), device=device, dtype=dtype) * torch.finfo(dtype).min
+ )
+ right_block = left_block.detach().clone()
+ # create bias
+ for stream_idx in range(ngram):
+ right_block[stream_idx].fill_diagonal_(0, wrap=False)
+ left_block[stream_idx].triu_(-stream_idx + 1)
+
+ left_block[:, :, 0] = 0
+ return torch.cat([left_block, right_block], dim=2)
+
+
+def compute_relative_buckets(num_buckets, max_distance, relative_positions, is_bidirectional=False):
+ """
+ This function computes individual parts of the relative position buckets. For more detail, see paper.
+ """
+ inv_relative_positions = -relative_positions
+ rel_positions_bucket = 0
+
+ if is_bidirectional:
+ num_buckets = num_buckets // 2
+ rel_positions_bucket = (
+ rel_positions_bucket
+ + torch.lt(inv_relative_positions, torch.zeros_like(inv_relative_positions)).int() * num_buckets
+ )
+ inv_relative_positions = torch.abs(inv_relative_positions)
+ else:
+ inv_relative_positions = torch.max(inv_relative_positions, torch.zeros_like(inv_relative_positions))
+
+ max_exact = num_buckets // 2
+ is_small = torch.lt(inv_relative_positions, max_exact)
+ val_if_large = max_exact + torch.log(inv_relative_positions.float() / max_exact) / math.log(
+ max_distance / max_exact
+ ) * (num_buckets - max_exact)
+ val_if_large = torch.min(val_if_large, torch.ones_like(val_if_large) * (num_buckets - 1)).int()
+ rel_positions_bucket = rel_positions_bucket + torch.where(is_small, inv_relative_positions.int(), val_if_large)
+ return rel_positions_bucket
+
+
+def compute_all_stream_relative_buckets(num_buckets, max_distance, position_ids):
+ """
+ This function computes both main and predict relative position buckets. For more detail, see paper.
+ """
+ # main stream
+ main_stream_relative_positions = position_ids.unsqueeze(1).repeat(1, position_ids.size(-1), 1)
+ main_stream_relative_positions = main_stream_relative_positions - position_ids.unsqueeze(-1)
+
+ # predicting stream
+ predicting_stream_relative_positions = torch.cat((position_ids - 1, position_ids), dim=-1).unsqueeze(1)
+ predicting_stream_relative_positions = predicting_stream_relative_positions.repeat(1, position_ids.size(-1), 1)
+ predicting_stream_relative_positions = predicting_stream_relative_positions - position_ids.unsqueeze(-1)
+
+ # get both position buckets
+ main_relative_position_buckets = compute_relative_buckets(
+ num_buckets, max_distance, main_stream_relative_positions, is_bidirectional=False
+ )
+ predict_relative_position_buckets = compute_relative_buckets(
+ num_buckets, max_distance, predicting_stream_relative_positions, is_bidirectional=False
+ )
+ return main_relative_position_buckets, predict_relative_position_buckets
+
+
+@dataclass
+class XLMProphetNetSeq2SeqLMOutput(ModelOutput):
+ """
+ Base class for sequence-to-sequence language models outputs.
+
+ Args:
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, decoder_sequence_length, config.vocab_size)`):
+ Prediction scores of the main stream language modeling head (scores for each vocabulary token before
+ SoftMax).
+ logits_ngram (`torch.FloatTensor` of shape `(batch_size, ngram * decoder_sequence_length, config.vocab_size)`):
+ Prediction scores of the predict stream language modeling head (scores for each vocabulary token before
+ SoftMax).
+ past_key_values (`list[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
+ num_attn_heads, decoder_sequence_length, embed_size_per_head)`).
+
+ Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
+ used (see `past_key_values` input) to speed up sequential decoding.
+ decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, decoder_sequence_length, hidden_size)`.
+
+ Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
+ decoder_ngram_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, ngram * decoder_sequence_length, hidden_size)`.
+
+ Hidden-states of the predict stream of the decoder at the output of each layer plus the initial embedding
+ outputs.
+ decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ decoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
+ self-attention heads.
+ decoder_ngram_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ decoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the predict stream of the decoder, after the attention softmax, used to compute the
+ weighted average in the self-attention heads.
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ encoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to
+ compute the weighted average in the
+ encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder of the model.
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, encoder_sequence_length, hidden_size)`.
+
+ Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ encoder_sequence_length, encoder_sequence_length)`. Attentions weights of the encoder, after the attention
+ softmax, used to compute the weighted average in the self-attention heads.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ logits_ngram: Optional[torch.FloatTensor] = None
+ past_key_values: Optional[tuple[torch.FloatTensor]] = None
+ decoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ decoder_ngram_hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ decoder_attentions: Optional[tuple[torch.FloatTensor]] = None
+ decoder_ngram_attentions: Optional[tuple[torch.FloatTensor]] = None
+ cross_attentions: Optional[tuple[torch.FloatTensor]] = None
+ encoder_last_hidden_state: Optional[torch.FloatTensor] = None
+ encoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ encoder_attentions: Optional[tuple[torch.FloatTensor]] = None
+
+ @property
+ def decoder_cross_attentions(self):
+ warnings.warn(
+ "`decoder_cross_attentions` is deprecated and will be removed soon. Please use `cross_attentions`"
+ " instead.",
+ FutureWarning,
+ )
+ return self.cross_attentions
+
+
+@dataclass
+class XLMProphetNetSeq2SeqModelOutput(ModelOutput):
+ """
+ Base class for model encoder's outputs that also contains : pre-computed hidden states that can speed up sequential
+ decoding.
+
+ Args:
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, decoder_sequence_length, hidden_size)`):
+ Sequence of main stream hidden-states at the output of the last layer of the decoder of the model.
+
+ If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
+ hidden_size)` is output.
+ last_hidden_state_ngram (`torch.FloatTensor` of shape `(batch_size,ngram * decoder_sequence_length, config.vocab_size)`, *optional*):
+ Sequence of predict stream hidden-states at the output of the last layer of the decoder of the model.
+ past_key_values (`list[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
+ num_attn_heads, decoder_sequence_length, embed_size_per_head)`).
+
+ Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
+ used (see `past_key_values` input) to speed up sequential decoding.
+ decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, decoder_sequence_length, hidden_size)`.
+
+ Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
+ decoder_ngram_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, ngram * decoder_sequence_length, hidden_size)`.
+
+ Hidden-states of the predict stream of the decoder at the output of each layer plus the initial embedding
+ outputs.
+ decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ decoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
+ self-attention heads.
+ decoder_ngram_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ decoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the predict stream of the decoder, after the attention softmax, used to compute the
+ weighted average in the
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ encoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to
+ compute the weighted average in the
+ encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder of the model.
+ encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, encoder_sequence_length, hidden_size)`.
+
+ Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
+ encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ encoder_sequence_length, encoder_sequence_length)`.
+
+ Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
+ self-attention heads.
+ """
+
+ last_hidden_state: torch.FloatTensor
+ last_hidden_state_ngram: Optional[torch.FloatTensor] = None
+ past_key_values: Optional[tuple[torch.FloatTensor]] = None
+ decoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ decoder_ngram_hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ decoder_attentions: Optional[tuple[torch.FloatTensor]] = None
+ decoder_ngram_attentions: Optional[tuple[torch.FloatTensor]] = None
+ cross_attentions: Optional[tuple[torch.FloatTensor]] = None
+ encoder_last_hidden_state: Optional[torch.FloatTensor] = None
+ encoder_hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ encoder_attentions: Optional[tuple[torch.FloatTensor]] = None
+
+ @property
+ def decoder_cross_attentions(self):
+ warnings.warn(
+ "`decoder_cross_attentions` is deprecated and will be removed soon. Please use `cross_attentions`"
+ " instead.",
+ FutureWarning,
+ )
+ return self.cross_attentions
+
+
+@dataclass
+class XLMProphetNetDecoderModelOutput(ModelOutput):
+ """
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
+
+ Args:
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, decoder_sequence_length, hidden_size)`):
+ Sequence of main stream hidden-states at the output of the last layer of the decoder of the model.
+
+ If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
+ hidden_size)` is output.
+ last_hidden_state_ngram (`torch.FloatTensor` of shape `(batch_size, ngram * decoder_sequence_length, config.vocab_size)`):
+ Sequence of predict stream hidden-states at the output of the last layer of the decoder of the model.
+ past_key_values (`list[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
+ num_attn_heads, decoder_sequence_length, embed_size_per_head)`).
+
+ Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
+ used (see `past_key_values` input) to speed up sequential decoding.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, decoder_sequence_length, hidden_size)`.
+
+ Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
+ ngram_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, ngram * decoder_sequence_length, hidden_size)`.
+
+ Hidden-states of the predict stream of the decoder at the output of each layer plus the initial embedding
+ outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ decoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
+ self-attention heads.
+ ngram_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ decoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the predict stream of the decoder, after the attention softmax, used to compute the
+ weighted average in the
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ encoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to
+ compute the weighted average in the
+ """
+
+ last_hidden_state: torch.FloatTensor
+ last_hidden_state_ngram: Optional[torch.FloatTensor] = None
+ past_key_values: Optional[tuple[torch.FloatTensor]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ hidden_states_ngram: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+ ngram_attentions: Optional[tuple[torch.FloatTensor]] = None
+ cross_attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+@dataclass
+class XLMProphetNetDecoderLMOutput(ModelOutput):
+ """
+ Base class for model's outputs that may also contain a past key/values (to speed up sequential decoding).
+
+ Args:
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, decoder_sequence_length, config.vocab_size)`):
+ Prediction scores of the main stream language modeling head (scores for each vocabulary token before
+ SoftMax).
+ logits_ngram (`torch.FloatTensor` of shape `(batch_size, ngram * decoder_sequence_length, config.vocab_size)`):
+ Prediction scores of the predict stream language modeling head (scores for each vocabulary token before
+ SoftMax).
+ past_key_values (`list[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
+ List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
+ num_attn_heads, decoder_sequence_length, embed_size_per_head)`).
+
+ Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
+ used (see `past_key_values` input) to speed up sequential decoding.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, decoder_sequence_length, hidden_size)`.
+
+ Hidden-states of main stream of the decoder at the output of each layer plus the initial embedding outputs.
+ ngram_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
+ shape `(batch_size, ngram * decoder_sequence_length, hidden_size)`.
+
+ Hidden-states of the predict stream of the decoder at the output of each layer plus the initial embedding
+ outputs.
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ decoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
+ self-attention heads.
+ ngram_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ decoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the predict stream of the decoder, after the attention softmax, used to compute the
+ weighted average in the
+ cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_attn_heads,
+ encoder_sequence_length, decoder_sequence_length)`.
+
+ Attentions weights of the cross-attention layer of the decoder, after the attention softmax, used to
+ compute the weighted average in the
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ logits_ngram: Optional[torch.FloatTensor] = None
+ past_key_values: Optional[tuple[torch.FloatTensor]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ hidden_states_ngram: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+ ngram_attentions: Optional[tuple[torch.FloatTensor]] = None
+ cross_attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+class XLMProphetNetPreTrainedModel(PreTrainedModel):
+ config: XLMProphetNetConfig
+ base_model_prefix = "prophetnet"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=self.config.init_std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.init_std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+
+ def _shift_right(self, input_ids):
+ decoder_start_token_id = self.config.decoder_start_token_id
+ pad_token_id = self.config.pad_token_id
+
+ assert decoder_start_token_id is not None, (
+ "self.model.config.decoder_start_token_id has to be defined. In XLMProphetNet it is usually set to the"
+ " pad_token_id. See XLMProphetNet docs for more information"
+ )
+
+ # shift inputs to the right
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
+ shifted_input_ids[..., 1:] = input_ids[..., :-1].clone()
+ shifted_input_ids[..., 0] = decoder_start_token_id
+
+ assert pad_token_id is not None, "self.model.config.pad_token_id has to be defined."
+ # replace possible -100 values in labels by `pad_token_id`
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
+
+ assert torch.all(shifted_input_ids >= 0).item(), "Verify that `shifted_input_ids` has only positive values"
+
+ return shifted_input_ids
+
+
+class XLMProphetNetPositionalEmbeddings(nn.Embedding):
+ """
+ This module learns positional embeddings up to a fixed maximum size. Padding ids are ignored by either offsetting
+ based on padding_idx or by setting padding_idx to None and ensuring that the appropriate position ids are passed to
+ the forward function.
+ """
+
+ def __init__(self, config: XLMProphetNetConfig) -> None:
+ self.max_length = config.max_position_embeddings
+ super().__init__(config.max_position_embeddings, config.hidden_size, config.pad_token_id)
+
+ def forward(self, inputs_shape, device, attention_mask=None, past_key_values=None, position_ids=None):
+ assert (position_ids is None) or (self.padding_idx is None), (
+ "If position_ids is pre-computed then padding_idx should not be set."
+ )
+
+ if position_ids is None:
+ if past_key_values is not None:
+ # position_ids is the same for every token when decoding a single step
+ # Without the int() cast, it doesn't work in some cases when exporting to ONNX
+ prev_num_input_ids = past_key_values.get_seq_length()
+ num_input_ids = inputs_shape[1] + prev_num_input_ids
+ position_ids = torch.ones((1, 1), dtype=torch.long, device=device) * (
+ int(self.padding_idx + num_input_ids)
+ )
+ else:
+ if attention_mask is None:
+ attention_mask = torch.ones(inputs_shape, dtype=torch.long, device=device)
+
+ # retrieve position_ids from input_ids / attention_mask
+ position_ids = (
+ torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask
+ ).long() + self.padding_idx
+
+ # make sure position_ids are not bigger then max_length
+ position_ids = position_ids.clamp(0, self.max_length - 1)
+
+ return super().forward(position_ids), position_ids
+
+ def _forward(self, position_ids):
+ return super().forward(position_ids)
+
+
+class XLMProphetNetAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ config: XLMProphetNetConfig,
+ num_attn_heads: int,
+ ):
+ super().__init__()
+ hidden_size = config.hidden_size
+
+ self.attention_dropout = config.attention_dropout
+ self.dropout = config.dropout
+ self.num_attn_heads = num_attn_heads
+ self.head_dim = hidden_size // num_attn_heads
+
+ assert self.head_dim * num_attn_heads == hidden_size, (
+ "`config.hidden_size` must be divisible by `config.num_encoder_attention_heads` and"
+ " `config.num_decoder_attention_heads`"
+ )
+
+ self.key_proj = nn.Linear(hidden_size, hidden_size)
+ self.value_proj = nn.Linear(hidden_size, hidden_size)
+ self.query_proj = nn.Linear(hidden_size, hidden_size)
+
+ self.out_proj = nn.Linear(hidden_size, hidden_size)
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
+ return tensor.view(bsz, seq_len, self.num_attn_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states,
+ key_value_states: Optional[Tensor] = None,
+ attention_mask: Optional[Tensor] = None,
+ layer_head_mask: Optional[Tensor] = None,
+ past_key_values: Optional[tuple[Tensor]] = None,
+ output_attentions: bool = False,
+ ) -> tuple[Tensor, Optional[Tensor]]:
+ batch_size, tgt_len, hidden_size = hidden_states.size()
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+ assert list(hidden_states.size()) == [
+ batch_size,
+ tgt_len,
+ hidden_size,
+ ], f"Size of hidden states should be {batch_size, tgt_len, hidden_size}, but is {hidden_states.size()}"
+
+ # previous time steps are cached - no need to recompute key and value if they are static
+ query_states = self.query_proj(hidden_states) / (self.head_dim**0.5)
+
+ if is_cross_attention and past_key_values is not None:
+ # reuse k,v, cross_attentions
+ key_states = past_key_values[0]
+ value_states = past_key_values[1]
+ elif is_cross_attention:
+ # cross_attentions
+ key_states = self._shape(self.key_proj(key_value_states), -1, batch_size)
+ value_states = self._shape(self.value_proj(key_value_states), -1, batch_size)
+ else:
+ # self_attention
+ key_states = self._shape(self.key_proj(hidden_states), -1, batch_size)
+ value_states = self._shape(self.value_proj(hidden_states), -1, batch_size)
+
+ if is_cross_attention:
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
+ # Further calls to cross_attention layer can then reuse all cross-attention
+ # key/value_states (first "if" case)
+ # if encoder bi-directional self-attention `past_key_values` is always `None`
+ past_key_values = (key_states, value_states)
+
+ # project states into the correct shape
+ proj_shape = (batch_size, self.num_attn_heads, -1, self.head_dim)
+ query_states = self._shape(query_states, tgt_len, batch_size).view(*proj_shape)
+ key_states = key_states.view(*proj_shape)
+ value_states = value_states.view(*proj_shape)
+ src_len = key_states.size(2)
+ attn_weights = torch.einsum("bsij,bsjk->bsik", query_states, key_states.transpose(2, 3))
+ expected_shape = (batch_size, self.num_attn_heads, tgt_len, src_len)
+ if attn_weights.size() != expected_shape:
+ raise ValueError(f"Attention weights should have size {expected_shape}, but is {attn_weights.size()}")
+
+ # This is part of a workaround to get around fork/join parallelism not supporting Optional types.
+ if attention_mask is not None and attention_mask.dim() == 0:
+ attention_mask = None
+
+ expected_shape = (batch_size, self.num_attn_heads, 1, src_len)
+ if attention_mask is not None and attention_mask.size() != expected_shape:
+ raise ValueError(f"Attention mask should have size {expected_shape}, but is {attention_mask.size()}")
+ if attention_mask is not None: # don't attend to padding symbols
+ attn_weights = attn_weights + attention_mask
+ if output_attentions:
+ attn_weights_reshaped = attn_weights
+ else:
+ attn_weights_reshaped = None
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ if layer_head_mask is not None:
+ assert layer_head_mask.size() == (self.num_attn_heads,), (
+ f"Head mask for a single layer should be of size {(self.num_attn_heads,)}, but is"
+ f" {layer_head_mask.size()}"
+ )
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(
+ batch_size, self.num_attn_heads, tgt_len, src_len
+ )
+
+ # apply head_mask also on attn_weights_reshaped which is used for n-gram attention inside the model
+ attn_weights_reshaped = layer_head_mask.view(1, -1, 1, 1) * attn_weights_reshaped
+
+ attn_probs = nn.functional.dropout(
+ attn_weights,
+ p=self.attention_dropout,
+ training=self.training,
+ )
+ attn_output = torch.einsum("bsij,bsjk->bsik", attn_probs, value_states)
+ expected_shape = (batch_size, self.num_attn_heads, tgt_len, self.head_dim)
+ if attn_output.size() != expected_shape:
+ raise ValueError(f"`attn_output` should have shape {expected_shape}, but is of shape {attn_output.size()}")
+
+ attn_output = attn_output.transpose(1, 2).reshape(batch_size, tgt_len, hidden_size)
+ attn_output = self.out_proj(attn_output)
+
+ attn_output = nn.functional.dropout(attn_output, p=self.dropout, training=self.training)
+ return attn_output, attn_weights_reshaped, past_key_values
+
+
+class XLMProphetNetFeedForward(nn.Module):
+ """
+ This is the residual two feed-forward layer block based on the original Transformer implementation.
+ """
+
+ def __init__(self, config: XLMProphetNetConfig, ffn_dim: int):
+ super().__init__()
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.intermediate = nn.Linear(config.hidden_size, ffn_dim)
+ self.output = nn.Linear(ffn_dim, config.hidden_size)
+ self.activation_dropout = config.activation_dropout
+ self.dropout = config.dropout
+
+ def forward(self, hidden_states):
+ hidden_states = self.intermediate(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.output(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ return hidden_states
+
+
+class XLMProphetNetNgramSelfAttention(nn.Module):
+ def __init__(self, config: XLMProphetNetConfig):
+ super().__init__()
+ self.hidden_size = config.hidden_size
+
+ self.num_buckets = config.num_buckets
+ self.relative_max_distance = config.relative_max_distance
+ self.num_attn_heads = config.num_decoder_attention_heads
+ self.dropout = config.dropout
+ self.attention_dropout = config.attention_dropout
+ self.head_dim = config.hidden_size // self.num_attn_heads
+ self.ngram = config.ngram
+
+ assert self.head_dim * self.num_attn_heads == config.hidden_size, (
+ "config.hidden_size must be divisible by num_attn_heads"
+ )
+ # key, value, query projection
+ self.key_proj = nn.Linear(config.hidden_size, config.hidden_size)
+ self.value_proj = nn.Linear(config.hidden_size, config.hidden_size)
+ self.query_proj = nn.Linear(config.hidden_size, config.hidden_size)
+
+ # out projection
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size)
+
+ # rel position embeddings
+ self.relative_pos_embeddings = nn.Linear(config.hidden_size, self.num_buckets * self.num_attn_heads)
+
+ # for onnx runtime
+ self.onnx_trace = False
+
+ def _shape(self, tensor, seq_len, batch_size):
+ return tensor.view(batch_size, seq_len, self.num_attn_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ def prepare_for_onnx_export_(self):
+ self.onnx_trace = True
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states,
+ past_key_values: Optional[tuple[Tensor]] = None,
+ attention_mask=None,
+ layer_head_mask=None,
+ extended_predict_attention_mask=None,
+ main_relative_position_buckets=None,
+ predict_relative_position_buckets=None,
+ position_ids=None,
+ ):
+ batch_size, ngram_sequence_length, hidden_size = hidden_states.size()
+ assert list(hidden_states.size()) == [batch_size, ngram_sequence_length, hidden_size], (
+ f"`hidden_states` should be of shape {batch_size, ngram_sequence_length, hidden_size}, but is of shape"
+ f" {hidden_states.shape}"
+ )
+
+ # project
+ query_states = self.query_proj(hidden_states)
+ key_states = self.key_proj(hidden_states)
+ value_states = self.value_proj(hidden_states)
+
+ # normalize
+ query_states = query_states / (self.head_dim**0.5)
+
+ # reshape
+ query_states = self._shape(query_states, ngram_sequence_length, batch_size)
+ key_states = self._shape(key_states, -1, batch_size)
+ value_states = self._shape(value_states, -1, batch_size)
+ proj_shape = (batch_size, self.num_attn_heads, -1, self.head_dim)
+
+ query_states = query_states.view(*proj_shape)
+ key_states = key_states.view(*proj_shape)
+ value_states = value_states.view(*proj_shape)
+
+ # chunk into main stream and predict stream
+ hidden_states_list = hidden_states.chunk(1 + self.ngram, dim=1)
+ query_states_list = query_states.chunk(1 + self.ngram, dim=2)
+ key_states_list = key_states.chunk(1 + self.ngram, dim=2)
+ value_states_list = value_states.chunk(1 + self.ngram, dim=2)
+
+ main_hidden_states, hidden_states_predict_list = hidden_states_list[0], hidden_states_list[1:]
+ main_query_states, predict_query_states_list = query_states_list[0], query_states_list[1:]
+ main_key_states, predict_key_states_list = key_states_list[0], key_states_list[1:]
+ main_value_states, predict_value_states_list = value_states_list[0], value_states_list[1:]
+
+ # saved states are stored with shape (batch_size, num_attn_heads, seq_len, head_dim)
+ if past_key_values is not None:
+ prev_main_key_states = past_key_values[0]
+ main_key_states = torch.cat((prev_main_key_states, main_key_states), dim=2)
+ prev_main_value_states = past_key_values[1]
+ main_value_states = torch.cat((prev_main_value_states, main_value_states), dim=2)
+
+ # Update cache
+ past_key_values = (main_key_states, main_value_states)
+
+ # get seq_length of main stream only
+ sequence_length = ngram_sequence_length // (1 + self.ngram)
+
+ # MAIN-STREAM
+ # main attn weights
+ # [batch_size, number_heads, sequence_length, head_dimesion]
+ # x [batch_size, number_heads, head_dimesion, sequence_length]
+ # -> [batch_size, number_heads, sequence_length, sequence_length]
+ main_attn_weights = torch.einsum("bntc,bncs->bnts", main_query_states, main_key_states.transpose(2, 3))
+
+ # retrieve relative position embeddings for each layer -> see paper for more details
+ main_relative_pos_embeddings = self.get_main_relative_pos_embeddings(
+ main_hidden_states, main_attn_weights, position_ids, main_relative_position_buckets
+ )
+
+ main_attn_weights = main_attn_weights + main_relative_pos_embeddings
+
+ if attention_mask is not None:
+ main_attn_weights = main_attn_weights + attention_mask
+
+ main_attn_probs = softmax(
+ main_attn_weights,
+ dim=-1,
+ onnx_trace=self.onnx_trace,
+ ).type_as(main_attn_weights)
+
+ if layer_head_mask is not None:
+ assert layer_head_mask.size() == (self.num_attn_heads,), (
+ f"Head mask for a single layer should be of size {(self.num_attn_heads,)}, but is"
+ f" {layer_head_mask.size()}"
+ )
+ main_attn_probs = layer_head_mask.view(1, -1, 1, 1) * main_attn_probs.view(
+ batch_size, self.num_attn_heads, -1, sequence_length
+ )
+
+ main_attn_probs = nn.functional.dropout(main_attn_probs, p=self.attention_dropout, training=self.training)
+ # project to attn_output
+ # [batch_size, number_heads, sequence_length, sequence_length]
+ # x [batch_size, number_heads, sequence_length, head_dimesion]
+ # -> [batch_size, number_heads, sequence_length, head_dimesion]
+ main_attn_output = torch.einsum("bntc,bncs->bnts", main_attn_probs, main_value_states)
+ # reshape so that num_heads dim is merged into last `head_dim` axis
+ main_attn_output = main_attn_output.transpose(1, 2).reshape(batch_size, 1, sequence_length, hidden_size)
+ main_attn_output = self.out_proj(main_attn_output)
+
+ # PREDICT-STREAM
+ # [batch_size, ngram, number_heads, sequence_length, head_dimesion]
+ predict_query_states = torch.stack(predict_query_states_list, 1).view(
+ batch_size, self.ngram, self.num_attn_heads, sequence_length, self.head_dim
+ )
+
+ # [batch_size, ngram, number_heads, 2*sequence_length, head_dimesion]
+ predict_key_states = torch.stack([torch.cat([main_key_states, key], 2) for key in predict_key_states_list], 1)
+
+ # [batch_size, sequence_length, ngram, hidden_size]
+ predict_hidden_states = torch.stack(hidden_states_predict_list, dim=2)
+
+ # [batch_size, number_heads, ngram, 2*sequence_length, head_dimesion]
+ predict_value_states = torch.cat(
+ [torch.cat([main_value_states, v_p], 2).unsqueeze(2) for v_p in predict_value_states_list], 2
+ )
+
+ # [batch_size, ngram, number_heads, sequence_length, head_dimesion]
+ # x [batch_size, ngram, number_heads, 2*sequence_length, head_dimesion]
+ # -> [batch_size, ngram, number_heads, sequence_length, 2*sequence_length]
+ predict_attn_weights = torch.einsum("bnhtc,bnhsc->bnhts", (predict_query_states, predict_key_states))
+
+ # retrieve relative position embeddings for each layer -> see paper for more details
+ # [batch_size, ngram, number_heads, sequence_length, predict_relative_pos_embeddings]
+ predict_relative_pos_embeddings = self.get_predict_relative_pos_embeddings(
+ predict_hidden_states, predict_attn_weights, position_ids, predict_relative_position_buckets
+ )
+
+ # [batch_size, ngram, number_heads, sequence_length, 2*sequence_length]
+ predict_attn_weights = predict_attn_weights + predict_relative_pos_embeddings
+
+ if extended_predict_attention_mask is not None:
+ # Permuting Predict attention mask to [batch_size, ngram, number_heads, sequence_length, 2*sequence_length]
+ extended_predict_attention_mask = extended_predict_attention_mask.permute(0, 2, 1, 3, 4)
+ extended_predict_attention_mask = extended_predict_attention_mask.to(predict_attn_weights.dtype)
+ predict_attn_weights = predict_attn_weights + extended_predict_attention_mask
+
+ predict_attn_probs = softmax(
+ predict_attn_weights,
+ dim=-1,
+ onnx_trace=self.onnx_trace,
+ ).type_as(predict_attn_weights)
+
+ if layer_head_mask is not None:
+ assert layer_head_mask.size() == (self.num_attn_heads,), (
+ f"Head mask for a single layer should be of size {(self.num_attn_heads,)}, but is"
+ f" {layer_head_mask.size()}"
+ )
+ predict_attn_probs = layer_head_mask.view(1, 1, -1, 1, 1) * predict_attn_probs
+
+ predict_attn_probs = nn.functional.dropout(
+ predict_attn_probs, p=self.attention_dropout, training=self.training
+ )
+ # project to attention output
+ # [batch_size, ngram, number_heads, sequence_length, 2*sequence_length]
+ # x [batch_size, ngram, number_heads, 2*sequence_length, head_dimesion]
+ # -> [batch_size, ngram, number_heads, sequence_length, head_dimesion]
+ predict_attn_output = torch.einsum(
+ "bnhts,bnhsc->bnhtc", (predict_attn_probs, predict_value_states.transpose(1, 2))
+ )
+
+ # reshape so that num_heads dim is merged into last `head_dim` axis
+ # [batch_size, ngram, number_heads, sequence_length, head_dimesion] -> [batch_size, ngram, sequence_length, hidden_size]
+ predict_attn_output = predict_attn_output.transpose(2, 3)
+ predict_attn_output = predict_attn_output.reshape(batch_size, self.ngram, sequence_length, hidden_size)
+ predict_attn_output = self.out_proj(predict_attn_output)
+
+ # concat to single attn output
+ # [batch_size, (1+ngram)*sequence_length, hidden_size]
+ attn_output = torch.cat([main_attn_output, predict_attn_output], 1).view(batch_size, -1, hidden_size)
+ # reshape into better form for `config.output_attentions`
+ main_attn_probs = main_attn_probs.view(batch_size, self.num_attn_heads, sequence_length, -1)
+
+ attn_output = nn.functional.dropout(attn_output, p=self.dropout, training=self.training)
+
+ return attn_output, main_attn_probs, predict_attn_probs, past_key_values
+
+ def get_main_relative_pos_embeddings(
+ self, hidden_states, attn_weights, position_ids, main_relative_position_buckets
+ ):
+ # input hidden_states [batch_size, sequence_length, hidden_size]
+ # input attn_weights [batch_size, num_heads, sequence_length, sequence_length]
+ # input position_ids [batch_size, sequence_length] or [1,1]
+ batch_size, num_attn_heads, tgt_len, src_len = attn_weights.shape
+ attn_weights = attn_weights.view(batch_size, num_attn_heads, tgt_len, src_len)
+ if main_relative_position_buckets is None:
+ batch_size, sequence_length = hidden_states.shape[:2]
+ relative_positions = (
+ torch.arange(1, attn_weights.shape[-1] + 1)
+ .unsqueeze(0)
+ .unsqueeze(0)
+ .repeat(batch_size, sequence_length, 1)
+ .to(position_ids.device)
+ )
+ # [batch_size, sequence_length, sequence_length+1]
+ relative_positions = relative_positions - position_ids.unsqueeze(0).repeat(batch_size, sequence_length, 1)
+ main_relative_position_buckets = compute_relative_buckets(
+ self.num_buckets, self.relative_max_distance, relative_positions, False
+ )
+
+ # [batch_size, sequence_length, num_buckets * num_heads]
+ rel_pos_embeddings = self.relative_pos_embeddings(hidden_states)
+ rel_pos_embeddings = rel_pos_embeddings.view(
+ rel_pos_embeddings.shape[:2] + (self.num_buckets, self.num_attn_heads)
+ )
+ rel_pos_embeddings = rel_pos_embeddings.permute(0, 3, 1, 2)
+ # [batch_size, num_heads, sequence_length, num_buckets]
+ rel_pos_embeddings = rel_pos_embeddings.reshape(attn_weights.shape[:3] + (-1,))
+
+ main_relative_position_buckets = main_relative_position_buckets.repeat(1, self.num_attn_heads, 1)
+ # [batch_size * num_heads * sequence_length, sequence_length]
+ main_relative_position_buckets = main_relative_position_buckets.view(
+ -1, main_relative_position_buckets.shape[-1]
+ )
+ main_relative_position_buckets = main_relative_position_buckets.long()
+ # [batch_size * num_heads * sequence_length, sequence_length]
+ rel_pos_embeddings = rel_pos_embeddings.reshape(-1, rel_pos_embeddings.size(-1))
+
+ main_relative_pos_embeddings = torch.gather(rel_pos_embeddings, dim=1, index=main_relative_position_buckets)
+ main_relative_pos_embeddings = main_relative_pos_embeddings.view(batch_size, num_attn_heads, tgt_len, -1)
+ return main_relative_pos_embeddings
+
+ def get_predict_relative_pos_embeddings(
+ self, hidden_states, attn_weights, position_ids, predict_relative_position_buckets
+ ):
+ # input hidden_states [batch_size, sequence_length, ngram, hidden_size]
+ # input attn_weights [batch_size, ngram, num_heads, sequence_length, 2*sequence_length]
+ # input position_ids [batch_size, sequence_length] or [1,1]
+ # input predict_relative_position_buckets [batch_size, sequence_length, 2*sequence_length] or None
+ batch_size, sequence_length = hidden_states.shape[0:2]
+
+ if predict_relative_position_buckets is None:
+ key_sequence_length = attn_weights.shape[-1]
+ assert position_ids[0][0] == key_sequence_length - 1, (
+ "`position_ids` are incorrect. They should be of the format 1 2 3 4 5 ... (key_sequence_length - 1)"
+ )
+ relative_positions = (
+ torch.arange(0, key_sequence_length)
+ .unsqueeze(0)
+ .unsqueeze(0)
+ .repeat(batch_size, sequence_length, 1)
+ .to(position_ids.device)
+ )
+
+ relative_positions = relative_positions - position_ids.unsqueeze(0).repeat(batch_size, sequence_length, 1)
+ predict_relative_position_buckets = compute_relative_buckets(
+ self.num_buckets, self.relative_max_distance, relative_positions, False
+ )
+
+ # [batch_size, ngram, sequence_length, hidden_size]
+ hidden_states = hidden_states.transpose(1, 2)
+ rel_pos_embeddings = self.relative_pos_embeddings(hidden_states)
+
+ # [batch_size, ngram, sequence_length, num_buckets, num_heads]
+ rel_pos_embeddings = rel_pos_embeddings.view(
+ hidden_states.shape[:-1] + (self.num_buckets, self.num_attn_heads)
+ )
+ rel_pos_embeddings = rel_pos_embeddings.permute(0, 2, 1, 4, 3)
+ # [batch_size * ngram * sequence_length * num_heads, num_buckets]
+ rel_pos_embeddings = rel_pos_embeddings.reshape(-1, self.num_buckets)
+ # [ngram, batch_size, num_heads * sequence_length, -1]
+ predict_relative_position_buckets = predict_relative_position_buckets.unsqueeze(0)
+ predict_relative_position_buckets = predict_relative_position_buckets.repeat(
+ self.ngram, 1, self.num_attn_heads, 1
+ )
+ # [ngram * batch_size * num_heads * sequence_length, -1]
+ predict_relative_position_buckets = predict_relative_position_buckets.view(
+ -1, predict_relative_position_buckets.size(-1)
+ ).long()
+
+ predict_relative_pos_embeddings = torch.gather(
+ rel_pos_embeddings, dim=1, index=predict_relative_position_buckets
+ )
+
+ # [batch_size, gram, num_heads, sequence_length, -1]
+ predict_relative_pos_embeddings = predict_relative_pos_embeddings.view(
+ batch_size, self.ngram, self.num_attn_heads, sequence_length, -1
+ )
+
+ return predict_relative_pos_embeddings
+
+
+class XLMProphetNetEncoderLayer(GradientCheckpointingLayer):
+ """
+ Encoder block for XLMProphetnet
+ """
+
+ def __init__(self, config: XLMProphetNetConfig):
+ super().__init__()
+ # 1st residual block
+ self.self_attn = XLMProphetNetAttention(config, config.num_encoder_attention_heads)
+ self.self_attn_layer_norm = LayerNorm(config.hidden_size)
+
+ # 2nd residual block
+ self.feed_forward = XLMProphetNetFeedForward(config, config.encoder_ffn_dim)
+ self.feed_forward_layer_norm = LayerNorm(config.hidden_size)
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ output_attentions: bool = False,
+ ):
+ # 1st residual block
+ attention_output, attn_weights, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ layer_head_mask=layer_head_mask,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self.self_attn_layer_norm(attention_output + hidden_states)
+
+ # 2nd residual block
+ feed_forward_output = self.feed_forward(hidden_states)
+ hidden_states = self.feed_forward_layer_norm(feed_forward_output + hidden_states)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (attn_weights,)
+
+ return outputs
+
+
+class XLMProphetNetDecoderLayer(GradientCheckpointingLayer):
+ """
+ Decoder block for XLMProphetnet
+ """
+
+ def __init__(self, config: XLMProphetNetConfig):
+ super().__init__()
+ # 1st residual block
+ self.self_attn = XLMProphetNetNgramSelfAttention(config)
+ self.self_attn_layer_norm = LayerNorm(config.hidden_size)
+
+ # 2nd residual block
+ if config.add_cross_attention:
+ self.cross_attn = XLMProphetNetAttention(config, config.num_decoder_attention_heads)
+ self.cross_attn_layer_norm = LayerNorm(config.hidden_size)
+
+ # 3rd residual block
+ self.feed_forward = XLMProphetNetFeedForward(config, config.decoder_ffn_dim)
+ self.feed_forward_layer_norm = LayerNorm(config.hidden_size)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ encoder_hidden_states=None,
+ encoder_attn_mask=None,
+ layer_head_mask=None,
+ cross_attn_layer_head_mask=None,
+ extended_predict_attention_mask=None,
+ main_relative_position_buckets=None,
+ predict_relative_position_buckets=None,
+ position_ids=None,
+ past_key_values=None,
+ use_cache: bool = True,
+ output_attentions: bool = False,
+ ):
+ # 1st residual block
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
+ self_attn_past_key_value = past_key_values[:2] if past_key_values is not None else None
+ ngram_attention_output, self_attn_weights, self_attn_weights_ngram, present_key_value = self.self_attn(
+ hidden_states=hidden_states,
+ past_key_values=self_attn_past_key_value,
+ attention_mask=attention_mask,
+ layer_head_mask=layer_head_mask,
+ extended_predict_attention_mask=extended_predict_attention_mask,
+ main_relative_position_buckets=main_relative_position_buckets,
+ predict_relative_position_buckets=predict_relative_position_buckets,
+ position_ids=position_ids,
+ )
+ hidden_states = self.self_attn_layer_norm(hidden_states + ngram_attention_output)
+
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
+ cross_attn_past_key_value = past_key_values[-2:] if past_key_values is not None else None
+ cross_attn_weights = None
+ if encoder_hidden_states is not None:
+ # 2nd residual block
+ attention_output, cross_attn_weights, cross_attn_present_key_value = self.cross_attn(
+ hidden_states=hidden_states,
+ key_value_states=encoder_hidden_states,
+ attention_mask=encoder_attn_mask,
+ layer_head_mask=cross_attn_layer_head_mask,
+ past_key_values=cross_attn_past_key_value,
+ output_attentions=output_attentions,
+ )
+ hidden_states = self.cross_attn_layer_norm(attention_output + hidden_states)
+
+ # add cross-attn to positions 3,4 of present_key_value tuple
+ present_key_value = present_key_value + cross_attn_present_key_value
+
+ # 3rd residual block
+ feed_forward_output = self.feed_forward(hidden_states)
+ hidden_states = self.feed_forward_layer_norm(feed_forward_output + hidden_states)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights, self_attn_weights_ngram, cross_attn_weights)
+
+ if use_cache:
+ outputs += (present_key_value,)
+
+ return outputs
+
+
+@add_start_docstrings(
+ "The standalone encoder part of the XLMProphetNetModel.",
+ XLM_PROPHETNET_START_DOCSTRING,
+)
+class XLMProphetNetEncoder(XLMProphetNetPreTrainedModel):
+ r"""
+ word_embeddings (`torch.nn.Embeddings` of shape `(config.vocab_size, config.hidden_size)`, *optional*):
+ The word embedding parameters. This can be used to initialize [`XLMProphetNetEncoder`] with pre-defined word
+ embeddings instead of randomly initialized word embeddings.
+ """
+
+ def __init__(self, config: XLMProphetNetConfig, word_embeddings: nn.Embedding = None):
+ super().__init__(config)
+
+ self.word_embeddings = (
+ word_embeddings
+ if word_embeddings is not None
+ else nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ )
+ self.position_embeddings = XLMProphetNetPositionalEmbeddings(config)
+ self.embeddings_layer_norm = LayerNorm(config.hidden_size)
+
+ self.layers = nn.ModuleList([XLMProphetNetEncoderLayer(config) for _ in range(config.num_encoder_layers)])
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.word_embeddings = value
+
+ @add_start_docstrings_to_model_forward(XLM_PROPHETNET_STANDALONE_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=BaseModelOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, BaseModelOutput]:
+ r"""
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLMProphetNetEncoder
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone")
+ >>> model = XLMProphetNetEncoder.from_pretrained("patrickvonplaten/prophetnet-large-uncased-standalone")
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> last_hidden_states = outputs.last_hidden_state
+ ```"""
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if input_ids is None and inputs_embeds is None:
+ raise ValueError("Either input_ids or inputs_embeds has to be passed.")
+ elif input_ids is not None and inputs_embeds is not None:
+ raise ValueError("Make sure to only pass input_ids or inputs_embeds.")
+ elif input_ids is not None and inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+
+ # prepare attention mask
+ if attention_mask is not None:
+ extended_attention_mask = (
+ 1.0 - attention_mask[:, None, None, :].repeat(1, self.config.num_encoder_attention_heads, 1, 1)
+ ) * torch.finfo(self.dtype).min
+ extended_attention_mask = extended_attention_mask.to(inputs_embeds.dtype)
+ else:
+ extended_attention_mask = None
+
+ position_embeddings, position_ids = self.position_embeddings(inputs_embeds.shape[:2], inputs_embeds.device)
+
+ hidden_states = inputs_embeds + position_embeddings
+ hidden_states = self.embeddings_layer_norm(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.config.dropout, training=self.training)
+
+ encoder_hidden_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+
+ # check if head_mask has a correct number of layers specified if desired
+ if head_mask is not None:
+ assert head_mask.size()[0] == (len(self.layers)), (
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
+ )
+ for idx, encoder_layer in enumerate(self.layers):
+ if output_hidden_states:
+ encoder_hidden_states = encoder_hidden_states + (hidden_states,)
+
+ layer_outputs = encoder_layer(
+ hidden_states,
+ attention_mask=extended_attention_mask,
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_attentions = all_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ encoder_hidden_states = encoder_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, encoder_hidden_states, all_attentions] if v is not None)
+ return BaseModelOutput(
+ last_hidden_state=hidden_states, hidden_states=encoder_hidden_states, attentions=all_attentions
+ )
+
+
+@add_start_docstrings(
+ "The standalone decoder part of the XLMProphetNetModel.",
+ XLM_PROPHETNET_START_DOCSTRING,
+)
+class XLMProphetNetDecoder(XLMProphetNetPreTrainedModel):
+ r"""
+ word_embeddings (`torch.nn.Embeddings` of shape `(config.vocab_size, config.hidden_size)`, *optional*):
+ The word embedding parameters. This can be used to initialize [`XLMProphetNetEncoder`] with pre-defined word
+ embeddings instead of randomly initialized word embeddings.
+ """
+
+ def __init__(self, config: XLMProphetNetConfig, word_embeddings: Optional[nn.Embedding] = None):
+ super().__init__(config)
+
+ self.ngram = config.ngram
+ self.num_buckets = config.num_buckets
+ self.relative_max_distance = config.relative_max_distance
+ self.dropout = config.dropout
+ self.max_target_positions = config.max_position_embeddings
+
+ self.word_embeddings = (
+ word_embeddings
+ if word_embeddings is not None
+ else nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ )
+ self.position_embeddings = XLMProphetNetPositionalEmbeddings(config)
+
+ self.ngram_embeddings = nn.Embedding(self.ngram, config.hidden_size, None)
+ self.layers = nn.ModuleList([XLMProphetNetDecoderLayer(config) for _ in range(config.num_decoder_layers)])
+ self.embeddings_layer_norm = LayerNorm(config.hidden_size)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.word_embeddings = value
+
+ @add_start_docstrings_to_model_forward(XLM_PROPHETNET_STANDALONE_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=XLMProphetNetDecoderModelOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.Tensor]]] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, XLMProphetNetDecoderModelOutput]:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLMProphetNetDecoder
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone")
+ >>> model = XLMProphetNetDecoder.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone", add_cross_attention=False)
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> last_hidden_states = outputs.last_hidden_state
+ ```"""
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if input_ids is None and inputs_embeds is None:
+ raise ValueError("Either `decoder_input_ids` or `decoder_inputs_embeds` has to be passed.")
+ elif input_ids is not None and inputs_embeds is not None:
+ raise ValueError("Make sure to only pass `decoder_input_ids` or `decoder_inputs_embeds`.")
+ elif input_ids is not None and inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+
+ batch_size, sequence_length = inputs_embeds.shape[:2]
+
+ main_stream_pos_embed, position_ids = self.position_embeddings(
+ (batch_size, sequence_length),
+ device=inputs_embeds.device,
+ past_key_values=past_key_values,
+ )
+
+ if past_key_values is not None:
+ main_relative_position_buckets, predict_relative_position_buckets = None, None
+ else:
+ (
+ main_relative_position_buckets,
+ predict_relative_position_buckets,
+ ) = self.compute_buffered_relative_buckets(position_ids)
+ predicting_stream_pos_embed = self.position_embeddings._forward(position_ids + 1)
+
+ # add position embeddings
+ hidden_states = inputs_embeds + main_stream_pos_embed
+
+ ngram_embeddings = self.ngram_embeddings.weight
+
+ # prepare attention mask
+ if past_key_values is not None:
+ assert hidden_states.size(1) == 1, (
+ "At the moment `use_cache` is only supported for `decoder_input_ids` of length 1"
+ )
+
+ ngram_hidden_states = [
+ (ngram_embeddings[ngram - 1] + predicting_stream_pos_embed).repeat(batch_size, 1, 1)
+ for ngram in range(self.ngram)
+ ]
+ extended_attention_mask = None
+ extended_predict_attention_mask = None
+ else:
+ ngram_hidden_states = [
+ (ngram_embeddings[ngram - 1] + predicting_stream_pos_embed) for ngram in range(self.ngram)
+ ]
+ extended_attention_mask = self.prepare_attention_mask(hidden_states, attention_mask)
+ extended_predict_attention_mask = self.prepare_predict_attention_mask(hidden_states, attention_mask)
+
+ # prepare encoder attention mask
+ if encoder_attention_mask is not None:
+ extended_encoder_attention_mask = (
+ 1.0 - encoder_attention_mask[:, None, None, :].repeat(1, self.config.num_decoder_attention_heads, 1, 1)
+ ) * torch.finfo(self.dtype).min
+ extended_encoder_attention_mask = extended_encoder_attention_mask.to(inputs_embeds.dtype)
+ else:
+ extended_encoder_attention_mask = None
+
+ hidden_states = torch.cat([hidden_states] + ngram_hidden_states, 1)
+
+ if self.embeddings_layer_norm:
+ hidden_states = self.embeddings_layer_norm(hidden_states)
+
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+
+ # init attentions, hidden_states and cache with empty tuples
+ all_main_stream_hidden_states = () if output_hidden_states else None
+ all_ngram_stream_hidden_states = () if output_hidden_states and self.config.ngram > 0 else None
+
+ all_main_stream_attns = () if output_attentions else None
+ all_ngram_stream_attns = () if output_attentions else None
+ all_cross_attns = () if output_attentions and self.config.add_cross_attention else None
+
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ present_key_values = () if use_cache else None
+
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
+ if attn_mask is not None:
+ assert attn_mask.size()[0] == (len(self.layers)), (
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
+ f" {head_mask.size()[0]}."
+ )
+ for idx, decoder_layer in enumerate(self.layers):
+ if output_hidden_states:
+ # grad cannot be kept because tensor is sliced
+ all_main_stream_hidden_states += (hidden_states[:, :sequence_length],)
+ if self.config.ngram > 0:
+ all_ngram_stream_hidden_states += (hidden_states[:, sequence_length:],)
+
+ layer_outputs = decoder_layer(
+ hidden_states,
+ attention_mask=extended_attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attn_mask=extended_encoder_attention_mask,
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
+ cross_attn_layer_head_mask=(cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None),
+ extended_predict_attention_mask=extended_predict_attention_mask,
+ main_relative_position_buckets=main_relative_position_buckets,
+ predict_relative_position_buckets=predict_relative_position_buckets,
+ position_ids=position_ids,
+ past_key_values=past_key_values[idx] if past_key_values is not None else None,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if use_cache:
+ present_key_values += (layer_outputs[4 if output_attentions else 1],)
+
+ if output_attentions:
+ all_main_stream_attns += (layer_outputs[1],)
+ all_ngram_stream_attns += (layer_outputs[2],)
+
+ if self.config.add_cross_attention:
+ all_cross_attns += (layer_outputs[3],)
+
+ if output_hidden_states:
+ all_main_stream_hidden_states += (hidden_states[:, :sequence_length],)
+ if self.config.ngram > 0:
+ all_ngram_stream_hidden_states += (hidden_states[:, sequence_length:],)
+
+ # split last_hidden_state for return
+ last_hidden_state = hidden_states[:, :sequence_length]
+ last_hidden_state_ngram = hidden_states[:, sequence_length:] if self.config.ngram > 0 else None
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ last_hidden_state,
+ last_hidden_state_ngram,
+ present_key_values,
+ all_main_stream_hidden_states,
+ all_ngram_stream_hidden_states,
+ all_main_stream_attns,
+ all_ngram_stream_attns,
+ all_cross_attns,
+ ]
+ if v is not None
+ )
+ return XLMProphetNetDecoderModelOutput(
+ last_hidden_state=last_hidden_state,
+ last_hidden_state_ngram=last_hidden_state_ngram,
+ past_key_values=present_key_values,
+ hidden_states=all_main_stream_hidden_states,
+ hidden_states_ngram=all_ngram_stream_hidden_states,
+ attentions=all_main_stream_attns,
+ ngram_attentions=all_ngram_stream_attns,
+ cross_attentions=all_cross_attns,
+ )
+
+ def compute_buffered_relative_buckets(self, position_ids):
+ batch_size, sequence_length = position_ids.shape
+
+ position_ids = torch.arange(1, self.max_target_positions).to(position_ids.device).repeat(1, 1)
+ main_relative_buckets, predict_relative_buckets = compute_all_stream_relative_buckets(
+ self.num_buckets, self.relative_max_distance, position_ids
+ )
+
+ # buffer relative buckets
+ main_relative_buckets = main_relative_buckets[:, :sequence_length, :sequence_length].repeat(batch_size, 1, 1)
+ predict_relative_buckets = torch.cat(
+ [
+ predict_relative_buckets[:, :sequence_length, :sequence_length],
+ predict_relative_buckets[
+ :, :sequence_length, self.max_target_positions : self.max_target_positions + sequence_length
+ ],
+ ],
+ 2,
+ ).repeat(batch_size, 1, 1)
+
+ return main_relative_buckets, predict_relative_buckets
+
+ def prepare_attention_mask(self, hidden_states, attention_mask):
+ batch_size, seq_length = hidden_states.shape[:2]
+
+ # get causal mask
+ causal_mask = torch.full(
+ (seq_length, seq_length),
+ torch.finfo(hidden_states.dtype).min,
+ dtype=hidden_states.dtype,
+ device=hidden_states.device,
+ )
+ causal_mask = torch.triu(causal_mask, 1)
+
+ extended_causal_mask = causal_mask[:seq_length, :seq_length][None, None, :, :].expand(
+ (batch_size, self.config.num_decoder_attention_heads) + causal_mask.shape
+ )
+
+ # add usual attention mask
+ if attention_mask is not None:
+ extended_attention_mask = (1.0 - attention_mask[:, None, None, :]) * torch.finfo(self.dtype).min
+ extended_attention_mask = extended_causal_mask + extended_attention_mask
+ else:
+ extended_attention_mask = extended_causal_mask
+ return extended_attention_mask.to(hidden_states.dtype)
+
+ def prepare_predict_attention_mask(self, hidden_states, attention_mask):
+ batch_size, seq_length = hidden_states.shape[:2]
+
+ # get causal mask
+ predict_causal_mask = ngram_attention_bias(
+ self.max_target_positions, self.ngram, hidden_states.device, hidden_states.dtype
+ )
+ predict_causal_mask = torch.cat(
+ [
+ predict_causal_mask[:, :seq_length, :seq_length],
+ predict_causal_mask[
+ :, :seq_length, self.max_target_positions : self.max_target_positions + seq_length
+ ],
+ ],
+ dim=-1,
+ )
+ extended_predict_causal_mask = predict_causal_mask[None, None, :, :, :].expand(
+ (batch_size, self.config.num_decoder_attention_heads) + predict_causal_mask.shape
+ )
+
+ # add usual attention mask
+ if attention_mask is not None:
+ extended_attention_mask = (1.0 - attention_mask[:, None, None, None, :]) * torch.finfo(self.dtype).min
+ extended_attention_mask = extended_attention_mask.expand(
+ (batch_size, self.config.num_decoder_attention_heads, self.ngram, seq_length, seq_length)
+ )
+ # predicted stream attention_mask should always be 0
+ extended_attention_mask = torch.cat(
+ [extended_attention_mask, torch.zeros_like(extended_attention_mask)], dim=-1
+ )
+ extended_predict_attention_mask = extended_predict_causal_mask + extended_attention_mask
+ else:
+ extended_predict_attention_mask = extended_predict_causal_mask
+ return extended_predict_attention_mask.to(hidden_states.dtype)
+
+
+@add_start_docstrings(
+ "The bare XLMProphetNet Model outputting raw hidden-states without any specific head on top.",
+ XLM_PROPHETNET_START_DOCSTRING,
+)
+class XLMProphetNetModel(XLMProphetNetPreTrainedModel):
+ _tied_weights_keys = ["encoder.word_embeddings.weight", "decoder.word_embeddings.weight"]
+
+ def __init__(self, config: XLMProphetNetConfig):
+ super().__init__(config)
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+
+ encoder_config = copy.deepcopy(config)
+ encoder_config.is_encoder_decoder = False
+ encoder_config.use_cache = False
+ self.encoder = XLMProphetNetEncoder(encoder_config, self.word_embeddings)
+
+ decoder_config = copy.deepcopy(config)
+ decoder_config.is_decoder = True
+ decoder_config.is_encoder_decoder = False
+ self.decoder = XLMProphetNetDecoder(decoder_config, self.word_embeddings)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.word_embeddings = value
+ self.encoder.word_embeddings = self.word_embeddings
+ self.decoder.word_embeddings = self.word_embeddings
+
+ def _tie_weights(self):
+ if self.config.tie_word_embeddings:
+ self._tie_or_clone_weights(self.encoder.word_embeddings, self.word_embeddings)
+ self._tie_or_clone_weights(self.decoder.word_embeddings, self.word_embeddings)
+
+ def get_encoder(self):
+ return self.encoder
+
+ @add_start_docstrings_to_model_forward(XLM_PROPHETNET_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=XLMProphetNetSeq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ decoder_input_ids: Optional[torch.Tensor] = None,
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ decoder_head_mask: Optional[torch.Tensor] = None,
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
+ encoder_outputs: Optional[tuple] = None,
+ past_key_values: Optional[tuple[tuple[torch.Tensor]]] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ decoder_inputs_embeds: Optional[torch.Tensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, XLMProphetNetSeq2SeqModelOutput]:
+ r"""
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLMProphetNetModel
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone")
+ >>> model = XLMProphetNetModel.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone")
+
+ >>> input_ids = tokenizer(
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
+ ... ).input_ids # Batch size 1
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
+ >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
+
+ >>> last_hidden_states = outputs.last_hidden_state # main stream hidden states
+ >>> last_hidden_states_ngram = outputs.last_hidden_state_ngram # predict hidden states
+ ```"""
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if encoder_outputs is None:
+ encoder_outputs = self.encoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
+ decoder_outputs = self.decoder(
+ input_ids=decoder_input_ids,
+ attention_mask=decoder_attention_mask,
+ encoder_hidden_states=encoder_outputs[0],
+ encoder_attention_mask=attention_mask,
+ head_mask=decoder_head_mask,
+ cross_attn_head_mask=cross_attn_head_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=decoder_inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ use_cache=use_cache,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ return decoder_outputs + encoder_outputs
+ return XLMProphetNetSeq2SeqModelOutput(
+ last_hidden_state=decoder_outputs.last_hidden_state,
+ last_hidden_state_ngram=decoder_outputs.last_hidden_state_ngram,
+ past_key_values=decoder_outputs.past_key_values,
+ decoder_hidden_states=decoder_outputs.hidden_states,
+ decoder_ngram_hidden_states=decoder_outputs.hidden_states_ngram,
+ decoder_attentions=decoder_outputs.attentions,
+ decoder_ngram_attentions=decoder_outputs.ngram_attentions,
+ cross_attentions=decoder_outputs.cross_attentions,
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
+ encoder_hidden_states=encoder_outputs.hidden_states,
+ encoder_attentions=encoder_outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ "The XLMProphetNet Model with a language modeling head. Can be used for sequence generation tasks.",
+ XLM_PROPHETNET_START_DOCSTRING,
+)
+class XLMProphetNetForConditionalGeneration(XLMProphetNetPreTrainedModel):
+ _tied_weights_keys = ["encoder.word_embeddings.weight", "decoder.word_embeddings.weight", "lm_head.weight"]
+
+ def __init__(self, config: XLMProphetNetConfig):
+ super().__init__(config)
+ self.prophetnet = XLMProphetNetModel(config)
+ self.padding_idx = config.pad_token_id
+ self.disable_ngram_loss = config.disable_ngram_loss
+
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def _tie_weights(self):
+ if self.config.tie_word_embeddings:
+ self._tie_or_clone_weights(self.prophetnet.word_embeddings, self.lm_head)
+
+ def get_input_embeddings(self):
+ return self.prophetnet.word_embeddings
+
+ @add_start_docstrings_to_model_forward(XLM_PROPHETNET_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=XLMProphetNetSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ decoder_input_ids: Optional[torch.Tensor] = None,
+ decoder_attention_mask: Optional[torch.BoolTensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ decoder_head_mask: Optional[torch.Tensor] = None,
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
+ encoder_outputs: Optional[torch.Tensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.Tensor]]] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ decoder_inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, XLMProphetNetSeq2SeqLMOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size - 1]`. All labels set to `-100` are ignored (masked), the loss is only computed for
+ labels in `[0, ..., config.vocab_size]`
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLMProphetNetForConditionalGeneration
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone")
+ >>> model = XLMProphetNetForConditionalGeneration.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone")
+
+ >>> input_ids = tokenizer(
+ ... "Studies have been shown that owning a dog is good for you", return_tensors="pt"
+ ... ).input_ids # Batch size 1
+ >>> decoder_input_ids = tokenizer("Studies show that", return_tensors="pt").input_ids # Batch size 1
+ >>> outputs = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
+
+ >>> logits_next_token = outputs.logits # logits to predict next token as usual
+ >>> logits_ngram_next_tokens = outputs.logits_ngram # logits to predict 2nd, 3rd, ... next tokens
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if labels is not None and decoder_input_ids is None and decoder_inputs_embeds is None:
+ # get decoder inputs from shifting lm labels to the right
+ decoder_input_ids = self._shift_right(labels)
+
+ outputs = self.prophetnet(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ decoder_input_ids=decoder_input_ids,
+ decoder_attention_mask=decoder_attention_mask,
+ head_mask=head_mask,
+ decoder_head_mask=decoder_head_mask,
+ cross_attn_head_mask=cross_attn_head_mask,
+ encoder_outputs=encoder_outputs,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ decoder_inputs_embeds=decoder_inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ batch_size, sequence_length = (
+ decoder_input_ids.shape if decoder_input_ids is not None else decoder_inputs_embeds.shape[:2]
+ )
+
+ predicting_streams = outputs[1].view(batch_size, self.config.ngram, sequence_length, -1)
+ predict_logits = self.lm_head(predicting_streams)
+
+ logits = predict_logits[:, 0]
+ logits_ngram = predict_logits[:, 1:] if self.config.ngram > 1 else None
+
+ # To use .view in loss computation, make sure that logits is contiguous.
+ if not logits.is_contiguous():
+ logits = logits.contiguous()
+
+ loss = None
+ if labels is not None:
+ loss = self._compute_loss(predict_logits, labels)
+
+ if not return_dict:
+ all_logits = tuple(v for v in [logits, logits_ngram] if v is not None)
+ return (loss,) + all_logits + outputs[2:] if loss is not None else all_logits + outputs[2:]
+ else:
+ return XLMProphetNetSeq2SeqLMOutput(
+ loss=loss,
+ logits=logits,
+ logits_ngram=logits_ngram,
+ past_key_values=outputs.past_key_values,
+ decoder_hidden_states=outputs.decoder_hidden_states,
+ decoder_ngram_hidden_states=outputs.decoder_ngram_hidden_states,
+ decoder_attentions=outputs.decoder_attentions,
+ decoder_ngram_attentions=outputs.decoder_ngram_attentions,
+ cross_attentions=outputs.cross_attentions,
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
+ encoder_hidden_states=outputs.encoder_hidden_states,
+ encoder_attentions=outputs.encoder_attentions,
+ )
+
+ def _compute_loss(self, logits, labels, ignore_index=-100):
+ expend_targets = labels.new_zeros(self.config.ngram, labels.size(0), labels.size(1)).fill_(ignore_index)
+
+ for i in range(self.config.ngram):
+ if i > 0 and self.disable_ngram_loss:
+ break
+ expend_targets[i, :, :] = labels
+
+ logits = logits.transpose(0, 1).contiguous()
+ lprobs = nn.functional.log_softmax(
+ logits.view(-1, logits.size(-1)),
+ dim=-1,
+ dtype=torch.float32,
+ )
+
+ loss = nn.functional.nll_loss(lprobs, expend_targets.view(-1), reduction="mean")
+
+ if self.config.eps > 0.0:
+ smooth_loss = -lprobs.sum(dim=-1, keepdim=True)
+ non_masked_tokens = expend_targets.ne(ignore_index).view(-1)
+ smooth_loss = smooth_loss[non_masked_tokens]
+ smooth_loss = smooth_loss.mean()
+
+ eps_i = self.config.eps / lprobs.size(-1)
+ loss = (1.0 - self.config.eps) * loss + eps_i * smooth_loss
+
+ return loss
+
+ def prepare_inputs_for_generation(
+ self,
+ decoder_input_ids,
+ past_key_values=None,
+ attention_mask=None,
+ head_mask=None,
+ decoder_head_mask=None,
+ cross_attn_head_mask=None,
+ use_cache=None,
+ encoder_outputs=None,
+ **kwargs,
+ ):
+ assert encoder_outputs is not None, "`encoder_outputs` have to be passed for generation."
+
+ if past_key_values:
+ decoder_input_ids = decoder_input_ids[:, -1:]
+ # first step, decoder_cached_states are empty
+ return {
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
+ "encoder_outputs": encoder_outputs,
+ "past_key_values": past_key_values,
+ "decoder_input_ids": decoder_input_ids,
+ "attention_mask": attention_mask,
+ "head_mask": head_mask,
+ "decoder_head_mask": decoder_head_mask,
+ "cross_attn_head_mask": cross_attn_head_mask,
+ "use_cache": use_cache,
+ }
+
+ def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
+ return self._shift_right(labels)
+
+ @staticmethod
+ def _reorder_cache(past_key_values, beam_idx):
+ reordered_past = ()
+ for layer_past in past_key_values:
+ # cached cross_attention states don't have to be reordered -> they are always the same
+ reordered_past += (
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
+ + layer_past[2:],
+ )
+ return reordered_past
+
+ def get_encoder(self):
+ return self.prophetnet.encoder
+
+ def get_decoder(self):
+ return self.prophetnet.decoder
+
+
+@add_start_docstrings(
+ "The standalone decoder part of the XLMProphetNetModel with a lm head on top. The model can be used for causal"
+ " language modeling.",
+ XLM_PROPHETNET_START_DOCSTRING,
+)
+class XLMProphetNetForCausalLM(XLMProphetNetPreTrainedModel):
+ _tied_weights_keys = [
+ "prophetnet.word_embeddings.weight",
+ "prophetnet.decoder.word_embeddings.weight",
+ "lm_head.weight",
+ ]
+
+ def __init__(self, config: XLMProphetNetConfig):
+ # set config for CLM
+ config = copy.deepcopy(config)
+ config.is_decoder = True
+ config.is_encoder_decoder = False
+ super().__init__(config)
+ self.prophetnet = XLMProphetNetDecoderWrapper(config)
+
+ self.padding_idx = config.pad_token_id
+ self.disable_ngram_loss = config.disable_ngram_loss
+
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.prophetnet.decoder.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.prophetnet.decoder.word_embeddings = value
+
+ def _tie_weights(self):
+ if self.config.tie_word_embeddings:
+ self._tie_or_clone_weights(self.prophetnet.decoder.word_embeddings, self.lm_head)
+
+ def set_decoder(self, decoder):
+ self.prophetnet.decoder = decoder
+
+ def get_decoder(self):
+ return self.prophetnet.decoder
+
+ @add_start_docstrings_to_model_forward(XLM_PROPHETNET_STANDALONE_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=XLMProphetNetDecoderLMOutput, config_class=_CONFIG_FOR_DOC)
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.Tensor]]] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, XLMProphetNetDecoderLMOutput]:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up decoding.
+
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
+
+ Returns:
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLMProphetNetForCausalLM
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone")
+ >>> model = XLMProphetNetForCausalLM.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone")
+ >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> logits = outputs.logits
+
+ >>> # Model can also be used with EncoderDecoder framework
+ >>> from transformers import BertTokenizer, EncoderDecoderModel, AutoTokenizer
+ >>> import torch
+
+ >>> tokenizer_enc = BertTokenizer.from_pretrained("google-bert/bert-large-uncased")
+ >>> tokenizer_dec = AutoTokenizer.from_pretrained("patrickvonplaten/xprophetnet-large-uncased-standalone")
+ >>> model = EncoderDecoderModel.from_encoder_decoder_pretrained(
+ ... "google-bert/bert-large-uncased", "patrickvonplaten/xprophetnet-large-uncased-standalone"
+ ... )
+
+ >>> ARTICLE = (
+ ... "the us state department said wednesday it had received no "
+ ... "formal word from bolivia that it was expelling the us ambassador there "
+ ... "but said the charges made against him are `` baseless ."
+ ... )
+ >>> input_ids = tokenizer_enc(ARTICLE, return_tensors="pt").input_ids
+ >>> labels = tokenizer_dec(
+ ... "us rejects charges against its ambassador in bolivia", return_tensors="pt"
+ ... ).input_ids
+ >>> outputs = model(input_ids=input_ids, decoder_input_ids=labels[:, :-1], labels=labels[:, 1:])
+
+ >>> loss = outputs.loss
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
+ outputs = self.prophetnet.decoder(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ head_mask=head_mask,
+ cross_attn_head_mask=cross_attn_head_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ batch_size, sequence_length = input_ids.shape if input_ids is not None else inputs_embeds.shape[:2]
+
+ predicting_streams = outputs[1].view(batch_size, self.config.ngram, sequence_length, -1)
+ predict_logits = self.lm_head(predicting_streams)
+
+ logits = predict_logits[:, 0]
+ logits_ngram = predict_logits[:, 1:] if self.config.ngram > 1 else None
+
+ loss = None
+ if labels is not None:
+ loss = self._compute_loss(predict_logits, labels)
+
+ if not return_dict:
+ all_logits = tuple(v for v in [logits, logits_ngram] if v is not None)
+ return (loss,) + all_logits + outputs[2:] if loss is not None else all_logits + outputs[2:]
+ else:
+ return XLMProphetNetDecoderLMOutput(
+ loss=loss,
+ logits=logits,
+ logits_ngram=logits_ngram,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ hidden_states_ngram=outputs.hidden_states_ngram,
+ attentions=outputs.attentions,
+ ngram_attentions=outputs.ngram_attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+ def _compute_loss(self, logits, labels, ignore_index=-100):
+ expend_targets = labels.new_zeros(self.config.ngram, labels.size(0), labels.size(1)).fill_(ignore_index)
+
+ for i in range(self.config.ngram):
+ if i > 0 and self.disable_ngram_loss:
+ break
+ expend_targets[i, :, :] = labels
+
+ logits = logits.transpose(0, 1).contiguous()
+ lprobs = nn.functional.log_softmax(
+ logits.view(-1, logits.size(-1)),
+ dim=-1,
+ dtype=torch.float32,
+ )
+
+ loss = nn.functional.nll_loss(lprobs, expend_targets.view(-1), reduction="mean")
+
+ if self.config.eps > 0.0:
+ smooth_loss = -lprobs.sum(dim=-1, keepdim=True)
+ non_masked_tokens = expend_targets.ne(ignore_index).view(-1)
+ smooth_loss = smooth_loss[non_masked_tokens]
+ smooth_loss = smooth_loss.mean()
+
+ eps_i = self.config.eps / lprobs.size(-1)
+ loss = (1.0 - self.config.eps) * loss + eps_i * smooth_loss
+
+ return loss
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ attention_mask=None,
+ head_mask=None,
+ use_cache=None,
+ **kwargs,
+ ):
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
+ if attention_mask is None:
+ attention_mask = input_ids.new_ones(input_ids.shape)
+
+ if past_key_values:
+ input_ids = input_ids[:, -1:]
+ # first step, decoder_cached_states are empty
+ return {
+ "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
+ "attention_mask": attention_mask,
+ "head_mask": head_mask,
+ "past_key_values": past_key_values,
+ "use_cache": use_cache,
+ }
+
+ @staticmethod
+ def _reorder_cache(past_key_values, beam_idx):
+ reordered_past = ()
+ for layer_past in past_key_values:
+ reordered_past += (
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
+ )
+ return reordered_past
+
+
+class XLMProphetNetDecoderWrapper(XLMProphetNetPreTrainedModel):
+ """
+ This is a wrapper class, so that [`XLMProphetNetForCausalLM`] can correctly be loaded from pretrained XLMProphetNet
+ classes.
+ """
+
+ def __init__(self, config: XLMProphetNetConfig):
+ super().__init__(config)
+
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.decoder = XLMProphetNetDecoder(config, word_embeddings=self.word_embeddings)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def _tie_weights(self):
+ self._tie_or_clone_weights(self.word_embeddings, self.decoder.get_input_embeddings())
+
+ def forward(self, *args, **kwargs):
+ return self.decoder(*args, **kwargs)
+
+
+__all__ = [
+ "XLMProphetNetDecoder",
+ "XLMProphetNetEncoder",
+ "XLMProphetNetForCausalLM",
+ "XLMProphetNetForConditionalGeneration",
+ "XLMProphetNetModel",
+ "XLMProphetNetPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/tokenization_xlm_prophetnet.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/tokenization_xlm_prophetnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..77431b13c49f47ac9df31b3d4e76ac9e2060895d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/deprecated/xlm_prophetnet/tokenization_xlm_prophetnet.py
@@ -0,0 +1,322 @@
+# coding=utf-8
+# Copyright 2020 The Microsoft Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import collections
+import os
+from shutil import copyfile
+from typing import Any, Optional
+
+from ....tokenization_utils import PreTrainedTokenizer
+from ....utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+SPIECE_UNDERLINE = "▁"
+
+VOCAB_FILES_NAMES = {"vocab_file": "prophetnet.tokenizer"}
+
+
+def load_vocab(vocab_file):
+ """Loads a vocabulary file into a dictionary."""
+ vocab = collections.OrderedDict()
+ with open(vocab_file, "r", encoding="utf-8") as reader:
+ tokens = reader.readlines()
+ for index, token in enumerate(tokens):
+ token = token.rstrip("\n")
+ vocab[token] = index
+ return vocab
+
+
+class XLMProphetNetTokenizer(PreTrainedTokenizer):
+ """
+ Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
+ [SentencePiece](https://github.com/google/sentencepiece).
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Path to the vocabulary file.
+ bos_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `"[SEP]"`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ unk_token (`str`, *optional*, defaults to `"[UNK]"`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `"[PAD]"`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `"[CLS]"`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `"[MASK]"`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ sp_model_kwargs (`dict`, *optional*):
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
+ to set:
+
+ - `enable_sampling`: Enable subword regularization.
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
+
+ - `nbest_size = {0,1}`: No sampling is performed.
+ - `nbest_size > 1`: samples from the nbest_size results.
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
+ using forward-filtering-and-backward-sampling algorithm.
+
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
+ BPE-dropout.
+
+ Attributes:
+ sp_model (`SentencePieceProcessor`):
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ vocab_file,
+ bos_token="[SEP]",
+ eos_token="[SEP]",
+ sep_token="[SEP]",
+ unk_token="[UNK]",
+ pad_token="[PAD]",
+ cls_token="[CLS]",
+ mask_token="[MASK]",
+ sp_model_kwargs: Optional[dict[str, Any]] = None,
+ **kwargs,
+ ) -> None:
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
+
+ try:
+ import sentencepiece as spm
+ except ImportError:
+ logger.warning(
+ "You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece"
+ " pip install sentencepiece"
+ )
+ raise
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.Load(str(vocab_file))
+ self.vocab_file = vocab_file
+
+ # Original fairseq vocab and spm vocab must be "aligned":
+ # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
+ # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
+ # fairseq | '' | '' | '' | '' | ',' | '.' | '▁' | 's' | '▁de' | '-'
+ # spm | '' | '' | '' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
+
+ # put special tokens and [unused] tokens into the vocab
+ self.fairseq_tokens_to_ids = {"[PAD]": 0, "[CLS]": 1, "[SEP]": 2, "[UNK]": 3, "[MASK]": 4}
+
+ for i in range(10):
+ tok = f"[unused{i}]"
+ self.fairseq_tokens_to_ids[tok] = 5 + i
+
+ # The first "real" token "," has position 15 in the embedding vocab and position 3 in the spm vocab
+ self.fairseq_offset = 12
+ self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
+
+ # TODO ArthurZ fairseq_ids_to_tokens should be removed
+
+ super().__init__(
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ sp_model_kwargs=self.sp_model_kwargs,
+ **kwargs,
+ )
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state["sp_model"] = None
+ return state
+
+ def __setstate__(self, d):
+ self.__dict__ = d
+ try:
+ import sentencepiece as spm
+ except ImportError:
+ logger.warning(
+ "You need to install SentencePiece to use XLMRobertaTokenizer: https://github.com/google/sentencepiece"
+ " pip install sentencepiece"
+ )
+ raise
+
+ # for backward compatibility
+ if not hasattr(self, "sp_model_kwargs"):
+ self.sp_model_kwargs = {}
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.Load(self.vocab_file)
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is None:
+ return ([0] * len(token_ids_0)) + [1]
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLMProphetNet
+ does not make use of token type ids, therefore a list of zeros is returned.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of zeros.
+
+ """
+
+ sep = [self.sep_token_id]
+
+ if token_ids_1 is None:
+ return len(token_ids_0 + sep) * [0]
+ return len(token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
+
+ @property
+ def vocab_size(self):
+ return len(self.sp_model) + self.fairseq_offset
+
+ def get_vocab(self):
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
+ vocab.update(self.added_tokens_encoder)
+ return vocab
+
+ def _tokenize(self, text: str) -> str:
+ return self.sp_model.encode(text, out_type=str)
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ if token in self.fairseq_tokens_to_ids:
+ return self.fairseq_tokens_to_ids[token]
+ spm_id = self.sp_model.PieceToId(token)
+
+ # Need to return unknown token if the SP model returned 0
+ return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ if index in self.fairseq_ids_to_tokens:
+ return self.fairseq_ids_to_tokens[index]
+ return self.sp_model.IdToPiece(index - self.fairseq_offset)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (strings for sub-words) in a single string."""
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
+ return out_string
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ out_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
+ copyfile(self.vocab_file, out_vocab_file)
+ elif not os.path.isfile(self.vocab_file):
+ with open(out_vocab_file, "wb") as fi:
+ content_spiece_model = self.sp_model.serialized_model_proto()
+ fi.write(content_spiece_model)
+
+ return (out_vocab_file,)
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. A XLMProphetNet sequence has the following format:
+
+ - single sequence: `X [SEP]`
+ - pair of sequences: `A [SEP] B [SEP]`
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: list of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+
+ if token_ids_1 is None:
+ return token_ids_0 + [self.sep_token_id]
+ sep = [self.sep_token_id]
+ return token_ids_0 + sep + token_ids_1 + sep
+
+
+__all__ = ["XLMProphetNetTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_anything/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_anything/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..18276a0e2eff84c095c06632a1fc12b6e9ce3ee5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_anything/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_anything/__pycache__/configuration_depth_anything.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_anything/__pycache__/configuration_depth_anything.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44a2e4cadd12692b047afaff0cbf90cf33ef811f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_anything/__pycache__/configuration_depth_anything.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_anything/__pycache__/modeling_depth_anything.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_anything/__pycache__/modeling_depth_anything.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d03e427dd28dde6bdf7af7e253ed3bfc789ee93
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_anything/__pycache__/modeling_depth_anything.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ee659d699044b424255c106b557b599c7133e3f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/configuration_depth_pro.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/configuration_depth_pro.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c27fdca8cd7283c4dc770ded5c4fdedd51a6d67e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/configuration_depth_pro.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/image_processing_depth_pro.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/image_processing_depth_pro.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6c38952dce304fb1aae72f73aa11fce2f3c86358
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/image_processing_depth_pro.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/image_processing_depth_pro_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/image_processing_depth_pro_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7649bdbcb62bda2fb99c0957039798736ae70bf8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/image_processing_depth_pro_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/modeling_depth_pro.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/modeling_depth_pro.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..839b66c18200098aee35d96b79937794b60ab6dd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/depth_pro/__pycache__/modeling_depth_pro.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5706ce53aa21b563f0900955786a7e681e48b0af
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/configuration_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/configuration_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a88b48d15600486f9aedc12e6e11a9baae689383
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/configuration_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/feature_extraction_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/feature_extraction_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44a2ab53129c6e53e6aa26feae7e735fecefced4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/feature_extraction_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/image_processing_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/image_processing_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff30dea7c41194d6ce73c6340592131eaaeaed67
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/image_processing_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/image_processing_detr_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/image_processing_detr_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13088ad800bc7e2e0c13cb5dca0f91863106a8b2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/image_processing_detr_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/modeling_detr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/modeling_detr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..81a446958a4076936a43f08f85a45ad9c8566e20
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/detr/__pycache__/modeling_detr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef71e04150f1c73dae6dd2e870829c1924429332
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/configuration_dia.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/configuration_dia.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9da623cf1d0725348e5e5d0c98064909f3e430b1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/configuration_dia.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/feature_extraction_dia.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/feature_extraction_dia.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed92a839fdfa050c3f91184064232bf622560585
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/feature_extraction_dia.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/generation_dia.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/generation_dia.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c0c0c30f6700ebbb4bb2dfc58483438be495534e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/generation_dia.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/modeling_dia.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/modeling_dia.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fd48e46c90fd3becf7632925622381add80ada7a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/modeling_dia.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/modular_dia.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/modular_dia.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ee92d296ea275204cb0d25fb1dfa0dfe20d762f6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/modular_dia.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/processing_dia.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/processing_dia.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5c0f67c27e03cc70fef3694e2ef02f7bf1ed7e85
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/processing_dia.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/tokenization_dia.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/tokenization_dia.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85198c31d3f144f954fe564d90acb4503217878a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dia/__pycache__/tokenization_dia.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dialogpt/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dialogpt/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8906f1da2f60b42bb0eac0ecec07c3306ac6938
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dialogpt/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..197d0f5f1b99ae4da729eae8404b36659935f64d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/configuration_diffllama.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/configuration_diffllama.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6960d2e441133d0b2c427b10385e6b19028aa111
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/configuration_diffllama.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/modeling_diffllama.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/modeling_diffllama.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..294ce7e128532f53e11e62dc43000c992e66fbd8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/modeling_diffllama.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/modular_diffllama.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/modular_diffllama.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e44d681569a17645b747ec9fe9023429e65f1e36
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/diffllama/__pycache__/modular_diffllama.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinat/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinat/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..990296a5e00f3e89e954464037909865cb34b34f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinat/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinat/__pycache__/configuration_dinat.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinat/__pycache__/configuration_dinat.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3de44bedb75bce8b0215db957e6729ff7db30957
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinat/__pycache__/configuration_dinat.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinat/__pycache__/modeling_dinat.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinat/__pycache__/modeling_dinat.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3c724bb6b937bbcb9630bde7905b13c2806d34a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinat/__pycache__/modeling_dinat.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..27f1f135432e69ac3746c5ff7963c282888b211c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/configuration_dinov2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/configuration_dinov2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a1f102f9c57bb14b7e132b8e30ea887799d5de53
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/configuration_dinov2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/modeling_dinov2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/modeling_dinov2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8c8d280359a9dac63092660d3b4e616782193e7f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/modeling_dinov2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/modeling_flax_dinov2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/modeling_flax_dinov2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8105e9c000aaad3666233d42707c9f4bd832290
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2/__pycache__/modeling_flax_dinov2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5e8e336b1c5c50a64598cf265895e3dfd59c357
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/configuration_dinov2_with_registers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/configuration_dinov2_with_registers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..641bfcdc7905e5240f5ad1cf58a3a40f2fb5a2c8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/configuration_dinov2_with_registers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/modeling_dinov2_with_registers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/modeling_dinov2_with_registers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0a1feeb0e59d3b9968fd71b31f2eda9c7714df9d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/modeling_dinov2_with_registers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/modular_dinov2_with_registers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/modular_dinov2_with_registers.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ba5635af81b2d24fdba9e7d4c6eee0de305be28
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov2_with_registers/__pycache__/modular_dinov2_with_registers.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_convnext/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_convnext/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1807d996515409c84b04d720887c138e5fcc7573
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_convnext/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_convnext/__pycache__/configuration_dinov3_convnext.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_convnext/__pycache__/configuration_dinov3_convnext.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2bee24781f616843aa99d61507513bf501aa78d9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_convnext/__pycache__/configuration_dinov3_convnext.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_convnext/__pycache__/modeling_dinov3_convnext.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_convnext/__pycache__/modeling_dinov3_convnext.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7405e5ded1103ebb03b3121cfc10a7187bd6c64f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_convnext/__pycache__/modeling_dinov3_convnext.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37d42d43e06bf3e234ea29be837e1dbf1f38dc33
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/configuration_dinov3_vit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/configuration_dinov3_vit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0f58c4c911f7df73a58bde3773209a4c88cc6440
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/configuration_dinov3_vit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/image_processing_dinov3_vit_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/image_processing_dinov3_vit_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9d0ff247cb760fb00de16a8307b1d7fe466be736
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/image_processing_dinov3_vit_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/modeling_dinov3_vit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/modeling_dinov3_vit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..30f4b11e5528543f04c8b320f778dc877fcde099
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/modeling_dinov3_vit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/modular_dinov3_vit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/modular_dinov3_vit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cf261a4fbc9aa37b8c1a831df50c87cab31b920
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dinov3_vit/__pycache__/modular_dinov3_vit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..93594c5c2ab6de31bcd3c52600f10c16590c8939
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/configuration_distilbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/configuration_distilbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..831a2defad1adb6e85169e18005ca9887e1117a3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/configuration_distilbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/modeling_distilbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/modeling_distilbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..620f24f222e9cd498d124c1e2476c0c59326efe7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/modeling_distilbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/modeling_flax_distilbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/modeling_flax_distilbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f8d428c68c85b0d120feb9f48dec23a98b3a8fea
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/modeling_flax_distilbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/modeling_tf_distilbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/modeling_tf_distilbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a2a6cb56d6261cd3b5a12b658c8f1f38417df57
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/modeling_tf_distilbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7afa4c7f14d2dc33c2820bb7d4b40ddd6df96b9f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..96ce827d82571b98d994e17e171648069d33ecc6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/distilbert/__pycache__/tokenization_distilbert_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dit/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dit/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8b032e3e434257e6a4b06321e74e8c41a181155
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dit/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d02225311d5edb214adae0df66b695774231d166
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/configuration_doge.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/configuration_doge.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb6504ba004545fedd76192fd6ed0be154b9c95b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/configuration_doge.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/modeling_doge.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/modeling_doge.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a064d6d2a4895c8f34659ba99017cc77ea5114b0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/modeling_doge.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/modular_doge.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/modular_doge.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1dbfa86ea279893037b0bc1e6ea627c271dcb10
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/doge/__pycache__/modular_doge.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed2a9a273ab1bf8d96539d1e2078a3ca120295e1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/configuration_donut_swin.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/configuration_donut_swin.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..976b9ccc6a3709f77799c50bbf1554097101d2ce
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/configuration_donut_swin.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/feature_extraction_donut.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/feature_extraction_donut.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44e702289a56090577c57bb1d8fe089b2e172d1e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/feature_extraction_donut.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/image_processing_donut.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/image_processing_donut.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aaef06a68e0ba45fccd74ebe590c5ede0e4edcbc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/image_processing_donut.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/image_processing_donut_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/image_processing_donut_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5a18bfcad74314ba02ee3c1f2b9462f8bf30e92
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/image_processing_donut_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/modeling_donut_swin.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/modeling_donut_swin.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6894e7decbd199724a4ceb06f4cba78b74146dfc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/modeling_donut_swin.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/processing_donut.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/processing_donut.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a98ae5cb44d66a76f318e72458d9c3a283dbfdac
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/donut/__pycache__/processing_donut.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59b721f31fecf5129efafee142697428eda995aa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/configuration_dots1.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/configuration_dots1.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bdb36a6c787cfcce06bd54d951ce3237c97857f2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/configuration_dots1.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/modeling_dots1.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/modeling_dots1.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6972024d2760344776de495ad682c65c34c13c99
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/modeling_dots1.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/modular_dots1.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/modular_dots1.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d4e3f52ede39cb670657600d1040126f727d3d94
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dots1/__pycache__/modular_dots1.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35a25e6944265ef2edc593392bb13cbcd23851f2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/configuration_dpr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/configuration_dpr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d817ad35d6c1e4f779b6233f2120538cf8fd81cd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/configuration_dpr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/modeling_dpr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/modeling_dpr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8ac7a0f633061bb3b50898580c50db7f00bdcc4b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/modeling_dpr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/modeling_tf_dpr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/modeling_tf_dpr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ae6433fd623c6b459086176e02ea6552a95b4c9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/modeling_tf_dpr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8efaccace39935c7270bd986459f5c1df049e3e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..efb2962a6331b2a5f0dc36456c12f11f86f179fb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpr/__pycache__/tokenization_dpr_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3e03c8354441f0f2833be9fc7d3437183e28d94
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/configuration_dpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/configuration_dpt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c7be499269071454235151ff4fd74aa45d309d7a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/configuration_dpt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/feature_extraction_dpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/feature_extraction_dpt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..24a7d9adee5d8f7dc4bf216b4c19550fa0e51340
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/feature_extraction_dpt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/image_processing_dpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/image_processing_dpt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a249807cf1f0098f0dc5ceb303285a51317add59
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/image_processing_dpt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/image_processing_dpt_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/image_processing_dpt_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0fa16d6e33b56850b86c01baa71f572bd6a5f190
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/image_processing_dpt_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/modeling_dpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/modeling_dpt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..99d3be97d63bfda6dc7489770b17086cd9b5ecc6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/modeling_dpt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/modular_dpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/modular_dpt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..071a6955435e0aecb6a85ddf6e68c3719cad9bc1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/dpt/__pycache__/modular_dpt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b25dde3c1254c8528fb3461d46b330eb42eaa2ce
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/configuration_efficientloftr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/configuration_efficientloftr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd9fc9e38e794f549cc1ca23ec2875dbe0c20ef9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/configuration_efficientloftr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/image_processing_efficientloftr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/image_processing_efficientloftr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b14616902df414a4b3a880ae8580c69559bdd0fa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/image_processing_efficientloftr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/modeling_efficientloftr.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/modeling_efficientloftr.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b4b3a4cd6eb2c801a1b5dc9a3a29e23d9684c3a4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientloftr/__pycache__/modeling_efficientloftr.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94a3f2cbd940c2552e95989a226c31d5a16c5db0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/configuration_efficientnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/configuration_efficientnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d961fe57102dad5b8922708bd509e967b00ae7b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/configuration_efficientnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d1871f1af9d2f093721f8a22ad58b99b7e74527
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cfe70305a706bf53173d7d19a6d4cc09aebbce9e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/image_processing_efficientnet_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/modeling_efficientnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/modeling_efficientnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..987da00f7df95874a07d152d5f388cbd458dec6c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/efficientnet/__pycache__/modeling_efficientnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ac809aabf09b87664e32093c4eedf7358813187
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/configuration_electra.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/configuration_electra.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20bb91a835941467fb38a0f7c0e93d3fe08bc02d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/configuration_electra.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/modeling_electra.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/modeling_electra.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a5e0585549b62d7e0285991a07b43243ed8e8c7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/modeling_electra.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/modeling_flax_electra.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/modeling_flax_electra.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..97bda2ba64fbed6ef6c906dec5da6a5dcc578520
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/modeling_flax_electra.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/modeling_tf_electra.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/modeling_tf_electra.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f161f3c29a49dc2071d382da8e31fe8916c4049e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/modeling_tf_electra.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/tokenization_electra.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/tokenization_electra.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0df7d1878770209aba5de1537636ed630f577b1c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/tokenization_electra.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/tokenization_electra_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/tokenization_electra_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acde84925bbf7e69f9c9c1a7317b9cd84d5ccb3e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/electra/__pycache__/tokenization_electra_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4fce684aaf450c7c4d8f10910c00f5906fadd4c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/configuration_emu3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/configuration_emu3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..452a088ed5e43c76243e8c705add2412137a7649
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/configuration_emu3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/image_processing_emu3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/image_processing_emu3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e583202fe71b316b460428c5cf9b942b1cf37e38
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/image_processing_emu3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/modeling_emu3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/modeling_emu3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2df6ef5b1b8973af5e2d9623539a786373f9f393
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/modeling_emu3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/modular_emu3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/modular_emu3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fe69327fe00786f2f78434d113baeea2dbb741f2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/modular_emu3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/processing_emu3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/processing_emu3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2baf20c1d2d5de1b2880849d011403a9e5b1cc63
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/emu3/__pycache__/processing_emu3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..016e2eeb212820143a370d82f4ae96225b06b8ee
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/configuration_encodec.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/configuration_encodec.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a755f107cab014ad17edaac249a4df4f72baeaa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/configuration_encodec.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/feature_extraction_encodec.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/feature_extraction_encodec.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa733f80dade8bcbbc2d161743c17c0ea11fcd79
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/feature_extraction_encodec.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/modeling_encodec.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/modeling_encodec.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7166c8f8e5598a699cb069389bc9d9d7d8c53501
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encodec/__pycache__/modeling_encodec.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..80c2628f9b73ecd3990b122d4f88b9844f541429
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/configuration_encoder_decoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/configuration_encoder_decoder.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..42970e8b942e28fb3101a5214d36d2eece8dc65b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/configuration_encoder_decoder.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_encoder_decoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_encoder_decoder.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd8f05072044c46fb46c23325540ca914d40a0b3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_encoder_decoder.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_flax_encoder_decoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_flax_encoder_decoder.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b282073ac692c7a6eabf98855ce5d91202e07dc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_flax_encoder_decoder.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_tf_encoder_decoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_tf_encoder_decoder.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8efc05c08688403a0ed9b70d767e616b19011bd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/encoder_decoder/__pycache__/modeling_tf_encoder_decoder.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0eb80b7be806b86edba002ef60af04456fa0062b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/configuration_eomt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/configuration_eomt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3e543afe99acc5f0088ac0afc0149dcb2d7239b2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/configuration_eomt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/image_processing_eomt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/image_processing_eomt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e19875c00bf7ec4913315d56d267953cba8a9418
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/image_processing_eomt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/image_processing_eomt_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/image_processing_eomt_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..632ef28dfae20f079b48ae1e9cd66f77b16015fc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/image_processing_eomt_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/modeling_eomt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/modeling_eomt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a53e1d2694ea6187687506cd069df77629d8a1f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/modeling_eomt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/modular_eomt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/modular_eomt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0ea65a226b3f7810ead0414f379399f3e6642480
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/eomt/__pycache__/modular_eomt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bc6eefb572711dd31826459a7d1958d1a28f40d6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie/__pycache__/configuration_ernie.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie/__pycache__/configuration_ernie.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..655ba2fb202c5af3e33d06ad2f8d741b0ed5d470
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie/__pycache__/configuration_ernie.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie/__pycache__/modeling_ernie.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie/__pycache__/modeling_ernie.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1560fdf0ef40832fa0e08fe480aa0c5c6c9c66fd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie/__pycache__/modeling_ernie.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6ee043ceadf41b607df0aea797ee5d7510cd6396
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/configuration_ernie4_5.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/configuration_ernie4_5.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..393664e492ee8da3a45ed80292f014ffe7fd90a4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/configuration_ernie4_5.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/modeling_ernie4_5.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/modeling_ernie4_5.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bebef8a3eacb37fe7709629cd294bc8150ee1480
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/modeling_ernie4_5.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/modular_ernie4_5.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/modular_ernie4_5.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..922dd9f1c8d8089fef0b2a3dfce90d60ff099890
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5/__pycache__/modular_ernie4_5.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d05334fbdd0201d7cf96428e9a2eb765059e1384
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/configuration_ernie4_5_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/configuration_ernie4_5_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..505a30ed9338a8e0864f7b345a2d46f029d8da39
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/configuration_ernie4_5_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/modeling_ernie4_5_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/modeling_ernie4_5_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06172c14c5347dcb4f0b8a32a44d3af5807b3f60
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/modeling_ernie4_5_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/modular_ernie4_5_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/modular_ernie4_5_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..492964d32a7583dce754489774d0e79aa26b7947
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ernie4_5_moe/__pycache__/modular_ernie4_5_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..093a2db9e7e1216a4ab8c65d90bfbe64515dc874
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/configuration_esm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/configuration_esm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0018fa63c67a4a1c858d40af585fc01714687778
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/configuration_esm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/modeling_esm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/modeling_esm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df3a562f3c1e8f1a54b9aa5b5951adb30d0a8dcc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/modeling_esm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/modeling_esmfold.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/modeling_esmfold.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df9a8b8bdd34dea10107e5db2871e5cc083b06cb
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/modeling_esmfold.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3f3970c8fe5f9cc6c753bd1c71a5223b7ec6e971212a5de164111e1842001209
+size 112053
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/modeling_tf_esm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/modeling_tf_esm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..82e62f4621a46ea54292d8c4528cb79db304915f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/modeling_tf_esm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/tokenization_esm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/tokenization_esm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..73b4deafbe9cb004b4ca922d6c08cdad4ae7f32b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/__pycache__/tokenization_esm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..02a8c149ae320dd9b045edc5df31760a4eebefd9
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__init__.py
@@ -0,0 +1,8 @@
+from .chunk_utils import chunk_layer
+from .data_transforms import make_atom14_masks
+from .feats import atom14_to_atom37, frames_and_literature_positions_to_atom14_pos, torsion_angles_to_frames
+from .loss import compute_predicted_aligned_error, compute_tm
+from .protein import Protein as OFProtein
+from .protein import to_pdb
+from .rigid_utils import Rigid, Rotation
+from .tensor_utils import dict_multimap, flatten_final_dims, permute_final_dims
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1af13940f6de2c6d328e5aeec9678ae0808a06ff
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/chunk_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/chunk_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1af18e1673b2c1537d5d3b2412079c525467ae7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/chunk_utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/data_transforms.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/data_transforms.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c11ea9e061942ba638f5b24b5e9688242f041f9f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/data_transforms.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/feats.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/feats.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..46c6bdc23a1d141d55a1dda951a31d2ab79d7fbf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/feats.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/loss.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/loss.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0c09f875eb969e8866584a00b43d12ec1aecd4b0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/loss.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/protein.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/protein.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0879349ef50b2fb977cd2662ffe0bd865881ea1a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/protein.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/residue_constants.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/residue_constants.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cad4fad91910ea9e0752c8e662b12f55db40ad40
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/residue_constants.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/rigid_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/rigid_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78cb3e5f9b74dca5f0fe450faf66a192315f1024
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/rigid_utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/tensor_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/tensor_utils.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7746afc3a5d37ce3c3c65d741e56cf79f9b276cd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/__pycache__/tensor_utils.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/chunk_utils.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/chunk_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..14703ba7d605dd9dbdbb55789d0ea960588048da
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/chunk_utils.py
@@ -0,0 +1,398 @@
+# Copyright 2021 AlQuraishi Laboratory
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import logging
+import math
+from collections.abc import Iterable, Sequence
+from functools import partial
+from typing import Any, Callable, Optional, Union
+
+import torch
+
+from .tensor_utils import tensor_tree_map, tree_map
+
+
+def _fetch_dims(tree: Union[dict, list, tuple, torch.Tensor]) -> list[tuple[int, ...]]:
+ shapes = []
+ if isinstance(tree, dict):
+ for v in tree.values():
+ shapes.extend(_fetch_dims(v))
+ elif isinstance(tree, (list, tuple)):
+ for t in tree:
+ shapes.extend(_fetch_dims(t))
+ elif isinstance(tree, torch.Tensor):
+ shapes.append(tree.shape)
+ else:
+ raise TypeError("Not supported")
+
+ return shapes
+
+
+@torch.jit.ignore
+def _flat_idx_to_idx(flat_idx: int, dims: tuple[int, ...]) -> tuple[int, ...]:
+ idx = []
+ for d in reversed(dims):
+ idx.append(flat_idx % d)
+ flat_idx = flat_idx // d
+
+ return tuple(reversed(idx))
+
+
+@torch.jit.ignore
+def _get_minimal_slice_set(
+ start: Sequence[int],
+ end: Sequence[int],
+ dims: Sequence[int],
+ start_edges: Optional[Sequence[bool]] = None,
+ end_edges: Optional[Sequence[bool]] = None,
+) -> list[tuple[slice, ...]]:
+ """
+ Produces an ordered sequence of tensor slices that, when used in sequence on a tensor with shape dims, yields
+ tensors that contain every leaf in the contiguous range [start, end]. Care is taken to yield a short sequence of
+ slices, and perhaps even the shortest possible (I'm pretty sure it's the latter).
+
+ end is INCLUSIVE.
+ """
+
+ # start_edges and end_edges both indicate whether, starting from any given
+ # dimension, the start/end index is at the top/bottom edge of the
+ # corresponding tensor, modeled as a tree
+ def reduce_edge_list(l: list[bool]) -> None:
+ tally = True
+ for i in range(len(l)):
+ reversed_idx = -1 * (i + 1)
+ l[reversed_idx] &= tally
+ tally = l[reversed_idx]
+
+ if start_edges is None:
+ start_edges = [s == 0 for s in start]
+ reduce_edge_list(start_edges)
+ if end_edges is None:
+ end_edges = [e == (d - 1) for e, d in zip(end, dims)]
+ reduce_edge_list(end_edges)
+
+ # Base cases. Either start/end are empty and we're done, or the final,
+ # one-dimensional tensor can be simply sliced
+ if len(start) == 0:
+ return [()]
+ elif len(start) == 1:
+ return [(slice(start[0], end[0] + 1),)]
+
+ slices: list[tuple[slice, ...]] = []
+ path_list: list[slice] = []
+
+ # Dimensions common to start and end can be selected directly
+ for s, e in zip(start, end):
+ if s == e:
+ path_list.append(slice(s, s + 1))
+ else:
+ break
+
+ path: tuple[slice, ...] = tuple(path_list)
+ divergence_idx = len(path)
+
+ # start == end, and we're done
+ if divergence_idx == len(dims):
+ return [path]
+
+ def upper() -> tuple[tuple[slice, ...], ...]:
+ assert start_edges is not None
+ assert end_edges is not None
+
+ sdi = start[divergence_idx]
+ return tuple(
+ path + (slice(sdi, sdi + 1),) + s
+ for s in _get_minimal_slice_set(
+ start[divergence_idx + 1 :],
+ [d - 1 for d in dims[divergence_idx + 1 :]],
+ dims[divergence_idx + 1 :],
+ start_edges=start_edges[divergence_idx + 1 :],
+ end_edges=[True for _ in end_edges[divergence_idx + 1 :]],
+ )
+ )
+
+ def lower() -> tuple[tuple[slice, ...], ...]:
+ assert start_edges is not None
+ assert end_edges is not None
+
+ edi = end[divergence_idx]
+ return tuple(
+ path + (slice(edi, edi + 1),) + s
+ for s in _get_minimal_slice_set(
+ [0 for _ in start[divergence_idx + 1 :]],
+ end[divergence_idx + 1 :],
+ dims[divergence_idx + 1 :],
+ start_edges=[True for _ in start_edges[divergence_idx + 1 :]],
+ end_edges=end_edges[divergence_idx + 1 :],
+ )
+ )
+
+ # If both start and end are at the edges of the subtree rooted at
+ # divergence_idx, we can just select the whole subtree at once
+ if start_edges[divergence_idx] and end_edges[divergence_idx]:
+ slices.append(path + (slice(start[divergence_idx], end[divergence_idx] + 1),))
+ # If just start is at the edge, we can grab almost all of the subtree,
+ # treating only the ragged bottom edge as an edge case
+ elif start_edges[divergence_idx]:
+ slices.append(path + (slice(start[divergence_idx], end[divergence_idx]),))
+ slices.extend(lower())
+ # Analogous to the previous case, but the top is ragged this time
+ elif end_edges[divergence_idx]:
+ slices.extend(upper())
+ slices.append(path + (slice(start[divergence_idx] + 1, end[divergence_idx] + 1),))
+ # If both sides of the range are ragged, we need to handle both sides
+ # separately. If there's contiguous meat in between them, we can index it
+ # in one big chunk
+ else:
+ slices.extend(upper())
+ middle_ground = end[divergence_idx] - start[divergence_idx]
+ if middle_ground > 1:
+ slices.append(path + (slice(start[divergence_idx] + 1, end[divergence_idx]),))
+ slices.extend(lower())
+
+ return slices
+
+
+@torch.jit.ignore
+def _chunk_slice(t: torch.Tensor, flat_start: int, flat_end: int, no_batch_dims: int) -> torch.Tensor:
+ """
+ Equivalent to
+
+ t.reshape((-1,) + t.shape[no_batch_dims:])[flat_start:flat_end]
+
+ but without the need for the initial reshape call, which can be memory-intensive in certain situations. The only
+ reshape operations in this function are performed on sub-tensors that scale with (flat_end - flat_start), the chunk
+ size.
+ """
+
+ batch_dims = t.shape[:no_batch_dims]
+ start_idx = list(_flat_idx_to_idx(flat_start, batch_dims))
+ # _get_minimal_slice_set is inclusive
+ end_idx = list(_flat_idx_to_idx(flat_end - 1, batch_dims))
+
+ # Get an ordered list of slices to perform
+ slices = _get_minimal_slice_set(
+ start_idx,
+ end_idx,
+ batch_dims,
+ )
+
+ sliced_tensors = [t[s] for s in slices]
+
+ return torch.cat([s.view((-1,) + t.shape[no_batch_dims:]) for s in sliced_tensors])
+
+
+def chunk_layer(
+ layer: Callable,
+ inputs: dict[str, Any],
+ chunk_size: int,
+ no_batch_dims: int,
+ low_mem: bool = False,
+ _out: Any = None,
+ _add_into_out: bool = False,
+) -> Any:
+ """
+ Implements the "chunking" procedure described in section 1.11.8.
+
+ Layer outputs and inputs are assumed to be simple "pytrees," consisting only of (arbitrarily nested) lists, tuples,
+ and dicts with torch.Tensor leaves.
+
+ Args:
+ layer:
+ The layer to be applied chunk-wise
+ inputs:
+ A (non-nested) dictionary of keyworded inputs. All leaves must be tensors and must share the same batch
+ dimensions.
+ chunk_size:
+ The number of sub-batches per chunk. If multiple batch dimensions are specified, a "sub-batch" is defined
+ as a single indexing of all batch dimensions simultaneously (s.t. the number of sub-batches is the product
+ of the batch dimensions).
+ no_batch_dims:
+ How many of the initial dimensions of each input tensor can be considered batch dimensions.
+ low_mem:
+ Avoids flattening potentially large input tensors. Unnecessary in most cases, and is ever so slightly
+ slower than the default setting.
+ Returns:
+ The reassembled output of the layer on the inputs.
+ """
+ if not (len(inputs) > 0):
+ raise ValueError("Must provide at least one input")
+
+ initial_dims = [shape[:no_batch_dims] for shape in _fetch_dims(inputs)]
+ orig_batch_dims = tuple(max(s) for s in zip(*initial_dims))
+
+ def _prep_inputs(t: torch.Tensor) -> torch.Tensor:
+ if not low_mem:
+ if sum(t.shape[:no_batch_dims]) != no_batch_dims:
+ t = t.expand(orig_batch_dims + t.shape[no_batch_dims:])
+ t = t.reshape(-1, *t.shape[no_batch_dims:])
+ else:
+ t = t.expand(orig_batch_dims + t.shape[no_batch_dims:])
+ return t
+
+ prepped_inputs: dict[str, Any] = tensor_tree_map(_prep_inputs, inputs)
+ prepped_outputs = None
+ if _out is not None:
+ prepped_outputs = tensor_tree_map(lambda t: t.view([-1] + list(t.shape[no_batch_dims:])), _out)
+
+ flat_batch_dim = 1
+ for d in orig_batch_dims:
+ flat_batch_dim *= d
+
+ no_chunks = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0)
+
+ def _select_chunk(t: torch.Tensor) -> torch.Tensor:
+ return t[i : i + chunk_size] if t.shape[0] != 1 else t
+
+ i = 0
+ out = prepped_outputs
+ for _ in range(no_chunks):
+ # Chunk the input
+ if not low_mem:
+ select_chunk = _select_chunk
+ else:
+ select_chunk = partial(
+ _chunk_slice,
+ flat_start=i,
+ flat_end=min(flat_batch_dim, i + chunk_size),
+ no_batch_dims=len(orig_batch_dims),
+ )
+
+ chunks: dict[str, Any] = tensor_tree_map(select_chunk, prepped_inputs)
+
+ # Run the layer on the chunk
+ output_chunk = layer(**chunks)
+
+ # Allocate space for the output
+ if out is None:
+ out = tensor_tree_map(lambda t: t.new_zeros((flat_batch_dim,) + t.shape[1:]), output_chunk)
+
+ # Put the chunk in its pre-allocated space
+ if isinstance(output_chunk, dict):
+
+ def assign(d1: dict, d2: dict) -> None:
+ for k, v in d1.items():
+ if isinstance(v, dict):
+ assign(v, d2[k])
+ else:
+ if _add_into_out:
+ v[i : i + chunk_size] += d2[k]
+ else:
+ v[i : i + chunk_size] = d2[k]
+
+ assign(out, output_chunk)
+ elif isinstance(output_chunk, tuple):
+ for x1, x2 in zip(out, output_chunk):
+ if _add_into_out:
+ x1[i : i + chunk_size] += x2
+ else:
+ x1[i : i + chunk_size] = x2
+ elif isinstance(output_chunk, torch.Tensor):
+ if _add_into_out:
+ out[i : i + chunk_size] += output_chunk
+ else:
+ out[i : i + chunk_size] = output_chunk
+ else:
+ raise TypeError("Not supported")
+
+ i += chunk_size
+
+ out = tensor_tree_map(lambda t: t.view(orig_batch_dims + t.shape[1:]), out)
+
+ return out
+
+
+class ChunkSizeTuner:
+ def __init__(
+ self,
+ # Heuristically, runtimes for most of the modules in the network
+ # plateau earlier than this on all GPUs I've run the model on.
+ max_chunk_size: int = 512,
+ ):
+ self.max_chunk_size = max_chunk_size
+ self.cached_chunk_size: Optional[int] = None
+ self.cached_arg_data: Optional[tuple] = None
+
+ def _determine_favorable_chunk_size(self, fn: Callable, args: tuple, min_chunk_size: int) -> int:
+ logging.info("Tuning chunk size...")
+
+ if min_chunk_size >= self.max_chunk_size:
+ return min_chunk_size
+
+ candidates: list[int] = [2**l for l in range(int(math.log(self.max_chunk_size, 2)) + 1)]
+ candidates = [c for c in candidates if c > min_chunk_size]
+ candidates = [min_chunk_size] + candidates
+ candidates[-1] += 4
+
+ def test_chunk_size(chunk_size: int) -> bool:
+ try:
+ with torch.no_grad():
+ fn(*args, chunk_size=chunk_size)
+ return True
+ except RuntimeError:
+ return False
+
+ min_viable_chunk_size_index = 0
+ i = len(candidates) - 1
+ while i > min_viable_chunk_size_index:
+ viable = test_chunk_size(candidates[i])
+ if not viable:
+ i = (min_viable_chunk_size_index + i) // 2
+ else:
+ min_viable_chunk_size_index = i
+ i = (i + len(candidates) - 1) // 2
+
+ return candidates[min_viable_chunk_size_index]
+
+ def _compare_arg_caches(self, ac1: Iterable, ac2: Iterable) -> bool:
+ consistent = True
+ for a1, a2 in zip(ac1, ac2):
+ assert type(ac1) is type(ac2)
+ if isinstance(ac1, (list, tuple)):
+ consistent &= self._compare_arg_caches(a1, a2)
+ elif isinstance(ac1, dict):
+ a1_items = [v for _, v in sorted(a1.items(), key=lambda x: x[0])]
+ a2_items = [v for _, v in sorted(a2.items(), key=lambda x: x[0])]
+ consistent &= self._compare_arg_caches(a1_items, a2_items)
+ else:
+ consistent &= a1 == a2
+
+ return consistent
+
+ def tune_chunk_size(
+ self,
+ representative_fn: Callable,
+ args: tuple,
+ min_chunk_size: int,
+ ) -> int:
+ consistent = True
+ arg_data: tuple = tree_map(lambda a: a.shape if isinstance(a, torch.Tensor) else a, args, object)
+ if self.cached_arg_data is not None:
+ # If args have changed shape/value, we need to re-tune
+ assert len(self.cached_arg_data) == len(arg_data)
+ consistent = self._compare_arg_caches(self.cached_arg_data, arg_data)
+ else:
+ # Otherwise, we can reuse the precomputed value
+ consistent = False
+
+ if not consistent:
+ self.cached_chunk_size = self._determine_favorable_chunk_size(
+ representative_fn,
+ args,
+ min_chunk_size,
+ )
+ self.cached_arg_data = arg_data
+
+ assert self.cached_chunk_size is not None
+
+ return self.cached_chunk_size
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/data_transforms.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/data_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcd67aacab8e5ee6d141166d1ec7fa94cba84e6d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/data_transforms.py
@@ -0,0 +1,90 @@
+# Copyright 2021 AlQuraishi Laboratory
+# Copyright 2021 DeepMind Technologies Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+import numpy as np
+import torch
+
+from . import residue_constants as rc
+from .tensor_utils import tensor_tree_map, tree_map
+
+
+def make_atom14_masks(protein: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
+ """Construct denser atom positions (14 dimensions instead of 37)."""
+ restype_atom14_to_atom37_list = []
+ restype_atom37_to_atom14_list = []
+ restype_atom14_mask_list = []
+
+ for rt in rc.restypes:
+ atom_names = rc.restype_name_to_atom14_names[rc.restype_1to3[rt]]
+ restype_atom14_to_atom37_list.append([(rc.atom_order[name] if name else 0) for name in atom_names])
+ atom_name_to_idx14 = {name: i for i, name in enumerate(atom_names)}
+ restype_atom37_to_atom14_list.append([(atom_name_to_idx14.get(name, 0)) for name in rc.atom_types])
+
+ restype_atom14_mask_list.append([(1.0 if name else 0.0) for name in atom_names])
+
+ # Add dummy mapping for restype 'UNK'
+ restype_atom14_to_atom37_list.append([0] * 14)
+ restype_atom37_to_atom14_list.append([0] * 37)
+ restype_atom14_mask_list.append([0.0] * 14)
+
+ restype_atom14_to_atom37 = torch.tensor(
+ restype_atom14_to_atom37_list,
+ dtype=torch.int32,
+ device=protein["aatype"].device,
+ )
+ restype_atom37_to_atom14 = torch.tensor(
+ restype_atom37_to_atom14_list,
+ dtype=torch.int32,
+ device=protein["aatype"].device,
+ )
+ restype_atom14_mask = torch.tensor(
+ restype_atom14_mask_list,
+ dtype=torch.float32,
+ device=protein["aatype"].device,
+ )
+ protein_aatype = protein["aatype"].to(torch.long)
+
+ # create the mapping for (residx, atom14) --> atom37, i.e. an array
+ # with shape (num_res, 14) containing the atom37 indices for this protein
+ residx_atom14_to_atom37 = restype_atom14_to_atom37[protein_aatype]
+ residx_atom14_mask = restype_atom14_mask[protein_aatype]
+
+ protein["atom14_atom_exists"] = residx_atom14_mask
+ protein["residx_atom14_to_atom37"] = residx_atom14_to_atom37.long()
+
+ # create the gather indices for mapping back
+ residx_atom37_to_atom14 = restype_atom37_to_atom14[protein_aatype]
+ protein["residx_atom37_to_atom14"] = residx_atom37_to_atom14.long()
+
+ # create the corresponding mask
+ restype_atom37_mask = torch.zeros([21, 37], dtype=torch.float32, device=protein["aatype"].device)
+ for restype, restype_letter in enumerate(rc.restypes):
+ restype_name = rc.restype_1to3[restype_letter]
+ atom_names = rc.residue_atoms[restype_name]
+ for atom_name in atom_names:
+ atom_type = rc.atom_order[atom_name]
+ restype_atom37_mask[restype, atom_type] = 1
+
+ residx_atom37_mask = restype_atom37_mask[protein_aatype]
+ protein["atom37_atom_exists"] = residx_atom37_mask
+
+ return protein
+
+
+def make_atom14_masks_np(batch: dict[str, torch.Tensor]) -> dict[str, np.ndarray]:
+ batch = tree_map(lambda n: torch.tensor(n, device=batch["aatype"].device), batch, np.ndarray)
+ out = tensor_tree_map(lambda t: np.array(t), make_atom14_masks(batch))
+ return out
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/feats.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/feats.py
new file mode 100644
index 0000000000000000000000000000000000000000..366f3c47d9466d0c5556b6eb7c365393785a82aa
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/feats.py
@@ -0,0 +1,253 @@
+# Copyright 2021 AlQuraishi Laboratory
+# Copyright 2021 DeepMind Technologies Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import overload
+
+import torch
+import torch.types
+from torch import nn
+
+from . import residue_constants as rc
+from .rigid_utils import Rigid, Rotation
+from .tensor_utils import batched_gather
+
+
+@overload
+def pseudo_beta_fn(aatype: torch.Tensor, all_atom_positions: torch.Tensor, all_atom_masks: None) -> torch.Tensor: ...
+
+
+@overload
+def pseudo_beta_fn(
+ aatype: torch.Tensor, all_atom_positions: torch.Tensor, all_atom_masks: torch.Tensor
+) -> tuple[torch.Tensor, torch.Tensor]: ...
+
+
+def pseudo_beta_fn(aatype, all_atom_positions, all_atom_masks):
+ is_gly = aatype == rc.restype_order["G"]
+ ca_idx = rc.atom_order["CA"]
+ cb_idx = rc.atom_order["CB"]
+ pseudo_beta = torch.where(
+ is_gly[..., None].expand(*((-1,) * len(is_gly.shape)), 3),
+ all_atom_positions[..., ca_idx, :],
+ all_atom_positions[..., cb_idx, :],
+ )
+
+ if all_atom_masks is not None:
+ pseudo_beta_mask = torch.where(
+ is_gly,
+ all_atom_masks[..., ca_idx],
+ all_atom_masks[..., cb_idx],
+ )
+ return pseudo_beta, pseudo_beta_mask
+ else:
+ return pseudo_beta
+
+
+def atom14_to_atom37(atom14: torch.Tensor, batch: dict[str, torch.Tensor]) -> torch.Tensor:
+ atom37_data = batched_gather(
+ atom14,
+ batch["residx_atom37_to_atom14"],
+ dim=-2,
+ no_batch_dims=len(atom14.shape[:-2]),
+ )
+
+ atom37_data = atom37_data * batch["atom37_atom_exists"][..., None]
+
+ return atom37_data
+
+
+def build_template_angle_feat(template_feats: dict[str, torch.Tensor]) -> torch.Tensor:
+ template_aatype = template_feats["template_aatype"]
+ torsion_angles_sin_cos = template_feats["template_torsion_angles_sin_cos"]
+ alt_torsion_angles_sin_cos = template_feats["template_alt_torsion_angles_sin_cos"]
+ torsion_angles_mask = template_feats["template_torsion_angles_mask"]
+ template_angle_feat = torch.cat(
+ [
+ nn.functional.one_hot(template_aatype, 22),
+ torsion_angles_sin_cos.reshape(*torsion_angles_sin_cos.shape[:-2], 14),
+ alt_torsion_angles_sin_cos.reshape(*alt_torsion_angles_sin_cos.shape[:-2], 14),
+ torsion_angles_mask,
+ ],
+ dim=-1,
+ )
+
+ return template_angle_feat
+
+
+def build_template_pair_feat(
+ batch: dict[str, torch.Tensor],
+ min_bin: torch.types.Number,
+ max_bin: torch.types.Number,
+ no_bins: int,
+ use_unit_vector: bool = False,
+ eps: float = 1e-20,
+ inf: float = 1e8,
+) -> torch.Tensor:
+ template_mask = batch["template_pseudo_beta_mask"]
+ template_mask_2d = template_mask[..., None] * template_mask[..., None, :]
+
+ # Compute distogram (this seems to differ slightly from Alg. 5)
+ tpb = batch["template_pseudo_beta"]
+ dgram = torch.sum((tpb[..., None, :] - tpb[..., None, :, :]) ** 2, dim=-1, keepdim=True)
+ lower = torch.linspace(min_bin, max_bin, no_bins, device=tpb.device) ** 2
+ upper = torch.cat([lower[1:], lower.new_tensor([inf])], dim=-1)
+ dgram = ((dgram > lower) * (dgram < upper)).type(dgram.dtype)
+
+ to_concat = [dgram, template_mask_2d[..., None]]
+
+ aatype_one_hot: torch.LongTensor = nn.functional.one_hot(
+ batch["template_aatype"],
+ rc.restype_num + 2,
+ )
+
+ n_res = batch["template_aatype"].shape[-1]
+ to_concat.append(aatype_one_hot[..., None, :, :].expand(*aatype_one_hot.shape[:-2], n_res, -1, -1))
+ to_concat.append(aatype_one_hot[..., None, :].expand(*aatype_one_hot.shape[:-2], -1, n_res, -1))
+
+ n, ca, c = [rc.atom_order[a] for a in ["N", "CA", "C"]]
+ rigids = Rigid.make_transform_from_reference(
+ n_xyz=batch["template_all_atom_positions"][..., n, :],
+ ca_xyz=batch["template_all_atom_positions"][..., ca, :],
+ c_xyz=batch["template_all_atom_positions"][..., c, :],
+ eps=eps,
+ )
+ points = rigids.get_trans()[..., None, :, :]
+ rigid_vec = rigids[..., None].invert_apply(points)
+
+ inv_distance_scalar = torch.rsqrt(eps + torch.sum(rigid_vec**2, dim=-1))
+
+ t_aa_masks = batch["template_all_atom_mask"]
+ template_mask = t_aa_masks[..., n] * t_aa_masks[..., ca] * t_aa_masks[..., c]
+ template_mask_2d = template_mask[..., None] * template_mask[..., None, :]
+
+ inv_distance_scalar = inv_distance_scalar * template_mask_2d
+ unit_vector = rigid_vec * inv_distance_scalar[..., None]
+
+ if not use_unit_vector:
+ unit_vector = unit_vector * 0.0
+
+ to_concat.extend(torch.unbind(unit_vector[..., None, :], dim=-1))
+ to_concat.append(template_mask_2d[..., None])
+
+ act = torch.cat(to_concat, dim=-1)
+ act = act * template_mask_2d[..., None]
+
+ return act
+
+
+def build_extra_msa_feat(batch: dict[str, torch.Tensor]) -> torch.Tensor:
+ msa_1hot: torch.LongTensor = nn.functional.one_hot(batch["extra_msa"], 23)
+ msa_feat = [
+ msa_1hot,
+ batch["extra_has_deletion"].unsqueeze(-1),
+ batch["extra_deletion_value"].unsqueeze(-1),
+ ]
+ return torch.cat(msa_feat, dim=-1)
+
+
+def torsion_angles_to_frames(
+ r: Rigid,
+ alpha: torch.Tensor,
+ aatype: torch.Tensor,
+ rrgdf: torch.Tensor,
+) -> Rigid:
+ # [*, N, 8, 4, 4]
+ default_4x4 = rrgdf[aatype, ...]
+
+ # [*, N, 8] transformations, i.e.
+ # One [*, N, 8, 3, 3] rotation matrix and
+ # One [*, N, 8, 3] translation matrix
+ default_r = r.from_tensor_4x4(default_4x4)
+
+ bb_rot = alpha.new_zeros((*((1,) * len(alpha.shape[:-1])), 2))
+ bb_rot[..., 1] = 1
+
+ # [*, N, 8, 2]
+ alpha = torch.cat([bb_rot.expand(*alpha.shape[:-2], -1, -1), alpha], dim=-2)
+
+ # [*, N, 8, 3, 3]
+ # Produces rotation matrices of the form:
+ # [
+ # [1, 0 , 0 ],
+ # [0, a_2,-a_1],
+ # [0, a_1, a_2]
+ # ]
+ # This follows the original code rather than the supplement, which uses
+ # different indices.
+
+ all_rots = alpha.new_zeros(default_r.get_rots().get_rot_mats().shape)
+ all_rots[..., 0, 0] = 1
+ all_rots[..., 1, 1] = alpha[..., 1]
+ all_rots[..., 1, 2] = -alpha[..., 0]
+ all_rots[..., 2, 1:] = alpha
+
+ all_frames = default_r.compose(Rigid(Rotation(rot_mats=all_rots), None))
+
+ chi2_frame_to_frame = all_frames[..., 5]
+ chi3_frame_to_frame = all_frames[..., 6]
+ chi4_frame_to_frame = all_frames[..., 7]
+
+ chi1_frame_to_bb = all_frames[..., 4]
+ chi2_frame_to_bb = chi1_frame_to_bb.compose(chi2_frame_to_frame)
+ chi3_frame_to_bb = chi2_frame_to_bb.compose(chi3_frame_to_frame)
+ chi4_frame_to_bb = chi3_frame_to_bb.compose(chi4_frame_to_frame)
+
+ all_frames_to_bb = Rigid.cat(
+ [
+ all_frames[..., :5],
+ chi2_frame_to_bb.unsqueeze(-1),
+ chi3_frame_to_bb.unsqueeze(-1),
+ chi4_frame_to_bb.unsqueeze(-1),
+ ],
+ dim=-1,
+ )
+
+ all_frames_to_global = r[..., None].compose(all_frames_to_bb)
+
+ return all_frames_to_global
+
+
+def frames_and_literature_positions_to_atom14_pos(
+ r: Rigid,
+ aatype: torch.Tensor,
+ default_frames: torch.Tensor,
+ group_idx: torch.Tensor,
+ atom_mask: torch.Tensor,
+ lit_positions: torch.Tensor,
+) -> torch.Tensor:
+ # [*, N, 14]
+ group_mask = group_idx[aatype, ...]
+
+ # [*, N, 14, 8]
+ group_mask_one_hot: torch.LongTensor = nn.functional.one_hot(
+ group_mask,
+ num_classes=default_frames.shape[-3],
+ )
+
+ # [*, N, 14, 8]
+ t_atoms_to_global = r[..., None, :] * group_mask_one_hot
+
+ # [*, N, 14]
+ t_atoms_to_global = t_atoms_to_global.map_tensor_fn(lambda x: torch.sum(x, dim=-1))
+
+ # [*, N, 14, 1]
+ atom_mask = atom_mask[aatype, ...].unsqueeze(-1)
+
+ # [*, N, 14, 3]
+ lit_positions = lit_positions[aatype, ...]
+ pred_positions = t_atoms_to_global.apply(lit_positions)
+ pred_positions = pred_positions * atom_mask
+
+ return pred_positions
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/loss.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cd9f8c6b42f3091b05bcb2fb6550c36b40e9943
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/loss.py
@@ -0,0 +1,105 @@
+# Copyright 2021 AlQuraishi Laboratory
+# Copyright 2021 DeepMind Technologies Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import Optional
+
+import torch
+
+
+def _calculate_bin_centers(boundaries: torch.Tensor) -> torch.Tensor:
+ step = boundaries[1] - boundaries[0]
+ bin_centers = boundaries + step / 2
+ bin_centers = torch.cat([bin_centers, (bin_centers[-1] + step).unsqueeze(-1)], dim=0)
+ return bin_centers
+
+
+def _calculate_expected_aligned_error(
+ alignment_confidence_breaks: torch.Tensor,
+ aligned_distance_error_probs: torch.Tensor,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ bin_centers = _calculate_bin_centers(alignment_confidence_breaks)
+ return (
+ torch.sum(aligned_distance_error_probs * bin_centers, dim=-1),
+ bin_centers[-1],
+ )
+
+
+def compute_predicted_aligned_error(
+ logits: torch.Tensor,
+ max_bin: int = 31,
+ no_bins: int = 64,
+ **kwargs,
+) -> dict[str, torch.Tensor]:
+ """Computes aligned confidence metrics from logits.
+
+ Args:
+ logits: [*, num_res, num_res, num_bins] the logits output from
+ PredictedAlignedErrorHead.
+ max_bin: Maximum bin value
+ no_bins: Number of bins
+ Returns:
+ aligned_confidence_probs: [*, num_res, num_res, num_bins] the predicted
+ aligned error probabilities over bins for each residue pair.
+ predicted_aligned_error: [*, num_res, num_res] the expected aligned distance
+ error for each pair of residues.
+ max_predicted_aligned_error: [*] the maximum predicted error possible.
+ """
+ boundaries = torch.linspace(0, max_bin, steps=(no_bins - 1), device=logits.device)
+
+ aligned_confidence_probs = torch.nn.functional.softmax(logits, dim=-1)
+ predicted_aligned_error, max_predicted_aligned_error = _calculate_expected_aligned_error(
+ alignment_confidence_breaks=boundaries,
+ aligned_distance_error_probs=aligned_confidence_probs,
+ )
+
+ return {
+ "aligned_confidence_probs": aligned_confidence_probs,
+ "predicted_aligned_error": predicted_aligned_error,
+ "max_predicted_aligned_error": max_predicted_aligned_error,
+ }
+
+
+def compute_tm(
+ logits: torch.Tensor,
+ residue_weights: Optional[torch.Tensor] = None,
+ max_bin: int = 31,
+ no_bins: int = 64,
+ eps: float = 1e-8,
+ **kwargs,
+) -> torch.Tensor:
+ if residue_weights is None:
+ residue_weights = logits.new_ones(logits.shape[-2])
+
+ boundaries = torch.linspace(0, max_bin, steps=(no_bins - 1), device=logits.device)
+
+ bin_centers = _calculate_bin_centers(boundaries)
+ torch.sum(residue_weights)
+ n = logits.shape[-2]
+ clipped_n = max(n, 19)
+
+ d0 = 1.24 * (clipped_n - 15) ** (1.0 / 3) - 1.8
+
+ probs = torch.nn.functional.softmax(logits, dim=-1)
+
+ tm_per_bin = 1.0 / (1 + (bin_centers**2) / (d0**2))
+ predicted_tm_term = torch.sum(probs * tm_per_bin, dim=-1)
+
+ normed_residue_mask = residue_weights / (eps + residue_weights.sum())
+ per_alignment = torch.sum(predicted_tm_term * normed_residue_mask, dim=-1)
+
+ weighted = per_alignment * residue_weights
+
+ argmax = (weighted == torch.max(weighted)).nonzero()[0]
+ return per_alignment[tuple(argmax)]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/protein.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/protein.py
new file mode 100644
index 0000000000000000000000000000000000000000..a943eb7acf72edf09974c250f21d74361b26484d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/protein.py
@@ -0,0 +1,331 @@
+# Copyright 2021 AlQuraishi Laboratory
+# Copyright 2021 DeepMind Technologies Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Protein data type."""
+
+import dataclasses
+import re
+import string
+from collections.abc import Iterator, Mapping, Sequence
+from typing import Any, Optional
+
+import numpy as np
+
+from . import residue_constants
+
+
+FeatureDict = Mapping[str, np.ndarray]
+ModelOutput = Mapping[str, Any] # Is a nested dict.
+PICO_TO_ANGSTROM = 0.01
+
+
+@dataclasses.dataclass(frozen=True)
+class Protein:
+ """Protein structure representation."""
+
+ # Cartesian coordinates of atoms in angstroms. The atom types correspond to
+ # residue_constants.atom_types, i.e. the first three are N, CA, CB.
+ atom_positions: np.ndarray # [num_res, num_atom_type, 3]
+
+ # Amino-acid type for each residue represented as an integer between 0 and
+ # 20, where 20 is 'X'.
+ aatype: np.ndarray # [num_res]
+
+ # Binary float mask to indicate presence of a particular atom. 1.0 if an atom
+ # is present and 0.0 if not. This should be used for loss masking.
+ atom_mask: np.ndarray # [num_res, num_atom_type]
+
+ # Residue index as used in PDB. It is not necessarily continuous or 0-indexed.
+ residue_index: np.ndarray # [num_res]
+
+ # B-factors, or temperature factors, of each residue (in sq. angstroms units),
+ # representing the displacement of the residue from its ground truth mean
+ # value.
+ b_factors: np.ndarray # [num_res, num_atom_type]
+
+ # Chain indices for multi-chain predictions
+ chain_index: Optional[np.ndarray] = None
+
+ # Optional remark about the protein. Included as a comment in output PDB
+ # files
+ remark: Optional[str] = None
+
+ # Templates used to generate this protein (prediction-only)
+ parents: Optional[Sequence[str]] = None
+
+ # Chain corresponding to each parent
+ parents_chain_index: Optional[Sequence[int]] = None
+
+
+def from_proteinnet_string(proteinnet_str: str) -> Protein:
+ tag_re = r"(\[[A-Z]+\]\n)"
+ tags: list[str] = [tag.strip() for tag in re.split(tag_re, proteinnet_str) if len(tag) > 0]
+ groups: Iterator[tuple[str, list[str]]] = zip(tags[0::2], [l.split("\n") for l in tags[1::2]])
+
+ atoms: list[str] = ["N", "CA", "C"]
+ aatype = None
+ atom_positions = None
+ atom_mask = None
+ for g in groups:
+ if "[PRIMARY]" == g[0]:
+ seq = g[1][0].strip()
+ for i in range(len(seq)):
+ if seq[i] not in residue_constants.restypes:
+ seq[i] = "X" # FIXME: strings are immutable
+ aatype = np.array(
+ [residue_constants.restype_order.get(res_symbol, residue_constants.restype_num) for res_symbol in seq]
+ )
+ elif "[TERTIARY]" == g[0]:
+ tertiary: list[list[float]] = []
+ for axis in range(3):
+ tertiary.append(list(map(float, g[1][axis].split())))
+ tertiary_np = np.array(tertiary)
+ atom_positions = np.zeros((len(tertiary[0]) // 3, residue_constants.atom_type_num, 3)).astype(np.float32)
+ for i, atom in enumerate(atoms):
+ atom_positions[:, residue_constants.atom_order[atom], :] = np.transpose(tertiary_np[:, i::3])
+ atom_positions *= PICO_TO_ANGSTROM
+ elif "[MASK]" == g[0]:
+ mask = np.array(list(map({"-": 0, "+": 1}.get, g[1][0].strip())))
+ atom_mask = np.zeros(
+ (
+ len(mask),
+ residue_constants.atom_type_num,
+ )
+ ).astype(np.float32)
+ for i, atom in enumerate(atoms):
+ atom_mask[:, residue_constants.atom_order[atom]] = 1
+ atom_mask *= mask[..., None]
+
+ assert aatype is not None
+
+ return Protein(
+ atom_positions=atom_positions,
+ atom_mask=atom_mask,
+ aatype=aatype,
+ residue_index=np.arange(len(aatype)),
+ b_factors=None,
+ )
+
+
+def get_pdb_headers(prot: Protein, chain_id: int = 0) -> list[str]:
+ pdb_headers: list[str] = []
+
+ remark = prot.remark
+ if remark is not None:
+ pdb_headers.append(f"REMARK {remark}")
+
+ parents = prot.parents
+ parents_chain_index = prot.parents_chain_index
+ if parents is not None and parents_chain_index is not None:
+ parents = [p for i, p in zip(parents_chain_index, parents) if i == chain_id]
+
+ if parents is None or len(parents) == 0:
+ parents = ["N/A"]
+
+ pdb_headers.append(f"PARENT {' '.join(parents)}")
+
+ return pdb_headers
+
+
+def add_pdb_headers(prot: Protein, pdb_str: str) -> str:
+ """Add pdb headers to an existing PDB string. Useful during multi-chain
+ recycling
+ """
+ out_pdb_lines: list[str] = []
+ lines = pdb_str.split("\n")
+
+ remark = prot.remark
+ if remark is not None:
+ out_pdb_lines.append(f"REMARK {remark}")
+
+ parents_per_chain: list[list[str]]
+ if prot.parents is not None and len(prot.parents) > 0:
+ parents_per_chain = []
+ if prot.parents_chain_index is not None:
+ parent_dict: dict[str, list[str]] = {}
+ for p, i in zip(prot.parents, prot.parents_chain_index):
+ parent_dict.setdefault(str(i), [])
+ parent_dict[str(i)].append(p)
+
+ max_idx = max([int(chain_idx) for chain_idx in parent_dict])
+ for i in range(max_idx + 1):
+ chain_parents = parent_dict.get(str(i), ["N/A"])
+ parents_per_chain.append(chain_parents)
+ else:
+ parents_per_chain.append(list(prot.parents))
+ else:
+ parents_per_chain = [["N/A"]]
+
+ def make_parent_line(p: Sequence[str]) -> str:
+ return f"PARENT {' '.join(p)}"
+
+ out_pdb_lines.append(make_parent_line(parents_per_chain[0]))
+
+ chain_counter = 0
+ for i, l in enumerate(lines):
+ if "PARENT" not in l and "REMARK" not in l:
+ out_pdb_lines.append(l)
+ if "TER" in l and "END" not in lines[i + 1]:
+ chain_counter += 1
+ if not chain_counter >= len(parents_per_chain):
+ chain_parents = parents_per_chain[chain_counter]
+ else:
+ chain_parents = ["N/A"]
+
+ out_pdb_lines.append(make_parent_line(chain_parents))
+
+ return "\n".join(out_pdb_lines)
+
+
+def to_pdb(prot: Protein) -> str:
+ """Converts a `Protein` instance to a PDB string.
+
+ Args:
+ prot: The protein to convert to PDB.
+
+ Returns:
+ PDB string.
+ """
+ restypes = residue_constants.restypes + ["X"]
+
+ def res_1to3(r: int) -> str:
+ return residue_constants.restype_1to3.get(restypes[r], "UNK")
+
+ atom_types = residue_constants.atom_types
+
+ pdb_lines: list[str] = []
+
+ atom_mask = prot.atom_mask
+ aatype = prot.aatype
+ atom_positions = prot.atom_positions
+ residue_index = prot.residue_index.astype(np.int32)
+ b_factors = prot.b_factors
+ chain_index = prot.chain_index
+
+ if np.any(aatype > residue_constants.restype_num):
+ raise ValueError("Invalid aatypes.")
+
+ headers = get_pdb_headers(prot)
+ if len(headers) > 0:
+ pdb_lines.extend(headers)
+
+ n = aatype.shape[0]
+ atom_index = 1
+ prev_chain_index = 0
+ chain_tags = string.ascii_uppercase
+ chain_tag = None
+ # Add all atom sites.
+ for i in range(n):
+ res_name_3 = res_1to3(aatype[i])
+ for atom_name, pos, mask, b_factor in zip(atom_types, atom_positions[i], atom_mask[i], b_factors[i]):
+ if mask < 0.5:
+ continue
+
+ record_type = "ATOM"
+ name = atom_name if len(atom_name) == 4 else f" {atom_name}"
+ alt_loc = ""
+ insertion_code = ""
+ occupancy = 1.00
+ element = atom_name[0] # Protein supports only C, N, O, S, this works.
+ charge = ""
+
+ chain_tag = "A"
+ if chain_index is not None:
+ chain_tag = chain_tags[chain_index[i]]
+
+ # PDB is a columnar format, every space matters here!
+ atom_line = (
+ f"{record_type:<6}{atom_index:>5} {name:<4}{alt_loc:>1}"
+ f"{res_name_3:>3} {chain_tag:>1}"
+ f"{residue_index[i]:>4}{insertion_code:>1} "
+ f"{pos[0]:>8.3f}{pos[1]:>8.3f}{pos[2]:>8.3f}"
+ f"{occupancy:>6.2f}{b_factor:>6.2f} "
+ f"{element:>2}{charge:>2}"
+ )
+ pdb_lines.append(atom_line)
+ atom_index += 1
+
+ should_terminate = i == n - 1
+ if chain_index is not None:
+ if i != n - 1 and chain_index[i + 1] != prev_chain_index:
+ should_terminate = True
+ prev_chain_index = chain_index[i + 1]
+
+ if should_terminate:
+ # Close the chain.
+ chain_end = "TER"
+ chain_termination_line = (
+ f"{chain_end:<6}{atom_index:>5} {res_1to3(aatype[i]):>3} {chain_tag:>1}{residue_index[i]:>4}"
+ )
+ pdb_lines.append(chain_termination_line)
+ atom_index += 1
+
+ if i != n - 1:
+ # "prev" is a misnomer here. This happens at the beginning of
+ # each new chain.
+ pdb_lines.extend(get_pdb_headers(prot, prev_chain_index))
+
+ pdb_lines.append("END")
+ pdb_lines.append("")
+ return "\n".join(pdb_lines)
+
+
+def ideal_atom_mask(prot: Protein) -> np.ndarray:
+ """Computes an ideal atom mask.
+
+ `Protein.atom_mask` typically is defined according to the atoms that are reported in the PDB. This function
+ computes a mask according to heavy atoms that should be present in the given sequence of amino acids.
+
+ Args:
+ prot: `Protein` whose fields are `numpy.ndarray` objects.
+
+ Returns:
+ An ideal atom mask.
+ """
+ return residue_constants.STANDARD_ATOM_MASK[prot.aatype]
+
+
+def from_prediction(
+ features: FeatureDict,
+ result: ModelOutput,
+ b_factors: Optional[np.ndarray] = None,
+ chain_index: Optional[np.ndarray] = None,
+ remark: Optional[str] = None,
+ parents: Optional[Sequence[str]] = None,
+ parents_chain_index: Optional[Sequence[int]] = None,
+) -> Protein:
+ """Assembles a protein from a prediction.
+
+ Args:
+ features: Dictionary holding model inputs.
+ result: Dictionary holding model outputs.
+ b_factors: (Optional) B-factors to use for the protein.
+ chain_index: (Optional) Chain indices for multi-chain predictions
+ remark: (Optional) Remark about the prediction
+ parents: (Optional) List of template names
+ Returns:
+ A protein instance.
+ """
+ return Protein(
+ aatype=features["aatype"],
+ atom_positions=result["final_atom_positions"],
+ atom_mask=result["final_atom_mask"],
+ residue_index=features["residue_index"] + 1,
+ b_factors=b_factors if b_factors is not None else np.zeros_like(result["final_atom_mask"]),
+ chain_index=chain_index,
+ remark=remark,
+ parents=parents,
+ parents_chain_index=parents_chain_index,
+ )
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/residue_constants.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/residue_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..e92e65d29bfb2e7a0ad640e71d983c1c467d3a54
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/residue_constants.py
@@ -0,0 +1,979 @@
+# Copyright 2021 AlQuraishi Laboratory
+# Copyright 2021 DeepMind Technologies Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Constants used in AlphaFold."""
+
+import collections
+import copy
+import functools
+from collections.abc import Mapping, Sequence
+from importlib import resources
+
+import numpy as np
+
+
+# Internal import (35fd).
+
+
+# Distance from one CA to next CA [trans configuration: omega = 180].
+ca_ca = 3.80209737096
+
+# Format: The list for each AA type contains chi1, chi2, chi3, chi4 in
+# this order (or a relevant subset from chi1 onwards). ALA and GLY don't have
+# chi angles so their chi angle lists are empty.
+chi_angles_atoms: dict[str, list[list[str]]] = {
+ "ALA": [],
+ # Chi5 in arginine is always 0 +- 5 degrees, so ignore it.
+ "ARG": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD"], ["CB", "CG", "CD", "NE"], ["CG", "CD", "NE", "CZ"]],
+ "ASN": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "OD1"]],
+ "ASP": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "OD1"]],
+ "CYS": [["N", "CA", "CB", "SG"]],
+ "GLN": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD"], ["CB", "CG", "CD", "OE1"]],
+ "GLU": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD"], ["CB", "CG", "CD", "OE1"]],
+ "GLY": [],
+ "HIS": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "ND1"]],
+ "ILE": [["N", "CA", "CB", "CG1"], ["CA", "CB", "CG1", "CD1"]],
+ "LEU": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD1"]],
+ "LYS": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD"], ["CB", "CG", "CD", "CE"], ["CG", "CD", "CE", "NZ"]],
+ "MET": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "SD"], ["CB", "CG", "SD", "CE"]],
+ "PHE": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD1"]],
+ "PRO": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD"]],
+ "SER": [["N", "CA", "CB", "OG"]],
+ "THR": [["N", "CA", "CB", "OG1"]],
+ "TRP": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD1"]],
+ "TYR": [["N", "CA", "CB", "CG"], ["CA", "CB", "CG", "CD1"]],
+ "VAL": [["N", "CA", "CB", "CG1"]],
+}
+
+# If chi angles given in fixed-length array, this matrix determines how to mask
+# them for each AA type. The order is as per restype_order (see below).
+chi_angles_mask: list[list[float]] = [
+ [0.0, 0.0, 0.0, 0.0], # ALA
+ [1.0, 1.0, 1.0, 1.0], # ARG
+ [1.0, 1.0, 0.0, 0.0], # ASN
+ [1.0, 1.0, 0.0, 0.0], # ASP
+ [1.0, 0.0, 0.0, 0.0], # CYS
+ [1.0, 1.0, 1.0, 0.0], # GLN
+ [1.0, 1.0, 1.0, 0.0], # GLU
+ [0.0, 0.0, 0.0, 0.0], # GLY
+ [1.0, 1.0, 0.0, 0.0], # HIS
+ [1.0, 1.0, 0.0, 0.0], # ILE
+ [1.0, 1.0, 0.0, 0.0], # LEU
+ [1.0, 1.0, 1.0, 1.0], # LYS
+ [1.0, 1.0, 1.0, 0.0], # MET
+ [1.0, 1.0, 0.0, 0.0], # PHE
+ [1.0, 1.0, 0.0, 0.0], # PRO
+ [1.0, 0.0, 0.0, 0.0], # SER
+ [1.0, 0.0, 0.0, 0.0], # THR
+ [1.0, 1.0, 0.0, 0.0], # TRP
+ [1.0, 1.0, 0.0, 0.0], # TYR
+ [1.0, 0.0, 0.0, 0.0], # VAL
+]
+
+# The following chi angles are pi periodic: they can be rotated by a multiple
+# of pi without affecting the structure.
+chi_pi_periodic: list[list[float]] = [
+ [0.0, 0.0, 0.0, 0.0], # ALA
+ [0.0, 0.0, 0.0, 0.0], # ARG
+ [0.0, 0.0, 0.0, 0.0], # ASN
+ [0.0, 1.0, 0.0, 0.0], # ASP
+ [0.0, 0.0, 0.0, 0.0], # CYS
+ [0.0, 0.0, 0.0, 0.0], # GLN
+ [0.0, 0.0, 1.0, 0.0], # GLU
+ [0.0, 0.0, 0.0, 0.0], # GLY
+ [0.0, 0.0, 0.0, 0.0], # HIS
+ [0.0, 0.0, 0.0, 0.0], # ILE
+ [0.0, 0.0, 0.0, 0.0], # LEU
+ [0.0, 0.0, 0.0, 0.0], # LYS
+ [0.0, 0.0, 0.0, 0.0], # MET
+ [0.0, 1.0, 0.0, 0.0], # PHE
+ [0.0, 0.0, 0.0, 0.0], # PRO
+ [0.0, 0.0, 0.0, 0.0], # SER
+ [0.0, 0.0, 0.0, 0.0], # THR
+ [0.0, 0.0, 0.0, 0.0], # TRP
+ [0.0, 1.0, 0.0, 0.0], # TYR
+ [0.0, 0.0, 0.0, 0.0], # VAL
+ [0.0, 0.0, 0.0, 0.0], # UNK
+]
+
+# Atoms positions relative to the 8 rigid groups, defined by the pre-omega, phi,
+# psi and chi angles:
+# 0: 'backbone group',
+# 1: 'pre-omega-group', (empty)
+# 2: 'phi-group', (currently empty, because it defines only hydrogens)
+# 3: 'psi-group',
+# 4,5,6,7: 'chi1,2,3,4-group'
+# The atom positions are relative to the axis-end-atom of the corresponding
+# rotation axis. The x-axis is in direction of the rotation axis, and the y-axis
+# is defined such that the dihedral-angle-definiting atom (the last entry in
+# chi_angles_atoms above) is in the xy-plane (with a positive y-coordinate).
+# format: [atomname, group_idx, rel_position]
+rigid_group_atom_positions: dict[str, list[tuple[str, int, tuple[float, float, float]]]] = {
+ "ALA": [
+ ("N", 0, (-0.525, 1.363, 0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.526, -0.000, -0.000)),
+ ("CB", 0, (-0.529, -0.774, -1.205)),
+ ("O", 3, (0.627, 1.062, 0.000)),
+ ],
+ "ARG": [
+ ("N", 0, (-0.524, 1.362, -0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.525, -0.000, -0.000)),
+ ("CB", 0, (-0.524, -0.778, -1.209)),
+ ("O", 3, (0.626, 1.062, 0.000)),
+ ("CG", 4, (0.616, 1.390, -0.000)),
+ ("CD", 5, (0.564, 1.414, 0.000)),
+ ("NE", 6, (0.539, 1.357, -0.000)),
+ ("NH1", 7, (0.206, 2.301, 0.000)),
+ ("NH2", 7, (2.078, 0.978, -0.000)),
+ ("CZ", 7, (0.758, 1.093, -0.000)),
+ ],
+ "ASN": [
+ ("N", 0, (-0.536, 1.357, 0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.526, -0.000, -0.000)),
+ ("CB", 0, (-0.531, -0.787, -1.200)),
+ ("O", 3, (0.625, 1.062, 0.000)),
+ ("CG", 4, (0.584, 1.399, 0.000)),
+ ("ND2", 5, (0.593, -1.188, 0.001)),
+ ("OD1", 5, (0.633, 1.059, 0.000)),
+ ],
+ "ASP": [
+ ("N", 0, (-0.525, 1.362, -0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.527, 0.000, -0.000)),
+ ("CB", 0, (-0.526, -0.778, -1.208)),
+ ("O", 3, (0.626, 1.062, -0.000)),
+ ("CG", 4, (0.593, 1.398, -0.000)),
+ ("OD1", 5, (0.610, 1.091, 0.000)),
+ ("OD2", 5, (0.592, -1.101, -0.003)),
+ ],
+ "CYS": [
+ ("N", 0, (-0.522, 1.362, -0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.524, 0.000, 0.000)),
+ ("CB", 0, (-0.519, -0.773, -1.212)),
+ ("O", 3, (0.625, 1.062, -0.000)),
+ ("SG", 4, (0.728, 1.653, 0.000)),
+ ],
+ "GLN": [
+ ("N", 0, (-0.526, 1.361, -0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.526, 0.000, 0.000)),
+ ("CB", 0, (-0.525, -0.779, -1.207)),
+ ("O", 3, (0.626, 1.062, -0.000)),
+ ("CG", 4, (0.615, 1.393, 0.000)),
+ ("CD", 5, (0.587, 1.399, -0.000)),
+ ("NE2", 6, (0.593, -1.189, -0.001)),
+ ("OE1", 6, (0.634, 1.060, 0.000)),
+ ],
+ "GLU": [
+ ("N", 0, (-0.528, 1.361, 0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.526, -0.000, -0.000)),
+ ("CB", 0, (-0.526, -0.781, -1.207)),
+ ("O", 3, (0.626, 1.062, 0.000)),
+ ("CG", 4, (0.615, 1.392, 0.000)),
+ ("CD", 5, (0.600, 1.397, 0.000)),
+ ("OE1", 6, (0.607, 1.095, -0.000)),
+ ("OE2", 6, (0.589, -1.104, -0.001)),
+ ],
+ "GLY": [
+ ("N", 0, (-0.572, 1.337, 0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.517, -0.000, -0.000)),
+ ("O", 3, (0.626, 1.062, -0.000)),
+ ],
+ "HIS": [
+ ("N", 0, (-0.527, 1.360, 0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.525, 0.000, 0.000)),
+ ("CB", 0, (-0.525, -0.778, -1.208)),
+ ("O", 3, (0.625, 1.063, 0.000)),
+ ("CG", 4, (0.600, 1.370, -0.000)),
+ ("CD2", 5, (0.889, -1.021, 0.003)),
+ ("ND1", 5, (0.744, 1.160, -0.000)),
+ ("CE1", 5, (2.030, 0.851, 0.002)),
+ ("NE2", 5, (2.145, -0.466, 0.004)),
+ ],
+ "ILE": [
+ ("N", 0, (-0.493, 1.373, -0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.527, -0.000, -0.000)),
+ ("CB", 0, (-0.536, -0.793, -1.213)),
+ ("O", 3, (0.627, 1.062, -0.000)),
+ ("CG1", 4, (0.534, 1.437, -0.000)),
+ ("CG2", 4, (0.540, -0.785, -1.199)),
+ ("CD1", 5, (0.619, 1.391, 0.000)),
+ ],
+ "LEU": [
+ ("N", 0, (-0.520, 1.363, 0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.525, -0.000, -0.000)),
+ ("CB", 0, (-0.522, -0.773, -1.214)),
+ ("O", 3, (0.625, 1.063, -0.000)),
+ ("CG", 4, (0.678, 1.371, 0.000)),
+ ("CD1", 5, (0.530, 1.430, -0.000)),
+ ("CD2", 5, (0.535, -0.774, 1.200)),
+ ],
+ "LYS": [
+ ("N", 0, (-0.526, 1.362, -0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.526, 0.000, 0.000)),
+ ("CB", 0, (-0.524, -0.778, -1.208)),
+ ("O", 3, (0.626, 1.062, -0.000)),
+ ("CG", 4, (0.619, 1.390, 0.000)),
+ ("CD", 5, (0.559, 1.417, 0.000)),
+ ("CE", 6, (0.560, 1.416, 0.000)),
+ ("NZ", 7, (0.554, 1.387, 0.000)),
+ ],
+ "MET": [
+ ("N", 0, (-0.521, 1.364, -0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.525, 0.000, 0.000)),
+ ("CB", 0, (-0.523, -0.776, -1.210)),
+ ("O", 3, (0.625, 1.062, -0.000)),
+ ("CG", 4, (0.613, 1.391, -0.000)),
+ ("SD", 5, (0.703, 1.695, 0.000)),
+ ("CE", 6, (0.320, 1.786, -0.000)),
+ ],
+ "PHE": [
+ ("N", 0, (-0.518, 1.363, 0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.524, 0.000, -0.000)),
+ ("CB", 0, (-0.525, -0.776, -1.212)),
+ ("O", 3, (0.626, 1.062, -0.000)),
+ ("CG", 4, (0.607, 1.377, 0.000)),
+ ("CD1", 5, (0.709, 1.195, -0.000)),
+ ("CD2", 5, (0.706, -1.196, 0.000)),
+ ("CE1", 5, (2.102, 1.198, -0.000)),
+ ("CE2", 5, (2.098, -1.201, -0.000)),
+ ("CZ", 5, (2.794, -0.003, -0.001)),
+ ],
+ "PRO": [
+ ("N", 0, (-0.566, 1.351, -0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.527, -0.000, 0.000)),
+ ("CB", 0, (-0.546, -0.611, -1.293)),
+ ("O", 3, (0.621, 1.066, 0.000)),
+ ("CG", 4, (0.382, 1.445, 0.0)),
+ # ('CD', 5, (0.427, 1.440, 0.0)),
+ ("CD", 5, (0.477, 1.424, 0.0)), # manually made angle 2 degrees larger
+ ],
+ "SER": [
+ ("N", 0, (-0.529, 1.360, -0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.525, -0.000, -0.000)),
+ ("CB", 0, (-0.518, -0.777, -1.211)),
+ ("O", 3, (0.626, 1.062, -0.000)),
+ ("OG", 4, (0.503, 1.325, 0.000)),
+ ],
+ "THR": [
+ ("N", 0, (-0.517, 1.364, 0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.526, 0.000, -0.000)),
+ ("CB", 0, (-0.516, -0.793, -1.215)),
+ ("O", 3, (0.626, 1.062, 0.000)),
+ ("CG2", 4, (0.550, -0.718, -1.228)),
+ ("OG1", 4, (0.472, 1.353, 0.000)),
+ ],
+ "TRP": [
+ ("N", 0, (-0.521, 1.363, 0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.525, -0.000, 0.000)),
+ ("CB", 0, (-0.523, -0.776, -1.212)),
+ ("O", 3, (0.627, 1.062, 0.000)),
+ ("CG", 4, (0.609, 1.370, -0.000)),
+ ("CD1", 5, (0.824, 1.091, 0.000)),
+ ("CD2", 5, (0.854, -1.148, -0.005)),
+ ("CE2", 5, (2.186, -0.678, -0.007)),
+ ("CE3", 5, (0.622, -2.530, -0.007)),
+ ("NE1", 5, (2.140, 0.690, -0.004)),
+ ("CH2", 5, (3.028, -2.890, -0.013)),
+ ("CZ2", 5, (3.283, -1.543, -0.011)),
+ ("CZ3", 5, (1.715, -3.389, -0.011)),
+ ],
+ "TYR": [
+ ("N", 0, (-0.522, 1.362, 0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.524, -0.000, -0.000)),
+ ("CB", 0, (-0.522, -0.776, -1.213)),
+ ("O", 3, (0.627, 1.062, -0.000)),
+ ("CG", 4, (0.607, 1.382, -0.000)),
+ ("CD1", 5, (0.716, 1.195, -0.000)),
+ ("CD2", 5, (0.713, -1.194, -0.001)),
+ ("CE1", 5, (2.107, 1.200, -0.002)),
+ ("CE2", 5, (2.104, -1.201, -0.003)),
+ ("OH", 5, (4.168, -0.002, -0.005)),
+ ("CZ", 5, (2.791, -0.001, -0.003)),
+ ],
+ "VAL": [
+ ("N", 0, (-0.494, 1.373, -0.000)),
+ ("CA", 0, (0.000, 0.000, 0.000)),
+ ("C", 0, (1.527, -0.000, -0.000)),
+ ("CB", 0, (-0.533, -0.795, -1.213)),
+ ("O", 3, (0.627, 1.062, -0.000)),
+ ("CG1", 4, (0.540, 1.429, -0.000)),
+ ("CG2", 4, (0.533, -0.776, 1.203)),
+ ],
+}
+
+# A list of atoms (excluding hydrogen) for each AA type. PDB naming convention.
+residue_atoms: dict[str, list[str]] = {
+ "ALA": ["C", "CA", "CB", "N", "O"],
+ "ARG": ["C", "CA", "CB", "CG", "CD", "CZ", "N", "NE", "O", "NH1", "NH2"],
+ "ASP": ["C", "CA", "CB", "CG", "N", "O", "OD1", "OD2"],
+ "ASN": ["C", "CA", "CB", "CG", "N", "ND2", "O", "OD1"],
+ "CYS": ["C", "CA", "CB", "N", "O", "SG"],
+ "GLU": ["C", "CA", "CB", "CG", "CD", "N", "O", "OE1", "OE2"],
+ "GLN": ["C", "CA", "CB", "CG", "CD", "N", "NE2", "O", "OE1"],
+ "GLY": ["C", "CA", "N", "O"],
+ "HIS": ["C", "CA", "CB", "CG", "CD2", "CE1", "N", "ND1", "NE2", "O"],
+ "ILE": ["C", "CA", "CB", "CG1", "CG2", "CD1", "N", "O"],
+ "LEU": ["C", "CA", "CB", "CG", "CD1", "CD2", "N", "O"],
+ "LYS": ["C", "CA", "CB", "CG", "CD", "CE", "N", "NZ", "O"],
+ "MET": ["C", "CA", "CB", "CG", "CE", "N", "O", "SD"],
+ "PHE": ["C", "CA", "CB", "CG", "CD1", "CD2", "CE1", "CE2", "CZ", "N", "O"],
+ "PRO": ["C", "CA", "CB", "CG", "CD", "N", "O"],
+ "SER": ["C", "CA", "CB", "N", "O", "OG"],
+ "THR": ["C", "CA", "CB", "CG2", "N", "O", "OG1"],
+ "TRP": ["C", "CA", "CB", "CG", "CD1", "CD2", "CE2", "CE3", "CZ2", "CZ3", "CH2", "N", "NE1", "O"],
+ "TYR": ["C", "CA", "CB", "CG", "CD1", "CD2", "CE1", "CE2", "CZ", "N", "O", "OH"],
+ "VAL": ["C", "CA", "CB", "CG1", "CG2", "N", "O"],
+}
+
+# Naming swaps for ambiguous atom names.
+# Due to symmetries in the amino acids the naming of atoms is ambiguous in
+# 4 of the 20 amino acids.
+# (The LDDT paper lists 7 amino acids as ambiguous, but the naming ambiguities
+# in LEU, VAL and ARG can be resolved by using the 3d constellations of
+# the 'ambiguous' atoms and their neighbours)
+# TODO: ^ interpret this
+residue_atom_renaming_swaps: dict[str, dict[str, str]] = {
+ "ASP": {"OD1": "OD2"},
+ "GLU": {"OE1": "OE2"},
+ "PHE": {"CD1": "CD2", "CE1": "CE2"},
+ "TYR": {"CD1": "CD2", "CE1": "CE2"},
+}
+
+# Van der Waals radii [Angstroem] of the atoms (from Wikipedia)
+van_der_waals_radius: dict[str, float] = {
+ "C": 1.7,
+ "N": 1.55,
+ "O": 1.52,
+ "S": 1.8,
+}
+
+Bond = collections.namedtuple("Bond", ["atom1_name", "atom2_name", "length", "stddev"])
+BondAngle = collections.namedtuple(
+ "BondAngle",
+ ["atom1_name", "atom2_name", "atom3name", "angle_rad", "stddev"],
+)
+
+
+def map_structure_with_atom_order(in_list: list, first_call: bool = True) -> list:
+ # Maps strings in a nested list structure to their corresponding index in atom_order
+ if first_call:
+ in_list = copy.deepcopy(in_list)
+ for i in range(len(in_list)):
+ if isinstance(in_list[i], list):
+ in_list[i] = map_structure_with_atom_order(in_list[i], first_call=False)
+ elif isinstance(in_list[i], str):
+ in_list[i] = atom_order[in_list[i]]
+ else:
+ raise TypeError("Unexpected type when mapping nested lists!")
+ return in_list
+
+
+@functools.cache
+def load_stereo_chemical_props() -> tuple[
+ Mapping[str, list[Bond]],
+ Mapping[str, list[Bond]],
+ Mapping[str, list[BondAngle]],
+]:
+ """Load stereo_chemical_props.txt into a nice structure.
+
+ Load literature values for bond lengths and bond angles and translate bond angles into the length of the opposite
+ edge of the triangle ("residue_virtual_bonds").
+
+ Returns:
+ residue_bonds: dict that maps resname --> list of Bond tuples residue_virtual_bonds: dict that maps resname -->
+ list of Bond tuples residue_bond_angles: dict that maps resname --> list of BondAngle tuples
+ """
+ # TODO: this file should be downloaded in a setup script
+ stereo_chemical_props = resources.read_text("openfold.resources", "stereo_chemical_props.txt")
+
+ lines_iter = iter(stereo_chemical_props.splitlines())
+ # Load bond lengths.
+ residue_bonds: dict[str, list[Bond]] = {}
+ next(lines_iter) # Skip header line.
+ for line in lines_iter:
+ if line.strip() == "-":
+ break
+ bond, resname, bond_length, stddev = line.split()
+ atom1, atom2 = bond.split("-")
+ if resname not in residue_bonds:
+ residue_bonds[resname] = []
+ residue_bonds[resname].append(Bond(atom1, atom2, float(bond_length), float(stddev)))
+ residue_bonds["UNK"] = []
+
+ # Load bond angles.
+ residue_bond_angles: dict[str, list[BondAngle]] = {}
+ next(lines_iter) # Skip empty line.
+ next(lines_iter) # Skip header line.
+ for line in lines_iter:
+ if line.strip() == "-":
+ break
+ bond, resname, angle_degree, stddev_degree = line.split()
+ atom1, atom2, atom3 = bond.split("-")
+ if resname not in residue_bond_angles:
+ residue_bond_angles[resname] = []
+ residue_bond_angles[resname].append(
+ BondAngle(
+ atom1,
+ atom2,
+ atom3,
+ float(angle_degree) / 180.0 * np.pi,
+ float(stddev_degree) / 180.0 * np.pi,
+ )
+ )
+ residue_bond_angles["UNK"] = []
+
+ def make_bond_key(atom1_name: str, atom2_name: str) -> str:
+ """Unique key to lookup bonds."""
+ return "-".join(sorted([atom1_name, atom2_name]))
+
+ # Translate bond angles into distances ("virtual bonds").
+ residue_virtual_bonds: dict[str, list[Bond]] = {}
+ for resname, bond_angles in residue_bond_angles.items():
+ # Create a fast lookup dict for bond lengths.
+ bond_cache: dict[str, Bond] = {}
+ for b in residue_bonds[resname]:
+ bond_cache[make_bond_key(b.atom1_name, b.atom2_name)] = b
+ residue_virtual_bonds[resname] = []
+ for ba in bond_angles:
+ bond1 = bond_cache[make_bond_key(ba.atom1_name, ba.atom2_name)]
+ bond2 = bond_cache[make_bond_key(ba.atom2_name, ba.atom3name)]
+
+ # Compute distance between atom1 and atom3 using the law of cosines
+ # c^2 = a^2 + b^2 - 2ab*cos(gamma).
+ gamma = ba.angle_rad
+ length = np.sqrt(bond1.length**2 + bond2.length**2 - 2 * bond1.length * bond2.length * np.cos(gamma))
+
+ # Propagation of uncertainty assuming uncorrelated errors.
+ dl_outer = 0.5 / length
+ dl_dgamma = (2 * bond1.length * bond2.length * np.sin(gamma)) * dl_outer
+ dl_db1 = (2 * bond1.length - 2 * bond2.length * np.cos(gamma)) * dl_outer
+ dl_db2 = (2 * bond2.length - 2 * bond1.length * np.cos(gamma)) * dl_outer
+ stddev = np.sqrt(
+ (dl_dgamma * ba.stddev) ** 2 + (dl_db1 * bond1.stddev) ** 2 + (dl_db2 * bond2.stddev) ** 2
+ )
+ residue_virtual_bonds[resname].append(Bond(ba.atom1_name, ba.atom3name, length, stddev))
+
+ return (residue_bonds, residue_virtual_bonds, residue_bond_angles)
+
+
+# Between-residue bond lengths for general bonds (first element) and for Proline
+# (second element).
+between_res_bond_length_c_n: tuple[float, float] = (1.329, 1.341)
+between_res_bond_length_stddev_c_n: tuple[float, float] = (0.014, 0.016)
+
+# Between-residue cos_angles.
+between_res_cos_angles_c_n_ca: tuple[float, float] = (-0.5203, 0.0353) # degrees: 121.352 +- 2.315
+between_res_cos_angles_ca_c_n: tuple[float, float] = (-0.4473, 0.0311) # degrees: 116.568 +- 1.995
+
+# This mapping is used when we need to store atom data in a format that requires
+# fixed atom data size for every residue (e.g. a numpy array).
+atom_types: list[str] = [
+ "N",
+ "CA",
+ "C",
+ "CB",
+ "O",
+ "CG",
+ "CG1",
+ "CG2",
+ "OG",
+ "OG1",
+ "SG",
+ "CD",
+ "CD1",
+ "CD2",
+ "ND1",
+ "ND2",
+ "OD1",
+ "OD2",
+ "SD",
+ "CE",
+ "CE1",
+ "CE2",
+ "CE3",
+ "NE",
+ "NE1",
+ "NE2",
+ "OE1",
+ "OE2",
+ "CH2",
+ "NH1",
+ "NH2",
+ "OH",
+ "CZ",
+ "CZ2",
+ "CZ3",
+ "NZ",
+ "OXT",
+]
+atom_order: dict[str, int] = {atom_type: i for i, atom_type in enumerate(atom_types)}
+atom_type_num = len(atom_types) # := 37.
+
+# A compact atom encoding with 14 columns
+# pylint: disable=line-too-long
+restype_name_to_atom14_names: dict[str, list[str]] = {
+ "ALA": ["N", "CA", "C", "O", "CB", "", "", "", "", "", "", "", "", ""],
+ "ARG": ["N", "CA", "C", "O", "CB", "CG", "CD", "NE", "CZ", "NH1", "NH2", "", "", ""],
+ "ASN": ["N", "CA", "C", "O", "CB", "CG", "OD1", "ND2", "", "", "", "", "", ""],
+ "ASP": ["N", "CA", "C", "O", "CB", "CG", "OD1", "OD2", "", "", "", "", "", ""],
+ "CYS": ["N", "CA", "C", "O", "CB", "SG", "", "", "", "", "", "", "", ""],
+ "GLN": ["N", "CA", "C", "O", "CB", "CG", "CD", "OE1", "NE2", "", "", "", "", ""],
+ "GLU": ["N", "CA", "C", "O", "CB", "CG", "CD", "OE1", "OE2", "", "", "", "", ""],
+ "GLY": ["N", "CA", "C", "O", "", "", "", "", "", "", "", "", "", ""],
+ "HIS": ["N", "CA", "C", "O", "CB", "CG", "ND1", "CD2", "CE1", "NE2", "", "", "", ""],
+ "ILE": ["N", "CA", "C", "O", "CB", "CG1", "CG2", "CD1", "", "", "", "", "", ""],
+ "LEU": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2", "", "", "", "", "", ""],
+ "LYS": ["N", "CA", "C", "O", "CB", "CG", "CD", "CE", "NZ", "", "", "", "", ""],
+ "MET": ["N", "CA", "C", "O", "CB", "CG", "SD", "CE", "", "", "", "", "", ""],
+ "PHE": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2", "CE1", "CE2", "CZ", "", "", ""],
+ "PRO": ["N", "CA", "C", "O", "CB", "CG", "CD", "", "", "", "", "", "", ""],
+ "SER": ["N", "CA", "C", "O", "CB", "OG", "", "", "", "", "", "", "", ""],
+ "THR": ["N", "CA", "C", "O", "CB", "OG1", "CG2", "", "", "", "", "", "", ""],
+ "TRP": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2", "NE1", "CE2", "CE3", "CZ2", "CZ3", "CH2"],
+ "TYR": ["N", "CA", "C", "O", "CB", "CG", "CD1", "CD2", "CE1", "CE2", "CZ", "OH", "", ""],
+ "VAL": ["N", "CA", "C", "O", "CB", "CG1", "CG2", "", "", "", "", "", "", ""],
+ "UNK": ["", "", "", "", "", "", "", "", "", "", "", "", "", ""],
+}
+# pylint: enable=line-too-long
+
+
+# This is the standard residue order when coding AA type as a number.
+# Reproduce it by taking 3-letter AA codes and sorting them alphabetically.
+restypes: list[str] = [
+ "A",
+ "R",
+ "N",
+ "D",
+ "C",
+ "Q",
+ "E",
+ "G",
+ "H",
+ "I",
+ "L",
+ "K",
+ "M",
+ "F",
+ "P",
+ "S",
+ "T",
+ "W",
+ "Y",
+ "V",
+]
+restype_order: dict[str, int] = {restype: i for i, restype in enumerate(restypes)}
+restype_num = len(restypes) # := 20.
+unk_restype_index = restype_num # Catch-all index for unknown restypes.
+
+restypes_with_x: list[str] = restypes + ["X"]
+restype_order_with_x: dict[str, int] = {restype: i for i, restype in enumerate(restypes_with_x)}
+
+
+def sequence_to_onehot(sequence: str, mapping: Mapping[str, int], map_unknown_to_x: bool = False) -> np.ndarray:
+ """Maps the given sequence into a one-hot encoded matrix.
+
+ Args:
+ sequence: An amino acid sequence.
+ mapping: A dictionary mapping amino acids to integers.
+ map_unknown_to_x: If True, any amino acid that is not in the mapping will be
+ mapped to the unknown amino acid 'X'. If the mapping doesn't contain amino acid 'X', an error will be thrown.
+ If False, any amino acid not in the mapping will throw an error.
+
+ Returns:
+ A numpy array of shape (seq_len, num_unique_aas) with one-hot encoding of the sequence.
+
+ Raises:
+ ValueError: If the mapping doesn't contain values from 0 to
+ num_unique_aas - 1 without any gaps.
+ """
+ num_entries = max(mapping.values()) + 1
+
+ if sorted(set(mapping.values())) != list(range(num_entries)):
+ raise ValueError(
+ "The mapping must have values from 0 to num_unique_aas-1 without any gaps. Got: %s"
+ % sorted(mapping.values())
+ )
+
+ one_hot_arr = np.zeros((len(sequence), num_entries), dtype=np.int32)
+
+ for aa_index, aa_type in enumerate(sequence):
+ if map_unknown_to_x:
+ if aa_type.isalpha() and aa_type.isupper():
+ aa_id = mapping.get(aa_type, mapping["X"])
+ else:
+ raise ValueError(f"Invalid character in the sequence: {aa_type}")
+ else:
+ aa_id = mapping[aa_type]
+ one_hot_arr[aa_index, aa_id] = 1
+
+ return one_hot_arr
+
+
+restype_1to3: dict[str, str] = {
+ "A": "ALA",
+ "R": "ARG",
+ "N": "ASN",
+ "D": "ASP",
+ "C": "CYS",
+ "Q": "GLN",
+ "E": "GLU",
+ "G": "GLY",
+ "H": "HIS",
+ "I": "ILE",
+ "L": "LEU",
+ "K": "LYS",
+ "M": "MET",
+ "F": "PHE",
+ "P": "PRO",
+ "S": "SER",
+ "T": "THR",
+ "W": "TRP",
+ "Y": "TYR",
+ "V": "VAL",
+}
+
+
+# NB: restype_3to1 differs from Bio.PDB.protein_letters_3to1 by being a simple
+# 1-to-1 mapping of 3 letter names to one letter names. The latter contains
+# many more, and less common, three letter names as keys and maps many of these
+# to the same one letter name (including 'X' and 'U' which we don't use here).
+restype_3to1: dict[str, str] = {v: k for k, v in restype_1to3.items()}
+
+# Define a restype name for all unknown residues.
+unk_restype = "UNK"
+
+resnames: list[str] = [restype_1to3[r] for r in restypes] + [unk_restype]
+resname_to_idx: dict[str, int] = {resname: i for i, resname in enumerate(resnames)}
+
+
+# The mapping here uses hhblits convention, so that B is mapped to D, J and O
+# are mapped to X, U is mapped to C, and Z is mapped to E. Other than that the
+# remaining 20 amino acids are kept in alphabetical order.
+# There are 2 non-amino acid codes, X (representing any amino acid) and
+# "-" representing a missing amino acid in an alignment. The id for these
+# codes is put at the end (20 and 21) so that they can easily be ignored if
+# desired.
+HHBLITS_AA_TO_ID: dict[str, int] = {
+ "A": 0,
+ "B": 2,
+ "C": 1,
+ "D": 2,
+ "E": 3,
+ "F": 4,
+ "G": 5,
+ "H": 6,
+ "I": 7,
+ "J": 20,
+ "K": 8,
+ "L": 9,
+ "M": 10,
+ "N": 11,
+ "O": 20,
+ "P": 12,
+ "Q": 13,
+ "R": 14,
+ "S": 15,
+ "T": 16,
+ "U": 1,
+ "V": 17,
+ "W": 18,
+ "X": 20,
+ "Y": 19,
+ "Z": 3,
+ "-": 21,
+}
+
+# Partial inversion of HHBLITS_AA_TO_ID.
+ID_TO_HHBLITS_AA: dict[int, str] = {
+ 0: "A",
+ 1: "C", # Also U.
+ 2: "D", # Also B.
+ 3: "E", # Also Z.
+ 4: "F",
+ 5: "G",
+ 6: "H",
+ 7: "I",
+ 8: "K",
+ 9: "L",
+ 10: "M",
+ 11: "N",
+ 12: "P",
+ 13: "Q",
+ 14: "R",
+ 15: "S",
+ 16: "T",
+ 17: "V",
+ 18: "W",
+ 19: "Y",
+ 20: "X", # Includes J and O.
+ 21: "-",
+}
+
+restypes_with_x_and_gap: list[str] = restypes + ["X", "-"]
+MAP_HHBLITS_AATYPE_TO_OUR_AATYPE: tuple[int, ...] = tuple(
+ restypes_with_x_and_gap.index(ID_TO_HHBLITS_AA[i]) for i in range(len(restypes_with_x_and_gap))
+)
+
+
+def _make_standard_atom_mask() -> np.ndarray:
+ """Returns [num_res_types, num_atom_types] mask array."""
+ # +1 to account for unknown (all 0s).
+ mask = np.zeros([restype_num + 1, atom_type_num], dtype=np.int32)
+ for restype, restype_letter in enumerate(restypes):
+ restype_name = restype_1to3[restype_letter]
+ atom_names = residue_atoms[restype_name]
+ for atom_name in atom_names:
+ atom_type = atom_order[atom_name]
+ mask[restype, atom_type] = 1
+ return mask
+
+
+STANDARD_ATOM_MASK = _make_standard_atom_mask()
+
+
+# A one hot representation for the first and second atoms defining the axis
+# of rotation for each chi-angle in each residue.
+def chi_angle_atom(atom_index: int) -> np.ndarray:
+ """Define chi-angle rigid groups via one-hot representations."""
+ chi_angles_index = {}
+ one_hots = []
+
+ for k, v in chi_angles_atoms.items():
+ indices = [atom_types.index(s[atom_index]) for s in v]
+ indices.extend([-1] * (4 - len(indices)))
+ chi_angles_index[k] = indices
+
+ for r in restypes:
+ res3 = restype_1to3[r]
+ one_hot = np.eye(atom_type_num)[chi_angles_index[res3]]
+ one_hots.append(one_hot)
+
+ one_hots.append(np.zeros([4, atom_type_num])) # Add zeros for residue `X`.
+ one_hot = np.stack(one_hots, axis=0)
+ one_hot = np.transpose(one_hot, [0, 2, 1])
+
+ return one_hot
+
+
+chi_atom_1_one_hot = chi_angle_atom(1)
+chi_atom_2_one_hot = chi_angle_atom(2)
+
+# An array like chi_angles_atoms but using indices rather than names.
+chi_angles_atom_indices_list: list[list[list[str]]] = [chi_angles_atoms[restype_1to3[r]] for r in restypes]
+chi_angles_atom_indices_ours: list = map_structure_with_atom_order(chi_angles_atom_indices_list)
+chi_angles_atom_indices = np.array(
+ [chi_atoms + ([[0, 0, 0, 0]] * (4 - len(chi_atoms))) for chi_atoms in chi_angles_atom_indices_list]
+)
+
+# Mapping from (res_name, atom_name) pairs to the atom's chi group index
+# and atom index within that group.
+chi_groups_for_atom: dict[tuple[str, str], list[tuple[int, int]]] = collections.defaultdict(list)
+for res_name, chi_angle_atoms_for_res in chi_angles_atoms.items():
+ for chi_group_i, chi_group in enumerate(chi_angle_atoms_for_res):
+ for atom_i, atom in enumerate(chi_group):
+ chi_groups_for_atom[(res_name, atom)].append((chi_group_i, atom_i))
+chi_groups_for_atom = dict(chi_groups_for_atom)
+
+
+def _make_rigid_transformation_4x4(ex: np.ndarray, ey: np.ndarray, translation: np.ndarray) -> np.ndarray:
+ """Create a rigid 4x4 transformation matrix from two axes and transl."""
+ # Normalize ex.
+ ex_normalized = ex / np.linalg.norm(ex)
+
+ # make ey perpendicular to ex
+ ey_normalized = ey - np.dot(ey, ex_normalized) * ex_normalized
+ ey_normalized /= np.linalg.norm(ey_normalized)
+
+ # compute ez as cross product
+ eznorm = np.cross(ex_normalized, ey_normalized)
+ m = np.stack([ex_normalized, ey_normalized, eznorm, translation]).transpose()
+ m = np.concatenate([m, [[0.0, 0.0, 0.0, 1.0]]], axis=0)
+ return m
+
+
+# create an array with (restype, atomtype) --> rigid_group_idx
+# and an array with (restype, atomtype, coord) for the atom positions
+# and compute affine transformation matrices (4,4) from one rigid group to the
+# previous group
+restype_atom37_to_rigid_group = np.zeros([21, 37], dtype=int)
+restype_atom37_mask = np.zeros([21, 37], dtype=np.float32)
+restype_atom37_rigid_group_positions = np.zeros([21, 37, 3], dtype=np.float32)
+restype_atom14_to_rigid_group = np.zeros([21, 14], dtype=int)
+restype_atom14_mask = np.zeros([21, 14], dtype=np.float32)
+restype_atom14_rigid_group_positions = np.zeros([21, 14, 3], dtype=np.float32)
+restype_rigid_group_default_frame = np.zeros([21, 8, 4, 4], dtype=np.float32)
+
+
+def _make_rigid_group_constants() -> None:
+ """Fill the arrays above."""
+ for restype, restype_letter in enumerate(restypes):
+ resname = restype_1to3[restype_letter]
+ for atomname, group_idx, atom_position in rigid_group_atom_positions[resname]:
+ atomtype = atom_order[atomname]
+ restype_atom37_to_rigid_group[restype, atomtype] = group_idx
+ restype_atom37_mask[restype, atomtype] = 1
+ restype_atom37_rigid_group_positions[restype, atomtype, :] = atom_position
+
+ atom14idx = restype_name_to_atom14_names[resname].index(atomname)
+ restype_atom14_to_rigid_group[restype, atom14idx] = group_idx
+ restype_atom14_mask[restype, atom14idx] = 1
+ restype_atom14_rigid_group_positions[restype, atom14idx, :] = atom_position
+
+ for restype, restype_letter in enumerate(restypes):
+ resname = restype_1to3[restype_letter]
+ atom_positions: dict[str, np.ndarray] = {
+ name: np.array(pos) for name, _, pos in rigid_group_atom_positions[resname]
+ }
+
+ # backbone to backbone is the identity transform
+ restype_rigid_group_default_frame[restype, 0, :, :] = np.eye(4)
+
+ # pre-omega-frame to backbone (currently dummy identity matrix)
+ restype_rigid_group_default_frame[restype, 1, :, :] = np.eye(4)
+
+ # phi-frame to backbone
+ mat = _make_rigid_transformation_4x4(
+ ex=atom_positions["N"] - atom_positions["CA"],
+ ey=np.array([1.0, 0.0, 0.0]),
+ translation=atom_positions["N"],
+ )
+ restype_rigid_group_default_frame[restype, 2, :, :] = mat
+
+ # psi-frame to backbone
+ mat = _make_rigid_transformation_4x4(
+ ex=atom_positions["C"] - atom_positions["CA"],
+ ey=atom_positions["CA"] - atom_positions["N"],
+ translation=atom_positions["C"],
+ )
+ restype_rigid_group_default_frame[restype, 3, :, :] = mat
+
+ # chi1-frame to backbone
+ if chi_angles_mask[restype][0]:
+ base_atom_names = chi_angles_atoms[resname][0]
+ base_atom_positions = [atom_positions[name] for name in base_atom_names]
+ mat = _make_rigid_transformation_4x4(
+ ex=base_atom_positions[2] - base_atom_positions[1],
+ ey=base_atom_positions[0] - base_atom_positions[1],
+ translation=base_atom_positions[2],
+ )
+ restype_rigid_group_default_frame[restype, 4, :, :] = mat
+
+ # chi2-frame to chi1-frame
+ # chi3-frame to chi2-frame
+ # chi4-frame to chi3-frame
+ # luckily all rotation axes for the next frame start at (0,0,0) of the
+ # previous frame
+ for chi_idx in range(1, 4):
+ if chi_angles_mask[restype][chi_idx]:
+ axis_end_atom_name = chi_angles_atoms[resname][chi_idx][2]
+ axis_end_atom_position = atom_positions[axis_end_atom_name]
+ mat = _make_rigid_transformation_4x4(
+ ex=axis_end_atom_position,
+ ey=np.array([-1.0, 0.0, 0.0]),
+ translation=axis_end_atom_position,
+ )
+ restype_rigid_group_default_frame[restype, 4 + chi_idx, :, :] = mat
+
+
+_make_rigid_group_constants()
+
+
+def make_atom14_dists_bounds(
+ overlap_tolerance: float = 1.5,
+ bond_length_tolerance_factor: int = 15,
+) -> dict[str, np.ndarray]:
+ """compute upper and lower bounds for bonds to assess violations."""
+ restype_atom14_bond_lower_bound = np.zeros([21, 14, 14], np.float32)
+ restype_atom14_bond_upper_bound = np.zeros([21, 14, 14], np.float32)
+ restype_atom14_bond_stddev = np.zeros([21, 14, 14], np.float32)
+ residue_bonds, residue_virtual_bonds, _ = load_stereo_chemical_props()
+ for restype, restype_letter in enumerate(restypes):
+ resname = restype_1to3[restype_letter]
+ atom_list = restype_name_to_atom14_names[resname]
+
+ # create lower and upper bounds for clashes
+ for atom1_idx, atom1_name in enumerate(atom_list):
+ if not atom1_name:
+ continue
+ atom1_radius = van_der_waals_radius[atom1_name[0]]
+ for atom2_idx, atom2_name in enumerate(atom_list):
+ if (not atom2_name) or atom1_idx == atom2_idx:
+ continue
+ atom2_radius = van_der_waals_radius[atom2_name[0]]
+ lower = atom1_radius + atom2_radius - overlap_tolerance
+ upper = 1e10
+ restype_atom14_bond_lower_bound[restype, atom1_idx, atom2_idx] = lower
+ restype_atom14_bond_lower_bound[restype, atom2_idx, atom1_idx] = lower
+ restype_atom14_bond_upper_bound[restype, atom1_idx, atom2_idx] = upper
+ restype_atom14_bond_upper_bound[restype, atom2_idx, atom1_idx] = upper
+
+ # overwrite lower and upper bounds for bonds and angles
+ for b in residue_bonds[resname] + residue_virtual_bonds[resname]:
+ atom1_idx = atom_list.index(b.atom1_name)
+ atom2_idx = atom_list.index(b.atom2_name)
+ lower = b.length - bond_length_tolerance_factor * b.stddev
+ upper = b.length + bond_length_tolerance_factor * b.stddev
+ restype_atom14_bond_lower_bound[restype, atom1_idx, atom2_idx] = lower
+ restype_atom14_bond_lower_bound[restype, atom2_idx, atom1_idx] = lower
+ restype_atom14_bond_upper_bound[restype, atom1_idx, atom2_idx] = upper
+ restype_atom14_bond_upper_bound[restype, atom2_idx, atom1_idx] = upper
+ restype_atom14_bond_stddev[restype, atom1_idx, atom2_idx] = b.stddev
+ restype_atom14_bond_stddev[restype, atom2_idx, atom1_idx] = b.stddev
+ return {
+ "lower_bound": restype_atom14_bond_lower_bound, # shape (21,14,14)
+ "upper_bound": restype_atom14_bond_upper_bound, # shape (21,14,14)
+ "stddev": restype_atom14_bond_stddev, # shape (21,14,14)
+ }
+
+
+restype_atom14_ambiguous_atoms = np.zeros((21, 14), dtype=np.float32)
+restype_atom14_ambiguous_atoms_swap_idx: np.ndarray = np.tile(np.arange(14, dtype=int), (21, 1))
+
+
+def _make_atom14_ambiguity_feats() -> None:
+ for res, pairs in residue_atom_renaming_swaps.items():
+ res_idx = restype_order[restype_3to1[res]]
+ for atom1, atom2 in pairs.items():
+ atom1_idx = restype_name_to_atom14_names[res].index(atom1)
+ atom2_idx = restype_name_to_atom14_names[res].index(atom2)
+ restype_atom14_ambiguous_atoms[res_idx, atom1_idx] = 1
+ restype_atom14_ambiguous_atoms[res_idx, atom2_idx] = 1
+ restype_atom14_ambiguous_atoms_swap_idx[res_idx, atom1_idx] = atom2_idx
+ restype_atom14_ambiguous_atoms_swap_idx[res_idx, atom2_idx] = atom1_idx
+
+
+_make_atom14_ambiguity_feats()
+
+
+def aatype_to_str_sequence(aatype: Sequence[int]) -> str:
+ return "".join([restypes_with_x[aatype[i]] for i in range(len(aatype))])
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/rigid_utils.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/rigid_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2bc25cb6d53f0428be3f6c1c25e67d67edab739
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/rigid_utils.py
@@ -0,0 +1,1243 @@
+# Copyright 2021 AlQuraishi Laboratory
+# Copyright 2021 DeepMind Technologies Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from functools import cache
+from typing import Any, Callable
+
+import numpy as np
+import torch
+
+
+def rot_matmul(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
+ """
+ Performs matrix multiplication of two rotation matrix tensors. Written out by hand to avoid AMP downcasting.
+
+ Args:
+ a: [*, 3, 3] left multiplicand
+ b: [*, 3, 3] right multiplicand
+ Returns:
+ The product ab
+ """
+
+ def row_mul(i: int) -> torch.Tensor:
+ return torch.stack(
+ [
+ a[..., i, 0] * b[..., 0, 0] + a[..., i, 1] * b[..., 1, 0] + a[..., i, 2] * b[..., 2, 0],
+ a[..., i, 0] * b[..., 0, 1] + a[..., i, 1] * b[..., 1, 1] + a[..., i, 2] * b[..., 2, 1],
+ a[..., i, 0] * b[..., 0, 2] + a[..., i, 1] * b[..., 1, 2] + a[..., i, 2] * b[..., 2, 2],
+ ],
+ dim=-1,
+ )
+
+ return torch.stack(
+ [
+ row_mul(0),
+ row_mul(1),
+ row_mul(2),
+ ],
+ dim=-2,
+ )
+
+
+def rot_vec_mul(r: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
+ """
+ Applies a rotation to a vector. Written out by hand to avoid transfer to avoid AMP downcasting.
+
+ Args:
+ r: [*, 3, 3] rotation matrices
+ t: [*, 3] coordinate tensors
+ Returns:
+ [*, 3] rotated coordinates
+ """
+ x, y, z = torch.unbind(t, dim=-1)
+ return torch.stack(
+ [
+ r[..., 0, 0] * x + r[..., 0, 1] * y + r[..., 0, 2] * z,
+ r[..., 1, 0] * x + r[..., 1, 1] * y + r[..., 1, 2] * z,
+ r[..., 2, 0] * x + r[..., 2, 1] * y + r[..., 2, 2] * z,
+ ],
+ dim=-1,
+ )
+
+
+@cache
+def identity_rot_mats(
+ batch_dims: tuple[int, ...],
+ dtype: torch.dtype | None = None,
+ device: torch.device | None = None,
+ requires_grad: bool = True,
+) -> torch.Tensor:
+ rots = torch.eye(3, dtype=dtype, device=device, requires_grad=requires_grad)
+ rots = rots.view(*((1,) * len(batch_dims)), 3, 3)
+ rots = rots.expand(*batch_dims, -1, -1)
+ rots = rots.contiguous()
+
+ return rots
+
+
+@cache
+def identity_trans(
+ batch_dims: tuple[int, ...],
+ dtype: torch.dtype | None = None,
+ device: torch.device | None = None,
+ requires_grad: bool = True,
+) -> torch.Tensor:
+ trans = torch.zeros((*batch_dims, 3), dtype=dtype, device=device, requires_grad=requires_grad)
+ return trans
+
+
+@cache
+def identity_quats(
+ batch_dims: tuple[int, ...],
+ dtype: torch.dtype | None = None,
+ device: torch.device | None = None,
+ requires_grad: bool = True,
+) -> torch.Tensor:
+ quat = torch.zeros((*batch_dims, 4), dtype=dtype, device=device, requires_grad=requires_grad)
+
+ with torch.no_grad():
+ quat[..., 0] = 1
+
+ return quat
+
+
+_quat_elements: list[str] = ["a", "b", "c", "d"]
+_qtr_keys: list[str] = [l1 + l2 for l1 in _quat_elements for l2 in _quat_elements]
+_qtr_ind_dict: dict[str, int] = {key: ind for ind, key in enumerate(_qtr_keys)}
+
+
+def _to_mat(pairs: list[tuple[str, int]]) -> np.ndarray:
+ mat = np.zeros((4, 4))
+ for key, value in pairs:
+ ind = _qtr_ind_dict[key]
+ mat[ind // 4][ind % 4] = value
+
+ return mat
+
+
+_QTR_MAT = np.zeros((4, 4, 3, 3))
+_QTR_MAT[..., 0, 0] = _to_mat([("aa", 1), ("bb", 1), ("cc", -1), ("dd", -1)])
+_QTR_MAT[..., 0, 1] = _to_mat([("bc", 2), ("ad", -2)])
+_QTR_MAT[..., 0, 2] = _to_mat([("bd", 2), ("ac", 2)])
+_QTR_MAT[..., 1, 0] = _to_mat([("bc", 2), ("ad", 2)])
+_QTR_MAT[..., 1, 1] = _to_mat([("aa", 1), ("bb", -1), ("cc", 1), ("dd", -1)])
+_QTR_MAT[..., 1, 2] = _to_mat([("cd", 2), ("ab", -2)])
+_QTR_MAT[..., 2, 0] = _to_mat([("bd", 2), ("ac", -2)])
+_QTR_MAT[..., 2, 1] = _to_mat([("cd", 2), ("ab", 2)])
+_QTR_MAT[..., 2, 2] = _to_mat([("aa", 1), ("bb", -1), ("cc", -1), ("dd", 1)])
+
+
+def quat_to_rot(quat: torch.Tensor) -> torch.Tensor:
+ """
+ Converts a quaternion to a rotation matrix.
+
+ Args:
+ quat: [*, 4] quaternions
+ Returns:
+ [*, 3, 3] rotation matrices
+ """
+ # [*, 4, 4]
+ quat = quat[..., None] * quat[..., None, :]
+
+ # [4, 4, 3, 3]
+ mat = _get_quat("_QTR_MAT", dtype=quat.dtype, device=quat.device)
+
+ # [*, 4, 4, 3, 3]
+ shaped_qtr_mat = mat.view((1,) * len(quat.shape[:-2]) + mat.shape)
+ quat = quat[..., None, None] * shaped_qtr_mat
+
+ # [*, 3, 3]
+ return torch.sum(quat, dim=(-3, -4))
+
+
+def rot_to_quat(rot: torch.Tensor) -> torch.Tensor:
+ if rot.shape[-2:] != (3, 3):
+ raise ValueError("Input rotation is incorrectly shaped")
+
+ [[xx, xy, xz], [yx, yy, yz], [zx, zy, zz]] = [[rot[..., i, j] for j in range(3)] for i in range(3)]
+
+ k = [
+ [
+ xx + yy + zz,
+ zy - yz,
+ xz - zx,
+ yx - xy,
+ ],
+ [
+ zy - yz,
+ xx - yy - zz,
+ xy + yx,
+ xz + zx,
+ ],
+ [
+ xz - zx,
+ xy + yx,
+ yy - xx - zz,
+ yz + zy,
+ ],
+ [
+ yx - xy,
+ xz + zx,
+ yz + zy,
+ zz - xx - yy,
+ ],
+ ]
+
+ _, vectors = torch.linalg.eigh((1.0 / 3.0) * torch.stack([torch.stack(t, dim=-1) for t in k], dim=-2))
+ return vectors[..., -1]
+
+
+_QUAT_MULTIPLY = np.zeros((4, 4, 4))
+_QUAT_MULTIPLY[:, :, 0] = [[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]
+
+_QUAT_MULTIPLY[:, :, 1] = [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, -1, 0]]
+
+_QUAT_MULTIPLY[:, :, 2] = [[0, 0, 1, 0], [0, 0, 0, -1], [1, 0, 0, 0], [0, 1, 0, 0]]
+
+_QUAT_MULTIPLY[:, :, 3] = [[0, 0, 0, 1], [0, 0, 1, 0], [0, -1, 0, 0], [1, 0, 0, 0]]
+
+_QUAT_MULTIPLY_BY_VEC = _QUAT_MULTIPLY[:, 1:, :]
+
+_CACHED_QUATS: dict[str, np.ndarray] = {
+ "_QTR_MAT": _QTR_MAT,
+ "_QUAT_MULTIPLY": _QUAT_MULTIPLY,
+ "_QUAT_MULTIPLY_BY_VEC": _QUAT_MULTIPLY_BY_VEC,
+}
+
+
+@cache
+def _get_quat(quat_key: str, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
+ return torch.tensor(_CACHED_QUATS[quat_key], dtype=dtype, device=device)
+
+
+def quat_multiply(quat1: torch.Tensor, quat2: torch.Tensor) -> torch.Tensor:
+ """Multiply a quaternion by another quaternion."""
+ mat = _get_quat("_QUAT_MULTIPLY", dtype=quat1.dtype, device=quat1.device)
+ reshaped_mat = mat.view((1,) * len(quat1.shape[:-1]) + mat.shape)
+ return torch.sum(reshaped_mat * quat1[..., :, None, None] * quat2[..., None, :, None], dim=(-3, -2))
+
+
+def quat_multiply_by_vec(quat: torch.Tensor, vec: torch.Tensor) -> torch.Tensor:
+ """Multiply a quaternion by a pure-vector quaternion."""
+ mat = _get_quat("_QUAT_MULTIPLY_BY_VEC", dtype=quat.dtype, device=quat.device)
+ reshaped_mat = mat.view((1,) * len(quat.shape[:-1]) + mat.shape)
+ return torch.sum(reshaped_mat * quat[..., :, None, None] * vec[..., None, :, None], dim=(-3, -2))
+
+
+def invert_rot_mat(rot_mat: torch.Tensor) -> torch.Tensor:
+ return rot_mat.transpose(-1, -2)
+
+
+def invert_quat(quat: torch.Tensor) -> torch.Tensor:
+ quat_prime = quat.clone()
+ quat_prime[..., 1:] *= -1
+ inv = quat_prime / torch.sum(quat**2, dim=-1, keepdim=True)
+ return inv
+
+
+class Rotation:
+ """
+ A 3D rotation. Depending on how the object is initialized, the rotation is represented by either a rotation matrix
+ or a quaternion, though both formats are made available by helper functions. To simplify gradient computation, the
+ underlying format of the rotation cannot be changed in-place. Like Rigid, the class is designed to mimic the
+ behavior of a torch Tensor, almost as if each Rotation object were a tensor of rotations, in one format or another.
+ """
+
+ def __init__(
+ self,
+ rot_mats: torch.Tensor | None = None,
+ quats: torch.Tensor | None = None,
+ normalize_quats: bool = True,
+ ):
+ """
+ Args:
+ rot_mats:
+ A [*, 3, 3] rotation matrix tensor. Mutually exclusive with quats
+ quats:
+ A [*, 4] quaternion. Mutually exclusive with rot_mats. If normalize_quats is not True, must be a unit
+ quaternion
+ normalize_quats:
+ If quats is specified, whether to normalize quats
+ """
+ if (rot_mats is None and quats is None) or (rot_mats is not None and quats is not None):
+ raise ValueError("Exactly one input argument must be specified")
+
+ if (rot_mats is not None and rot_mats.shape[-2:] != (3, 3)) or (quats is not None and quats.shape[-1] != 4):
+ raise ValueError("Incorrectly shaped rotation matrix or quaternion")
+
+ # Force full-precision
+ if quats is not None:
+ quats = quats.to(dtype=torch.float32)
+ if rot_mats is not None:
+ rot_mats = rot_mats.to(dtype=torch.float32)
+
+ if quats is not None and normalize_quats:
+ quats = quats / torch.linalg.norm(quats, dim=-1, keepdim=True)
+
+ self._rot_mats = rot_mats
+ self._quats = quats
+
+ @staticmethod
+ def identity(
+ shape,
+ dtype: torch.dtype | None = None,
+ device: torch.device | None = None,
+ requires_grad: bool = True,
+ fmt: str = "quat",
+ ) -> Rotation:
+ """
+ Returns an identity Rotation.
+
+ Args:
+ shape:
+ The "shape" of the resulting Rotation object. See documentation for the shape property
+ dtype:
+ The torch dtype for the rotation
+ device:
+ The torch device for the new rotation
+ requires_grad:
+ Whether the underlying tensors in the new rotation object should require gradient computation
+ fmt:
+ One of "quat" or "rot_mat". Determines the underlying format of the new object's rotation
+ Returns:
+ A new identity rotation
+ """
+ if fmt == "rot_mat":
+ rot_mats = identity_rot_mats(
+ shape,
+ dtype,
+ device,
+ requires_grad,
+ )
+ return Rotation(rot_mats=rot_mats, quats=None)
+ elif fmt == "quat":
+ quats = identity_quats(shape, dtype, device, requires_grad)
+ return Rotation(rot_mats=None, quats=quats, normalize_quats=False)
+ else:
+ raise ValueError(f"Invalid format: f{fmt}")
+
+ # Magic methods
+
+ def __getitem__(self, index: Any) -> Rotation:
+ """
+ Allows torch-style indexing over the virtual shape of the rotation object. See documentation for the shape
+ property.
+
+ Args:
+ index:
+ A torch index. E.g. (1, 3, 2), or (slice(None,))
+ Returns:
+ The indexed rotation
+ """
+ if type(index) is not tuple:
+ index = (index,)
+
+ if self._rot_mats is not None:
+ rot_mats = self._rot_mats[index + (slice(None), slice(None))]
+ return Rotation(rot_mats=rot_mats)
+ elif self._quats is not None:
+ quats = self._quats[index + (slice(None),)]
+ return Rotation(quats=quats, normalize_quats=False)
+ else:
+ raise ValueError("Both rotations are None")
+
+ def __mul__(self, right: torch.Tensor) -> Rotation:
+ """
+ Pointwise left multiplication of the rotation with a tensor. Can be used to e.g. mask the Rotation.
+
+ Args:
+ right:
+ The tensor multiplicand
+ Returns:
+ The product
+ """
+ if not (isinstance(right, torch.Tensor)):
+ raise TypeError("The other multiplicand must be a Tensor")
+
+ if self._rot_mats is not None:
+ rot_mats = self._rot_mats * right[..., None, None]
+ return Rotation(rot_mats=rot_mats, quats=None)
+ elif self._quats is not None:
+ quats = self._quats * right[..., None]
+ return Rotation(rot_mats=None, quats=quats, normalize_quats=False)
+ else:
+ raise ValueError("Both rotations are None")
+
+ def __rmul__(self, left: torch.Tensor) -> Rotation:
+ """
+ Reverse pointwise multiplication of the rotation with a tensor.
+
+ Args:
+ left:
+ The left multiplicand
+ Returns:
+ The product
+ """
+ return self.__mul__(left)
+
+ # Properties
+
+ @property
+ def shape(self) -> torch.Size:
+ """
+ Returns the virtual shape of the rotation object. This shape is defined as the batch dimensions of the
+ underlying rotation matrix or quaternion. If the Rotation was initialized with a [10, 3, 3] rotation matrix
+ tensor, for example, the resulting shape would be [10].
+
+ Returns:
+ The virtual shape of the rotation object
+ """
+ if self._rot_mats is not None:
+ return self._rot_mats.shape[:-2]
+ elif self._quats is not None:
+ return self._quats.shape[:-1]
+ else:
+ raise ValueError("Both rotations are None")
+
+ @property
+ def dtype(self) -> torch.dtype:
+ """
+ Returns the dtype of the underlying rotation.
+
+ Returns:
+ The dtype of the underlying rotation
+ """
+ if self._rot_mats is not None:
+ return self._rot_mats.dtype
+ elif self._quats is not None:
+ return self._quats.dtype
+ else:
+ raise ValueError("Both rotations are None")
+
+ @property
+ def device(self) -> torch.device:
+ """
+ The device of the underlying rotation
+
+ Returns:
+ The device of the underlying rotation
+ """
+ if self._rot_mats is not None:
+ return self._rot_mats.device
+ elif self._quats is not None:
+ return self._quats.device
+ else:
+ raise ValueError("Both rotations are None")
+
+ @property
+ def requires_grad(self) -> bool:
+ """
+ Returns the requires_grad property of the underlying rotation
+
+ Returns:
+ The requires_grad property of the underlying tensor
+ """
+ if self._rot_mats is not None:
+ return self._rot_mats.requires_grad
+ elif self._quats is not None:
+ return self._quats.requires_grad
+ else:
+ raise ValueError("Both rotations are None")
+
+ def get_rot_mats(self) -> torch.Tensor:
+ """
+ Returns the underlying rotation as a rotation matrix tensor.
+
+ Returns:
+ The rotation as a rotation matrix tensor
+ """
+ if self._rot_mats is not None:
+ return self._rot_mats
+ elif self._quats is not None:
+ return quat_to_rot(self._quats)
+ else:
+ raise ValueError("Both rotations are None")
+
+ def get_quats(self) -> torch.Tensor:
+ """
+ Returns the underlying rotation as a quaternion tensor.
+
+ Depending on whether the Rotation was initialized with a quaternion, this function may call torch.linalg.eigh.
+
+ Returns:
+ The rotation as a quaternion tensor.
+ """
+ if self._rot_mats is not None:
+ return rot_to_quat(self._rot_mats)
+ elif self._quats is not None:
+ return self._quats
+ else:
+ raise ValueError("Both rotations are None")
+
+ def get_cur_rot(self) -> torch.Tensor:
+ """
+ Return the underlying rotation in its current form
+
+ Returns:
+ The stored rotation
+ """
+ if self._rot_mats is not None:
+ return self._rot_mats
+ elif self._quats is not None:
+ return self._quats
+ else:
+ raise ValueError("Both rotations are None")
+
+ # Rotation functions
+
+ def compose_q_update_vec(self, q_update_vec: torch.Tensor, normalize_quats: bool = True) -> Rotation:
+ """
+ Returns a new quaternion Rotation after updating the current object's underlying rotation with a quaternion
+ update, formatted as a [*, 3] tensor whose final three columns represent x, y, z such that (1, x, y, z) is the
+ desired (not necessarily unit) quaternion update.
+
+ Args:
+ q_update_vec:
+ A [*, 3] quaternion update tensor
+ normalize_quats:
+ Whether to normalize the output quaternion
+ Returns:
+ An updated Rotation
+ """
+ quats = self.get_quats()
+ new_quats = quats + quat_multiply_by_vec(quats, q_update_vec)
+ return Rotation(
+ rot_mats=None,
+ quats=new_quats,
+ normalize_quats=normalize_quats,
+ )
+
+ def compose_r(self, r: Rotation) -> Rotation:
+ """
+ Compose the rotation matrices of the current Rotation object with those of another.
+
+ Args:
+ r:
+ An update rotation object
+ Returns:
+ An updated rotation object
+ """
+ r1 = self.get_rot_mats()
+ r2 = r.get_rot_mats()
+ new_rot_mats = rot_matmul(r1, r2)
+ return Rotation(rot_mats=new_rot_mats, quats=None)
+
+ def compose_q(self, r: Rotation, normalize_quats: bool = True) -> Rotation:
+ """
+ Compose the quaternions of the current Rotation object with those of another.
+
+ Depending on whether either Rotation was initialized with quaternions, this function may call
+ torch.linalg.eigh.
+
+ Args:
+ r:
+ An update rotation object
+ Returns:
+ An updated rotation object
+ """
+ q1 = self.get_quats()
+ q2 = r.get_quats()
+ new_quats = quat_multiply(q1, q2)
+ return Rotation(rot_mats=None, quats=new_quats, normalize_quats=normalize_quats)
+
+ def apply(self, pts: torch.Tensor) -> torch.Tensor:
+ """
+ Apply the current Rotation as a rotation matrix to a set of 3D coordinates.
+
+ Args:
+ pts:
+ A [*, 3] set of points
+ Returns:
+ [*, 3] rotated points
+ """
+ rot_mats = self.get_rot_mats()
+ return rot_vec_mul(rot_mats, pts)
+
+ def invert_apply(self, pts: torch.Tensor) -> torch.Tensor:
+ """
+ The inverse of the apply() method.
+
+ Args:
+ pts:
+ A [*, 3] set of points
+ Returns:
+ [*, 3] inverse-rotated points
+ """
+ rot_mats = self.get_rot_mats()
+ inv_rot_mats = invert_rot_mat(rot_mats)
+ return rot_vec_mul(inv_rot_mats, pts)
+
+ def invert(self) -> Rotation:
+ """
+ Returns the inverse of the current Rotation.
+
+ Returns:
+ The inverse of the current Rotation
+ """
+ if self._rot_mats is not None:
+ return Rotation(rot_mats=invert_rot_mat(self._rot_mats), quats=None)
+ elif self._quats is not None:
+ return Rotation(
+ rot_mats=None,
+ quats=invert_quat(self._quats),
+ normalize_quats=False,
+ )
+ else:
+ raise ValueError("Both rotations are None")
+
+ # "Tensor" stuff
+
+ def unsqueeze(self, dim: int) -> Rotation:
+ """
+ Analogous to torch.unsqueeze. The dimension is relative to the shape of the Rotation object.
+
+ Args:
+ dim: A positive or negative dimension index.
+ Returns:
+ The unsqueezed Rotation.
+ """
+ if dim >= len(self.shape):
+ raise ValueError("Invalid dimension")
+
+ if self._rot_mats is not None:
+ rot_mats = self._rot_mats.unsqueeze(dim if dim >= 0 else dim - 2)
+ return Rotation(rot_mats=rot_mats, quats=None)
+ elif self._quats is not None:
+ quats = self._quats.unsqueeze(dim if dim >= 0 else dim - 1)
+ return Rotation(rot_mats=None, quats=quats, normalize_quats=False)
+ else:
+ raise ValueError("Both rotations are None")
+
+ @staticmethod
+ def cat(rs: Sequence[Rotation], dim: int) -> Rotation:
+ """
+ Concatenates rotations along one of the batch dimensions. Analogous to torch.cat().
+
+ Note that the output of this operation is always a rotation matrix, regardless of the format of input
+ rotations.
+
+ Args:
+ rs:
+ A list of rotation objects
+ dim:
+ The dimension along which the rotations should be concatenated
+ Returns:
+ A concatenated Rotation object in rotation matrix format
+ """
+ rot_mats = torch.cat(
+ [r.get_rot_mats() for r in rs],
+ dim=dim if dim >= 0 else dim - 2,
+ )
+
+ return Rotation(rot_mats=rot_mats, quats=None)
+
+ def map_tensor_fn(self, fn: Callable[[torch.Tensor], torch.Tensor]) -> Rotation:
+ """
+ Apply a Tensor -> Tensor function to underlying rotation tensors, mapping over the rotation dimension(s). Can
+ be used e.g. to sum out a one-hot batch dimension.
+
+ Args:
+ fn:
+ A Tensor -> Tensor function to be mapped over the Rotation
+ Returns:
+ The transformed Rotation object
+ """
+ if self._rot_mats is not None:
+ rot_mats = self._rot_mats.view(self._rot_mats.shape[:-2] + (9,))
+ rot_mats = torch.stack(list(map(fn, torch.unbind(rot_mats, dim=-1))), dim=-1)
+ rot_mats = rot_mats.view(rot_mats.shape[:-1] + (3, 3))
+ return Rotation(rot_mats=rot_mats, quats=None)
+ elif self._quats is not None:
+ quats = torch.stack(list(map(fn, torch.unbind(self._quats, dim=-1))), dim=-1)
+ return Rotation(rot_mats=None, quats=quats, normalize_quats=False)
+ else:
+ raise ValueError("Both rotations are None")
+
+ def cuda(self) -> Rotation:
+ """
+ Analogous to the cuda() method of torch Tensors
+
+ Returns:
+ A copy of the Rotation in CUDA memory
+ """
+ if self._rot_mats is not None:
+ return Rotation(rot_mats=self._rot_mats.cuda(), quats=None)
+ elif self._quats is not None:
+ return Rotation(rot_mats=None, quats=self._quats.cuda(), normalize_quats=False)
+ else:
+ raise ValueError("Both rotations are None")
+
+ def to(self, device: torch.device | None, dtype: torch.dtype | None) -> Rotation:
+ """
+ Analogous to the to() method of torch Tensors
+
+ Args:
+ device:
+ A torch device
+ dtype:
+ A torch dtype
+ Returns:
+ A copy of the Rotation using the new device and dtype
+ """
+ if self._rot_mats is not None:
+ return Rotation(
+ rot_mats=self._rot_mats.to(device=device, dtype=dtype),
+ quats=None,
+ )
+ elif self._quats is not None:
+ return Rotation(
+ rot_mats=None,
+ quats=self._quats.to(device=device, dtype=dtype),
+ normalize_quats=False,
+ )
+ else:
+ raise ValueError("Both rotations are None")
+
+ def detach(self) -> Rotation:
+ """
+ Returns a copy of the Rotation whose underlying Tensor has been detached from its torch graph.
+
+ Returns:
+ A copy of the Rotation whose underlying Tensor has been detached from its torch graph
+ """
+ if self._rot_mats is not None:
+ return Rotation(rot_mats=self._rot_mats.detach(), quats=None)
+ elif self._quats is not None:
+ return Rotation(
+ rot_mats=None,
+ quats=self._quats.detach(),
+ normalize_quats=False,
+ )
+ else:
+ raise ValueError("Both rotations are None")
+
+
+class Rigid:
+ """
+ A class representing a rigid transformation. Little more than a wrapper around two objects: a Rotation object and a
+ [*, 3] translation Designed to behave approximately like a single torch tensor with the shape of the shared batch
+ dimensions of its component parts.
+ """
+
+ def __init__(self, rots: Rotation | None, trans: torch.Tensor | None):
+ """
+ Args:
+ rots: A [*, 3, 3] rotation tensor
+ trans: A corresponding [*, 3] translation tensor
+ """
+ # (we need device, dtype, etc. from at least one input)
+
+ batch_dims, dtype, device, requires_grad = None, None, None, None
+ if trans is not None:
+ batch_dims = trans.shape[:-1]
+ dtype = trans.dtype
+ device = trans.device
+ requires_grad = trans.requires_grad
+ elif rots is not None:
+ batch_dims = rots.shape
+ dtype = rots.dtype
+ device = rots.device
+ requires_grad = rots.requires_grad
+ else:
+ raise ValueError("At least one input argument must be specified")
+
+ if rots is None:
+ rots = Rotation.identity(
+ batch_dims,
+ dtype,
+ device,
+ requires_grad,
+ )
+ elif trans is None:
+ trans = identity_trans(
+ batch_dims,
+ dtype,
+ device,
+ requires_grad,
+ )
+
+ assert rots is not None
+ assert trans is not None
+
+ if (rots.shape != trans.shape[:-1]) or (rots.device != trans.device):
+ raise ValueError("Rots and trans incompatible")
+
+ # Force full precision. Happens to the rotations automatically.
+ trans = trans.to(dtype=torch.float32)
+
+ self._rots = rots
+ self._trans = trans
+
+ @staticmethod
+ def identity(
+ shape: tuple[int, ...],
+ dtype: torch.dtype | None = None,
+ device: torch.device | None = None,
+ requires_grad: bool = True,
+ fmt: str = "quat",
+ ) -> Rigid:
+ """
+ Constructs an identity transformation.
+
+ Args:
+ shape:
+ The desired shape
+ dtype:
+ The dtype of both internal tensors
+ device:
+ The device of both internal tensors
+ requires_grad:
+ Whether grad should be enabled for the internal tensors
+ Returns:
+ The identity transformation
+ """
+ return Rigid(
+ Rotation.identity(shape, dtype, device, requires_grad, fmt=fmt),
+ identity_trans(shape, dtype, device, requires_grad),
+ )
+
+ def __getitem__(self, index: Any) -> Rigid:
+ """
+ Indexes the affine transformation with PyTorch-style indices. The index is applied to the shared dimensions of
+ both the rotation and the translation.
+
+ E.g.::
+
+ r = Rotation(rot_mats=torch.rand(10, 10, 3, 3), quats=None) t = Rigid(r, torch.rand(10, 10, 3)) indexed =
+ t[3, 4:6] assert(indexed.shape == (2,)) assert(indexed.get_rots().shape == (2,))
+ assert(indexed.get_trans().shape == (2, 3))
+
+ Args:
+ index: A standard torch tensor index. E.g. 8, (10, None, 3),
+ or (3, slice(0, 1, None))
+ Returns:
+ The indexed tensor
+ """
+ if type(index) is not tuple:
+ index = (index,)
+
+ return Rigid(
+ self._rots[index],
+ self._trans[index + (slice(None),)],
+ )
+
+ def __mul__(self, right: torch.Tensor) -> Rigid:
+ """
+ Pointwise left multiplication of the transformation with a tensor. Can be used to e.g. mask the Rigid.
+
+ Args:
+ right:
+ The tensor multiplicand
+ Returns:
+ The product
+ """
+ if not (isinstance(right, torch.Tensor)):
+ raise TypeError("The other multiplicand must be a Tensor")
+
+ new_rots = self._rots * right
+ new_trans = self._trans * right[..., None]
+
+ return Rigid(new_rots, new_trans)
+
+ def __rmul__(self, left: torch.Tensor) -> Rigid:
+ """
+ Reverse pointwise multiplication of the transformation with a tensor.
+
+ Args:
+ left:
+ The left multiplicand
+ Returns:
+ The product
+ """
+ return self.__mul__(left)
+
+ @property
+ def shape(self) -> torch.Size:
+ """
+ Returns the shape of the shared dimensions of the rotation and the translation.
+
+ Returns:
+ The shape of the transformation
+ """
+ return self._trans.shape[:-1]
+
+ @property
+ def device(self) -> torch.device:
+ """
+ Returns the device on which the Rigid's tensors are located.
+
+ Returns:
+ The device on which the Rigid's tensors are located
+ """
+ return self._trans.device
+
+ def get_rots(self) -> Rotation:
+ """
+ Getter for the rotation.
+
+ Returns:
+ The rotation object
+ """
+ return self._rots
+
+ def get_trans(self) -> torch.Tensor:
+ """
+ Getter for the translation.
+
+ Returns:
+ The stored translation
+ """
+ return self._trans
+
+ def compose_q_update_vec(self, q_update_vec: torch.Tensor) -> Rigid:
+ """
+ Composes the transformation with a quaternion update vector of shape [*, 6], where the final 6 columns
+ represent the x, y, and z values of a quaternion of form (1, x, y, z) followed by a 3D translation.
+
+ Args:
+ q_vec: The quaternion update vector.
+ Returns:
+ The composed transformation.
+ """
+ q_vec, t_vec = q_update_vec[..., :3], q_update_vec[..., 3:]
+ new_rots = self._rots.compose_q_update_vec(q_vec)
+
+ trans_update = self._rots.apply(t_vec)
+ new_translation = self._trans + trans_update
+
+ return Rigid(new_rots, new_translation)
+
+ def compose(self, r: Rigid) -> Rigid:
+ """
+ Composes the current rigid object with another.
+
+ Args:
+ r:
+ Another Rigid object
+ Returns:
+ The composition of the two transformations
+ """
+ new_rot = self._rots.compose_r(r._rots)
+ new_trans = self._rots.apply(r._trans) + self._trans
+ return Rigid(new_rot, new_trans)
+
+ def apply(self, pts: torch.Tensor) -> torch.Tensor:
+ """
+ Applies the transformation to a coordinate tensor.
+
+ Args:
+ pts: A [*, 3] coordinate tensor.
+ Returns:
+ The transformed points.
+ """
+ rotated = self._rots.apply(pts)
+ return rotated + self._trans
+
+ def invert_apply(self, pts: torch.Tensor) -> torch.Tensor:
+ """
+ Applies the inverse of the transformation to a coordinate tensor.
+
+ Args:
+ pts: A [*, 3] coordinate tensor
+ Returns:
+ The transformed points.
+ """
+ pts = pts - self._trans
+ return self._rots.invert_apply(pts)
+
+ def invert(self) -> Rigid:
+ """
+ Inverts the transformation.
+
+ Returns:
+ The inverse transformation.
+ """
+ rot_inv = self._rots.invert()
+ trn_inv = rot_inv.apply(self._trans)
+
+ return Rigid(rot_inv, -1 * trn_inv)
+
+ def map_tensor_fn(self, fn: Callable[[torch.Tensor], torch.Tensor]) -> Rigid:
+ """
+ Apply a Tensor -> Tensor function to underlying translation and rotation tensors, mapping over the
+ translation/rotation dimensions respectively.
+
+ Args:
+ fn:
+ A Tensor -> Tensor function to be mapped over the Rigid
+ Returns:
+ The transformed Rigid object
+ """
+ new_rots = self._rots.map_tensor_fn(fn)
+ new_trans = torch.stack(list(map(fn, torch.unbind(self._trans, dim=-1))), dim=-1)
+
+ return Rigid(new_rots, new_trans)
+
+ def to_tensor_4x4(self) -> torch.Tensor:
+ """
+ Converts a transformation to a homogeneous transformation tensor.
+
+ Returns:
+ A [*, 4, 4] homogeneous transformation tensor
+ """
+ tensor = self._trans.new_zeros((*self.shape, 4, 4))
+ tensor[..., :3, :3] = self._rots.get_rot_mats()
+ tensor[..., :3, 3] = self._trans
+ tensor[..., 3, 3] = 1
+ return tensor
+
+ @staticmethod
+ def from_tensor_4x4(t: torch.Tensor) -> Rigid:
+ """
+ Constructs a transformation from a homogeneous transformation tensor.
+
+ Args:
+ t: [*, 4, 4] homogeneous transformation tensor
+ Returns:
+ T object with shape [*]
+ """
+ if t.shape[-2:] != (4, 4):
+ raise ValueError("Incorrectly shaped input tensor")
+
+ rots = Rotation(rot_mats=t[..., :3, :3], quats=None)
+ trans = t[..., :3, 3]
+
+ return Rigid(rots, trans)
+
+ def to_tensor_7(self) -> torch.Tensor:
+ """
+ Converts a transformation to a tensor with 7 final columns, four for the quaternion followed by three for the
+ translation.
+
+ Returns:
+ A [*, 7] tensor representation of the transformation
+ """
+ tensor = self._trans.new_zeros((*self.shape, 7))
+ tensor[..., :4] = self._rots.get_quats()
+ tensor[..., 4:] = self._trans
+
+ return tensor
+
+ @staticmethod
+ def from_tensor_7(t: torch.Tensor, normalize_quats: bool = False) -> Rigid:
+ if t.shape[-1] != 7:
+ raise ValueError("Incorrectly shaped input tensor")
+
+ quats, trans = t[..., :4], t[..., 4:]
+
+ rots = Rotation(rot_mats=None, quats=quats, normalize_quats=normalize_quats)
+
+ return Rigid(rots, trans)
+
+ @staticmethod
+ def from_3_points(
+ p_neg_x_axis: torch.Tensor, origin: torch.Tensor, p_xy_plane: torch.Tensor, eps: float = 1e-8
+ ) -> Rigid:
+ """
+ Implements algorithm 21. Constructs transformations from sets of 3 points using the Gram-Schmidt algorithm.
+
+ Args:
+ p_neg_x_axis: [*, 3] coordinates
+ origin: [*, 3] coordinates used as frame origins
+ p_xy_plane: [*, 3] coordinates
+ eps: Small epsilon value
+ Returns:
+ A transformation object of shape [*]
+ """
+ p_neg_x_axis_unbound = torch.unbind(p_neg_x_axis, dim=-1)
+ origin_unbound = torch.unbind(origin, dim=-1)
+ p_xy_plane_unbound = torch.unbind(p_xy_plane, dim=-1)
+
+ e0 = [c1 - c2 for c1, c2 in zip(origin_unbound, p_neg_x_axis_unbound)]
+ e1 = [c1 - c2 for c1, c2 in zip(p_xy_plane_unbound, origin_unbound)]
+
+ denom = torch.sqrt(sum(c * c for c in e0) + eps * torch.ones_like(e0[0]))
+ e0 = [c / denom for c in e0]
+ dot = sum((c1 * c2 for c1, c2 in zip(e0, e1)))
+ e1 = [c2 - c1 * dot for c1, c2 in zip(e0, e1)]
+ denom = torch.sqrt(sum(c * c for c in e1) + eps * torch.ones_like(e1[0]))
+ e1 = [c / denom for c in e1]
+ e2 = [
+ e0[1] * e1[2] - e0[2] * e1[1],
+ e0[2] * e1[0] - e0[0] * e1[2],
+ e0[0] * e1[1] - e0[1] * e1[0],
+ ]
+
+ rots = torch.stack([c for tup in zip(e0, e1, e2) for c in tup], dim=-1)
+ rots = rots.reshape(rots.shape[:-1] + (3, 3))
+
+ rot_obj = Rotation(rot_mats=rots, quats=None)
+
+ return Rigid(rot_obj, torch.stack(origin_unbound, dim=-1))
+
+ def unsqueeze(self, dim: int) -> Rigid:
+ """
+ Analogous to torch.unsqueeze. The dimension is relative to the shared dimensions of the rotation/translation.
+
+ Args:
+ dim: A positive or negative dimension index.
+ Returns:
+ The unsqueezed transformation.
+ """
+ if dim >= len(self.shape):
+ raise ValueError("Invalid dimension")
+ rots = self._rots.unsqueeze(dim)
+ trans = self._trans.unsqueeze(dim if dim >= 0 else dim - 1)
+
+ return Rigid(rots, trans)
+
+ @staticmethod
+ def cat(ts: Sequence[Rigid], dim: int) -> Rigid:
+ """
+ Concatenates transformations along a new dimension.
+
+ Args:
+ ts:
+ A list of T objects
+ dim:
+ The dimension along which the transformations should be concatenated
+ Returns:
+ A concatenated transformation object
+ """
+ rots = Rotation.cat([t._rots for t in ts], dim)
+ trans = torch.cat([t._trans for t in ts], dim=dim if dim >= 0 else dim - 1)
+
+ return Rigid(rots, trans)
+
+ def apply_rot_fn(self, fn: Callable[[Rotation], Rotation]) -> Rigid:
+ """
+ Applies a Rotation -> Rotation function to the stored rotation object.
+
+ Args:
+ fn: A function of type Rotation -> Rotation
+ Returns:
+ A transformation object with a transformed rotation.
+ """
+ return Rigid(fn(self._rots), self._trans)
+
+ def apply_trans_fn(self, fn: Callable[[torch.Tensor], torch.Tensor]) -> Rigid:
+ """
+ Applies a Tensor -> Tensor function to the stored translation.
+
+ Args:
+ fn:
+ A function of type Tensor -> Tensor to be applied to the translation
+ Returns:
+ A transformation object with a transformed translation.
+ """
+ return Rigid(self._rots, fn(self._trans))
+
+ def scale_translation(self, trans_scale_factor: float) -> Rigid:
+ """
+ Scales the translation by a constant factor.
+
+ Args:
+ trans_scale_factor:
+ The constant factor
+ Returns:
+ A transformation object with a scaled translation.
+ """
+ return self.apply_trans_fn(lambda t: t * trans_scale_factor)
+
+ def stop_rot_gradient(self) -> Rigid:
+ """
+ Detaches the underlying rotation object
+
+ Returns:
+ A transformation object with detached rotations
+ """
+ return self.apply_rot_fn(lambda r: r.detach())
+
+ @staticmethod
+ def make_transform_from_reference(
+ n_xyz: torch.Tensor, ca_xyz: torch.Tensor, c_xyz: torch.Tensor, eps: float = 1e-20
+ ) -> Rigid:
+ """
+ Returns a transformation object from reference coordinates.
+
+ Note that this method does not take care of symmetries. If you provide the atom positions in the non-standard
+ way, the N atom will end up not at [-0.527250, 1.359329, 0.0] but instead at [-0.527250, -1.359329, 0.0]. You
+ need to take care of such cases in your code.
+
+ Args:
+ n_xyz: A [*, 3] tensor of nitrogen xyz coordinates.
+ ca_xyz: A [*, 3] tensor of carbon alpha xyz coordinates.
+ c_xyz: A [*, 3] tensor of carbon xyz coordinates.
+ Returns:
+ A transformation object. After applying the translation and rotation to the reference backbone, the
+ coordinates will approximately equal to the input coordinates.
+ """
+ translation = -1 * ca_xyz
+ n_xyz = n_xyz + translation
+ c_xyz = c_xyz + translation
+
+ c_x, c_y, c_z = [c_xyz[..., i] for i in range(3)]
+ norm = torch.sqrt(eps + c_x**2 + c_y**2)
+ sin_c1 = -c_y / norm
+ cos_c1 = c_x / norm
+
+ c1_rots = sin_c1.new_zeros((*sin_c1.shape, 3, 3))
+ c1_rots[..., 0, 0] = cos_c1
+ c1_rots[..., 0, 1] = -1 * sin_c1
+ c1_rots[..., 1, 0] = sin_c1
+ c1_rots[..., 1, 1] = cos_c1
+ c1_rots[..., 2, 2] = 1
+
+ norm = torch.sqrt(eps + c_x**2 + c_y**2 + c_z**2)
+ sin_c2 = c_z / norm
+ cos_c2 = torch.sqrt(c_x**2 + c_y**2) / norm
+
+ c2_rots = sin_c2.new_zeros((*sin_c2.shape, 3, 3))
+ c2_rots[..., 0, 0] = cos_c2
+ c2_rots[..., 0, 2] = sin_c2
+ c2_rots[..., 1, 1] = 1
+ c2_rots[..., 2, 0] = -1 * sin_c2
+ c2_rots[..., 2, 2] = cos_c2
+
+ c_rots = rot_matmul(c2_rots, c1_rots)
+ n_xyz = rot_vec_mul(c_rots, n_xyz)
+
+ _, n_y, n_z = [n_xyz[..., i] for i in range(3)]
+ norm = torch.sqrt(eps + n_y**2 + n_z**2)
+ sin_n = -n_z / norm
+ cos_n = n_y / norm
+
+ n_rots = sin_c2.new_zeros((*sin_c2.shape, 3, 3))
+ n_rots[..., 0, 0] = 1
+ n_rots[..., 1, 1] = cos_n
+ n_rots[..., 1, 2] = -1 * sin_n
+ n_rots[..., 2, 1] = sin_n
+ n_rots[..., 2, 2] = cos_n
+
+ rots = rot_matmul(n_rots, c_rots)
+
+ rots = rots.transpose(-1, -2)
+ translation = -1 * translation
+
+ rot_obj = Rotation(rot_mats=rots, quats=None)
+
+ return Rigid(rot_obj, translation)
+
+ def cuda(self) -> Rigid:
+ """
+ Moves the transformation object to GPU memory
+
+ Returns:
+ A version of the transformation on GPU
+ """
+ return Rigid(self._rots.cuda(), self._trans.cuda())
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/tensor_utils.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/tensor_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..449c810aed3f51b34a96674f29d5dc8bdfc35103
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/esm/openfold_utils/tensor_utils.py
@@ -0,0 +1,140 @@
+# Copyright 2021 AlQuraishi Laboratory
+# Copyright 2021 DeepMind Technologies Limited
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from functools import partial
+from typing import Any, Callable, TypeVar, Union, overload
+
+import torch
+import torch.nn as nn
+import torch.types
+
+
+def add(m1: torch.Tensor, m2: torch.Tensor, inplace: bool) -> torch.Tensor:
+ # The first operation in a checkpoint can't be in-place, but it's
+ # nice to have in-place addition during inference. Thus...
+ if not inplace:
+ m1 = m1 + m2
+ else:
+ m1 += m2
+
+ return m1
+
+
+def permute_final_dims(tensor: torch.Tensor, inds: list[int]) -> torch.Tensor:
+ zero_index = -1 * len(inds)
+ first_inds = list(range(len(tensor.shape[:zero_index])))
+ return tensor.permute(first_inds + [zero_index + i for i in inds])
+
+
+def flatten_final_dims(t: torch.Tensor, no_dims: int) -> torch.Tensor:
+ return t.reshape(t.shape[:-no_dims] + (-1,))
+
+
+def masked_mean(mask: torch.Tensor, value: torch.Tensor, dim: int, eps: float = 1e-4) -> torch.Tensor:
+ mask = mask.expand(*value.shape)
+ return torch.sum(mask * value, dim=dim) / (eps + torch.sum(mask, dim=dim))
+
+
+def pts_to_distogram(
+ pts: torch.Tensor, min_bin: torch.types.Number = 2.3125, max_bin: torch.types.Number = 21.6875, no_bins: int = 64
+) -> torch.Tensor:
+ boundaries = torch.linspace(min_bin, max_bin, no_bins - 1, device=pts.device)
+ dists = torch.sqrt(torch.sum((pts.unsqueeze(-2) - pts.unsqueeze(-3)) ** 2, dim=-1))
+ return torch.bucketize(dists, boundaries)
+
+
+def dict_multimap(fn: Callable[[list], Any], dicts: list[dict]) -> dict:
+ first = dicts[0]
+ new_dict = {}
+ for k, v in first.items():
+ all_v = [d[k] for d in dicts]
+ if isinstance(v, dict):
+ new_dict[k] = dict_multimap(fn, all_v)
+ else:
+ new_dict[k] = fn(all_v)
+
+ return new_dict
+
+
+def one_hot(x: torch.Tensor, v_bins: torch.Tensor) -> torch.Tensor:
+ reshaped_bins = v_bins.view(((1,) * len(x.shape)) + (len(v_bins),))
+ diffs = x[..., None] - reshaped_bins
+ am = torch.argmin(torch.abs(diffs), dim=-1)
+ return nn.functional.one_hot(am, num_classes=len(v_bins)).float()
+
+
+def batched_gather(data: torch.Tensor, inds: torch.Tensor, dim: int = 0, no_batch_dims: int = 0) -> torch.Tensor:
+ ranges: list[Union[slice, torch.Tensor]] = []
+ for i, s in enumerate(data.shape[:no_batch_dims]):
+ r = torch.arange(s)
+ r = r.view(*(*((1,) * i), -1, *((1,) * (len(inds.shape) - i - 1))))
+ ranges.append(r)
+
+ remaining_dims: list[Union[slice, torch.Tensor]] = [slice(None) for _ in range(len(data.shape) - no_batch_dims)]
+ remaining_dims[dim - no_batch_dims if dim >= 0 else dim] = inds
+ ranges.extend(remaining_dims)
+ # Matt note: Editing this to get around the behaviour of using a list as an array index changing
+ # in recent Numpy versions
+ return data[tuple(ranges)]
+
+
+T = TypeVar("T")
+
+
+# With tree_map, a poor man's JAX tree_map
+def dict_map(
+ fn: Callable[[T], Any], dic: dict[Any, Union[dict, list, tuple, T]], leaf_type: type[T]
+) -> dict[Any, Union[dict, list, tuple, Any]]:
+ new_dict: dict[Any, Union[dict, list, tuple, Any]] = {}
+ for k, v in dic.items():
+ if isinstance(v, dict):
+ new_dict[k] = dict_map(fn, v, leaf_type)
+ else:
+ new_dict[k] = tree_map(fn, v, leaf_type)
+
+ return new_dict
+
+
+@overload
+def tree_map(fn: Callable[[T], Any], tree: T, leaf_type: type[T]) -> Any: ...
+
+
+@overload
+def tree_map(fn: Callable[[T], Any], tree: dict, leaf_type: type[T]) -> dict: ...
+
+
+@overload
+def tree_map(fn: Callable[[T], Any], tree: list, leaf_type: type[T]) -> list: ...
+
+
+@overload
+def tree_map(fn: Callable[[T], Any], tree: tuple, leaf_type: type[T]) -> tuple: ...
+
+
+def tree_map(fn, tree, leaf_type):
+ if isinstance(tree, dict):
+ return dict_map(fn, tree, leaf_type)
+ elif isinstance(tree, list):
+ return [tree_map(fn, x, leaf_type) for x in tree]
+ elif isinstance(tree, tuple):
+ return tuple(tree_map(fn, x, leaf_type) for x in tree)
+ elif isinstance(tree, leaf_type):
+ return fn(tree)
+ else:
+ print(type(tree))
+ raise TypeError("Not supported")
+
+
+tensor_tree_map = partial(tree_map, leaf_type=torch.Tensor)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3c249f7bc2784db86718bca1cbd46ff5ed9fd86a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/configuration_evolla.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/configuration_evolla.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..157d9162402065cf2339b91fa704af15ccfef8f4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/configuration_evolla.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/modeling_evolla.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/modeling_evolla.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10276cbea9e623f1e3096a5126a0e84db2a61e30
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/modeling_evolla.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/modular_evolla.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/modular_evolla.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..52d534100194e5b5ad51b5338acf651214956794
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/modular_evolla.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/processing_evolla.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/processing_evolla.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ce5df483ffce674eae5b532a0884988ebcb802d4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/evolla/__pycache__/processing_evolla.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7f7cd39517dc7a206bd6450c26620fd6223992e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/configuration_exaone4.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/configuration_exaone4.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d34052d656367132b5d7e8a20e5a4b64e2625d34
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/configuration_exaone4.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/modeling_exaone4.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/modeling_exaone4.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0230f66229ee1b180d98fd4703b745a23a88bfa5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/modeling_exaone4.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/modular_exaone4.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/modular_exaone4.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..57339d3e7b102e2ff7176bcdcc7fbdab8b42bb38
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/exaone4/__pycache__/modular_exaone4.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7738a40937ef7f6112ab10675b6da8d15e0a8bfa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon/__pycache__/configuration_falcon.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon/__pycache__/configuration_falcon.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af6a05adc640d22c9987b4eadec4ae046b59c248
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon/__pycache__/configuration_falcon.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon/__pycache__/modeling_falcon.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon/__pycache__/modeling_falcon.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bfea13e1e7f35a41a61bc87e970f9f7fe004ed4f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon/__pycache__/modeling_falcon.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb40a173d2719029c60250db7a2d9086043effe1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/configuration_falcon_h1.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/configuration_falcon_h1.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..969025ddc360e315c9823a51bc97172c242b9ba0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/configuration_falcon_h1.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/modeling_falcon_h1.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/modeling_falcon_h1.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..129051d416e631c08f44bb213486beaafd05066f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/modeling_falcon_h1.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/modular_falcon_h1.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/modular_falcon_h1.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..675c17a77e7a4ed3e6a78c6ba917ded110e417b7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_h1/__pycache__/modular_falcon_h1.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c3e07d1d4114e91b28901fb000b0fafd2783439d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/configuration_falcon_mamba.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/configuration_falcon_mamba.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ff4e7254610a0a9c0808ae673bda00250d362fb8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/configuration_falcon_mamba.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/modeling_falcon_mamba.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/modeling_falcon_mamba.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a50abb16a89048e19a712ea8fe9d78c5f93a0f77
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/modeling_falcon_mamba.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/modular_falcon_mamba.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/modular_falcon_mamba.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b5c2518868a4f7e4ea65d6b1f82d02ce6abc669e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/falcon_mamba/__pycache__/modular_falcon_mamba.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb899520f4e711c0d67d0900af01608228437b98
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/configuration_fastspeech2_conformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/configuration_fastspeech2_conformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3ce0864f6d354018b936a967d6a2c32af341f20
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/configuration_fastspeech2_conformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/modeling_fastspeech2_conformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/modeling_fastspeech2_conformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cdb9d73f16cbaa8913139a78a864eb564167ade1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/modeling_fastspeech2_conformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/tokenization_fastspeech2_conformer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/tokenization_fastspeech2_conformer.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1c15fa572af579e081975859a7ff32f7e3e5d6d9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fastspeech2_conformer/__pycache__/tokenization_fastspeech2_conformer.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e7f72354546484faee48b139fa2979ab82cc469a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/configuration_flaubert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/configuration_flaubert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a84c152090b6504400495bee095df1cd0ffe357
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/configuration_flaubert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/modeling_flaubert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/modeling_flaubert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cae40387cf2515431fe9bf60a3467711c6dd94fa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/modeling_flaubert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/modeling_tf_flaubert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/modeling_tf_flaubert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5249148b24fcde044f0228dfc49eb6793d15f72f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/modeling_tf_flaubert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/tokenization_flaubert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/tokenization_flaubert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cfc4237e2a9dc58d36068057aeafda67e9c7f5f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flaubert/__pycache__/tokenization_flaubert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea89ef1a7305678856e7650075bd48d85f2a5c47
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/configuration_flava.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/configuration_flava.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b12bbeb0ba8886518d7a95867a128e43af18a85
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/configuration_flava.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/feature_extraction_flava.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/feature_extraction_flava.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d27f6aa2dd3e80bd6331988c19c998a4643e8ef
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/feature_extraction_flava.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/image_processing_flava.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/image_processing_flava.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd41b29a323a1364533634dca22637fac3c6a9c2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/image_processing_flava.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/image_processing_flava_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/image_processing_flava_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc1dba9de3d6df5222fcbcd0f2868be238adff78
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/image_processing_flava_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/modeling_flava.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/modeling_flava.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f584c856b868c1c3806c4db9cd653cb8eb2cc254
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/modeling_flava.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8bd25d1c25de238c55d688063dc9eb50ad0d8bddcd5691fef509d773c214619b
+size 103984
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/processing_flava.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/processing_flava.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7b8ad08c626cbae48087ad0b2eb3f88eb89f90d5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/flava/__pycache__/processing_flava.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f34a6b44b661ade762fc4e85681b5fbdd87511e0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/configuration_florence2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/configuration_florence2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ef3f76e5ed44ea9a85f61b4ef0f0520f238f8cb7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/configuration_florence2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/modeling_florence2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/modeling_florence2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8320328572d2f05fbe9935604f7831f5c7b8d4b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/modeling_florence2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/modular_florence2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/modular_florence2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59222ff3a8ad6bc9b92dbb4d4978504939f09938
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/modular_florence2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/processing_florence2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/processing_florence2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4742c424d3b9d55fad75acfdba1fa13204a990bb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/florence2/__pycache__/processing_florence2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63a819055550d61f3eab5d919fe0bd75089f9af4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/configuration_fnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/configuration_fnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fa02d787d6ef3f41fb55b363e32d56e8587570d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/configuration_fnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/modeling_fnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/modeling_fnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..599c4f141eb9b03dfa0f6fbf5c8106f476d42940
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/modeling_fnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a990c8e49f1c7800f4d55dbf0f5e6adc97c6a1b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4d17080653ac0fe05f271c922652f4825ed0ac70
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fnet/__pycache__/tokenization_fnet_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/focalnet/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/focalnet/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4a2824b42148da811bfd9f4ce509ff566b84e06a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/focalnet/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/focalnet/__pycache__/configuration_focalnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/focalnet/__pycache__/configuration_focalnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a29b8298d6207647e4bde2147ae2bd6aed4625c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/focalnet/__pycache__/configuration_focalnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/focalnet/__pycache__/modeling_focalnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/focalnet/__pycache__/modeling_focalnet.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf9068332000cbfeb24951d6a058dc418971b79f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/focalnet/__pycache__/modeling_focalnet.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c9f09b554c1cdd1f7783bd6c4e34867a860dfa30
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/configuration_fsmt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/configuration_fsmt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13a4a404468b8ff1ce30e0479f7c265bc995f056
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/configuration_fsmt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/modeling_fsmt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/modeling_fsmt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..397bea903c088773a3de51350690a97ee77348f8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/modeling_fsmt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/tokenization_fsmt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/tokenization_fsmt.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f22f5d454d8cbc7ab8ba5dee3f4ecfa5d21b2fdd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fsmt/__pycache__/tokenization_fsmt.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a31291f8a1b20a3afff91bb2eb5a1c9475529e4e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/configuration_funnel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/configuration_funnel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..431af0cd4a58947eb77a7fa40c81283cf532fa65
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/configuration_funnel.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/modeling_funnel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/modeling_funnel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..530901bd2a3a124e15693459e7d695e54146bc2a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/modeling_funnel.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/modeling_tf_funnel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/modeling_tf_funnel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f327a1886fc966e3b12e63244815558c995fa955
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/modeling_tf_funnel.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/tokenization_funnel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/tokenization_funnel.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d05caa8656b4f6f5a499b83bb87a765594f3f71c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/tokenization_funnel.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/tokenization_funnel_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/tokenization_funnel_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fc5f162405c0cde50b6af74cc587d85482cd462a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/funnel/__pycache__/tokenization_funnel_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..181d78a4bfabd39e885c356977711e3eef4a344f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/configuration_fuyu.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/configuration_fuyu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd062d83b78dc46698b3bcf6655d344af1e43d41
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/configuration_fuyu.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/image_processing_fuyu.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/image_processing_fuyu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85458cdaa077f570de341e4f1570df82f9afc679
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/image_processing_fuyu.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/modeling_fuyu.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/modeling_fuyu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..971f01e4341762d1f6cedc4a5679df612f3644c4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/modeling_fuyu.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/processing_fuyu.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/processing_fuyu.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b35305aeb35a7d975f35c8e8d5ae1cdde710fc2a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/fuyu/__pycache__/processing_fuyu.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..44ecdacabb842a2cf4a09cffced661e22d57edd4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/configuration_gemma.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/configuration_gemma.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d1dcaaec7f4ae86c207b3d6a551d76fb93e2ca27
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/configuration_gemma.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/modeling_flax_gemma.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/modeling_flax_gemma.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00244cab8ec676ccac02006b162b4e67015c344b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/modeling_flax_gemma.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/modeling_gemma.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/modeling_gemma.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d7c831aa77c2eb58584fe7d0b32b74ac86365fca
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/modeling_gemma.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/modular_gemma.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/modular_gemma.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04316614cda003b13542139850eacc6f0cd5b78e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/modular_gemma.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/tokenization_gemma.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/tokenization_gemma.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3658fb15f7802537e0e791b4365ebcee482bd36f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/tokenization_gemma.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/tokenization_gemma_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/tokenization_gemma_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d4b8b636b4e5e6571bd105c04baf9ef962db6e2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma/__pycache__/tokenization_gemma_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..98b4fb76fd62842d546ce1f528dc091f8501391f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/configuration_gemma2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/configuration_gemma2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67f314e835060596cfc23aa0c859cee79bfa507e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/configuration_gemma2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/modeling_gemma2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/modeling_gemma2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13e740ecf9416a145a8c018f9462a4a7f46ae3f8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/modeling_gemma2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/modular_gemma2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/modular_gemma2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bbc99006354e88ac77e19db4a881ca653368bb13
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma2/__pycache__/modular_gemma2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c35f0d43f7bfa0be65de381a5d558ca7eba6dd33
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/configuration_gemma3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/configuration_gemma3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64eaa1f4874f7b539beb253a92bcffbb62d21b51
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/configuration_gemma3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/image_processing_gemma3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/image_processing_gemma3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d7667f535229d454f6dea876045212d45672392b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/image_processing_gemma3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/image_processing_gemma3_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/image_processing_gemma3_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5a86b6d73a83e5fa2fc01972ce01558ad857a61f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/image_processing_gemma3_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/modeling_gemma3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/modeling_gemma3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..286f5fd51c031c1a6ddbf1f300c49d30ce66d84d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/modeling_gemma3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/modular_gemma3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/modular_gemma3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..79edeef87e87f0fd698d93ca45c93b35693cd9b8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/modular_gemma3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/processing_gemma3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/processing_gemma3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..40d8219dd1a9d0c89423afe03078e57a2a1d192b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3/__pycache__/processing_gemma3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fdccf7baa28b0c92d965ebcfb19412ec10c4363b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/configuration_gemma3n.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/configuration_gemma3n.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f0b39bacdae823c7c8dd5a2ea52938f98ff54172
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/configuration_gemma3n.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/feature_extraction_gemma3n.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/feature_extraction_gemma3n.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..29414491b1bc5518e047a2c8632b219d9017f441
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/feature_extraction_gemma3n.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/modeling_gemma3n.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/modeling_gemma3n.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4974e5f93296bc50e3d240a811596be9df8d8d81
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/modeling_gemma3n.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6b77214aac6bf1ecb2344dad9c847134877bcdb15f226722836f5044262c488d
+size 124243
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/modular_gemma3n.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/modular_gemma3n.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..144c44279f03ce95ea51ec7a1eb941230d6c61a1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/modular_gemma3n.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0db50a2cbdbdcc7fbe0930290040e316ea70580708b2c4edd7457836b5ffd775
+size 136471
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/processing_gemma3n.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/processing_gemma3n.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33523d2e771b970fd116c9aa668f11343ab0ee9d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gemma3n/__pycache__/processing_gemma3n.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36e8e6d40e1b0da1728a1a5da37bed1e294a66ed
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/configuration_git.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/configuration_git.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0dcbbe618912b3cc28f8893c9ce7cdfbef4ad26c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/configuration_git.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/modeling_git.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/modeling_git.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0e44adedcb0280d08256b007f19a692c7273b731
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/modeling_git.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/processing_git.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/processing_git.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0d150cb10a38c02b86dd25730c497f162ab130df
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/git/__pycache__/processing_git.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7f9e62a703b0e3b18454fdee9bf8848742cb3f8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/configuration_glm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/configuration_glm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b8d484d71d701437a69bd9d729c443be44bb487
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/configuration_glm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/modeling_glm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/modeling_glm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a2debf9734497c925f7f84ab9a031ee33276f4c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/modeling_glm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/modular_glm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/modular_glm.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b7bf74a2e4f20f75156456fcab56bec12a609847
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm/__pycache__/modular_glm.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9032a301f3e9456e99667fd7b6ded00f8a310065
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/configuration_glm4.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/configuration_glm4.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b2225afe1c2515830f0fd0d413a9cb07096c2f6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/configuration_glm4.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/modeling_glm4.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/modeling_glm4.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e81e20135e452651c5ba8f337bf98c272e548bd5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/modeling_glm4.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/modular_glm4.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/modular_glm4.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..39acd89d61b6678ec1d7e7525764efff4952a8e5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4/__pycache__/modular_glm4.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb1be0b667bfe9c97b5b68566a9bd72fbd5f7d20
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/configuration_glm4_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/configuration_glm4_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2e6bf5f6e0caf7000a88aa0fa251041ddd2f8150
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/configuration_glm4_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/modeling_glm4_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/modeling_glm4_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6d092d5795eb33303e19bfaa64a410c82de2cb7e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/modeling_glm4_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/modular_glm4_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/modular_glm4_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5282cbeeed7b7452464bc8426f6d160b1e01973c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4_moe/__pycache__/modular_glm4_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d960598f564903db4bb01d5929c8eb2ea081b92
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/configuration_glm4v.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/configuration_glm4v.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e791bcef17c9451e33d8c060e138bd69e140ffe9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/configuration_glm4v.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/image_processing_glm4v.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/image_processing_glm4v.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4256762b49a78bf8733665b80008b7d2bed4b953
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/image_processing_glm4v.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/image_processing_glm4v_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/image_processing_glm4v_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b3b1b081d95c736c9b4958f5e6c9ce43df106082
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/image_processing_glm4v_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/modeling_glm4v.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/modeling_glm4v.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a73e1ab2bdd5d7e76e59cfbb17b4c9b965b09855
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/modeling_glm4v.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/modular_glm4v.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/modular_glm4v.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..befbfe913a4510e99f896620a4a33c042b54d0a3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/modular_glm4v.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/processing_glm4v.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/processing_glm4v.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a05cdc0eb3841ff1b50ecffae7fac1b9a8ee4ddf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/processing_glm4v.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/video_processing_glm4v.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/video_processing_glm4v.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b36e292a578fbc8820bd6519dcf6a10a87eeff0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v/__pycache__/video_processing_glm4v.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dd0f7dea199a1d2df172e05072a5ba17a19b0be4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/configuration_glm4v_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/configuration_glm4v_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..af78687c0c7fccca96544d0babed62d448e9ddbf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/configuration_glm4v_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/modeling_glm4v_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/modeling_glm4v_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..305f8830c63553e0eaf9ee3fead342cc0f932fc0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/modeling_glm4v_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/modular_glm4v_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/modular_glm4v_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..808eaff86c5a6fcc2ab739f947e58698925b8254
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glm4v_moe/__pycache__/modular_glm4v_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3363354c9fefed243e21aabcff3880fed51cc5e5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/configuration_glpn.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/configuration_glpn.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..094c80bcb959ccba8ae07f6f4c56eaedc73195af
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/configuration_glpn.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/feature_extraction_glpn.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/feature_extraction_glpn.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fdb398f2ee40c24b0c29cf0ff7ba68b19ab3bf0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/feature_extraction_glpn.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/image_processing_glpn.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/image_processing_glpn.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbfd7c28bd474f015d756e062dcf0d9ff3b41e95
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/image_processing_glpn.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/modeling_glpn.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/modeling_glpn.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f234c7e3fe694ad914dc97b36e36d75347a9ccc0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/glpn/__pycache__/modeling_glpn.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd732cde842234305e3cddd08afebcb53de000a6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/configuration_got_ocr2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/configuration_got_ocr2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..00fd3bb6739a29c031e18d4cb108774aa0f8e985
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/configuration_got_ocr2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab538036aa17be288d05c9f1621d867c10919a68
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb42001136bf089265871d3e7a4274d7c914f1bd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/image_processing_got_ocr2_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/modeling_got_ocr2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/modeling_got_ocr2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b0e4097ebb9479933217d7669f9601ec0163a246
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/modeling_got_ocr2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/modular_got_ocr2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/modular_got_ocr2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..192a8db172d4cf2262c5b40dc941d220a84409e2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/modular_got_ocr2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/processing_got_ocr2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/processing_got_ocr2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3cb5b9e70804479ffcac1164b491f16277faf3ca
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/got_ocr2/__pycache__/processing_got_ocr2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2a3ef205b93bc47134325508f1ffb9e4d94d330d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/configuration_gpt2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/configuration_gpt2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc8aeb364f50507caf7cabcd80d380e4d1a51ba7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/configuration_gpt2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/modeling_flax_gpt2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/modeling_flax_gpt2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a1f4b2e26238c81b0e45929d8dbf5a095881d6ab
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/modeling_flax_gpt2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/modeling_gpt2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/modeling_gpt2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..92a1482ee8dc9ac41736e1a9785ecdc0bce42bb9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/modeling_gpt2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/modeling_tf_gpt2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/modeling_tf_gpt2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..31f09ac12029c074eb9f986416ceb0d841e9d604
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/modeling_tf_gpt2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/tokenization_gpt2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/tokenization_gpt2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c96df1f989be499ef9abcd3521c5db19c2cc76bc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/tokenization_gpt2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/tokenization_gpt2_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/tokenization_gpt2_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..67fbe0e8b564f2336af615d5ded63492106bed31
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/tokenization_gpt2_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/tokenization_gpt2_tf.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/tokenization_gpt2_tf.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b81cf8511afeb925a0abd5ad2aeaf3afd231c21
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt2/__pycache__/tokenization_gpt2_tf.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_bigcode/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_bigcode/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..72ecb0043389c431f6227d8d7837a5e62ec1f947
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_bigcode/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_bigcode/__pycache__/configuration_gpt_bigcode.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_bigcode/__pycache__/configuration_gpt_bigcode.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10a68e640f7be50c242884817130a009065bde1b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_bigcode/__pycache__/configuration_gpt_bigcode.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_bigcode/__pycache__/modeling_gpt_bigcode.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_bigcode/__pycache__/modeling_gpt_bigcode.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3accc12adda3e912f3e041bfd3081a4dc3e587fc
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_bigcode/__pycache__/modeling_gpt_bigcode.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1087d1a7f4232ccb9bc5b241ca8ecc8d3ee13fe7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/configuration_gpt_neo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/configuration_gpt_neo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0febe8b95d5a461fbc9f4843042711e84e81b15
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/configuration_gpt_neo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/modeling_flax_gpt_neo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/modeling_flax_gpt_neo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4e52163fb9c86ace1c07de25151d09eec93a34dd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/modeling_flax_gpt_neo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/modeling_gpt_neo.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/modeling_gpt_neo.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21e58d4e183fe293e7a2ef1cce73ec1446cd278d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neo/__pycache__/modeling_gpt_neo.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..889c1fc45396fd074a0d2c2b0768aed270868649
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/configuration_gpt_neox.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/configuration_gpt_neox.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..692778458a79d39894597cc6c5bd963b7e10c222
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/configuration_gpt_neox.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/modeling_gpt_neox.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/modeling_gpt_neox.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..431869c937d819b75912eb00abc8ef605670671e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/modeling_gpt_neox.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/modular_gpt_neox.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/modular_gpt_neox.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d0d135255ad0269737c02f5547b0919d0c68873
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/modular_gpt_neox.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/tokenization_gpt_neox_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/tokenization_gpt_neox_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de1bd0afd425e92a3f964300171488cc4dda2357
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox/__pycache__/tokenization_gpt_neox_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..be51ab08922d2cd5d9e9adda05ee03bce604933e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/configuration_gpt_neox_japanese.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/configuration_gpt_neox_japanese.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fbf8d6483461d07695b9afaebeadc165bc5b3cc3
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/configuration_gpt_neox_japanese.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/modeling_gpt_neox_japanese.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/modeling_gpt_neox_japanese.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8fb82b2b1b5fac68c212eb13389fa37c0ec4c6ed
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/modeling_gpt_neox_japanese.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/tokenization_gpt_neox_japanese.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/tokenization_gpt_neox_japanese.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d53c0c7fe2c935623b73519b55ad02b998f2c7b4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_neox_japanese/__pycache__/tokenization_gpt_neox_japanese.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..029c0ee15c9389e8b0dfa4e2278263b113d08fbe
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/configuration_gpt_oss.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/configuration_gpt_oss.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..74aeed310c7299709201086ae29b72111137ed04
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/configuration_gpt_oss.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/modeling_gpt_oss.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/modeling_gpt_oss.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e8d5a138007c89e461447a8b2092a1c1a7806ffe
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/modeling_gpt_oss.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/modular_gpt_oss.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/modular_gpt_oss.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..36a1088d1dd3419472d369b261066bf3d9fb21e0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_oss/__pycache__/modular_gpt_oss.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_sw3/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_sw3/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..288cbcde76df0c305eed6b8468529c535f5b420f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_sw3/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_sw3/__pycache__/tokenization_gpt_sw3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_sw3/__pycache__/tokenization_gpt_sw3.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6198048d047f6d40975673ac2677d1eb035a1a64
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gpt_sw3/__pycache__/tokenization_gpt_sw3.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..609a210d10fe72acdd312908de40562df32cd026
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/configuration_gptj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/configuration_gptj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..410c93c8aa2232b9abe261cf0f8e5001ebb7d5b5
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/configuration_gptj.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/modeling_flax_gptj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/modeling_flax_gptj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c23bc635fec649a1f506786bd95710170e7d78de
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/modeling_flax_gptj.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/modeling_gptj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/modeling_gptj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bb4dda0636247e7c4ea53048e55a169a654109a8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/modeling_gptj.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/modeling_tf_gptj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/modeling_tf_gptj.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4f7d5ef4aeb0e15d04f3bdde0d174bc1363d1088
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/gptj/__pycache__/modeling_tf_gptj.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cd468e5057feba97c55e820816a60b3ea50ecacf
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/configuration_granite.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/configuration_granite.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..894ae6cd60c5667c45f5978304a15d0b84e6948d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/configuration_granite.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/modeling_granite.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/modeling_granite.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3ebed32b9bced767894e59485ed9c42617c21b5f
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/modeling_granite.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/modular_granite.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/modular_granite.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..33e6573545052e2407d7e288b04dd26d0cf78f5d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite/__pycache__/modular_granite.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2cae99791b8aa64d12e68db5c227597218610048
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/configuration_granite_speech.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/configuration_granite_speech.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1d9394d2ede07a199200da380ff3533949aada33
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/configuration_granite_speech.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/feature_extraction_granite_speech.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/feature_extraction_granite_speech.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d89b51049e0ce365f1d0260637ee866ea0416d0d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/feature_extraction_granite_speech.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/modeling_granite_speech.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/modeling_granite_speech.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b58a9a648d8fa49c174ecd3631cb4861eda4da65
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/modeling_granite_speech.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/processing_granite_speech.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/processing_granite_speech.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5635ed5503ea1bbf885a6238efe21237a45ee328
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granite_speech/__pycache__/processing_granite_speech.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoe/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoe/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d542719a6bc072919e9eee81b7c2b90e2c401e17
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoe/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoe/__pycache__/configuration_granitemoe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoe/__pycache__/configuration_granitemoe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c70c01a5a8cdb3dbeb25d3fe5c7f035593054f1c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoe/__pycache__/configuration_granitemoe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoe/__pycache__/modeling_granitemoe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoe/__pycache__/modeling_granitemoe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..823ba85bc91d36cc04dcb1036d50802dd4a92cad
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoe/__pycache__/modeling_granitemoe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9666d700a76f73ea91ed0337c7681e5863afc6aa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/configuration_granitemoehybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/configuration_granitemoehybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a7946bb7eae86c17013382b6932e2806933bc8de
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/configuration_granitemoehybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/modeling_granitemoehybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/modeling_granitemoehybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..13aa2dc140ad0b0d41638f82895eaeff93f03c75
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/modeling_granitemoehybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/modular_granitemoehybrid.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/modular_granitemoehybrid.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ab20eb5f8627875134d2bbc4f08c22960088c2c0
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoehybrid/__pycache__/modular_granitemoehybrid.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eee95c8a6bcff81173781c2fef98928586284cac
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/configuration_granitemoeshared.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/configuration_granitemoeshared.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..17719f46b886edfc25b6dfb0d7432167304c28d1
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/configuration_granitemoeshared.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/modeling_granitemoeshared.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/modeling_granitemoeshared.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4af944ff2ba2493135fb4fb0e74b8da1766dd591
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/modeling_granitemoeshared.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/modular_granitemoeshared.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/modular_granitemoeshared.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78dfa247ba4ce8e3c84b25d855dcd0fd0d246ece
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/granitemoeshared/__pycache__/modular_granitemoeshared.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8bbb762fd2f8619c349dd2e73d57f90bfb2cf1f9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/configuration_grounding_dino.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/configuration_grounding_dino.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b53a873a2daed4abeca13bafc186039199897ada
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/configuration_grounding_dino.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/image_processing_grounding_dino.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/image_processing_grounding_dino.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bd4cd58d3b4c35759173fb76af3476f015b8a34c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/image_processing_grounding_dino.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/image_processing_grounding_dino_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/image_processing_grounding_dino_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f5523a32e13f65e326638f7205c78e0b626aa238
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/image_processing_grounding_dino_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/modeling_grounding_dino.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/modeling_grounding_dino.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8c2c89cc839fb5cbed4a3285109e676bbccbff1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/modeling_grounding_dino.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ca861027307c500091f47cf3605454e2a181ea95ea0a9ddae3a6f7a08c72f3a0
+size 142656
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/modular_grounding_dino.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/modular_grounding_dino.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26278936c007798931d8c99c74fd1c0240b0891c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/modular_grounding_dino.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/processing_grounding_dino.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/processing_grounding_dino.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b1c25eaf21bd2104ec65ec324f1529bc07eca1ca
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/grounding_dino/__pycache__/processing_grounding_dino.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ef6976687f334a7180eb47904060f06437dae77
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/configuration_groupvit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/configuration_groupvit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d402a9b03622caf09f63826af40752b585eea5b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/configuration_groupvit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/modeling_groupvit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/modeling_groupvit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..431c92bd19bc0f95f6192bbe438e11b83a283e49
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/modeling_groupvit.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/modeling_tf_groupvit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/modeling_tf_groupvit.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..663db502796dd0e94db1d0032c08fea5fb3873fe
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/groupvit/__pycache__/modeling_tf_groupvit.cpython-312.pyc
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:cf97a6f14616a3e581e20190daa9b330c46a1388e4bfc03cb1897e8fca1970b0
+size 102952
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..069593a454487e09f4d026a1198bc944b1e8e984
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/configuration_helium.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/configuration_helium.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..21d2bf5ff71068ec595e4c60ccc47037f46e039d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/configuration_helium.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/modeling_helium.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/modeling_helium.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8aa648c3189246cc8432aece5aa2d1a86798852b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/modeling_helium.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/modular_helium.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/modular_helium.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f3f83a7b5cb77c69c0e8d7994a4da9ea7376bbb7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/helium/__pycache__/modular_helium.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/herbert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/herbert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ddc0fa9aa550f046c84daeca69b5575eea9f3fb
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/herbert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/herbert/__pycache__/tokenization_herbert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/herbert/__pycache__/tokenization_herbert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26417e22a2f77e5db2f520a7e3aed9e776becc5e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/herbert/__pycache__/tokenization_herbert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/herbert/__pycache__/tokenization_herbert_fast.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/herbert/__pycache__/tokenization_herbert_fast.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c03ea08abeb1b5d351e969b8cc1f97273c75fa4e
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/herbert/__pycache__/tokenization_herbert_fast.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..587da8dcdf289e56c8754caefec448bf2befafc6
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/configuration_hgnet_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/configuration_hgnet_v2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1b7cb9ed26677594c63390e7a2132898b4a9d48d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/configuration_hgnet_v2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/modeling_hgnet_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/modeling_hgnet_v2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..de0082f5db6a004202b3fb0860074546bd093ae4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/modeling_hgnet_v2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/modular_hgnet_v2.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/modular_hgnet_v2.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..122903e1b38e2b1fcea23ab126f6e9780f71fb67
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hgnet_v2/__pycache__/modular_hgnet_v2.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hiera/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hiera/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3cff807620a06c3c30b2b794cc98749702dd3f5b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hiera/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hiera/__pycache__/configuration_hiera.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hiera/__pycache__/configuration_hiera.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..257b5223fc989c1a69fc3d0c12e4ad8465b8fc2d
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hiera/__pycache__/configuration_hiera.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hiera/__pycache__/modeling_hiera.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hiera/__pycache__/modeling_hiera.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3951ac66d6b8562c7052515837aa9b5e5e058caa
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hiera/__pycache__/modeling_hiera.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f7cad57e6a5708350334230c6d359f4a0416e359
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/configuration_hubert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/configuration_hubert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c230e17181962e425f2bacbb34d1f01e71eb7dfd
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/configuration_hubert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/modeling_hubert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/modeling_hubert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..0b61dc1b6e4536835d3e48968129eec14ac56fd4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/modeling_hubert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/modeling_tf_hubert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/modeling_tf_hubert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..54e713fdb715de9472b5a0249e00487ebea56263
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/modeling_tf_hubert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/modular_hubert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/modular_hubert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a3c2c5fd6bfc1901043c939a221fc55c68a236c2
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hubert/__pycache__/modular_hubert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..989b7dfa83654bcfe396be444d52bb56810088f7
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/configuration_hunyuan_v1_dense.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/configuration_hunyuan_v1_dense.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ca16cfef719220bb21c70a9c5cea3c6b5911943c
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/configuration_hunyuan_v1_dense.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/modeling_hunyuan_v1_dense.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/modeling_hunyuan_v1_dense.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6585cb432f0f0f17e964b4c8218fca115ce78766
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/modeling_hunyuan_v1_dense.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/modular_hunyuan_v1_dense.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/modular_hunyuan_v1_dense.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f119707d6572f0c67f37fc31c2756108b0a9f26
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_dense/__pycache__/modular_hunyuan_v1_dense.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e79dea6c4bc59a3d4f06f4e001b316eb81898285
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/configuration_hunyuan_v1_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/configuration_hunyuan_v1_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9afa3fe4b90398c8722523b1e6b72d7eb98c6478
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/configuration_hunyuan_v1_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/modeling_hunyuan_v1_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/modeling_hunyuan_v1_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3161891ed698ae592e200007fb81aa60820f1cec
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/modeling_hunyuan_v1_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/modular_hunyuan_v1_moe.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/modular_hunyuan_v1_moe.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5d0a0f9b4745595e5541ffb5fb78681c7140f7ab
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/hunyuan_v1_moe/__pycache__/modular_hunyuan_v1_moe.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f1aba7ffa217897b584a2593173cc470d3e07057
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/configuration_ibert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/configuration_ibert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3f40ba40c01a6ad19880008a4e6228602ee65d0a
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/configuration_ibert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/modeling_ibert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/modeling_ibert.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7cd6cade8d0cbbc7a77fab418cc7ccf66f6f82ce
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/modeling_ibert.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/quant_modules.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/quant_modules.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5831bdf37e64533c86e41e84484fb174c7937eb8
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/ibert/__pycache__/quant_modules.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/__init__.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4592aa45f8759b3daada83b8b1caa93ab1cdb5b
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/__init__.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/configuration_idefics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/configuration_idefics.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5ac35cd48835c4229e046524b57796c19cd2e3d4
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/configuration_idefics.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/image_processing_idefics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/image_processing_idefics.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2fb88c03fb39e9f4a63b79a8ecd8e5053047acb9
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/image_processing_idefics.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/modeling_idefics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/modeling_idefics.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..eb546445cecf3e7fda505fc3edff068de769cd53
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/modeling_idefics.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/modeling_tf_idefics.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/modeling_tf_idefics.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..37fddd1f11dcc786572b581fb4a5890e6d0b0e66
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/modeling_tf_idefics.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/perceiver.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/perceiver.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..06f1647e1ef5992327d6cb218bd36c2fc0672263
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/perceiver.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/perceiver_tf.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/perceiver_tf.cpython-312.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e26a3c80368682206de748fb0025104608cfb162
Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/idefics/__pycache__/perceiver_tf.cpython-312.pyc differ
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/modeling_tf_xglm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/modeling_tf_xglm.py
new file mode 100644
index 0000000000000000000000000000000000000000..d799ced792080d6df30a14e787f187c4484c62c8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/modeling_tf_xglm.py
@@ -0,0 +1,1002 @@
+# coding=utf-8
+# Copyright 2021 The Fairseq Authors The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""TF 2.0 XGLM model."""
+
+from __future__ import annotations
+
+import math
+import random
+from typing import Any
+
+import numpy as np
+import tensorflow as tf
+
+from ...activations_tf import get_tf_activation
+
+# Public API
+from ...file_utils import (
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ replace_return_docstrings,
+)
+from ...modeling_tf_outputs import TFBaseModelOutputWithPastAndCrossAttentions, TFCausalLMOutputWithCrossAttentions
+from ...modeling_tf_utils import (
+ TFCausalLanguageModelingLoss,
+ TFModelInputType,
+ TFPreTrainedModel,
+ TFSharedEmbeddings,
+ get_initializer,
+ keras,
+ keras_serializable,
+ unpack_inputs,
+)
+from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
+from ...utils import logging
+from .configuration_xglm import XGLMConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "facebook/xglm-564M"
+_CONFIG_FOR_DOC = "XGLMConfig"
+
+
+LARGE_NEGATIVE = -1e8
+
+
+def create_sinusoidal_positions(num_positions: int, embedding_dim: int, padding_idx: int | None) -> tf.Tensor:
+ half_dim = embedding_dim // 2
+ emb = math.log(10000) / (half_dim - 1)
+ emb = tf.exp(tf.range(half_dim, dtype=tf.float32) * -emb)
+ emb = tf.expand_dims(tf.range(num_positions, dtype=tf.float32), axis=1) * tf.expand_dims(emb, axis=0)
+ emb = tf.reshape(tf.concat([tf.sin(emb), tf.cos(emb)], axis=1), (num_positions, -1))
+ if embedding_dim % 2 == 1:
+ # zero pad
+ emb = tf.concat([emb, tf.zeros((num_positions, 1))], axis=1)
+ if padding_idx is not None:
+ _padding_mask = tf.concat(
+ [
+ tf.ones((padding_idx, shape_list(emb)[1])),
+ tf.zeros((1, shape_list(emb)[1])),
+ tf.ones((shape_list(emb)[0] - padding_idx - 1, shape_list(emb)[1])),
+ ],
+ axis=0,
+ )
+ emb *= _padding_mask
+
+ return tf.constant(emb, name="embed_positions")
+
+
+def _create_position_ids_from_input_ids(
+ input_ids: tf.Tensor, past_key_values_length: int, padding_idx: int | None
+) -> tf.Tensor:
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = tf.where(input_ids != padding_idx, 1, 0)
+ incremental_indices = (tf.cast(tf.cumsum(mask, axis=1), dtype=mask.dtype) + past_key_values_length) * mask
+ return tf.cast(incremental_indices, dtype=tf.int64) + padding_idx
+
+
+def _create_position_ids_from_inputs_embeds(
+ inputs_embeds: tf.Tensor, past_key_values_length: int, padding_idx: int | None
+) -> tf.Tensor:
+ """
+ Args:
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+ inputs_embeds: tf.Tensor
+ Returns: tf.Tensor
+ """
+ input_shape = shape_list(inputs_embeds)[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = tf.range(padding_idx + 1, sequence_length + padding_idx + 1, dtype=tf.int64)
+
+ return tf.broadcast_to(tf.expand_dims(position_ids, axis=0), input_shape) + past_key_values_length
+
+
+# Copied from transformers.models.bart.modeling_tf_bart._make_causal_mask
+def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
+ """
+ Make causal mask used for bi-directional self-attention.
+ """
+ bsz = input_ids_shape[0]
+ tgt_len = input_ids_shape[1]
+ mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
+ mask_cond = tf.range(shape_list(mask)[-1])
+
+ mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
+
+ if past_key_values_length > 0:
+ mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
+
+ return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1))
+
+
+# Copied from transformers.models.bart.modeling_tf_bart._expand_mask
+def _expand_mask(mask: tf.Tensor, tgt_len: int | None = None):
+ """
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
+ """
+ src_len = shape_list(mask)[1]
+ tgt_len = tgt_len if tgt_len is not None else src_len
+ one_cst = tf.constant(1.0)
+ mask = tf.cast(mask, dtype=one_cst.dtype)
+ expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
+
+ return (one_cst - expanded_mask) * LARGE_NEGATIVE
+
+
+# Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->XGLM
+class TFXGLMAttention(keras.layers.Layer):
+ """Multi-headed attention from "Attention Is All You Need"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: float = 0.0,
+ is_decoder: bool = False,
+ bias: bool = True,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.embed_dim = embed_dim
+
+ self.num_heads = num_heads
+ self.dropout = keras.layers.Dropout(dropout)
+ self.head_dim = embed_dim // num_heads
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+
+ self.k_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
+ self.q_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
+ self.v_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
+ self.out_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
+
+ def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
+ return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
+
+ def call(
+ self,
+ hidden_states: tf.Tensor,
+ key_value_states: tf.Tensor | None = None,
+ past_key_value: tuple[tuple[tf.Tensor]] | None = None,
+ attention_mask: tf.Tensor | None = None,
+ layer_head_mask: tf.Tensor | None = None,
+ training: bool | None = False,
+ ) -> tuple[tf.Tensor, tf.Tensor | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+ bsz, tgt_len, embed_dim = shape_list(hidden_states)
+
+ # get query proj
+ query_states = self.q_proj(hidden_states) * self.scaling
+ # get key, value proj
+ if is_cross_attention and past_key_value is not None:
+ # reuse k,v, cross_attentions
+ key_states = past_key_value[0]
+ value_states = past_key_value[1]
+ elif is_cross_attention:
+ # cross_attentions
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
+ elif past_key_value is not None:
+ # reuse k, v, self_attention
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
+ key_states = tf.concat([past_key_value[0], key_states], axis=2)
+ value_states = tf.concat([past_key_value[1], value_states], axis=2)
+ else:
+ # self_attention
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
+
+ if self.is_decoder:
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
+ # Further calls to cross_attention layer can then reuse all cross-attention
+ # key/value_states (first "if" case)
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
+ past_key_value = (key_states, value_states)
+
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
+ query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
+ key_states = tf.reshape(key_states, proj_shape)
+ value_states = tf.reshape(value_states, proj_shape)
+
+ src_len = shape_list(key_states)[1]
+ attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
+
+ tf.debugging.assert_equal(
+ shape_list(attn_weights),
+ [bsz * self.num_heads, tgt_len, src_len],
+ message=(
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
+ f" {shape_list(attn_weights)}"
+ ),
+ )
+
+ if attention_mask is not None:
+ tf.debugging.assert_equal(
+ shape_list(attention_mask),
+ [bsz, 1, tgt_len, src_len],
+ message=(
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
+ f" {shape_list(attention_mask)}"
+ ),
+ )
+
+ attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)
+ attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
+
+ attn_weights = stable_softmax(attn_weights, axis=-1)
+
+ if layer_head_mask is not None:
+ tf.debugging.assert_equal(
+ shape_list(layer_head_mask),
+ [self.num_heads],
+ message=(
+ f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
+ f" {shape_list(layer_head_mask)}"
+ ),
+ )
+
+ attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
+ attn_weights, (bsz, self.num_heads, tgt_len, src_len)
+ )
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
+
+ attn_probs = self.dropout(attn_weights, training=training)
+ attn_output = tf.matmul(attn_probs, value_states)
+
+ tf.debugging.assert_equal(
+ shape_list(attn_output),
+ [bsz * self.num_heads, tgt_len, self.head_dim],
+ message=(
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
+ f" {shape_list(attn_output)}"
+ ),
+ )
+
+ attn_output = tf.transpose(
+ tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
+ )
+ attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
+
+ attn_output = self.out_proj(attn_output)
+ attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
+
+ return attn_output, attn_weights, past_key_value
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "k_proj", None) is not None:
+ with tf.name_scope(self.k_proj.name):
+ self.k_proj.build([None, None, self.embed_dim])
+ if getattr(self, "q_proj", None) is not None:
+ with tf.name_scope(self.q_proj.name):
+ self.q_proj.build([None, None, self.embed_dim])
+ if getattr(self, "v_proj", None) is not None:
+ with tf.name_scope(self.v_proj.name):
+ self.v_proj.build([None, None, self.embed_dim])
+ if getattr(self, "out_proj", None) is not None:
+ with tf.name_scope(self.out_proj.name):
+ self.out_proj.build([None, None, self.embed_dim])
+
+
+class TFXGLMDecoderLayer(keras.layers.Layer):
+ def __init__(self, config: XGLMConfig, **kwargs: Any) -> None:
+ super().__init__(**kwargs)
+ self.embed_dim = config.d_model
+ self.self_attn = TFXGLMAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ name="self_attn",
+ )
+ self.dropout = keras.layers.Dropout(config.dropout)
+ self.activation_fn = get_tf_activation(config.activation_function)
+ self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
+
+ if config.add_cross_attention:
+ self.encoder_attn = TFXGLMAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ name="encoder_attn",
+ )
+ self.encoder_attn_layer_norm = keras.layers.LayerNormalization(
+ epsilon=1e-5, name="encoder_attn_layer_norm"
+ )
+
+ self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
+ self.fc1 = keras.layers.Dense(config.ffn_dim, name="fc1")
+ self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
+ self.config = config
+
+ # Copied from transformers.models.mbart.modeling_tf_mbart.TFMBartDecoderLayer.call
+ def call(
+ self,
+ hidden_states: tf.Tensor,
+ attention_mask: tf.Tensor | None = None,
+ encoder_hidden_states: tf.Tensor | None = None,
+ encoder_attention_mask: tf.Tensor | None = None,
+ layer_head_mask: tf.Tensor | None = None,
+ cross_attn_layer_head_mask: tf.Tensor | None = None,
+ past_key_value: tuple[tf.Tensor] | None = None,
+ training: bool | None = False,
+ ) -> tuple[tf.Tensor, tf.Tensor, tuple[tuple[tf.Tensor]]]:
+ """
+ Args:
+ hidden_states (`tf.Tensor`): input to the layer of shape *(batch, seq_len, embed_dim)*
+ attention_mask (`tf.Tensor`): attention mask of size
+ *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
+ encoder_hidden_states (`tf.Tensor`):
+ cross attention input to the layer of shape *(batch, seq_len, embed_dim)*
+ encoder_attention_mask (`tf.Tensor`): encoder attention mask of size
+ *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
+ *(decoder_attention_heads,)*
+ cross_attn_layer_head_mask (`tf.Tensor`): mask for heads of the cross-attention module.
+ *(decoder_attention_heads,)*
+ past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states
+ """
+ residual = hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ # Self Attention
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
+ hidden_states=hidden_states,
+ past_key_value=self_attn_past_key_value,
+ attention_mask=attention_mask,
+ layer_head_mask=layer_head_mask,
+ )
+ hidden_states = self.dropout(hidden_states, training=training)
+ hidden_states = residual + hidden_states
+
+ # Cross-Attention Block
+ cross_attn_present_key_value = None
+ cross_attn_weights = None
+ if encoder_hidden_states is not None:
+ residual = hidden_states
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
+ hidden_states=hidden_states,
+ key_value_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ layer_head_mask=cross_attn_layer_head_mask,
+ past_key_value=cross_attn_past_key_value,
+ )
+ hidden_states = self.dropout(hidden_states, training=training)
+ hidden_states = residual + hidden_states
+
+ # add cross-attn to positions 3,4 of present_key_value tuple
+ present_key_value = present_key_value + cross_attn_present_key_value
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = self.activation_dropout(hidden_states, training=training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = self.dropout(hidden_states, training=training)
+ hidden_states = residual + hidden_states
+
+ return (
+ hidden_states,
+ self_attn_weights,
+ cross_attn_weights,
+ present_key_value,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "self_attn", None) is not None:
+ with tf.name_scope(self.self_attn.name):
+ self.self_attn.build(None)
+ if getattr(self, "self_attn_layer_norm", None) is not None:
+ with tf.name_scope(self.self_attn_layer_norm.name):
+ self.self_attn_layer_norm.build([None, None, self.embed_dim])
+ if getattr(self, "fc1", None) is not None:
+ with tf.name_scope(self.fc1.name):
+ self.fc1.build([None, None, self.embed_dim])
+ if getattr(self, "fc2", None) is not None:
+ with tf.name_scope(self.fc2.name):
+ self.fc2.build([None, None, self.config.ffn_dim])
+ if getattr(self, "final_layer_norm", None) is not None:
+ with tf.name_scope(self.final_layer_norm.name):
+ self.final_layer_norm.build([None, None, self.embed_dim])
+ if getattr(self, "encoder_attn", None) is not None:
+ with tf.name_scope(self.encoder_attn.name):
+ self.encoder_attn.build(None)
+ if getattr(self, "encoder_attn_layer_norm", None) is not None:
+ with tf.name_scope(self.encoder_attn_layer_norm.name):
+ self.encoder_attn_layer_norm.build([None, None, self.embed_dim])
+
+
+@keras_serializable
+class TFXGLMMainLayer(keras.layers.Layer):
+ config_class = XGLMConfig
+
+ def __init__(
+ self, config: XGLMConfig, embed_tokens: TFSharedEmbeddings | None = None, *inputs, **kwargs: Any
+ ) -> None:
+ super().__init__(*inputs, **kwargs)
+
+ self.config = config
+ self.padding_idx = config.pad_token_id
+ self.max_target_positions = config.max_position_embeddings
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
+
+ if embed_tokens is not None:
+ self.embed_tokens = embed_tokens
+ else:
+ self.embed_tokens = TFSharedEmbeddings(
+ config.vocab_size, config.d_model, self.padding_idx, name="embed_tokens"
+ )
+
+ self.offset = 2
+ self._embed_positions_weights = create_sinusoidal_positions(
+ num_positions=config.max_position_embeddings + self.offset,
+ embedding_dim=config.d_model,
+ padding_idx=config.pad_token_id,
+ )
+
+ self.dropout = keras.layers.Dropout(config.dropout)
+ self.layers = [TFXGLMDecoderLayer(config, name=f"layers.{i}") for i in range(config.num_layers)]
+ self.layerdrop = config.layerdrop
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="layer_norm")
+
+ def get_input_embeddings(self) -> TFSharedEmbeddings:
+ return self.embed_tokens
+
+ def set_input_embeddings(self, value: TFSharedEmbeddings) -> None:
+ self.embed_tokens = value
+
+ def _prepare_decoder_attention_mask(
+ self,
+ attention_mask: tf.Tensor | None,
+ input_shape: tf.TensorShape,
+ past_key_values_length: int,
+ ) -> tf.Tensor:
+ # create causal mask
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
+ combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length)
+ combined_attention_mask = tf.cond(
+ input_shape[-1] > 1, lambda: combined_attention_mask, lambda: tf.ones_like(combined_attention_mask)
+ )
+ if attention_mask is None:
+ return combined_attention_mask
+ expand_attention_mask = _expand_mask(attention_mask, tgt_len=input_shape[-1])
+ return expand_attention_mask + combined_attention_mask
+
+ def embed_positions(self, position_ids: np.ndarray | tf.Tensor | None = None) -> tf.Tensor:
+ position_ids += self.offset
+ positions = tf.gather(self._embed_positions_weights, position_ids, axis=0)
+ return positions
+
+ @unpack_inputs
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,
+ past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ training: bool | None = False,
+ **kwargs: Any,
+ ) -> TFBaseModelOutputWithPastAndCrossAttentions | tuple[tf.Tensor]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # retrieve input_ids and inputs_embeds
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_shape = tf.shape(input_ids)
+ input_ids = tf.reshape(input_ids, (-1, input_shape[-1]))
+ elif inputs_embeds is not None:
+ input_shape = tf.shape(inputs_embeds)[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
+
+ if position_ids is None:
+ position_ids = tf.expand_dims(
+ tf.range(past_key_values_length, input_shape[-1] + past_key_values_length), axis=0
+ )
+ position_ids = tf.reshape(position_ids, [-1, shape_list(position_ids)[-1]])
+
+ if inputs_embeds is None:
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.vocab_size)
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
+
+ attention_mask = self._prepare_decoder_attention_mask(attention_mask, input_shape, past_key_values_length)
+
+ # expand encoder attention mask
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])
+
+ # embed positions
+ positions = self.embed_positions(position_ids)
+
+ hidden_states = tf.cast(inputs_embeds, dtype=tf.float32) + positions
+
+ hidden_states = self.dropout(hidden_states, training=training)
+
+ # decoder layers
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
+ next_decoder_cache = () if use_cache else None
+
+ # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired
+ for attn_mask_name, attn_mask in [("head_mask", head_mask), ("cross_attn_head_mask", cross_attn_head_mask)]:
+ if attn_mask is not None:
+ tf.debugging.assert_equal(
+ shape_list(attn_mask)[0],
+ len(self.layers),
+ message=(
+ f"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for"
+ f" {shape_list(attn_mask)[0]}."
+ ),
+ )
+
+ for idx, decoder_layer in enumerate(self.layers):
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ dropout_probability = random.uniform(0, 1)
+ if training and (dropout_probability < self.layerdrop):
+ continue
+
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
+
+ hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(
+ hidden_states,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
+ cross_attn_layer_head_mask=(cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None),
+ past_key_value=past_key_value,
+ )
+
+ if use_cache:
+ next_decoder_cache += (present_key_value,)
+
+ if output_attentions:
+ all_self_attns += (layer_self_attn,)
+
+ if encoder_hidden_states is not None:
+ all_cross_attentions += (layer_cross_attn,)
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ next_cache = next_decoder_cache if use_cache else None
+ if not return_dict:
+ return tuple(
+ v
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
+ if v is not None
+ )
+ return TFBaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=next_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ cross_attentions=all_cross_attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "layer_norm", None) is not None:
+ with tf.name_scope(self.layer_norm.name):
+ self.layer_norm.build([None, None, self.config.d_model])
+ if getattr(self, "embed_tokens", None) is not None:
+ with tf.name_scope(self.embed_tokens.name):
+ self.embed_tokens.build(None)
+ if getattr(self, "layers", None) is not None:
+ for layer in self.layers:
+ with tf.name_scope(layer.name):
+ layer.build(None)
+
+
+class TFXGLMPreTrainedModel(TFPreTrainedModel):
+ config_class = XGLMConfig
+ base_model_prefix = "model"
+
+
+XGLM_START_DOCSTRING = r"""
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
+ behavior.
+
+
+
+ TensorFlow models and layers in `transformers` accept two formats as input:
+
+ - having all inputs as keyword arguments (like PyTorch models), or
+ - having all inputs as a list, tuple or dict in the first positional argument.
+
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
+ positional argument:
+
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
+
+ Note that when creating models and layers with
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
+ about any of this, as you can just pass inputs like you would to any other Python function!
+
+
+
+ Args:
+ config ([`XGLMConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+XGLM_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`tf.Tensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`tf.Tensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ position_ids (`tf.Tensor` or `Numpy array` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of
+ the decoder.
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
+ selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ head_mask (`tf.Tensor` of shape `(num_layers, attention_heads)`, *optional*):
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ cross_attn_head_mask (`tf.Tensor` of shape `(num_layers, attention_heads)`, *optional*):
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ past_key_values (`tuple[tuple[tf.Tensor]]` of length `config.num_layers`)
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`). Set to `False` during training, `True` during generation
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
+ config will be used instead.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
+ used instead.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
+ eager mode, in graph mode the value will always be set to True.
+ training (`bool`, *optional*, defaults to `False`):
+ Whether or not to use the model in training mode (some modules like dropout modules have different
+ behaviors between training and evaluation).
+"""
+
+
+@add_start_docstrings(
+ "The bare XGLM Model transformer outputting raw hidden-states without any specific head on top.",
+ XGLM_START_DOCSTRING,
+)
+class TFXGLMModel(TFXGLMPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.num_layers* layers. Each layer is a [`TFXGLMDecoderLayer`]
+
+ Args:
+ config: XGLMConfig
+ embed_tokens: [TFSharedEmbeddings]: output embedding
+ """
+
+ def __init__(
+ self, config: XGLMConfig, embed_tokens: TFSharedEmbeddings | None = None, *inputs: Any, **kwargs: Any
+ ) -> None:
+ super().__init__(config, *inputs, **kwargs)
+
+ self.model = TFXGLMMainLayer(config, embed_tokens=embed_tokens, name="model")
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XGLM_INPUTS_DOCSTRING)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFBaseModelOutputWithPastAndCrossAttentions,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,
+ past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ training: bool | None = False,
+ **kwargs: Any,
+ ) -> TFBaseModelOutputWithPastAndCrossAttentions | tuple[tf.Tensor]:
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ head_mask=head_mask,
+ cross_attn_head_mask=cross_attn_head_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ return outputs
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "model", None) is not None:
+ with tf.name_scope(self.model.name):
+ self.model.build(None)
+
+
+@add_start_docstrings(
+ """
+ The XGLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
+ embeddings).
+ """,
+ XGLM_START_DOCSTRING,
+)
+class TFXGLMForCausalLM(TFXGLMPreTrainedModel, TFCausalLanguageModelingLoss):
+ base_model_prefix = "model"
+ _keys_to_ignore_on_load_missing = [
+ r"model.embed_positions.weights",
+ r"lm_head.weight",
+ ]
+ _keys_to_ignore_on_save = [
+ r"model.embed_positions.weights",
+ ]
+
+ def __init__(
+ self, config: XGLMConfig, embed_tokens: TFSharedEmbeddings | None = None, *inputs: Any, **kwargs: Any
+ ) -> None:
+ super().__init__(config, *inputs, **kwargs)
+
+ self.model = TFXGLMMainLayer(config, embed_tokens=embed_tokens, name="model")
+ self.lm_head = keras.layers.Dense(
+ config.vocab_size,
+ use_bias=False,
+ kernel_initializer=get_initializer(config.init_std),
+ name="lm_head",
+ )
+ self.config = config
+
+ def prepare_inputs_for_generation(self, inputs, past_key_values=None, use_cache=None, **kwargs):
+ # only last token for inputs_ids if past is defined in kwargs
+ if past_key_values:
+ inputs = tf.expand_dims(inputs[:, -1], -1)
+
+ position_ids = kwargs.get("position_ids")
+ attention_mask = kwargs.get("attention_mask")
+
+ if attention_mask is not None and position_ids is None:
+ position_ids = tf.math.cumsum(attention_mask, axis=-1, exclusive=True)
+ if past_key_values:
+ position_ids = tf.expand_dims(position_ids[:, -1], -1)
+
+ return {
+ "input_ids": inputs,
+ "attention_mask": attention_mask,
+ "position_ids": position_ids,
+ "past_key_values": past_key_values,
+ "use_cache": use_cache,
+ }
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XGLM_INPUTS_DOCSTRING)
+ @replace_return_docstrings(output_type=TFCausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFCausalLMOutputWithCrossAttentions,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ cross_attn_head_mask: np.ndarray | tf.Tensor | None = None,
+ past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ training: bool | None = False,
+ **kwargs: Any,
+ ) -> TFCausalLMOutputWithCrossAttentions | tuple[tf.Tensor]:
+ r"""
+ labels (`np.ndarray` or `tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
+ """
+
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ head_mask=head_mask,
+ cross_attn_head_mask=cross_attn_head_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ hidden_states = outputs[0]
+ lm_logits = self.lm_head(hidden_states)
+
+ loss = None
+ if labels is not None:
+ # shift labels to the left and cut last logit token
+ labels = tf.concat(
+ [labels[:, 1:], tf.fill((labels.shape[0], 1), tf.cast(-100, labels.dtype))],
+ axis=-1,
+ )
+ loss = self.hf_compute_loss(labels, lm_logits)
+
+ if not return_dict:
+ output = (lm_logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFCausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=lm_logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "model", None) is not None:
+ with tf.name_scope(self.model.name):
+ self.model.build(None)
+ if getattr(self, "lm_head", None) is not None:
+ with tf.name_scope(self.lm_head.name):
+ self.lm_head.build([None, None, self.config.hidden_size])
+
+ def tf_to_pt_weight_rename(self, tf_weight):
+ if tf_weight == "lm_head.weight":
+ return tf_weight, "model.embed_tokens.weight"
+ else:
+ return (tf_weight,)
+
+
+__all__ = ["TFXGLMForCausalLM", "TFXGLMModel", "TFXGLMPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/modeling_xglm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/modeling_xglm.py
new file mode 100644
index 0000000000000000000000000000000000000000..244135b7d2e50565b4ab84b05a30bcd0fbc8da66
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/modeling_xglm.py
@@ -0,0 +1,711 @@
+# coding=utf-8
+# Copyright 2021 The Fairseq Authors The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch XGLM model."""
+
+import math
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions
+from ...modeling_utils import PreTrainedModel
+from ...utils import auto_docstring, logging
+from ...utils.deprecation import deprecate_kwarg
+from .configuration_xglm import XGLMConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.bart.modeling_bart.BartScaledWordEmbedding with Bart->XGLM
+class XGLMScaledWordEmbedding(nn.Embedding):
+ """
+ This module overrides nn.Embeddings' forward by multiplying with embeddings scale.
+ """
+
+ def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx: int, embed_scale: Optional[float] = 1.0):
+ super().__init__(num_embeddings, embedding_dim, padding_idx)
+ self.embed_scale = embed_scale
+
+ def forward(self, input_ids: torch.Tensor):
+ return super().forward(input_ids) * self.embed_scale
+
+
+class XGLMSinusoidalPositionalEmbedding(nn.Module):
+ """This module produces sinusoidal positional embeddings of any length."""
+
+ def __init__(self, num_positions: int, embedding_dim: int, padding_idx: Optional[int] = None):
+ super().__init__()
+ self.offset = 2
+ self.embedding_dim = embedding_dim
+ self.padding_idx = padding_idx
+ self.make_weights(num_positions + self.offset, embedding_dim, padding_idx)
+
+ def make_weights(self, num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
+ emb_weights = self.get_embedding(num_embeddings, embedding_dim, padding_idx)
+ if hasattr(self, "weights"):
+ # in forward put the weights on the correct dtype and device of the param
+ emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device)
+
+ self.register_buffer("weights", emb_weights, persistent=False)
+
+ @staticmethod
+ def get_embedding(num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None):
+ """
+ Build sinusoidal embeddings.
+
+ This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of
+ "Attention Is All You Need".
+ """
+ half_dim = embedding_dim // 2
+ emb = math.log(10000) / (half_dim - 1)
+ emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb)
+ emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0)
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1).view(num_embeddings, -1)
+ if embedding_dim % 2 == 1:
+ # zero pad
+ emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
+ if padding_idx is not None:
+ emb[padding_idx, :] = 0
+
+ return emb.to(torch.get_default_dtype())
+
+ @torch.no_grad()
+ def forward(self, position_ids: Optional[torch.Tensor] = None, past_key_values_length: int = 0):
+ bsz, seq_len = position_ids.size()
+ position_ids += self.offset
+
+ # Expand embeddings if needed. `position_ids.max()` is NOT used to keep torch.fx compatibility.
+ max_pos = 2 + seq_len + past_key_values_length
+ if max_pos > self.weights.size(0):
+ self.make_weights(max_pos, self.embedding_dim, self.padding_idx)
+
+ return self.weights.index_select(0, position_ids.view(-1)).view(bsz, seq_len, self.weights.shape[-1]).detach()
+
+
+class XGLMAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ dropout: Optional[float] = 0.0,
+ is_decoder: Optional[bool] = False,
+ bias: Optional[bool] = True,
+ layer_idx: Optional[bool] = None,
+ ):
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+
+ if (self.head_dim * num_heads) != self.embed_dim:
+ raise ValueError(
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
+ f" and `num_heads`: {num_heads})."
+ )
+ self.scaling = self.head_dim**-0.5
+ self.is_decoder = is_decoder
+ self.layer_idx = layer_idx
+
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ key_value_states: Optional[torch.Tensor] = None,
+ past_key_values: Optional[Cache] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ layer_head_mask: Optional[torch.Tensor] = None,
+ output_attentions: bool = False,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
+ """Input shape: Batch x Time x Channel"""
+
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+
+ bsz, tgt_len, _ = hidden_states.size()
+ src_len = key_value_states.shape[1] if is_cross_attention else tgt_len
+
+ # get query proj
+ query_states = self.q_proj(hidden_states) * self.scaling
+
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_value = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_value = past_key_values.self_attention_cache
+ else:
+ curr_past_key_value = past_key_values
+
+ current_states = key_value_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_states = curr_past_key_value.layers[self.layer_idx].keys
+ value_states = curr_past_key_value.layers[self.layer_idx].values
+ else:
+ key_states = self.k_proj(current_states)
+ value_states = self.v_proj(current_states)
+ key_states = key_states.view(bsz, src_len, -1, self.head_dim).transpose(1, 2)
+ value_states = value_states.view(bsz, src_len, -1, self.head_dim).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
+ cache_position = cache_position if not is_cross_attention else None
+ key_states, value_states = curr_past_key_value.update(
+ key_states, value_states, self.layer_idx, {"cache_position": cache_position}
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention:
+ past_key_values.is_updated[self.layer_idx] = True
+
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
+ query_states = query_states.view(bsz, tgt_len, self.num_heads, self.head_dim).transpose(1, 2)
+ query_states = query_states.reshape(*proj_shape)
+ key_states = key_states.reshape(*proj_shape)
+ value_states = value_states.reshape(*proj_shape)
+
+ src_len = key_states.size(1)
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
+
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
+ raise ValueError(
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
+ f" {attn_weights.size()}"
+ )
+
+ if attention_mask is not None:
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
+ raise ValueError(
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
+ )
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
+ attn_weights = torch.max(
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min, device=attn_weights.device)
+ )
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437
+ if attn_weights.dtype == torch.float16:
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16)
+ else:
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
+
+ if layer_head_mask is not None:
+ if layer_head_mask.size() != (self.num_heads,):
+ raise ValueError(
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
+ f" {layer_head_mask.size()}"
+ )
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
+
+ if output_attentions:
+ # this operation is a bit awkward, but it's required to
+ # make sure that attn_weights keeps its gradient.
+ # In order to do so, attn_weights have to be reshaped
+ # twice and have to be reused in the following
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
+ else:
+ attn_weights_reshaped = None
+
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
+
+ attn_output = torch.bmm(attn_probs, value_states)
+
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
+ f" {attn_output.size()}"
+ )
+
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
+ attn_output = attn_output.transpose(1, 2)
+
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
+ # partitioned aross GPUs when using tensor-parallelism.
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
+
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights_reshaped
+
+
+class XGLMDecoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: XGLMConfig, layer_idx=None):
+ super().__init__()
+ self.embed_dim = config.d_model
+
+ self.self_attn = XGLMAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ layer_idx=layer_idx,
+ )
+ self.dropout = config.dropout
+ self.activation_fn = ACT2FN[config.activation_function]
+ self.activation_dropout = config.activation_dropout
+
+ if config.add_cross_attention:
+ self.encoder_attn = XGLMAttention(
+ embed_dim=self.embed_dim,
+ num_heads=config.attention_heads,
+ dropout=config.attention_dropout,
+ is_decoder=True,
+ layer_idx=layer_idx,
+ )
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
+ self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim)
+ self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim)
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ # Copied from transformers.models.musicgen.modeling_musicgen.MusicgenDecoderLayer.forward
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ layer_head_mask: Optional[torch.Tensor] = None,
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = True,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`): attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ encoder_hidden_states (`torch.FloatTensor`):
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
+ `(encoder_attention_heads,)`.
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
+ size `(decoder_attention_heads,)`.
+ past_key_values (`Tuple(torch.FloatTensor)`): cached past key and value projection states
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ """
+ residual = hidden_states
+ hidden_states = self.self_attn_layer_norm(hidden_states)
+
+ # Self Attention
+ hidden_states, self_attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ past_key_values=past_key_values,
+ attention_mask=attention_mask,
+ layer_head_mask=layer_head_mask,
+ output_attentions=output_attentions,
+ cache_position=cache_position,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Cross-Attention Block
+ cross_attn_weights = None
+ if encoder_hidden_states is not None:
+ residual = hidden_states
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
+
+ hidden_states, cross_attn_weights = self.encoder_attn(
+ hidden_states=hidden_states,
+ key_value_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ layer_head_mask=cross_attn_layer_head_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ cache_position=cache_position,
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ # Fully Connected
+ residual = hidden_states
+ hidden_states = self.final_layer_norm(hidden_states)
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
+ hidden_states = self.fc2(hidden_states)
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
+ hidden_states = residual + hidden_states
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights, cross_attn_weights)
+
+ return outputs
+
+
+@auto_docstring
+class XGLMPreTrainedModel(PreTrainedModel):
+ config: XGLMConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["XGLMDecoderLayer"]
+
+ def _init_weights(self, module):
+ std = self.config.init_std
+ if isinstance(module, nn.Linear):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+
+
+@auto_docstring
+class XGLMModel(XGLMPreTrainedModel):
+ def __init__(self, config: XGLMConfig, embed_tokens: Optional[nn.Embedding] = None):
+ r"""
+ embed_tokens (`nn.Embedding`, *optional*):
+ output embeddings
+ """
+ super().__init__(config)
+ self.dropout = config.dropout
+ self.layerdrop = config.layerdrop
+ self.padding_idx = config.pad_token_id
+ self.max_target_positions = config.max_position_embeddings
+ embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
+
+ if embed_tokens is not None:
+ self.embed_tokens = embed_tokens
+ else:
+ self.embed_tokens = XGLMScaledWordEmbedding(
+ config.vocab_size, config.d_model, self.padding_idx, embed_scale=embed_scale
+ )
+
+ self.embed_positions = XGLMSinusoidalPositionalEmbedding(
+ config.max_position_embeddings,
+ config.d_model,
+ config.pad_token_id,
+ )
+ self.layers = nn.ModuleList([XGLMDecoderLayer(config, layer_idx=i) for i in range(config.num_layers)])
+ self.layer_norm = nn.LayerNorm(config.d_model)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of
+ the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
+ selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ cross_attn_head_mask (`torch.Tensor` of shape `(num_layers, attention_heads)`, *optional*):
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # retrieve input_ids and inputs_embeds
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ input_ids = input_ids.view(-1, input_shape[-1])
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache = True` is incompatible with gradient checkpointing`. Setting `use_cache = False`..."
+ )
+ use_cache = False
+
+ # initialize `past_key_values`
+ if use_cache and past_key_values is None:
+ past_key_values = (
+ EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if encoder_hidden_states is not None
+ else DynamicCache(config=self.config)
+ )
+ if use_cache and isinstance(past_key_values, tuple):
+ logger.warning_once(
+ "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
+ "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
+ "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
+ )
+ past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
+
+ past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
+ attention_mask = _prepare_4d_causal_attention_mask(
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
+ )
+
+ if position_ids is None:
+ position_ids = torch.arange(
+ past_key_values_length,
+ input_shape[-1] + past_key_values_length,
+ dtype=torch.long,
+ device=input_ids.device if input_ids is not None else inputs_embeds.device,
+ )
+ position_ids = position_ids.unsqueeze(0)
+
+ # expand encoder attention mask
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
+ encoder_attention_mask = _prepare_4d_attention_mask(
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
+ )
+
+ hidden_states = inputs_embeds + self.embed_positions(position_ids, past_key_values_length).to(
+ inputs_embeds.device
+ )
+ hidden_states = nn.functional.dropout(hidden_states, p=float(self.dropout), training=self.training)
+
+ # decoder layers
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
+
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
+ if attn_mask is not None:
+ if attn_mask.size()[0] != len(self.layers):
+ raise ValueError(
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
+ f" {head_mask.size()[0]}."
+ )
+ for idx, decoder_layer in enumerate(self.layers):
+ # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+ if self.training:
+ dropout_probability = torch.rand([])
+ if dropout_probability < self.layerdrop:
+ continue
+
+ layer_outputs = decoder_layer(
+ hidden_states,
+ attention_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
+ cross_attn_layer_head_mask=(cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None),
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ cache_position=cache_position,
+ )
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_self_attns += (layer_outputs[1],)
+
+ if encoder_hidden_states is not None:
+ all_cross_attentions += (layer_outputs[2],)
+
+ hidden_states = self.layer_norm(hidden_states)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns, all_cross_attentions]
+ if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The XGLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
+ embeddings).
+ """
+)
+class XGLMForCausalLM(XGLMPreTrainedModel, GenerationMixin):
+ base_model_prefix = "model"
+ _tied_weights_keys = ["lm_head.weight"]
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.model = XGLMModel(config)
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
+ r"""
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of
+ the decoder.
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
+ selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ cross_attn_head_mask (`torch.Tensor` of shape `(num_layers, attention_heads)`, *optional*):
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ """
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ head_mask=head_mask,
+ cross_attn_head_mask=cross_attn_head_mask,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+
+ logits = self.lm_head(outputs[0])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(
+ logits,
+ labels,
+ vocab_size=self.config.vocab_size,
+ pad_token_id=self.config.pad_token_id,
+ **kwargs,
+ )
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return (loss,) + output if loss is not None else output
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+__all__ = ["XGLMForCausalLM", "XGLMModel", "XGLMPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/tokenization_xglm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/tokenization_xglm.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e0a8706683f9695001a71bcbe87e697666333e1
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/tokenization_xglm.py
@@ -0,0 +1,302 @@
+# coding=utf-8
+# Copyright The HuggingFace Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for ."""
+
+import os
+from shutil import copyfile
+from typing import Any, Optional
+
+import sentencepiece as spm
+
+from ...tokenization_utils import PreTrainedTokenizer
+from ...utils import logging
+from ...utils.import_utils import requires
+
+
+logger = logging.get_logger(__name__)
+
+SPIECE_UNDERLINE = "▁"
+
+VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"}
+
+
+@requires(backends=("sentencepiece",))
+class XGLMTokenizer(PreTrainedTokenizer):
+ """
+ Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
+ [SentencePiece](https://github.com/google/sentencepiece).
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Path to the vocabulary file.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ sp_model_kwargs (`dict`, *optional*):
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
+ to set:
+
+ - `enable_sampling`: Enable subword regularization.
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
+
+ - `nbest_size = {0,1}`: No sampling is performed.
+ - `nbest_size > 1`: samples from the nbest_size results.
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
+ using forward-filtering-and-backward-sampling algorithm.
+
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
+ BPE-dropout.
+
+ Attributes:
+ sp_model (`SentencePieceProcessor`):
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ vocab_file,
+ bos_token="",
+ eos_token="",
+ sep_token="",
+ cls_token="",
+ unk_token="",
+ pad_token="",
+ sp_model_kwargs: Optional[dict[str, Any]] = None,
+ **kwargs,
+ ) -> None:
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
+
+ # Compatibility with the original tokenizer
+ self.num_madeup_words = 7
+ madeup_words = [f"" for i in range(self.num_madeup_words)]
+
+ kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", []) or []
+ kwargs["additional_special_tokens"] += [
+ word for word in madeup_words if word not in kwargs["additional_special_tokens"]
+ ]
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.Load(str(vocab_file))
+ self.vocab_file = vocab_file
+
+ # Original fairseq vocab and spm vocab must be "aligned":
+ # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
+ # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
+ # fairseq | '' | '' | '' | '' | ',' | '.' | '▁' | 's' | '▁de' | '-'
+ # spm | '' | '' | '' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
+
+ # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
+ self.fairseq_offset = 1
+
+ # Mimic fairseq token-to-id alignment for the first 4 token
+ self.fairseq_tokens_to_ids = {"": 0, "": 1, "": 2, "": 3}
+
+ sp_size = len(self.sp_model)
+ madeup_words = {f"": sp_size + i + self.fairseq_offset for i in range(self.num_madeup_words)}
+ self.fairseq_tokens_to_ids.update(madeup_words)
+
+ self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
+
+ super().__init__(
+ bos_token=bos_token,
+ eos_token=eos_token,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ pad_token=pad_token,
+ sp_model_kwargs=self.sp_model_kwargs,
+ **kwargs,
+ )
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state["sp_model"] = None
+ state["sp_model_proto"] = self.sp_model.serialized_model_proto()
+ return state
+
+ def __setstate__(self, d):
+ self.__dict__ = d
+
+ # for backward compatibility
+ if not hasattr(self, "sp_model_kwargs"):
+ self.sp_model_kwargs = {}
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An XLM-RoBERTa sequence has the following format:
+
+ - single sequence: ` X `
+ - pair of sequences: ` A B `
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+
+ if token_ids_1 is None:
+ return [self.sep_token_id] + token_ids_0
+ sep = [self.sep_token_id]
+ return sep + token_ids_0 + sep + sep + token_ids_1
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is None:
+ return [1] + ([0] * len(token_ids_0))
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1))
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does
+ not make use of token type ids, therefore a list of zeros is returned.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of zeros.
+
+ """
+
+ sep = [self.sep_token_id]
+
+ if token_ids_1 is None:
+ return len(sep + token_ids_0) * [0]
+ return len(sep + token_ids_0 + sep + sep + token_ids_1) * [0]
+
+ @property
+ def vocab_size(self):
+ return len(self.sp_model) + self.fairseq_offset + self.num_madeup_words
+
+ def get_vocab(self):
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
+ vocab.update(self.added_tokens_encoder)
+ return vocab
+
+ def _tokenize(self, text: str) -> list[str]:
+ return self.sp_model.encode(text, out_type=str)
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ if token in self.fairseq_tokens_to_ids:
+ return self.fairseq_tokens_to_ids[token]
+ spm_id = self.sp_model.PieceToId(token)
+
+ # Need to return unknown token if the SP model returned 0
+ return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ if index in self.fairseq_ids_to_tokens:
+ return self.fairseq_ids_to_tokens[index]
+ return self.sp_model.IdToPiece(index - self.fairseq_offset)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (strings for sub-words) in a single string."""
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
+ return out_string
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ out_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
+ copyfile(self.vocab_file, out_vocab_file)
+ elif not os.path.isfile(self.vocab_file):
+ with open(out_vocab_file, "wb") as fi:
+ content_spiece_model = self.sp_model.serialized_model_proto()
+ fi.write(content_spiece_model)
+
+ return (out_vocab_file,)
+
+
+__all__ = ["XGLMTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/tokenization_xglm_fast.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/tokenization_xglm_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9c8b3aac257abcd2e67bc2302b148bb943cb373
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xglm/tokenization_xglm_fast.py
@@ -0,0 +1,192 @@
+# coding=utf-8
+# Copyright The HuggingFace Team and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for XGLM."""
+
+import os
+from shutil import copyfile
+from typing import Optional
+
+from ...tokenization_utils_fast import PreTrainedTokenizerFast
+from ...utils import is_sentencepiece_available, logging
+
+
+if is_sentencepiece_available():
+ from .tokenization_xglm import XGLMTokenizer
+else:
+ XGLMTokenizer = None
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
+
+
+class XGLMTokenizerFast(PreTrainedTokenizerFast):
+ """
+ Construct a "fast" XGLM tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from [`RobertaTokenizer`]
+ and [`XLNetTokenizer`]. Based on
+ [BPE](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=BPE#models).
+
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Path to the vocabulary file.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["NOTUSED", "NOTUSED"]`):
+ Additional special tokens used by the tokenizer.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ slow_tokenizer_class = XGLMTokenizer
+
+ def __init__(
+ self,
+ vocab_file=None,
+ tokenizer_file=None,
+ bos_token="",
+ eos_token="",
+ sep_token="",
+ cls_token="",
+ unk_token="",
+ pad_token="",
+ **kwargs,
+ ):
+ # Compatibility with the original tokenizer
+ self.num_madeup_words = 7
+ madeup_words = [f"" for i in range(self.num_madeup_words)]
+
+ kwargs["additional_special_tokens"] = kwargs.get("additional_special_tokens", []) or []
+ kwargs["additional_special_tokens"] += [
+ word for word in madeup_words if word not in kwargs["additional_special_tokens"]
+ ]
+
+ super().__init__(
+ vocab_file,
+ tokenizer_file=tokenizer_file,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ **kwargs,
+ )
+
+ self.vocab_file = vocab_file
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An XLM-RoBERTa sequence has the following format:
+
+ - single sequence: ` X `
+ - pair of sequences: ` A B `
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+
+ if token_ids_1 is None:
+ return [self.sep_token_id] + token_ids_0
+ sep = [self.sep_token_id]
+ return sep + token_ids_0 + sep + sep + token_ids_1
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does
+ not make use of token type ids, therefore a list of zeros is returned.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of zeros.
+
+ """
+
+ sep = [self.sep_token_id]
+
+ if token_ids_1 is None:
+ return len(sep + token_ids_0) * [0]
+ return len(sep + token_ids_0 + sep + sep + token_ids_1) * [0]
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if not self.can_save_slow_tokenizer:
+ raise ValueError(
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
+ "tokenizer."
+ )
+
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory.")
+ return
+ out_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
+ copyfile(self.vocab_file, out_vocab_file)
+
+ return (out_vocab_file,)
+
+
+__all__ = ["XGLMTokenizerFast"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1167fc93a10101636288751b692a4daf8a0cf2b4
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xlm import *
+ from .modeling_tf_xlm import *
+ from .modeling_xlm import *
+ from .tokenization_xlm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/configuration_xlm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/configuration_xlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4c85bf582703663c4f4eff99a49c9cc394e0854
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/configuration_xlm.py
@@ -0,0 +1,241 @@
+# coding=utf-8
+# Copyright 2019-present, Facebook, Inc and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""XLM configuration"""
+
+from collections import OrderedDict
+from collections.abc import Mapping
+
+from ...configuration_utils import PretrainedConfig
+from ...onnx import OnnxConfig
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class XLMConfig(PretrainedConfig):
+ """
+ This is the configuration class to store the configuration of a [`XLMModel`] or a [`TFXLMModel`]. It is used to
+ instantiate a XLM model according to the specified arguments, defining the model architecture. Instantiating a
+ configuration with the defaults will yield a similar configuration to that of the
+ [FacebookAI/xlm-mlm-en-2048](https://huggingface.co/FacebookAI/xlm-mlm-en-2048) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 30145):
+ Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`XLMModel`] or [`TFXLMModel`].
+ emb_dim (`int`, *optional*, defaults to 2048):
+ Dimensionality of the encoder layers and the pooler layer.
+ n_layer (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ n_head (`int`, *optional*, defaults to 16):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for the attention mechanism
+ gelu_activation (`bool`, *optional*, defaults to `True`):
+ Whether or not to use *gelu* for the activations instead of *relu*.
+ sinusoidal_embeddings (`bool`, *optional*, defaults to `False`):
+ Whether or not to use sinusoidal positional embeddings instead of absolute positional embeddings.
+ causal (`bool`, *optional*, defaults to `False`):
+ Whether or not the model should behave in a causal manner. Causal models use a triangular attention mask in
+ order to only attend to the left-side context instead if a bidirectional context.
+ asm (`bool`, *optional*, defaults to `False`):
+ Whether or not to use an adaptive log softmax projection layer instead of a linear layer for the prediction
+ layer.
+ n_langs (`int`, *optional*, defaults to 1):
+ The number of languages the model handles. Set to 1 for monolingual models.
+ use_lang_emb (`bool`, *optional*, defaults to `True`)
+ Whether to use language embeddings. Some models use additional language embeddings, see [the multilingual
+ models page](http://huggingface.co/transformers/multilingual.html#xlm-language-embeddings) for information
+ on how to use them.
+ max_position_embeddings (`int`, *optional*, defaults to 512):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ embed_init_std (`float`, *optional*, defaults to 2048^-0.5):
+ The standard deviation of the truncated_normal_initializer for initializing the embedding matrices.
+ init_std (`int`, *optional*, defaults to 50257):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices except the
+ embedding matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ bos_index (`int`, *optional*, defaults to 0):
+ The index of the beginning of sentence token in the vocabulary.
+ eos_index (`int`, *optional*, defaults to 1):
+ The index of the end of sentence token in the vocabulary.
+ pad_index (`int`, *optional*, defaults to 2):
+ The index of the padding token in the vocabulary.
+ unk_index (`int`, *optional*, defaults to 3):
+ The index of the unknown token in the vocabulary.
+ mask_index (`int`, *optional*, defaults to 5):
+ The index of the masking token in the vocabulary.
+ is_encoder(`bool`, *optional*, defaults to `True`):
+ Whether or not the initialized model should be a transformer encoder or decoder as seen in Vaswani et al.
+ summary_type (`string`, *optional*, defaults to "first"):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+
+ Has to be one of the following options:
+
+ - `"last"`: Take the last token hidden state (like XLNet).
+ - `"first"`: Take the first token hidden state (like BERT).
+ - `"mean"`: Take the mean of all tokens hidden states.
+ - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
+ - `"attn"`: Not implemented now, use multi-head attention.
+ summary_use_proj (`bool`, *optional*, defaults to `True`):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+
+ Whether or not to add a projection after the vector extraction.
+ summary_activation (`str`, *optional*):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+
+ Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
+ summary_proj_to_labels (`bool`, *optional*, defaults to `True`):
+ Used in the sequence classification and multiple choice models.
+
+ Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
+ summary_first_dropout (`float`, *optional*, defaults to 0.1):
+ Used in the sequence classification and multiple choice models.
+
+ The dropout ratio to be used after the projection and activation.
+ start_n_top (`int`, *optional*, defaults to 5):
+ Used in the SQuAD evaluation script.
+ end_n_top (`int`, *optional*, defaults to 5):
+ Used in the SQuAD evaluation script.
+ mask_token_id (`int`, *optional*, defaults to 0):
+ Model agnostic parameter to identify masked tokens when generating text in an MLM context.
+ lang_id (`int`, *optional*, defaults to 1):
+ The ID of the language used by the model. This parameter is used when generating text in a given language.
+
+ Examples:
+
+ ```python
+ >>> from transformers import XLMConfig, XLMModel
+
+ >>> # Initializing a XLM configuration
+ >>> configuration = XLMConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = XLMModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xlm"
+ attribute_map = {
+ "hidden_size": "emb_dim",
+ "num_attention_heads": "n_heads",
+ "num_hidden_layers": "n_layers",
+ "n_words": "vocab_size", # For backward compatibility
+ }
+
+ def __init__(
+ self,
+ vocab_size=30145,
+ emb_dim=2048,
+ n_layers=12,
+ n_heads=16,
+ dropout=0.1,
+ attention_dropout=0.1,
+ gelu_activation=True,
+ sinusoidal_embeddings=False,
+ causal=False,
+ asm=False,
+ n_langs=1,
+ use_lang_emb=True,
+ max_position_embeddings=512,
+ embed_init_std=2048**-0.5,
+ layer_norm_eps=1e-12,
+ init_std=0.02,
+ bos_index=0,
+ eos_index=1,
+ pad_index=2,
+ unk_index=3,
+ mask_index=5,
+ is_encoder=True,
+ summary_type="first",
+ summary_use_proj=True,
+ summary_activation=None,
+ summary_proj_to_labels=True,
+ summary_first_dropout=0.1,
+ start_n_top=5,
+ end_n_top=5,
+ mask_token_id=0,
+ lang_id=0,
+ pad_token_id=2,
+ bos_token_id=0,
+ **kwargs,
+ ):
+ """Constructs XLMConfig."""
+ self.vocab_size = vocab_size
+ self.emb_dim = emb_dim
+ self.n_layers = n_layers
+ self.n_heads = n_heads
+ self.dropout = dropout
+ self.attention_dropout = attention_dropout
+ self.gelu_activation = gelu_activation
+ self.sinusoidal_embeddings = sinusoidal_embeddings
+ self.causal = causal
+ self.asm = asm
+ self.n_langs = n_langs
+ self.use_lang_emb = use_lang_emb
+ self.layer_norm_eps = layer_norm_eps
+ self.bos_index = bos_index
+ self.eos_index = eos_index
+ self.pad_index = pad_index
+ self.unk_index = unk_index
+ self.mask_index = mask_index
+ self.is_encoder = is_encoder
+ self.max_position_embeddings = max_position_embeddings
+ self.embed_init_std = embed_init_std
+ self.init_std = init_std
+ self.summary_type = summary_type
+ self.summary_use_proj = summary_use_proj
+ self.summary_activation = summary_activation
+ self.summary_proj_to_labels = summary_proj_to_labels
+ self.summary_first_dropout = summary_first_dropout
+ self.start_n_top = start_n_top
+ self.end_n_top = end_n_top
+ self.mask_token_id = mask_token_id
+ self.lang_id = lang_id
+
+ if "n_words" in kwargs:
+ self.n_words = kwargs["n_words"]
+
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, **kwargs)
+
+
+# Copied from transformers.models.bert.configuration_bert.BertOnnxConfig
+class XLMOnnxConfig(OnnxConfig):
+ @property
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
+ if self.task == "multiple-choice":
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
+ else:
+ dynamic_axis = {0: "batch", 1: "sequence"}
+ return OrderedDict(
+ [
+ ("input_ids", dynamic_axis),
+ ("attention_mask", dynamic_axis),
+ ("token_type_ids", dynamic_axis),
+ ]
+ )
+
+
+__all__ = ["XLMConfig", "XLMOnnxConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/modeling_tf_xlm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/modeling_tf_xlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..db89b4686f84bd6e19fdb340cbe91e3b9573c678
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/modeling_tf_xlm.py
@@ -0,0 +1,1356 @@
+# coding=utf-8
+# Copyright 2019-present, Facebook, Inc and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+TF 2.0 XLM model.
+"""
+
+from __future__ import annotations
+
+import itertools
+import warnings
+from dataclasses import dataclass
+
+import numpy as np
+import tensorflow as tf
+
+from ...activations_tf import get_tf_activation
+from ...modeling_tf_outputs import (
+ TFBaseModelOutput,
+ TFMultipleChoiceModelOutput,
+ TFQuestionAnsweringModelOutput,
+ TFSequenceClassifierOutput,
+ TFTokenClassifierOutput,
+)
+from ...modeling_tf_utils import (
+ TFModelInputType,
+ TFMultipleChoiceLoss,
+ TFPreTrainedModel,
+ TFQuestionAnsweringLoss,
+ TFSequenceClassificationLoss,
+ TFSequenceSummary,
+ TFSharedEmbeddings,
+ TFTokenClassificationLoss,
+ get_initializer,
+ keras,
+ keras_serializable,
+ unpack_inputs,
+)
+from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
+from ...utils import (
+ MULTIPLE_CHOICE_DUMMY_INPUTS,
+ ModelOutput,
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+)
+from .configuration_xlm import XLMConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "FacebookAI/xlm-mlm-en-2048"
+_CONFIG_FOR_DOC = "XLMConfig"
+
+
+def create_sinusoidal_embeddings(n_pos, dim, out):
+ position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
+ out[:, 0::2] = tf.constant(np.sin(position_enc[:, 0::2]))
+ out[:, 1::2] = tf.constant(np.cos(position_enc[:, 1::2]))
+
+
+def get_masks(slen, lengths, causal, padding_mask=None):
+ """
+ Generate hidden states mask, and optionally an attention mask.
+ """
+ bs = shape_list(lengths)[0]
+ if padding_mask is not None:
+ mask = padding_mask
+ else:
+ # assert lengths.max().item() <= slen
+ alen = tf.range(slen, dtype=lengths.dtype)
+ mask = alen < tf.expand_dims(lengths, axis=1)
+
+ # attention mask is the same as mask, or triangular inferior attention (causal)
+ if causal:
+ attn_mask = tf.less_equal(
+ tf.tile(tf.reshape(alen, (1, 1, slen)), (bs, slen, 1)), tf.reshape(alen, (1, slen, 1))
+ )
+ else:
+ attn_mask = mask
+
+ # sanity check
+ # assert shape_list(mask) == [bs, slen]
+ tf.debugging.assert_equal(shape_list(mask), [bs, slen])
+ if causal:
+ tf.debugging.assert_equal(shape_list(attn_mask), [bs, slen, slen])
+
+ return mask, attn_mask
+
+
+class TFXLMMultiHeadAttention(keras.layers.Layer):
+ NEW_ID = itertools.count()
+
+ def __init__(self, n_heads, dim, config, **kwargs):
+ super().__init__(**kwargs)
+ self.layer_id = next(TFXLMMultiHeadAttention.NEW_ID)
+ self.dim = dim
+ self.n_heads = n_heads
+ self.output_attentions = config.output_attentions
+ assert self.dim % self.n_heads == 0
+
+ self.q_lin = keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name="q_lin")
+ self.k_lin = keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name="k_lin")
+ self.v_lin = keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name="v_lin")
+ self.out_lin = keras.layers.Dense(dim, kernel_initializer=get_initializer(config.init_std), name="out_lin")
+ self.dropout = keras.layers.Dropout(config.attention_dropout)
+ self.pruned_heads = set()
+ self.dim = dim
+
+ def prune_heads(self, heads):
+ raise NotImplementedError
+
+ def call(self, input, mask, kv, cache, head_mask, output_attentions, training=False):
+ """
+ Self-attention (if kv is None) or attention over source sentence (provided by kv).
+ """
+ # Input is (bs, qlen, dim)
+ # Mask is (bs, klen) (non-causal) or (bs, klen, klen)
+ bs, qlen, dim = shape_list(input)
+
+ if kv is None:
+ klen = qlen if cache is None else cache["slen"] + qlen
+ else:
+ klen = shape_list(kv)[1]
+
+ # assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
+ dim_per_head = self.dim // self.n_heads
+ mask_reshape = (bs, 1, qlen, klen) if len(shape_list(mask)) == 3 else (bs, 1, 1, klen)
+
+ def shape(x):
+ """projection"""
+ return tf.transpose(tf.reshape(x, (bs, -1, self.n_heads, dim_per_head)), perm=(0, 2, 1, 3))
+
+ def unshape(x):
+ """compute context"""
+ return tf.reshape(tf.transpose(x, perm=(0, 2, 1, 3)), (bs, -1, self.n_heads * dim_per_head))
+
+ q = shape(self.q_lin(input)) # (bs, n_heads, qlen, dim_per_head)
+
+ if kv is None:
+ k = shape(self.k_lin(input)) # (bs, n_heads, qlen, dim_per_head)
+ v = shape(self.v_lin(input)) # (bs, n_heads, qlen, dim_per_head)
+ elif cache is None or self.layer_id not in cache:
+ k = v = kv
+ k = shape(self.k_lin(k)) # (bs, n_heads, qlen, dim_per_head)
+ v = shape(self.v_lin(v)) # (bs, n_heads, qlen, dim_per_head)
+
+ if cache is not None:
+ if self.layer_id in cache:
+ if kv is None:
+ k_, v_ = cache[self.layer_id]
+ k = tf.concat([k_, k], axis=2) # (bs, n_heads, klen, dim_per_head)
+ v = tf.concat([v_, v], axis=2) # (bs, n_heads, klen, dim_per_head)
+ else:
+ k, v = cache[self.layer_id]
+
+ cache[self.layer_id] = (k, v)
+
+ f_dim_per_head = tf.cast(dim_per_head, dtype=q.dtype)
+ q = tf.multiply(q, tf.math.rsqrt(f_dim_per_head)) # (bs, n_heads, qlen, dim_per_head)
+ k = tf.cast(k, dtype=q.dtype)
+ scores = tf.matmul(q, k, transpose_b=True) # (bs, n_heads, qlen, klen)
+ mask = tf.reshape(mask, mask_reshape) # (bs, n_heads, qlen, klen)
+ # scores.masked_fill_(mask, -float('inf')) # (bs, n_heads, qlen, klen)
+ mask = tf.cast(mask, dtype=scores.dtype)
+ scores = scores - 1e30 * (1.0 - mask)
+ weights = stable_softmax(scores, axis=-1) # (bs, n_heads, qlen, klen)
+ weights = self.dropout(weights, training=training) # (bs, n_heads, qlen, klen)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ weights = weights * head_mask
+
+ context = tf.matmul(weights, v) # (bs, n_heads, qlen, dim_per_head)
+ context = unshape(context) # (bs, qlen, dim)
+ outputs = (self.out_lin(context),)
+
+ if output_attentions:
+ outputs = outputs + (weights,)
+
+ return outputs
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "q_lin", None) is not None:
+ with tf.name_scope(self.q_lin.name):
+ self.q_lin.build([None, None, self.dim])
+ if getattr(self, "k_lin", None) is not None:
+ with tf.name_scope(self.k_lin.name):
+ self.k_lin.build([None, None, self.dim])
+ if getattr(self, "v_lin", None) is not None:
+ with tf.name_scope(self.v_lin.name):
+ self.v_lin.build([None, None, self.dim])
+ if getattr(self, "out_lin", None) is not None:
+ with tf.name_scope(self.out_lin.name):
+ self.out_lin.build([None, None, self.dim])
+
+
+class TFXLMTransformerFFN(keras.layers.Layer):
+ def __init__(self, in_dim, dim_hidden, out_dim, config, **kwargs):
+ super().__init__(**kwargs)
+
+ self.lin1 = keras.layers.Dense(dim_hidden, kernel_initializer=get_initializer(config.init_std), name="lin1")
+ self.lin2 = keras.layers.Dense(out_dim, kernel_initializer=get_initializer(config.init_std), name="lin2")
+ self.act = get_tf_activation("gelu") if config.gelu_activation else get_tf_activation("relu")
+ self.dropout = keras.layers.Dropout(config.dropout)
+ self.in_dim = in_dim
+ self.dim_hidden = dim_hidden
+
+ def call(self, input, training=False):
+ x = self.lin1(input)
+ x = self.act(x)
+ x = self.lin2(x)
+ x = self.dropout(x, training=training)
+
+ return x
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "lin1", None) is not None:
+ with tf.name_scope(self.lin1.name):
+ self.lin1.build([None, None, self.in_dim])
+ if getattr(self, "lin2", None) is not None:
+ with tf.name_scope(self.lin2.name):
+ self.lin2.build([None, None, self.dim_hidden])
+
+
+@keras_serializable
+class TFXLMMainLayer(keras.layers.Layer):
+ config_class = XLMConfig
+
+ def __init__(self, config, **kwargs):
+ super().__init__(**kwargs)
+
+ self.config = config
+ self.output_hidden_states = config.output_hidden_states
+ self.output_attentions = config.output_attentions
+ self.return_dict = config.use_return_dict
+
+ # encoder / decoder, output layer
+ self.is_encoder = config.is_encoder
+ self.is_decoder = not config.is_encoder
+
+ if self.is_decoder:
+ raise NotImplementedError("Currently XLM can only be used as an encoder")
+
+ # self.with_output = with_output
+ self.causal = config.causal
+
+ # dictionary / languages
+ self.n_langs = config.n_langs
+ self.use_lang_emb = config.use_lang_emb
+ self.n_words = config.n_words
+ self.eos_index = config.eos_index
+ self.pad_index = config.pad_index
+ # self.dico = dico
+ # self.id2lang = config.id2lang
+ # self.lang2id = config.lang2id
+ # assert len(self.dico) == self.n_words
+ # assert len(self.id2lang) == len(self.lang2id) == self.n_langs
+
+ # model parameters
+ self.dim = config.emb_dim # 512 by default
+ self.hidden_dim = self.dim * 4 # 2048 by default
+ self.n_heads = config.n_heads # 8 by default
+ self.n_layers = config.n_layers
+ self.max_position_embeddings = config.max_position_embeddings
+ self.embed_init_std = config.embed_init_std
+ if self.dim % self.n_heads != 0:
+ raise ValueError("transformer dim must be a multiple of n_heads")
+
+ # embeddings
+ self.dropout = keras.layers.Dropout(config.dropout)
+ self.attention_dropout = keras.layers.Dropout(config.attention_dropout)
+
+ if config.sinusoidal_embeddings:
+ raise NotImplementedError
+ # create_sinusoidal_embeddings(config.max_position_embeddings, self.dim, out=self.position_embeddings.weight)
+
+ self.embeddings = TFSharedEmbeddings(
+ self.n_words, self.dim, initializer_range=config.embed_init_std, name="embeddings"
+ ) # padding_idx=self.pad_index)
+ self.layer_norm_emb = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm_emb")
+
+ # transformer layers
+ self.attentions = []
+ self.layer_norm1 = []
+ self.ffns = []
+ self.layer_norm2 = []
+ # if self.is_decoder:
+ # self.layer_norm15 = []
+ # self.encoder_attn = []
+
+ for i in range(self.n_layers):
+ self.attentions.append(
+ TFXLMMultiHeadAttention(self.n_heads, self.dim, config=config, name=f"attentions_._{i}")
+ )
+ self.layer_norm1.append(
+ keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=f"layer_norm1_._{i}")
+ )
+ # if self.is_decoder:
+ # self.layer_norm15.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
+ # self.encoder_attn.append(MultiHeadAttention(self.n_heads, self.dim, dropout=self.attention_dropout))
+ self.ffns.append(
+ TFXLMTransformerFFN(self.dim, self.hidden_dim, self.dim, config=config, name=f"ffns_._{i}")
+ )
+ self.layer_norm2.append(
+ keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name=f"layer_norm2_._{i}")
+ )
+
+ if hasattr(config, "pruned_heads"):
+ pruned_heads = config.pruned_heads.copy().items()
+ config.pruned_heads = {}
+
+ for layer, heads in pruned_heads:
+ if self.attentions[int(layer)].n_heads == config.n_heads:
+ self.prune_heads({int(layer): list(map(int, heads))})
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ with tf.name_scope("position_embeddings"):
+ self.position_embeddings = self.add_weight(
+ name="embeddings",
+ shape=[self.max_position_embeddings, self.dim],
+ initializer=get_initializer(self.embed_init_std),
+ )
+
+ if self.n_langs > 1 and self.use_lang_emb:
+ with tf.name_scope("lang_embeddings"):
+ self.lang_embeddings = self.add_weight(
+ name="embeddings",
+ shape=[self.n_langs, self.dim],
+ initializer=get_initializer(self.embed_init_std),
+ )
+ if getattr(self, "embeddings", None) is not None:
+ with tf.name_scope(self.embeddings.name):
+ self.embeddings.build(None)
+ if getattr(self, "layer_norm_emb", None) is not None:
+ with tf.name_scope(self.layer_norm_emb.name):
+ self.layer_norm_emb.build([None, None, self.dim])
+ for layer in self.attentions:
+ with tf.name_scope(layer.name):
+ layer.build(None)
+ for layer in self.layer_norm1:
+ with tf.name_scope(layer.name):
+ layer.build([None, None, self.dim])
+ for layer in self.ffns:
+ with tf.name_scope(layer.name):
+ layer.build(None)
+ for layer in self.layer_norm2:
+ with tf.name_scope(layer.name):
+ layer.build([None, None, self.dim])
+
+ def get_input_embeddings(self):
+ return self.embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.weight = value
+ self.embeddings.vocab_size = shape_list(value)[0]
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ raise NotImplementedError
+
+ @unpack_inputs
+ def call(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ langs=None,
+ token_type_ids=None,
+ position_ids=None,
+ lengths=None,
+ cache=None,
+ head_mask=None,
+ inputs_embeds=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ training=False,
+ ) -> TFBaseModelOutput | tuple[tf.Tensor]:
+ # removed: src_enc=None, src_len=None
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ bs, slen = shape_list(input_ids)
+ elif inputs_embeds is not None:
+ bs, slen = shape_list(inputs_embeds)[:2]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ if lengths is None:
+ if input_ids is not None:
+ lengths = tf.reduce_sum(
+ tf.cast(tf.not_equal(input_ids, self.pad_index), dtype=input_ids.dtype), axis=1
+ )
+ else:
+ lengths = tf.convert_to_tensor([slen] * bs)
+ # mask = input_ids != self.pad_index
+
+ # check inputs
+ # assert shape_list(lengths)[0] == bs
+ (
+ tf.debugging.assert_equal(shape_list(lengths)[0], bs),
+ f"Expected batch size {shape_list(lengths)[0]} and received batch size {bs} mismatched",
+ )
+ # assert lengths.max().item() <= slen
+ # input_ids = input_ids.transpose(0, 1) # batch size as dimension 0
+ # assert (src_enc is None) == (src_len is None)
+ # if src_enc is not None:
+ # assert self.is_decoder
+ # assert src_enc.size(0) == bs
+
+ # generate masks
+ mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)
+ # if self.is_decoder and src_enc is not None:
+ # src_mask = torch.arange(src_len.max(), dtype=torch.long, device=lengths.device) < src_len[:, None]
+
+ # position_ids
+ if position_ids is None:
+ position_ids = tf.expand_dims(tf.range(slen), axis=0)
+ position_ids = tf.tile(position_ids, (bs, 1))
+
+ # assert shape_list(position_ids) == [bs, slen] # (slen, bs)
+ (
+ tf.debugging.assert_equal(shape_list(position_ids), [bs, slen]),
+ f"Position id shape {shape_list(position_ids)} and input shape {[bs, slen]} mismatched",
+ )
+ # position_ids = position_ids.transpose(0, 1)
+
+ # langs
+ if langs is not None:
+ # assert shape_list(langs) == [bs, slen] # (slen, bs)
+ (
+ tf.debugging.assert_equal(shape_list(langs), [bs, slen]),
+ f"Lang shape {shape_list(langs)} and input shape {[bs, slen]} mismatched",
+ )
+ # langs = langs.transpose(0, 1)
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x qlen x klen]
+ if head_mask is not None:
+ raise NotImplementedError
+ else:
+ head_mask = [None] * self.n_layers
+
+ # do not recompute cached elements
+ if cache is not None and input_ids is not None:
+ _slen = slen - cache["slen"]
+ input_ids = input_ids[:, -_slen:]
+ position_ids = position_ids[:, -_slen:]
+ if langs is not None:
+ langs = langs[:, -_slen:]
+ mask = mask[:, -_slen:]
+ attn_mask = attn_mask[:, -_slen:]
+
+ # embeddings
+ if inputs_embeds is None:
+ check_embeddings_within_bounds(input_ids, self.embeddings.vocab_size)
+ inputs_embeds = self.embeddings(input_ids)
+
+ tensor = inputs_embeds + tf.gather(self.position_embeddings, position_ids)
+
+ if langs is not None and self.use_lang_emb and self.n_langs > 1:
+ tensor = tensor + tf.gather(self.lang_embeddings, langs)
+ if token_type_ids is not None:
+ tensor = tensor + self.embeddings(token_type_ids)
+
+ tensor = self.layer_norm_emb(tensor)
+ tensor = self.dropout(tensor, training=training)
+ mask = tf.cast(mask, dtype=tensor.dtype)
+ tensor = tensor * tf.expand_dims(mask, axis=-1)
+
+ # transformer layers
+ hidden_states = () if output_hidden_states else None
+ attentions = () if output_attentions else None
+
+ for i in range(self.n_layers):
+ if output_hidden_states:
+ hidden_states = hidden_states + (tensor,)
+
+ # self attention
+ attn_outputs = self.attentions[i](
+ tensor,
+ attn_mask,
+ None,
+ cache,
+ head_mask[i],
+ output_attentions,
+ training=training,
+ )
+ attn = attn_outputs[0]
+
+ if output_attentions:
+ attentions = attentions + (attn_outputs[1],)
+
+ attn = self.dropout(attn, training=training)
+ tensor = tensor + attn
+ tensor = self.layer_norm1[i](tensor)
+
+ # encoder attention (for decoder only)
+ # if self.is_decoder and src_enc is not None:
+ # attn = self.encoder_attn[i](tensor, src_mask, kv=src_enc, cache=cache)
+ # attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)
+ # tensor = tensor + attn
+ # tensor = self.layer_norm15[i](tensor)
+
+ # FFN
+ tensor = tensor + self.ffns[i](tensor)
+ tensor = self.layer_norm2[i](tensor)
+ tensor = tensor * tf.expand_dims(mask, axis=-1)
+
+ # Add last hidden state
+ if output_hidden_states:
+ hidden_states = hidden_states + (tensor,)
+
+ # update cache length
+ if cache is not None:
+ cache["slen"] += tensor.size(1)
+
+ # move back sequence length to dimension 0
+ # tensor = tensor.transpose(0, 1)
+
+ if not return_dict:
+ return tuple(v for v in [tensor, hidden_states, attentions] if v is not None)
+
+ return TFBaseModelOutput(last_hidden_state=tensor, hidden_states=hidden_states, attentions=attentions)
+
+
+class TFXLMPreTrainedModel(TFPreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config_class = XLMConfig
+ base_model_prefix = "transformer"
+
+ @property
+ def dummy_inputs(self):
+ # Sometimes XLM has language embeddings so don't forget to build them as well if needed
+ inputs_list = tf.constant([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]], dtype=tf.int32)
+ attns_list = tf.constant([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]], dtype=tf.int32)
+ if self.config.use_lang_emb and self.config.n_langs > 1:
+ return {
+ "input_ids": inputs_list,
+ "attention_mask": attns_list,
+ "langs": tf.constant([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]], dtype=tf.int32),
+ }
+ else:
+ return {"input_ids": inputs_list, "attention_mask": attns_list}
+
+
+# Remove when XLMWithLMHead computes loss like other LM models
+@dataclass
+class TFXLMWithLMHeadModelOutput(ModelOutput):
+ """
+ Base class for [`TFXLMWithLMHeadModel`] outputs.
+
+ Args:
+ logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ logits: tf.Tensor | None = None
+ hidden_states: tuple[tf.Tensor, ...] | None = None
+ attentions: tuple[tf.Tensor, ...] | None = None
+
+
+XLM_START_DOCSTRING = r"""
+
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
+ behavior.
+
+
+
+ TensorFlow models and layers in `transformers` accept two formats as input:
+
+ - having all inputs as keyword arguments (like PyTorch models), or
+ - having all inputs as a list, tuple or dict in the first positional argument.
+
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
+ positional argument:
+
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
+
+ Note that when creating models and layers with
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
+ about any of this, as you can just pass inputs like you would to any other Python function!
+
+
+
+ Parameters:
+ config ([`XLMConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+XLM_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.__call__`] and
+ [`PreTrainedTokenizer.encode`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ langs (`tf.Tensor` or `Numpy array` of shape `({0})`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ lengths (`tf.Tensor` or `Numpy array` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, tf.Tensor]`, *optional*):
+ Dictionary string to `tf.Tensor` that contains precomputed hidden states (key and values in the attention
+ blocks) as computed by the model (see `cache` output below). Can be used to speed up sequential decoding.
+
+ The dictionary object will be modified in-place during the forward pass to add newly computed
+ hidden-states.
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
+ config will be used instead.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
+ used instead.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
+ eager mode, in graph mode the value will always be set to True.
+ training (`bool`, *optional*, defaults to `False`):
+ Whether or not to use the model in training mode (some modules like dropout modules have different
+ behaviors between training and evaluation).
+"""
+
+
+@add_start_docstrings(
+ "The bare XLM Model transformer outputting raw hidden-states without any specific head on top.",
+ XLM_START_DOCSTRING,
+)
+class TFXLMModel(TFXLMPreTrainedModel):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.transformer = TFXLMMainLayer(config, name="transformer")
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFBaseModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: tf.Tensor | None = None,
+ langs: tf.Tensor | None = None,
+ token_type_ids: tf.Tensor | None = None,
+ position_ids: tf.Tensor | None = None,
+ lengths: tf.Tensor | None = None,
+ cache: dict[str, tf.Tensor] | None = None,
+ head_mask: tf.Tensor | None = None,
+ inputs_embeds: tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ training: bool = False,
+ ) -> TFBaseModelOutput | tuple[tf.Tensor]:
+ outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ return outputs
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+
+
+class TFXLMPredLayer(keras.layers.Layer):
+ """
+ Prediction layer (cross_entropy or adaptive_softmax).
+ """
+
+ def __init__(self, config, input_embeddings, **kwargs):
+ super().__init__(**kwargs)
+
+ self.asm = config.asm
+ self.n_words = config.n_words
+ self.pad_index = config.pad_index
+
+ if config.asm is False:
+ self.input_embeddings = input_embeddings
+ else:
+ raise NotImplementedError
+ # self.proj = nn.AdaptiveLogSoftmaxWithLoss(
+ # in_features=dim,
+ # n_classes=config.n_words,
+ # cutoffs=config.asm_cutoffs,
+ # div_value=config.asm_div_value,
+ # head_bias=True, # default is False
+ # )
+
+ def build(self, input_shape):
+ # The output weights are the same as the input embeddings, but there is an output-only bias for each token.
+ self.bias = self.add_weight(shape=(self.n_words,), initializer="zeros", trainable=True, name="bias")
+
+ super().build(input_shape)
+
+ def get_output_embeddings(self):
+ return self.input_embeddings
+
+ def set_output_embeddings(self, value):
+ self.input_embeddings.weight = value
+ self.input_embeddings.vocab_size = shape_list(value)[0]
+
+ def get_bias(self):
+ return {"bias": self.bias}
+
+ def set_bias(self, value):
+ self.bias = value["bias"]
+ self.vocab_size = shape_list(value["bias"])[0]
+
+ def call(self, hidden_states):
+ hidden_states = self.input_embeddings(hidden_states, mode="linear")
+ hidden_states = hidden_states + self.bias
+
+ return hidden_states
+
+
+@add_start_docstrings(
+ """
+ The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
+ embeddings).
+ """,
+ XLM_START_DOCSTRING,
+)
+class TFXLMWithLMHeadModel(TFXLMPreTrainedModel):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.transformer = TFXLMMainLayer(config, name="transformer")
+ self.pred_layer = TFXLMPredLayer(config, self.transformer.embeddings, name="pred_layer_._proj")
+ # XLM does not have past caching features
+ self.supports_xla_generation = False
+
+ def get_lm_head(self):
+ return self.pred_layer
+
+ def get_prefix_bias_name(self):
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
+ return self.name + "/" + self.pred_layer.name
+
+ def prepare_inputs_for_generation(self, inputs, **kwargs):
+ mask_token_id = self.config.mask_token_id
+ lang_id = self.config.lang_id
+
+ effective_batch_size = inputs.shape[0]
+ mask_token = tf.fill((effective_batch_size, 1), 1) * mask_token_id
+ inputs = tf.concat([inputs, mask_token], axis=1)
+
+ if lang_id is not None:
+ langs = tf.ones_like(inputs) * lang_id
+ else:
+ langs = None
+ return {"input_ids": inputs, "langs": langs}
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFXLMWithLMHeadModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ langs: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ lengths: np.ndarray | tf.Tensor | None = None,
+ cache: dict[str, tf.Tensor] | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ training: bool = False,
+ ) -> TFXLMWithLMHeadModelOutput | tuple[tf.Tensor]:
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ output = transformer_outputs[0]
+ outputs = self.pred_layer(output)
+
+ if not return_dict:
+ return (outputs,) + transformer_outputs[1:]
+
+ return TFXLMWithLMHeadModelOutput(
+ logits=outputs, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+ if getattr(self, "pred_layer", None) is not None:
+ with tf.name_scope(self.pred_layer.name):
+ self.pred_layer.build(None)
+
+
+@add_start_docstrings(
+ """
+ XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g.
+ for GLUE tasks.
+ """,
+ XLM_START_DOCSTRING,
+)
+class TFXLMForSequenceClassification(TFXLMPreTrainedModel, TFSequenceClassificationLoss):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.num_labels = config.num_labels
+
+ self.transformer = TFXLMMainLayer(config, name="transformer")
+ self.sequence_summary = TFSequenceSummary(config, initializer_range=config.init_std, name="sequence_summary")
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFSequenceClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ langs: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ lengths: np.ndarray | tf.Tensor | None = None,
+ cache: dict[str, tf.Tensor] | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ) -> TFSequenceClassifierOutput | tuple[tf.Tensor]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ output = transformer_outputs[0]
+
+ logits = self.sequence_summary(output)
+
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFSequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+ if getattr(self, "sequence_summary", None) is not None:
+ with tf.name_scope(self.sequence_summary.name):
+ self.sequence_summary.build(None)
+
+
+@add_start_docstrings(
+ """
+ XLM Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
+ softmax) e.g. for RocStories/SWAG tasks.
+ """,
+ XLM_START_DOCSTRING,
+)
+class TFXLMForMultipleChoice(TFXLMPreTrainedModel, TFMultipleChoiceLoss):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+
+ self.transformer = TFXLMMainLayer(config, name="transformer")
+ self.sequence_summary = TFSequenceSummary(config, initializer_range=config.init_std, name="sequence_summary")
+ self.logits_proj = keras.layers.Dense(
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="logits_proj"
+ )
+ self.config = config
+
+ @property
+ def dummy_inputs(self):
+ """
+ Dummy inputs to build the network.
+
+ Returns:
+ tf.Tensor with dummy inputs
+ """
+ # Sometimes XLM has language embeddings so don't forget to build them as well if needed
+ if self.config.use_lang_emb and self.config.n_langs > 1:
+ return {
+ "input_ids": tf.constant(MULTIPLE_CHOICE_DUMMY_INPUTS, dtype=tf.int32),
+ "langs": tf.constant(MULTIPLE_CHOICE_DUMMY_INPUTS, dtype=tf.int32),
+ }
+ else:
+ return {
+ "input_ids": tf.constant(MULTIPLE_CHOICE_DUMMY_INPUTS, dtype=tf.int32),
+ }
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFMultipleChoiceModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ langs: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ lengths: np.ndarray | tf.Tensor | None = None,
+ cache: dict[str, tf.Tensor] | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ) -> TFMultipleChoiceModelOutput | tuple[tf.Tensor]:
+ if input_ids is not None:
+ num_choices = shape_list(input_ids)[1]
+ seq_length = shape_list(input_ids)[2]
+ else:
+ num_choices = shape_list(inputs_embeds)[1]
+ seq_length = shape_list(inputs_embeds)[2]
+
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
+ flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
+ flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
+ flat_langs = tf.reshape(langs, (-1, seq_length)) if langs is not None else None
+ flat_inputs_embeds = (
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
+ if inputs_embeds is not None
+ else None
+ )
+
+ if lengths is not None:
+ logger.warning(
+ "The `lengths` parameter cannot be used with the XLM multiple choice models. Please use the "
+ "attention mask instead.",
+ )
+ lengths = None
+
+ transformer_outputs = self.transformer(
+ flat_input_ids,
+ flat_attention_mask,
+ flat_langs,
+ flat_token_type_ids,
+ flat_position_ids,
+ lengths,
+ cache,
+ head_mask,
+ flat_inputs_embeds,
+ output_attentions,
+ output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ output = transformer_outputs[0]
+ logits = self.sequence_summary(output)
+ logits = self.logits_proj(logits)
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
+
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
+
+ if not return_dict:
+ output = (reshaped_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFMultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+ if getattr(self, "sequence_summary", None) is not None:
+ with tf.name_scope(self.sequence_summary.name):
+ self.sequence_summary.build(None)
+ if getattr(self, "logits_proj", None) is not None:
+ with tf.name_scope(self.logits_proj.name):
+ self.logits_proj.build([None, None, self.config.num_labels])
+
+
+@add_start_docstrings(
+ """
+ XLM Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
+ Named-Entity-Recognition (NER) tasks.
+ """,
+ XLM_START_DOCSTRING,
+)
+class TFXLMForTokenClassification(TFXLMPreTrainedModel, TFTokenClassificationLoss):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.num_labels = config.num_labels
+
+ self.transformer = TFXLMMainLayer(config, name="transformer")
+ self.dropout = keras.layers.Dropout(config.dropout)
+ self.classifier = keras.layers.Dense(
+ config.num_labels, kernel_initializer=get_initializer(config.init_std), name="classifier"
+ )
+ self.config = config
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFTokenClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ langs: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ lengths: np.ndarray | tf.Tensor | None = None,
+ cache: dict[str, tf.Tensor] | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ) -> TFTokenClassifierOutput | tuple[tf.Tensor]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ sequence_output = transformer_outputs[0]
+
+ sequence_output = self.dropout(sequence_output, training=training)
+ logits = self.classifier(sequence_output)
+
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFTokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+ if getattr(self, "classifier", None) is not None:
+ with tf.name_scope(self.classifier.name):
+ self.classifier.build([None, None, self.config.hidden_size])
+
+
+@add_start_docstrings(
+ """
+ XLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layer
+ on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """,
+ XLM_START_DOCSTRING,
+)
+class TFXLMForQuestionAnsweringSimple(TFXLMPreTrainedModel, TFQuestionAnsweringLoss):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.transformer = TFXLMMainLayer(config, name="transformer")
+ self.qa_outputs = keras.layers.Dense(
+ config.num_labels, kernel_initializer=get_initializer(config.init_std), name="qa_outputs"
+ )
+ self.config = config
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFQuestionAnsweringModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ langs: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ lengths: np.ndarray | tf.Tensor | None = None,
+ cache: dict[str, tf.Tensor] | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ start_positions: np.ndarray | tf.Tensor | None = None,
+ end_positions: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ) -> TFQuestionAnsweringModelOutput | tuple[tf.Tensor]:
+ r"""
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ """
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ sequence_output = transformer_outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
+ start_logits = tf.squeeze(start_logits, axis=-1)
+ end_logits = tf.squeeze(end_logits, axis=-1)
+
+ loss = None
+ if start_positions is not None and end_positions is not None:
+ labels = {"start_position": start_positions}
+ labels["end_position"] = end_positions
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
+
+ if not return_dict:
+ output = (start_logits, end_logits) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFQuestionAnsweringModelOutput(
+ loss=loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+ if getattr(self, "qa_outputs", None) is not None:
+ with tf.name_scope(self.qa_outputs.name):
+ self.qa_outputs.build([None, None, self.config.hidden_size])
+
+
+__all__ = [
+ "TFXLMForMultipleChoice",
+ "TFXLMForQuestionAnsweringSimple",
+ "TFXLMForSequenceClassification",
+ "TFXLMForTokenClassification",
+ "TFXLMMainLayer",
+ "TFXLMModel",
+ "TFXLMPreTrainedModel",
+ "TFXLMWithLMHeadModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/modeling_xlm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/modeling_xlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e7316fb781bfdf5b93a06c97c3577719e5da54d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/modeling_xlm.py
@@ -0,0 +1,1635 @@
+# coding=utf-8
+# Copyright 2019-present, Facebook, Inc and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+PyTorch XLM model.
+"""
+
+import math
+from dataclasses import dataclass
+from typing import Callable, Optional, Union
+
+import numpy as np
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import gelu, get_activation
+from ...cache_utils import DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...modeling_outputs import (
+ BaseModelOutput,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
+from ...utils import ModelOutput, auto_docstring, logging
+from .configuration_xlm import XLMConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+def create_sinusoidal_embeddings(n_pos, dim, out):
+ position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
+ out.requires_grad = False
+ out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
+ out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
+ out.detach_()
+
+
+def get_masks(slen, lengths, causal, padding_mask=None):
+ """
+ Generate hidden states mask, and optionally an attention mask.
+ """
+ alen = torch.arange(slen, dtype=torch.long, device=lengths.device)
+ if padding_mask is not None:
+ mask = padding_mask
+ else:
+ assert lengths.max().item() <= slen
+ mask = alen < lengths[:, None]
+
+ # attention mask is the same as mask, or triangular inferior attention (causal)
+ bs = lengths.size(0)
+ if causal:
+ attn_mask = alen[None, None, :].repeat(bs, slen, 1) <= alen[None, :, None]
+ else:
+ attn_mask = mask
+
+ # sanity check
+ assert mask.size() == (bs, slen)
+ assert causal is False or attn_mask.size() == (bs, slen, slen)
+
+ return mask, attn_mask
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of question answering models using a [`~modeling_utils.XLMSQuADHead`].
+ """
+)
+class XLMSquadHeadOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
+ Classification loss as the sum of start token, end token (and is_impossible if provided) classification
+ losses.
+ start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top config.start_n_top start token possibilities (beam-search).
+ start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top config.start_n_top start token possibilities (beam-search).
+ end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
+ (beam-search).
+ end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
+ cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the `is_impossible` label of the answers.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ start_top_log_probs: Optional[torch.FloatTensor] = None
+ start_top_index: Optional[torch.LongTensor] = None
+ end_top_log_probs: Optional[torch.FloatTensor] = None
+ end_top_index: Optional[torch.LongTensor] = None
+ cls_logits: Optional[torch.FloatTensor] = None
+
+
+class XLMPoolerStartLogits(nn.Module):
+ """
+ Compute SQuAD start logits from sequence hidden states.
+
+ Args:
+ config ([`XLMConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model.
+ """
+
+ def __init__(self, config: XLMConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, 1)
+
+ def forward(
+ self, hidden_states: torch.FloatTensor, p_mask: Optional[torch.FloatTensor] = None
+ ) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
+ Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
+ should be masked.
+
+ Returns:
+ `torch.FloatTensor`: The start logits for SQuAD.
+ """
+ x = self.dense(hidden_states).squeeze(-1)
+
+ if p_mask is not None:
+ if p_mask.dtype == torch.float16:
+ x = x * (1 - p_mask) - 65500 * p_mask
+ else:
+ x = x * (1 - p_mask) - 1e30 * p_mask
+
+ return x
+
+
+class XLMPoolerEndLogits(nn.Module):
+ """
+ Compute SQuAD end logits from sequence hidden states.
+
+ Args:
+ config ([`XLMConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
+ to use.
+ """
+
+ def __init__(self, config: XLMConfig):
+ super().__init__()
+ self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
+ self.activation = nn.Tanh()
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dense_1 = nn.Linear(config.hidden_size, 1)
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ start_states: Optional[torch.FloatTensor] = None,
+ start_positions: Optional[torch.LongTensor] = None,
+ p_mask: Optional[torch.FloatTensor] = None,
+ ) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
+ The hidden states of the first tokens for the labeled span.
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ The position of the first token for the labeled span.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
+ Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
+ should be masked.
+
+
+
+ One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
+ `start_states`.
+
+
+
+ Returns:
+ `torch.FloatTensor`: The end logits for SQuAD.
+ """
+ assert start_states is not None or start_positions is not None, (
+ "One of start_states, start_positions should be not None"
+ )
+ if start_positions is not None:
+ slen, hsz = hidden_states.shape[-2:]
+ start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ start_states = hidden_states.gather(-2, start_positions) # shape (bsz, 1, hsz)
+ start_states = start_states.expand(-1, slen, -1) # shape (bsz, slen, hsz)
+
+ x = self.dense_0(torch.cat([hidden_states, start_states], dim=-1))
+ x = self.activation(x)
+ x = self.LayerNorm(x)
+ x = self.dense_1(x).squeeze(-1)
+
+ if p_mask is not None:
+ if p_mask.dtype == torch.float16:
+ x = x * (1 - p_mask) - 65500 * p_mask
+ else:
+ x = x * (1 - p_mask) - 1e30 * p_mask
+
+ return x
+
+
+class XLMPoolerAnswerClass(nn.Module):
+ """
+ Compute SQuAD 2.0 answer class from classification and start tokens hidden states.
+
+ Args:
+ config ([`XLMConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model.
+ """
+
+ def __init__(self, config: XLMConfig):
+ super().__init__()
+ self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
+ self.activation = nn.Tanh()
+ self.dense_1 = nn.Linear(config.hidden_size, 1, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ start_states: Optional[torch.FloatTensor] = None,
+ start_positions: Optional[torch.LongTensor] = None,
+ cls_index: Optional[torch.LongTensor] = None,
+ ) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
+ The hidden states of the first tokens for the labeled span.
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ The position of the first token for the labeled span.
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
+
+
+
+ One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
+ `start_states`.
+
+
+
+ Returns:
+ `torch.FloatTensor`: The SQuAD 2.0 answer class.
+ """
+ # No dependency on end_feature so that we can obtain one single `cls_logits` for each sample.
+ hsz = hidden_states.shape[-1]
+ assert start_states is not None or start_positions is not None, (
+ "One of start_states, start_positions should be not None"
+ )
+ if start_positions is not None:
+ start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ start_states = hidden_states.gather(-2, start_positions).squeeze(-2) # shape (bsz, hsz)
+
+ if cls_index is not None:
+ cls_index = cls_index[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ cls_token_state = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, hsz)
+ else:
+ cls_token_state = hidden_states[:, -1, :] # shape (bsz, hsz)
+
+ x = self.dense_0(torch.cat([start_states, cls_token_state], dim=-1))
+ x = self.activation(x)
+ x = self.dense_1(x).squeeze(-1)
+
+ return x
+
+
+class XLMSQuADHead(nn.Module):
+ r"""
+ A SQuAD head inspired by XLNet.
+
+ Args:
+ config ([`XLMConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
+ to use.
+ """
+
+ def __init__(self, config: XLMConfig):
+ super().__init__()
+ self.start_n_top = config.start_n_top
+ self.end_n_top = config.end_n_top
+
+ self.start_logits = XLMPoolerStartLogits(config)
+ self.end_logits = XLMPoolerEndLogits(config)
+ self.answer_class = XLMPoolerAnswerClass(config)
+
+ @auto_docstring
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ start_positions: Optional[torch.LongTensor] = None,
+ end_positions: Optional[torch.LongTensor] = None,
+ cls_index: Optional[torch.LongTensor] = None,
+ is_impossible: Optional[torch.LongTensor] = None,
+ p_mask: Optional[torch.FloatTensor] = None,
+ return_dict: bool = False,
+ ) -> Union[XLMSquadHeadOutput, tuple[torch.FloatTensor]]:
+ r"""
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ Final hidden states of the model on the sequence tokens.
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Positions of the first token for the labeled span.
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Positions of the last token for the labeled span.
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
+ is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Whether the question has a possible answer in the paragraph or not.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
+ Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
+ should be masked.
+ """
+ start_logits = self.start_logits(hidden_states, p_mask=p_mask)
+
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, let's remove the dimension added by batch splitting
+ for x in (start_positions, end_positions, cls_index, is_impossible):
+ if x is not None and x.dim() > 1:
+ x.squeeze_(-1)
+
+ # during training, compute the end logits based on the ground truth of the start position
+ end_logits = self.end_logits(hidden_states, start_positions=start_positions, p_mask=p_mask)
+
+ loss_fct = CrossEntropyLoss()
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if cls_index is not None and is_impossible is not None:
+ # Predict answerability from the representation of CLS and START
+ cls_logits = self.answer_class(hidden_states, start_positions=start_positions, cls_index=cls_index)
+ loss_fct_cls = nn.BCEWithLogitsLoss()
+ cls_loss = loss_fct_cls(cls_logits, is_impossible)
+
+ # note(zhiliny): by default multiply the loss by 0.5 so that the scale is comparable to start_loss and end_loss
+ total_loss += cls_loss * 0.5
+
+ return XLMSquadHeadOutput(loss=total_loss) if return_dict else (total_loss,)
+
+ else:
+ # during inference, compute the end logits based on beam search
+ bsz, slen, hsz = hidden_states.size()
+ start_log_probs = nn.functional.softmax(start_logits, dim=-1) # shape (bsz, slen)
+
+ start_top_log_probs, start_top_index = torch.topk(
+ start_log_probs, self.start_n_top, dim=-1
+ ) # shape (bsz, start_n_top)
+ start_top_index_exp = start_top_index.unsqueeze(-1).expand(-1, -1, hsz) # shape (bsz, start_n_top, hsz)
+ start_states = torch.gather(hidden_states, -2, start_top_index_exp) # shape (bsz, start_n_top, hsz)
+ start_states = start_states.unsqueeze(1).expand(-1, slen, -1, -1) # shape (bsz, slen, start_n_top, hsz)
+
+ hidden_states_expanded = hidden_states.unsqueeze(2).expand_as(
+ start_states
+ ) # shape (bsz, slen, start_n_top, hsz)
+ p_mask = p_mask.unsqueeze(-1) if p_mask is not None else None
+ end_logits = self.end_logits(hidden_states_expanded, start_states=start_states, p_mask=p_mask)
+ end_log_probs = nn.functional.softmax(end_logits, dim=1) # shape (bsz, slen, start_n_top)
+
+ end_top_log_probs, end_top_index = torch.topk(
+ end_log_probs, self.end_n_top, dim=1
+ ) # shape (bsz, end_n_top, start_n_top)
+ end_top_log_probs = end_top_log_probs.view(-1, self.start_n_top * self.end_n_top)
+ end_top_index = end_top_index.view(-1, self.start_n_top * self.end_n_top)
+
+ start_states = torch.einsum("blh,bl->bh", hidden_states, start_log_probs)
+ cls_logits = self.answer_class(hidden_states, start_states=start_states, cls_index=cls_index)
+
+ if not return_dict:
+ return (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits)
+ else:
+ return XLMSquadHeadOutput(
+ start_top_log_probs=start_top_log_probs,
+ start_top_index=start_top_index,
+ end_top_log_probs=end_top_log_probs,
+ end_top_index=end_top_index,
+ cls_logits=cls_logits,
+ )
+
+
+class XLMSequenceSummary(nn.Module):
+ r"""
+ Compute a single vector summary of a sequence hidden states.
+
+ Args:
+ config ([`XLMConfig`]):
+ The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
+ config class of your model for the default values it uses):
+
+ - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
+
+ - `"last"` -- Take the last token hidden state (like XLNet)
+ - `"first"` -- Take the first token hidden state (like Bert)
+ - `"mean"` -- Take the mean of all tokens hidden states
+ - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
+ - `"attn"` -- Not implemented now, use multi-head attention
+
+ - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
+ - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
+ (otherwise to `config.hidden_size`).
+ - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
+ another string or `None` will add no activation.
+ - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
+ - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
+ """
+
+ def __init__(self, config: XLMConfig):
+ super().__init__()
+
+ self.summary_type = getattr(config, "summary_type", "last")
+ if self.summary_type == "attn":
+ # We should use a standard multi-head attention module with absolute positional embedding for that.
+ # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
+ # We can probably just use the multi-head attention module of PyTorch >=1.1.0
+ raise NotImplementedError
+
+ self.summary = nn.Identity()
+ if hasattr(config, "summary_use_proj") and config.summary_use_proj:
+ if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
+ num_classes = config.num_labels
+ else:
+ num_classes = config.hidden_size
+ self.summary = nn.Linear(config.hidden_size, num_classes)
+
+ activation_string = getattr(config, "summary_activation", None)
+ self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
+
+ self.first_dropout = nn.Identity()
+ if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
+ self.first_dropout = nn.Dropout(config.summary_first_dropout)
+
+ self.last_dropout = nn.Identity()
+ if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
+ self.last_dropout = nn.Dropout(config.summary_last_dropout)
+
+ def forward(
+ self, hidden_states: torch.FloatTensor, cls_index: Optional[torch.LongTensor] = None
+ ) -> torch.FloatTensor:
+ """
+ Compute a single vector summary of a sequence hidden states.
+
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
+ The hidden states of the last layer.
+ cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
+ Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
+
+ Returns:
+ `torch.FloatTensor`: The summary of the sequence hidden states.
+ """
+ if self.summary_type == "last":
+ output = hidden_states[:, -1]
+ elif self.summary_type == "first":
+ output = hidden_states[:, 0]
+ elif self.summary_type == "mean":
+ output = hidden_states.mean(dim=1)
+ elif self.summary_type == "cls_index":
+ if cls_index is None:
+ cls_index = torch.full_like(
+ hidden_states[..., :1, :],
+ hidden_states.shape[-2] - 1,
+ dtype=torch.long,
+ )
+ else:
+ cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
+ cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
+ # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
+ output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
+ elif self.summary_type == "attn":
+ raise NotImplementedError
+
+ output = self.first_dropout(output)
+ output = self.summary(output)
+ output = self.activation(output)
+ output = self.last_dropout(output)
+
+ return output
+
+
+class MultiHeadAttention(nn.Module):
+ def __init__(self, n_heads, dim, config, layer_idx: int = 0):
+ super().__init__()
+ self.layer_id = layer_idx
+ self.dim = dim
+ self.n_heads = n_heads
+ self.head_dim = dim // n_heads
+ self.dropout = config.attention_dropout
+ assert self.dim % self.n_heads == 0
+
+ self.q_lin = nn.Linear(dim, dim)
+ self.k_lin = nn.Linear(dim, dim)
+ self.v_lin = nn.Linear(dim, dim)
+ self.out_lin = nn.Linear(dim, dim)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ attention_head_size = self.dim // self.n_heads
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(heads, self.n_heads, attention_head_size, self.pruned_heads)
+ # Prune linear layers
+ self.q_lin = prune_linear_layer(self.q_lin, index)
+ self.k_lin = prune_linear_layer(self.k_lin, index)
+ self.v_lin = prune_linear_layer(self.v_lin, index)
+ self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)
+ # Update hyper params
+ self.n_heads = self.n_heads - len(heads)
+ self.dim = attention_head_size * self.n_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ def forward(
+ self,
+ input,
+ mask,
+ kv=None,
+ cache=None,
+ head_mask=None,
+ output_attentions=False,
+ cache_position=None,
+ ):
+ """
+ Self-attention (if kv is None) or attention over source sentence (provided by kv).
+ """
+ # Input is (bs, qlen, dim)
+ # Mask is (bs, klen) (non-causal) or (bs, klen, klen)
+ bs, qlen, dim = input.size()
+ is_cross_attention = kv is not None
+ mask_reshape = (bs, 1, qlen, -1) if mask.dim() == 3 else (bs, 1, 1, -1)
+
+ q = self.q_lin(input).view(bs, -1, self.n_heads, self.head_dim).transpose(1, 2)
+ if cache is not None:
+ if isinstance(cache, EncoderDecoderCache):
+ is_updated = cache.is_updated.get(self.layer_id)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_value = cache.cross_attention_cache
+ else:
+ curr_past_key_value = cache.self_attention_cache
+ else:
+ curr_past_key_value = cache
+
+ current_states = kv if is_cross_attention else input
+ if is_cross_attention and cache is not None and is_updated:
+ # reuse k,v, cross_attentions
+ k = curr_past_key_value.key_cache[self.layer_id]
+ v = curr_past_key_value.value_cache[self.layer_id]
+ else:
+ k = self.k_lin(current_states)
+ v = self.v_lin(current_states)
+ k = k.view(bs, -1, self.n_heads, self.head_dim).transpose(1, 2)
+ v = v.view(bs, -1, self.n_heads, self.head_dim).transpose(1, 2)
+
+ if cache is not None:
+ # save all key/value_states to cache to be re-used for fast auto-regressive generation
+ cache_position = cache_position if not is_cross_attention else None
+ k, v = curr_past_key_value.update(k, v, self.layer_id, {"cache_position": cache_position})
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention:
+ cache.is_updated[self.layer_id] = True
+
+ q = q / math.sqrt(self.head_dim) # (bs, n_heads, qlen, head_dim)
+ scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, qlen, klen)
+ mask = (mask == 0).view(mask_reshape).expand_as(scores) # (bs, n_heads, qlen, klen)
+ scores.masked_fill_(mask, torch.finfo(scores.dtype).min) # (bs, n_heads, qlen, klen)
+
+ weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores) # (bs, n_heads, qlen, klen)
+ weights = nn.functional.dropout(weights, p=self.dropout, training=self.training) # (bs, n_heads, qlen, klen)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ weights = weights * head_mask
+
+ context = torch.matmul(weights, v) # (bs, n_heads, qlen, head_dim)
+ context = context.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * self.head_dim)
+
+ outputs = (self.out_lin(context),)
+ if output_attentions:
+ outputs = outputs + (weights,)
+ return outputs
+
+
+class TransformerFFN(nn.Module):
+ def __init__(self, in_dim, dim_hidden, out_dim, config):
+ super().__init__()
+ self.dropout = config.dropout
+ self.lin1 = nn.Linear(in_dim, dim_hidden)
+ self.lin2 = nn.Linear(dim_hidden, out_dim)
+ self.act = gelu if config.gelu_activation else nn.functional.relu
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+
+ def forward(self, input):
+ return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)
+
+ def ff_chunk(self, input):
+ x = self.lin1(input)
+ x = self.act(x)
+ x = self.lin2(x)
+ x = nn.functional.dropout(x, p=self.dropout, training=self.training)
+ return x
+
+
+@auto_docstring
+class XLMPreTrainedModel(PreTrainedModel):
+ config: XLMConfig
+ load_tf_weights = None
+ base_model_prefix = "transformer"
+
+ def __init__(self, *inputs, **kwargs):
+ super().__init__(*inputs, **kwargs)
+
+ @property
+ def dummy_inputs(self):
+ inputs_list = torch.tensor([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])
+ attns_list = torch.tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]])
+ if self.config.use_lang_emb and self.config.n_langs > 1:
+ langs_list = torch.tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]])
+ else:
+ langs_list = None
+ return {"input_ids": inputs_list, "attention_mask": attns_list, "langs": langs_list}
+
+ def _init_weights(self, module):
+ """Initialize the weights."""
+ if isinstance(module, nn.Embedding):
+ if self.config is not None and self.config.embed_init_std is not None:
+ nn.init.normal_(module.weight, mean=0, std=self.config.embed_init_std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ if isinstance(module, nn.Linear):
+ if self.config is not None and self.config.init_std is not None:
+ nn.init.normal_(module.weight, mean=0, std=self.config.init_std)
+ if module.bias is not None:
+ nn.init.constant_(module.bias, 0.0)
+ if isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ if isinstance(module, XLMModel) and self.config.sinusoidal_embeddings:
+ create_sinusoidal_embeddings(
+ self.config.max_position_embeddings, self.config.emb_dim, out=module.position_embeddings.weight
+ )
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Base class for outputs of question answering models using a `XLMSQuADHead`.
+ """
+)
+class XLMForQuestionAnsweringOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
+ Classification loss as the sum of start token, end token (and is_impossible if provided) classification
+ losses.
+ start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top config.start_n_top start token possibilities (beam-search).
+ start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top config.start_n_top start token possibilities (beam-search).
+ end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
+ (beam-search).
+ end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
+ cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the `is_impossible` label of the answers.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ start_top_log_probs: Optional[torch.FloatTensor] = None
+ start_top_index: Optional[torch.LongTensor] = None
+ end_top_log_probs: Optional[torch.FloatTensor] = None
+ end_top_index: Optional[torch.LongTensor] = None
+ cls_logits: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@auto_docstring
+class XLMModel(XLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ # encoder / decoder, output layer
+ self.is_encoder = config.is_encoder
+ self.is_decoder = not config.is_encoder
+ if self.is_decoder:
+ raise NotImplementedError("Currently XLM can only be used as an encoder")
+ # self.with_output = with_output
+ self.causal = config.causal
+
+ # dictionary / languages
+ self.n_langs = config.n_langs
+ self.use_lang_emb = config.use_lang_emb
+ self.n_words = config.n_words
+ self.eos_index = config.eos_index
+ self.pad_index = config.pad_index
+ # self.dico = dico
+ # self.id2lang = config.id2lang
+ # self.lang2id = config.lang2id
+ # assert len(self.dico) == self.n_words
+ # assert len(self.id2lang) == len(self.lang2id) == self.n_langs
+
+ # model parameters
+ self.dim = config.emb_dim # 512 by default
+ self.hidden_dim = self.dim * 4 # 2048 by default
+ self.n_heads = config.n_heads # 8 by default
+ self.n_layers = config.n_layers
+ self.dropout = config.dropout
+ self.attention_dropout = config.attention_dropout
+ assert self.dim % self.n_heads == 0, "transformer dim must be a multiple of n_heads"
+
+ # embeddings
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.dim)
+ if config.n_langs > 1 and config.use_lang_emb:
+ self.lang_embeddings = nn.Embedding(self.n_langs, self.dim)
+ self.embeddings = nn.Embedding(self.n_words, self.dim, padding_idx=self.pad_index)
+ self.layer_norm_emb = nn.LayerNorm(self.dim, eps=config.layer_norm_eps)
+
+ # transformer layers
+ self.attentions = nn.ModuleList()
+ self.layer_norm1 = nn.ModuleList()
+ self.ffns = nn.ModuleList()
+ self.layer_norm2 = nn.ModuleList()
+ # if self.is_decoder:
+ # self.layer_norm15 = nn.ModuleList()
+ # self.encoder_attn = nn.ModuleList()
+
+ for i in range(self.n_layers):
+ self.attentions.append(MultiHeadAttention(self.n_heads, self.dim, config=config, layer_idx=i))
+ self.layer_norm1.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
+ # if self.is_decoder:
+ # self.layer_norm15.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
+ # self.encoder_attn.append(MultiHeadAttention(self.n_heads, self.dim, dropout=self.attention_dropout))
+ self.ffns.append(TransformerFFN(self.dim, self.hidden_dim, self.dim, config=config))
+ self.layer_norm2.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
+
+ if hasattr(config, "pruned_heads"):
+ pruned_heads = config.pruned_heads.copy().items()
+ config.pruned_heads = {}
+ for layer, heads in pruned_heads:
+ if self.attentions[int(layer)].n_heads == config.n_heads:
+ self.prune_heads({int(layer): list(map(int, heads))})
+
+ # Initialize weights and apply final processing
+ self.post_init()
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+
+ def get_input_embeddings(self):
+ return self.embeddings
+
+ def set_input_embeddings(self, new_embeddings):
+ self.embeddings = new_embeddings
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.attentions[layer].prune_heads(heads)
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ langs: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ lengths: Optional[torch.Tensor] = None,
+ cache: Optional[dict[str, torch.Tensor]] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.Tensor] = None,
+ **kwargs, # Dummy kwargs for now
+ ) -> Union[tuple, BaseModelOutput]:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if input_ids is not None:
+ bs, slen = input_ids.size()
+ else:
+ bs, slen = inputs_embeds.size()[:-1]
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if cache is None:
+ cache = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+
+ if isinstance(cache, tuple):
+ cache = EncoderDecoderCache.from_legacy_cache(cache)
+
+ if lengths is None:
+ if input_ids is not None:
+ lengths = (input_ids != self.pad_index).sum(dim=1).long()
+ else:
+ lengths = torch.tensor([slen] * bs, device=device)
+
+ # check inputs
+ assert lengths.size(0) == bs
+ assert lengths.max().item() <= slen
+
+ # generate masks
+ mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)
+
+ # position_ids
+ if position_ids is None:
+ position_ids = self.position_ids[:, :slen]
+ else:
+ assert position_ids.size() == (bs, slen) # (slen, bs)
+
+ # langs
+ if langs is not None:
+ assert langs.size() == (bs, slen) # (slen, bs)
+
+ # Prepare head mask if needed
+ head_mask = self.get_head_mask(head_mask, self.config.n_layers)
+
+ # do not recompute cached elements
+ if cache is not None and input_ids is not None:
+ _slen = slen - cache.get_seq_length()
+ input_ids = input_ids[:, -_slen:]
+ position_ids = position_ids[:, -_slen:]
+ if langs is not None:
+ langs = langs[:, -_slen:]
+ mask = mask[:, -_slen:]
+ attn_mask = attn_mask[:, -_slen:]
+
+ # embeddings
+ if inputs_embeds is None:
+ inputs_embeds = self.embeddings(input_ids)
+
+ tensor = inputs_embeds + self.position_embeddings(position_ids).expand_as(inputs_embeds)
+ if langs is not None and self.use_lang_emb and self.n_langs > 1:
+ tensor = tensor + self.lang_embeddings(langs)
+ if token_type_ids is not None:
+ tensor = tensor + self.embeddings(token_type_ids)
+ tensor = self.layer_norm_emb(tensor)
+ tensor = nn.functional.dropout(tensor, p=self.dropout, training=self.training)
+ tensor *= mask.unsqueeze(-1).to(tensor.dtype)
+
+ # transformer layers
+ hidden_states = () if output_hidden_states else None
+ attentions = () if output_attentions else None
+ for i in range(self.n_layers):
+ if output_hidden_states:
+ hidden_states = hidden_states + (tensor,)
+
+ # self attention
+ attn_outputs = self.attentions[i](
+ tensor,
+ attn_mask,
+ cache=cache,
+ head_mask=head_mask[i],
+ output_attentions=output_attentions,
+ cache_position=cache_position,
+ )
+ attn = attn_outputs[0]
+ if output_attentions:
+ attentions = attentions + (attn_outputs[1],)
+ attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)
+ tensor = tensor + attn
+ tensor = self.layer_norm1[i](tensor)
+
+ # FFN
+ tensor = tensor + self.ffns[i](tensor)
+ tensor = self.layer_norm2[i](tensor)
+ tensor *= mask.unsqueeze(-1).to(tensor.dtype)
+
+ # Add last hidden state
+ if output_hidden_states:
+ hidden_states = hidden_states + (tensor,)
+
+ if not return_dict:
+ return tuple(v for v in [tensor, hidden_states, attentions] if v is not None)
+ return BaseModelOutput(last_hidden_state=tensor, hidden_states=hidden_states, attentions=attentions)
+
+
+class XLMPredLayer(nn.Module):
+ """
+ Prediction layer (cross_entropy or adaptive_softmax).
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.asm = config.asm
+ self.n_words = config.n_words
+ self.pad_index = config.pad_index
+ dim = config.emb_dim
+
+ if config.asm is False:
+ self.proj = nn.Linear(dim, config.n_words, bias=True)
+ else:
+ self.proj = nn.AdaptiveLogSoftmaxWithLoss(
+ in_features=dim,
+ n_classes=config.n_words,
+ cutoffs=config.asm_cutoffs,
+ div_value=config.asm_div_value,
+ head_bias=True, # default is False
+ )
+
+ def forward(self, x, y=None):
+ """Compute the loss, and optionally the scores."""
+ outputs = ()
+ if self.asm is False:
+ scores = self.proj(x)
+ outputs = (scores,) + outputs
+ if y is not None:
+ loss = nn.functional.cross_entropy(scores.view(-1, self.n_words), y.view(-1), reduction="mean")
+ outputs = (loss,) + outputs
+ else:
+ scores = self.proj.log_prob(x)
+ outputs = (scores,) + outputs
+ if y is not None:
+ _, loss = self.proj(x, y)
+ outputs = (loss,) + outputs
+
+ return outputs
+
+
+@auto_docstring(
+ custom_intro="""
+ The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
+ embeddings).
+ """
+)
+class XLMWithLMHeadModel(XLMPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = ["pred_layer.proj.weight"]
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.transformer = XLMModel(config)
+ self.pred_layer = XLMPredLayer(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.pred_layer.proj
+
+ def set_output_embeddings(self, new_embeddings):
+ self.pred_layer.proj = new_embeddings
+
+ def prepare_inputs_for_generation(self, input_ids, **kwargs):
+ # Overwritten -- this model uses config options to prepare inputs
+
+ mask_token_id = self.config.mask_token_id
+ lang_id = self.config.lang_id
+
+ effective_batch_size = input_ids.shape[0]
+ mask_token = torch.full((effective_batch_size, 1), mask_token_id, dtype=torch.long, device=input_ids.device)
+ input_ids = torch.cat([input_ids, mask_token], dim=1)
+ if lang_id is not None:
+ langs = torch.full_like(input_ids, lang_id)
+ else:
+ langs = None
+ return {"input_ids": input_ids, "langs": langs}
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ langs: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ lengths: Optional[torch.Tensor] = None,
+ cache: Optional[dict[str, torch.Tensor]] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[tuple, MaskedLMOutput]:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ **kwargs,
+ )
+
+ output = transformer_outputs[0]
+ outputs = self.pred_layer(output, labels) # (loss, logits) or (logits,) depending on if labels are provided.
+
+ if not return_dict:
+ return outputs + transformer_outputs[1:]
+
+ return MaskedLMOutput(
+ loss=outputs[0] if labels is not None else None,
+ logits=outputs[0] if labels is None else outputs[1],
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g.
+ for GLUE tasks.
+ """
+)
+class XLMForSequenceClassification(XLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.transformer = XLMModel(config)
+ self.sequence_summary = XLMSequenceSummary(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ langs: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ lengths: Optional[torch.Tensor] = None,
+ cache: Optional[dict[str, torch.Tensor]] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, SequenceClassifierOutput]:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ output = transformer_outputs[0]
+ logits = self.sequence_summary(output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """
+)
+class XLMForQuestionAnsweringSimple(XLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.transformer = XLMModel(config)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ langs: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ lengths: Optional[torch.Tensor] = None,
+ cache: Optional[dict[str, torch.Tensor]] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ start_positions: Optional[torch.Tensor] = None,
+ end_positions: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, QuestionAnsweringModelOutput]:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = transformer_outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + transformer_outputs[1:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMForQuestionAnswering(XLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.transformer = XLMModel(config)
+ self.qa_outputs = XLMSQuADHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ langs: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ lengths: Optional[torch.Tensor] = None,
+ cache: Optional[dict[str, torch.Tensor]] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ start_positions: Optional[torch.Tensor] = None,
+ end_positions: Optional[torch.Tensor] = None,
+ is_impossible: Optional[torch.Tensor] = None,
+ cls_index: Optional[torch.Tensor] = None,
+ p_mask: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, XLMForQuestionAnsweringOutput]:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels whether a question has an answer or no answer (SQuAD 2.0)
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the classification token to use as input for computing plausibility of the
+ answer.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be
+ masked. 0.0 mean token is not masked.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLMForQuestionAnswering
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
+ >>> model = XLMForQuestionAnswering.from_pretrained("FacebookAI/xlm-mlm-en-2048")
+
+ >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(
+ ... 0
+ ... ) # Batch size 1
+ >>> start_positions = torch.tensor([1])
+ >>> end_positions = torch.tensor([3])
+
+ >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
+ >>> loss = outputs.loss
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ output = transformer_outputs[0]
+
+ outputs = self.qa_outputs(
+ output,
+ start_positions=start_positions,
+ end_positions=end_positions,
+ cls_index=cls_index,
+ is_impossible=is_impossible,
+ p_mask=p_mask,
+ return_dict=return_dict,
+ )
+
+ if not return_dict:
+ return outputs + transformer_outputs[1:]
+
+ return XLMForQuestionAnsweringOutput(
+ loss=outputs.loss,
+ start_top_log_probs=outputs.start_top_log_probs,
+ start_top_index=outputs.start_top_index,
+ end_top_log_probs=outputs.end_top_log_probs,
+ end_top_index=outputs.end_top_index,
+ cls_logits=outputs.cls_logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMForTokenClassification(XLMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.transformer = XLMModel(config)
+ self.dropout = nn.Dropout(config.dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ langs: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ lengths: Optional[torch.Tensor] = None,
+ cache: Optional[dict[str, torch.Tensor]] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, TokenClassifierOutput]:
+ r"""
+ langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMForMultipleChoice(XLMPreTrainedModel):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+
+ self.transformer = XLMModel(config)
+ self.sequence_summary = XLMSequenceSummary(config)
+ self.logits_proj = nn.Linear(config.num_labels, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ langs: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ lengths: Optional[torch.Tensor] = None,
+ cache: Optional[dict[str, torch.Tensor]] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, MultipleChoiceModelOutput]:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ langs (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
+ languages ids which can be obtained from the language names by using two conversion mappings provided in
+ the configuration of the model (only provided for multilingual models). More precisely, the *language name
+ to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
+ *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
+
+ See usage examples detailed in the [multilingual documentation](../multilingual).
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Length of each sentence that can be used to avoid performing attention on padding token indices. You can
+ also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
+ `[0, ..., input_ids.size(-1)]`.
+ cache (`dict[str, torch.FloatTensor]`, *optional*):
+ Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
+ decoding.
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ langs = langs.view(-1, langs.size(-1)) if langs is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ if lengths is not None:
+ logger.warning(
+ "The `lengths` parameter cannot be used with the XLM multiple choice models. Please use the "
+ "attention mask instead."
+ )
+ lengths = None
+
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ langs=langs,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ lengths=lengths,
+ cache=cache,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ output = transformer_outputs[0]
+ logits = self.sequence_summary(output)
+ logits = self.logits_proj(logits)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = [
+ "XLMForMultipleChoice",
+ "XLMForQuestionAnswering",
+ "XLMForQuestionAnsweringSimple",
+ "XLMForSequenceClassification",
+ "XLMForTokenClassification",
+ "XLMModel",
+ "XLMPreTrainedModel",
+ "XLMWithLMHeadModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/tokenization_xlm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/tokenization_xlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..14d8aae2764b71b23b2a88374262cbd8d360ceb8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm/tokenization_xlm.py
@@ -0,0 +1,577 @@
+# coding=utf-8
+# Copyright 2019 The Open AI Team Authors and The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for XLM."""
+
+import json
+import os
+import re
+import sys
+import unicodedata
+from typing import Optional
+
+from ...tokenization_utils import PreTrainedTokenizer
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {
+ "vocab_file": "vocab.json",
+ "merges_file": "merges.txt",
+}
+
+
+def get_pairs(word):
+ """
+ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length
+ strings)
+ """
+ pairs = set()
+ prev_char = word[0]
+ for char in word[1:]:
+ pairs.add((prev_char, char))
+ prev_char = char
+ return pairs
+
+
+def lowercase_and_remove_accent(text):
+ """
+ Lowercase and strips accents from a piece of text based on
+ https://github.com/facebookresearch/XLM/blob/master/tools/lowercase_and_remove_accent.py
+ """
+ text = " ".join(text)
+ text = text.lower()
+ text = unicodedata.normalize("NFD", text)
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat == "Mn":
+ continue
+ output.append(char)
+ return "".join(output).lower().split(" ")
+
+
+def replace_unicode_punct(text):
+ """
+ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl
+ """
+ text = text.replace(",", ",")
+ text = re.sub(r"。\s*", ". ", text)
+ text = text.replace("、", ",")
+ text = text.replace("”", '"')
+ text = text.replace("“", '"')
+ text = text.replace("∶", ":")
+ text = text.replace(":", ":")
+ text = text.replace("?", "?")
+ text = text.replace("《", '"')
+ text = text.replace("》", '"')
+ text = text.replace(")", ")")
+ text = text.replace("!", "!")
+ text = text.replace("(", "(")
+ text = text.replace(";", ";")
+ text = text.replace("1", "1")
+ text = text.replace("」", '"')
+ text = text.replace("「", '"')
+ text = text.replace("0", "0")
+ text = text.replace("3", "3")
+ text = text.replace("2", "2")
+ text = text.replace("5", "5")
+ text = text.replace("6", "6")
+ text = text.replace("9", "9")
+ text = text.replace("7", "7")
+ text = text.replace("8", "8")
+ text = text.replace("4", "4")
+ text = re.sub(r".\s*", ". ", text)
+ text = text.replace("~", "~")
+ text = text.replace("’", "'")
+ text = text.replace("…", "...")
+ text = text.replace("━", "-")
+ text = text.replace("〈", "<")
+ text = text.replace("〉", ">")
+ text = text.replace("【", "[")
+ text = text.replace("】", "]")
+ text = text.replace("%", "%")
+ return text
+
+
+def remove_non_printing_char(text):
+ """
+ Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl
+ """
+ output = []
+ for char in text:
+ cat = unicodedata.category(char)
+ if cat.startswith("C"):
+ continue
+ output.append(char)
+ return "".join(output)
+
+
+def romanian_preprocessing(text):
+ """Sennrich's WMT16 scripts for Romanian preprocessing, used by model `FacebookAI/xlm-mlm-enro-1024`"""
+ # https://github.com/rsennrich/wmt16-scripts/blob/master/preprocess/normalise-romanian.py
+ text = text.replace("\u015e", "\u0218").replace("\u015f", "\u0219")
+ text = text.replace("\u0162", "\u021a").replace("\u0163", "\u021b")
+ # https://github.com/rsennrich/wmt16-scripts/blob/master/preprocess/remove-diacritics.py
+ text = text.replace("\u0218", "S").replace("\u0219", "s") # s-comma
+ text = text.replace("\u021a", "T").replace("\u021b", "t") # t-comma
+ text = text.replace("\u0102", "A").replace("\u0103", "a")
+ text = text.replace("\u00c2", "A").replace("\u00e2", "a")
+ text = text.replace("\u00ce", "I").replace("\u00ee", "i")
+ return text
+
+
+class XLMTokenizer(PreTrainedTokenizer):
+ """
+ Construct an XLM tokenizer. Based on Byte-Pair Encoding. The tokenization process is the following:
+
+ - Moses preprocessing and tokenization for most supported languages.
+ - Language specific tokenization for Chinese (Jieba), Japanese (KyTea) and Thai (PyThaiNLP).
+ - Optionally lowercases and normalizes all inputs text.
+ - The arguments `special_tokens` and the function `set_special_tokens`, can be used to add additional symbols (like
+ "__classify__") to a vocabulary.
+ - The `lang2id` attribute maps the languages supported by the model with their IDs if provided (automatically set
+ for pretrained vocabularies).
+ - The `id2lang` attributes does reverse mapping if provided (automatically set for pretrained vocabularies).
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Vocabulary file.
+ merges_file (`str`):
+ Merges file.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ additional_special_tokens (`List[str]`, *optional*, defaults to `['', '', '', '', '', '', '', '', '', '']`):
+ List of additional special tokens.
+ lang2id (`Dict[str, int]`, *optional*):
+ Dictionary mapping languages string identifiers to their IDs.
+ id2lang (`Dict[int, str]`, *optional*):
+ Dictionary mapping language IDs to their string identifiers.
+ do_lowercase_and_remove_accent (`bool`, *optional*, defaults to `True`):
+ Whether to lowercase and remove accents when tokenizing.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+
+ def __init__(
+ self,
+ vocab_file,
+ merges_file,
+ unk_token="",
+ bos_token="",
+ sep_token="",
+ pad_token="",
+ cls_token="",
+ mask_token="",
+ additional_special_tokens=[
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ],
+ lang2id=None,
+ id2lang=None,
+ do_lowercase_and_remove_accent=True,
+ **kwargs,
+ ):
+ try:
+ import sacremoses
+ except ImportError:
+ raise ImportError(
+ "You need to install sacremoses to use XLMTokenizer. "
+ "See https://pypi.org/project/sacremoses/ for installation."
+ )
+
+ self.sm = sacremoses
+
+ # cache of sm.MosesPunctNormalizer instance
+ self.cache_moses_punct_normalizer = {}
+ # cache of sm.MosesTokenizer instance
+ self.cache_moses_tokenizer = {}
+ self.lang_with_custom_tokenizer = {"zh", "th", "ja"}
+ # True for current supported model (v1.2.0), False for XLM-17 & 100
+ self.do_lowercase_and_remove_accent = do_lowercase_and_remove_accent
+ self.lang2id = lang2id
+ self.id2lang = id2lang
+ if lang2id is not None and id2lang is not None:
+ assert len(lang2id) == len(id2lang)
+
+ self.ja_word_tokenizer = None
+ self.zh_word_tokenizer = None
+
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
+ self.encoder = json.load(vocab_handle)
+ self.decoder = {v: k for k, v in self.encoder.items()}
+ with open(merges_file, encoding="utf-8") as merges_handle:
+ merges = merges_handle.read().split("\n")[:-1]
+ merges = [tuple(merge.split()[:2]) for merge in merges]
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
+ self.cache = {}
+ super().__init__(
+ unk_token=unk_token,
+ bos_token=bos_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ additional_special_tokens=additional_special_tokens,
+ lang2id=lang2id,
+ id2lang=id2lang,
+ do_lowercase_and_remove_accent=do_lowercase_and_remove_accent,
+ **kwargs,
+ )
+
+ @property
+ def do_lower_case(self):
+ return self.do_lowercase_and_remove_accent
+
+ def moses_punct_norm(self, text, lang):
+ if lang not in self.cache_moses_punct_normalizer:
+ punct_normalizer = self.sm.MosesPunctNormalizer(lang=lang)
+ self.cache_moses_punct_normalizer[lang] = punct_normalizer
+ else:
+ punct_normalizer = self.cache_moses_punct_normalizer[lang]
+ return punct_normalizer.normalize(text)
+
+ def moses_tokenize(self, text, lang):
+ if lang not in self.cache_moses_tokenizer:
+ moses_tokenizer = self.sm.MosesTokenizer(lang=lang)
+ self.cache_moses_tokenizer[lang] = moses_tokenizer
+ else:
+ moses_tokenizer = self.cache_moses_tokenizer[lang]
+ return moses_tokenizer.tokenize(text, return_str=False, escape=False)
+
+ def moses_pipeline(self, text, lang):
+ text = replace_unicode_punct(text)
+ text = self.moses_punct_norm(text, lang)
+ text = remove_non_printing_char(text)
+ return text
+
+ def ja_tokenize(self, text):
+ if self.ja_word_tokenizer is None:
+ try:
+ import Mykytea
+
+ self.ja_word_tokenizer = Mykytea.Mykytea(
+ f"-model {os.path.expanduser('~')}/local/share/kytea/model.bin"
+ )
+ except (AttributeError, ImportError):
+ logger.error(
+ "Make sure you install KyTea (https://github.com/neubig/kytea) and it's python wrapper"
+ " (https://github.com/chezou/Mykytea-python) with the following steps"
+ )
+ logger.error("1. git clone git@github.com:neubig/kytea.git && cd kytea")
+ logger.error("2. autoreconf -i")
+ logger.error("3. ./configure --prefix=$HOME/local")
+ logger.error("4. make && make install")
+ logger.error("5. pip install kytea")
+ raise
+ return list(self.ja_word_tokenizer.getWS(text))
+
+ @property
+ def vocab_size(self):
+ return len(self.encoder)
+
+ def get_vocab(self):
+ return dict(self.encoder, **self.added_tokens_encoder)
+
+ def bpe(self, token):
+ word = tuple(token[:-1]) + (token[-1] + "",)
+ if token in self.cache:
+ return self.cache[token]
+ pairs = get_pairs(word)
+
+ if not pairs:
+ return token + ""
+
+ while True:
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
+ if bigram not in self.bpe_ranks:
+ break
+ first, second = bigram
+ new_word = []
+ i = 0
+ while i < len(word):
+ try:
+ j = word.index(first, i)
+ except ValueError:
+ new_word.extend(word[i:])
+ break
+ else:
+ new_word.extend(word[i:j])
+ i = j
+
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
+ new_word.append(first + second)
+ i += 2
+ else:
+ new_word.append(word[i])
+ i += 1
+ new_word = tuple(new_word)
+ word = new_word
+ if len(word) == 1:
+ break
+ else:
+ pairs = get_pairs(word)
+ word = " ".join(word)
+ if word == "\n ":
+ word = "\n"
+ self.cache[token] = word
+ return word
+
+ def _tokenize(self, text, lang="en", bypass_tokenizer=False):
+ """
+ Tokenize a string given language code. For Chinese, Japanese and Thai, we use a language specific tokenizer.
+ Otherwise, we use Moses.
+
+ Details of tokenization:
+
+ - [sacremoses](https://github.com/alvations/sacremoses): port of Moses
+ - Install with `pip install sacremoses`
+ - [pythainlp](https://github.com/PyThaiNLP/pythainlp): Thai tokenizer
+ - Install with `pip install pythainlp`
+ - [kytea](https://github.com/chezou/Mykytea-python): Japanese tokenizer, wrapper of
+ [KyTea](https://github.com/neubig/kytea)
+ - Install with the following steps:
+
+ ::
+
+ git clone git@github.com:neubig/kytea.git && cd kytea autoreconf -i ./configure --prefix=$HOME/local
+ make && make install pip install kytea
+
+ - [jieba](https://github.com/fxsjy/jieba): Chinese tokenizer (*)
+ - Install with `pip install jieba`
+
+ (*) The original XLM used [Stanford
+ Segmenter](https://nlp.stanford.edu/software/stanford-segmenter-2018-10-16.zip). However, the wrapper
+ (`nltk.tokenize.stanford_segmenter`) is slow due to JVM overhead, and it will be deprecated. Jieba is a lot
+ faster and pip-installable. Note there is some mismatch with the Stanford Segmenter. It should be fine if you
+ fine-tune the model with Chinese supervisionself. If you want the same exact behaviour, use the original XLM
+ [preprocessing script](https://github.com/facebookresearch/XLM/tree/master/tools) to tokenize the sentence
+ externally, and set `bypass_tokenizer=True` to bypass the tokenizer.
+
+ Args:
+ - lang: ISO language code (default = 'en') (string). Languages should belong of the model supported
+ languages. However, we don't enforce it.
+ - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False)
+ (bool). If True, we only apply BPE.
+
+ Returns:
+ List of tokens.
+ """
+ if lang and self.lang2id and lang not in self.lang2id:
+ logger.error(
+ "Supplied language code not found in lang2id mapping. Please check that your language is supported by"
+ " the loaded pretrained model."
+ )
+ if bypass_tokenizer:
+ text = text.split()
+ elif lang not in self.lang_with_custom_tokenizer:
+ text = self.moses_pipeline(text, lang=lang)
+ # TODO: make sure we are using `FacebookAI/xlm-mlm-enro-1024`, since XLM-100 doesn't have this step
+ if lang == "ro":
+ text = romanian_preprocessing(text)
+ text = self.moses_tokenize(text, lang=lang)
+ elif lang == "th":
+ text = self.moses_pipeline(text, lang=lang)
+ try:
+ if "pythainlp" not in sys.modules:
+ from pythainlp.tokenize import word_tokenize as th_word_tokenize
+ else:
+ th_word_tokenize = sys.modules["pythainlp"].word_tokenize
+ except (AttributeError, ImportError):
+ logger.error(
+ "Make sure you install PyThaiNLP (https://github.com/PyThaiNLP/pythainlp) with the following steps"
+ )
+ logger.error("1. pip install pythainlp")
+ raise
+ text = th_word_tokenize(text)
+ elif lang == "zh":
+ try:
+ if "jieba" not in sys.modules:
+ import jieba
+ else:
+ jieba = sys.modules["jieba"]
+ except (AttributeError, ImportError):
+ logger.error("Make sure you install Jieba (https://github.com/fxsjy/jieba) with the following steps")
+ logger.error("1. pip install jieba")
+ raise
+ text = " ".join(jieba.cut(text))
+ text = self.moses_pipeline(text, lang=lang)
+ text = text.split()
+ elif lang == "ja":
+ text = self.moses_pipeline(text, lang=lang)
+ text = self.ja_tokenize(text)
+ else:
+ raise ValueError("It should not reach here")
+
+ if self.do_lowercase_and_remove_accent and not bypass_tokenizer:
+ text = lowercase_and_remove_accent(text)
+
+ split_tokens = []
+ for token in text:
+ if token:
+ split_tokens.extend(list(self.bpe(token).split(" ")))
+
+ return split_tokens
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.decoder.get(index, self.unk_token)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (string) in a single string."""
+ out_string = "".join(tokens).replace("", " ").strip()
+ return out_string
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An XLM sequence has the following format:
+
+ - single sequence: ` X `
+ - pair of sequences: ` A B `
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+
+ """
+ bos = [self.bos_token_id]
+ sep = [self.sep_token_id]
+
+ if token_ids_1 is None:
+ return bos + token_ids_0 + sep
+ return bos + token_ids_0 + sep + token_ids_1 + sep
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`List[int]`):
+ List of IDs.
+ token_ids_1 (`List[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is not None:
+ return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
+ return [1] + ([0] * len(token_ids_0)) + [1]
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+ merge_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
+ )
+
+ with open(vocab_file, "w", encoding="utf-8") as f:
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
+
+ index = 0
+ with open(merge_file, "w", encoding="utf-8") as writer:
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
+ if index != token_index:
+ logger.warning(
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
+ " Please check that the tokenizer is not corrupted!"
+ )
+ index = token_index
+ writer.write(" ".join(bpe_tokens) + "\n")
+ index += 1
+
+ return vocab_file, merge_file
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state["sm"] = None
+ return state
+
+ def __setstate__(self, d):
+ self.__dict__ = d
+
+ try:
+ import sacremoses
+ except ImportError:
+ raise ImportError(
+ "You need to install sacremoses to use XLMTokenizer. "
+ "See https://pypi.org/project/sacremoses/ for installation."
+ )
+
+ self.sm = sacremoses
+
+
+__all__ = ["XLMTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e684c6c9b2c2c261fb4e6ad6998daa9bea6191e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/__init__.py
@@ -0,0 +1,31 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xlm_roberta import *
+ from .modeling_flax_xlm_roberta import *
+ from .modeling_tf_xlm_roberta import *
+ from .modeling_xlm_roberta import *
+ from .tokenization_xlm_roberta import *
+ from .tokenization_xlm_roberta_fast import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/configuration_xlm_roberta.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/configuration_xlm_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..97d6245cb1d7ea772a3606ca5c8d981f8f8ffdf7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/configuration_xlm_roberta.py
@@ -0,0 +1,157 @@
+# coding=utf-8
+# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""XLM-RoBERTa configuration"""
+
+from collections import OrderedDict
+from collections.abc import Mapping
+
+from ...configuration_utils import PretrainedConfig
+from ...onnx import OnnxConfig
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class XLMRobertaConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`XLMRobertaModel`] or a [`TFXLMRobertaModel`]. It
+ is used to instantiate a XLM-RoBERTa model according to the specified arguments, defining the model architecture.
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the XLMRoBERTa
+ [FacebookAI/xlm-roberta-base](https://huggingface.co/FacebookAI/xlm-roberta-base) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 30522):
+ Vocabulary size of the XLM-RoBERTa model. Defines the number of different tokens that can be represented by
+ the `inputs_ids` passed when calling [`XLMRobertaModel`] or [`TFXLMRobertaModel`].
+ hidden_size (`int`, *optional*, defaults to 768):
+ Dimensionality of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 3072):
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention probabilities.
+ max_position_embeddings (`int`, *optional*, defaults to 512):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ type_vocab_size (`int`, *optional*, defaults to 2):
+ The vocabulary size of the `token_type_ids` passed when calling [`XLMRobertaModel`] or
+ [`TFXLMRobertaModel`].
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
+ with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
+ is_decoder (`bool`, *optional*, defaults to `False`):
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+ classifier_dropout (`float`, *optional*):
+ The dropout ratio for the classification head.
+
+ Examples:
+
+ ```python
+ >>> from transformers import XLMRobertaConfig, XLMRobertaModel
+
+ >>> # Initializing a XLM-RoBERTa FacebookAI/xlm-roberta-base style configuration
+ >>> configuration = XLMRobertaConfig()
+
+ >>> # Initializing a model (with random weights) from the FacebookAI/xlm-roberta-base style configuration
+ >>> model = XLMRobertaModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xlm-roberta"
+
+ def __init__(
+ self,
+ vocab_size=30522,
+ hidden_size=768,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=512,
+ type_vocab_size=2,
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ pad_token_id=1,
+ bos_token_id=0,
+ eos_token_id=2,
+ position_embedding_type="absolute",
+ use_cache=True,
+ classifier_dropout=None,
+ **kwargs,
+ ):
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
+
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.hidden_act = hidden_act
+ self.intermediate_size = intermediate_size
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.max_position_embeddings = max_position_embeddings
+ self.type_vocab_size = type_vocab_size
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.position_embedding_type = position_embedding_type
+ self.use_cache = use_cache
+ self.classifier_dropout = classifier_dropout
+
+
+# Copied from transformers.models.roberta.configuration_roberta.RobertaOnnxConfig with Roberta->XLMRoberta
+class XLMRobertaOnnxConfig(OnnxConfig):
+ @property
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
+ if self.task == "multiple-choice":
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
+ else:
+ dynamic_axis = {0: "batch", 1: "sequence"}
+ return OrderedDict(
+ [
+ ("input_ids", dynamic_axis),
+ ("attention_mask", dynamic_axis),
+ ]
+ )
+
+
+__all__ = ["XLMRobertaConfig", "XLMRobertaOnnxConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_flax_xlm_roberta.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_flax_xlm_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdbc06620a1bf85c0a752eb6f64a8a6e351afbf3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_flax_xlm_roberta.py
@@ -0,0 +1,1511 @@
+# coding=utf-8
+# Copyright 2022 Facebook AI Research and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Flax XLM-RoBERTa model."""
+
+from typing import Callable, Optional
+
+import flax.linen as nn
+import jax
+import jax.numpy as jnp
+import numpy as np
+from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
+from flax.linen import combine_masks, make_causal_mask
+from flax.linen import partitioning as nn_partitioning
+from flax.linen.attention import dot_product_attention_weights
+from flax.traverse_util import flatten_dict, unflatten_dict
+from jax import lax
+
+from ...modeling_flax_outputs import (
+ FlaxBaseModelOutputWithPastAndCrossAttentions,
+ FlaxBaseModelOutputWithPooling,
+ FlaxBaseModelOutputWithPoolingAndCrossAttentions,
+ FlaxCausalLMOutputWithCrossAttentions,
+ FlaxMaskedLMOutput,
+ FlaxMultipleChoiceModelOutput,
+ FlaxQuestionAnsweringModelOutput,
+ FlaxSequenceClassifierOutput,
+ FlaxTokenClassifierOutput,
+)
+from ...modeling_flax_utils import ACT2FN, FlaxPreTrainedModel, append_call_sample_docstring, overwrite_call_docstring
+from ...utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging
+from .configuration_xlm_roberta import XLMRobertaConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "FacebookAI/xlm-roberta-base"
+_CONFIG_FOR_DOC = "XLMRobertaConfig"
+
+remat = nn_partitioning.remat
+
+
+# Copied from transformers.models.roberta.modeling_flax_roberta.create_position_ids_from_input_ids
+def create_position_ids_from_input_ids(input_ids, padding_idx):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ input_ids: jnp.ndarray
+ padding_idx: int
+
+ Returns: jnp.ndarray
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = (input_ids != padding_idx).astype("i4")
+
+ if mask.ndim > 2:
+ mask = mask.reshape((-1, mask.shape[-1]))
+ incremental_indices = jnp.cumsum(mask, axis=1).astype("i4") * mask
+ incremental_indices = incremental_indices.reshape(input_ids.shape)
+ else:
+ incremental_indices = jnp.cumsum(mask, axis=1).astype("i4") * mask
+
+ return incremental_indices.astype("i4") + padding_idx
+
+
+XLM_ROBERTA_START_DOCSTRING = r"""
+
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading, saving and converting weights from PyTorch models)
+
+ This model is also a
+ [flax.linen.Module](https://flax.readthedocs.io/en/latest/api_reference/flax.linen/module.html) subclass. Use it as
+ a regular Flax linen Module and refer to the Flax documentation for all matter related to general usage and
+ behavior.
+
+ Finally, this model supports inherent JAX features such as:
+
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
+
+ Parameters:
+ config ([`XLMRobertaConfig`]): Model configuration class with all the parameters of the
+ model. Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+XLM_ROBERTA_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`numpy.ndarray` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`numpy.ndarray` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ token_type_ids (`numpy.ndarray` of shape `({0})`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`numpy.ndarray` of shape `({0})`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+ head_mask (`numpy.ndarray` of shape `({0})`, `optional):
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertEmbeddings with Bert->XLMRoberta
+class FlaxXLMRobertaEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
+
+ def setup(self):
+ self.word_embeddings = nn.Embed(
+ self.config.vocab_size,
+ self.config.hidden_size,
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
+ dtype=self.dtype,
+ )
+ self.position_embeddings = nn.Embed(
+ self.config.max_position_embeddings,
+ self.config.hidden_size,
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
+ dtype=self.dtype,
+ )
+ self.token_type_embeddings = nn.Embed(
+ self.config.type_vocab_size,
+ self.config.hidden_size,
+ embedding_init=jax.nn.initializers.normal(stddev=self.config.initializer_range),
+ dtype=self.dtype,
+ )
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
+
+ def __call__(self, input_ids, token_type_ids, position_ids, attention_mask, deterministic: bool = True):
+ # Embed
+ inputs_embeds = self.word_embeddings(input_ids.astype("i4"))
+ position_embeds = self.position_embeddings(position_ids.astype("i4"))
+ token_type_embeddings = self.token_type_embeddings(token_type_ids.astype("i4"))
+
+ # Sum all embeddings
+ hidden_states = inputs_embeds + token_type_embeddings + position_embeds
+
+ # Layer Norm
+ hidden_states = self.LayerNorm(hidden_states)
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertSelfAttention with Bert->XLMRoberta
+class FlaxXLMRobertaSelfAttention(nn.Module):
+ config: XLMRobertaConfig
+ causal: bool = False
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
+
+ def setup(self):
+ self.head_dim = self.config.hidden_size // self.config.num_attention_heads
+ if self.config.hidden_size % self.config.num_attention_heads != 0:
+ raise ValueError(
+ "`config.hidden_size`: {self.config.hidden_size} has to be a multiple of `config.num_attention_heads` "
+ " : {self.config.num_attention_heads}"
+ )
+
+ self.query = nn.Dense(
+ self.config.hidden_size,
+ dtype=self.dtype,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ )
+ self.key = nn.Dense(
+ self.config.hidden_size,
+ dtype=self.dtype,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ )
+ self.value = nn.Dense(
+ self.config.hidden_size,
+ dtype=self.dtype,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ )
+
+ if self.causal:
+ self.causal_mask = make_causal_mask(
+ jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
+ )
+
+ def _split_heads(self, hidden_states):
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.config.num_attention_heads, self.head_dim))
+
+ def _merge_heads(self, hidden_states):
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.config.hidden_size,))
+
+ @nn.compact
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention._concatenate_to_cache
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
+ """
+ This function takes projected key, value states from a single input token and concatenates the states to cached
+ states from previous steps. This function is slightly adapted from the official Flax repository:
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
+ """
+ # detect if we're initializing by absence of existing cache data.
+ is_initialized = self.has_variable("cache", "cached_key")
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
+
+ if is_initialized:
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
+ # update key, value caches with our new 1d spatial slices
+ cur_index = cache_index.value
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
+ cached_key.value = key
+ cached_value.value = value
+ num_updated_cache_vectors = query.shape[1]
+ cache_index.value = cache_index.value + num_updated_cache_vectors
+ # causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
+ pad_mask = jnp.broadcast_to(
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
+ )
+ attention_mask = combine_masks(pad_mask, attention_mask)
+ return key, value, attention_mask
+
+ def __call__(
+ self,
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ key_value_states: Optional[jnp.ndarray] = None,
+ init_cache: bool = False,
+ deterministic=True,
+ output_attentions: bool = False,
+ ):
+ # if key_value_states are provided this layer is used as a cross-attention layer
+ # for the decoder
+ is_cross_attention = key_value_states is not None
+ batch_size = hidden_states.shape[0]
+
+ # get query proj
+ query_states = self.query(hidden_states)
+ # get key, value proj
+ if is_cross_attention:
+ # cross_attentions
+ key_states = self.key(key_value_states)
+ value_states = self.value(key_value_states)
+ else:
+ # self_attention
+ key_states = self.key(hidden_states)
+ value_states = self.value(hidden_states)
+
+ query_states = self._split_heads(query_states)
+ key_states = self._split_heads(key_states)
+ value_states = self._split_heads(value_states)
+
+ # handle cache prepare causal attention mask
+ if self.causal:
+ query_length, key_length = query_states.shape[1], key_states.shape[1]
+ if self.has_variable("cache", "cached_key"):
+ mask_shift = self.variables["cache"]["cache_index"]
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
+ causal_mask = lax.dynamic_slice(
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
+ )
+ else:
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
+
+ # combine masks if needed
+ if attention_mask is not None and self.causal:
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
+ attention_mask = combine_masks(attention_mask, causal_mask)
+ elif self.causal:
+ attention_mask = causal_mask
+ elif attention_mask is not None:
+ attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
+
+ # During fast autoregressive decoding, we feed one position at a time,
+ # and cache the keys and values step by step.
+ if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
+ key_states, value_states, attention_mask = self._concatenate_to_cache(
+ key_states, value_states, query_states, attention_mask
+ )
+
+ # Convert the boolean attention mask to an attention bias.
+ if attention_mask is not None:
+ # attention mask in the form of attention bias
+ attention_bias = lax.select(
+ attention_mask > 0,
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
+ )
+ else:
+ attention_bias = None
+
+ dropout_rng = None
+ if not deterministic and self.config.attention_probs_dropout_prob > 0.0:
+ dropout_rng = self.make_rng("dropout")
+
+ attn_weights = dot_product_attention_weights(
+ query_states,
+ key_states,
+ bias=attention_bias,
+ dropout_rng=dropout_rng,
+ dropout_rate=self.config.attention_probs_dropout_prob,
+ broadcast_dropout=True,
+ deterministic=deterministic,
+ dtype=self.dtype,
+ precision=None,
+ )
+
+ # Mask heads if we want to
+ if layer_head_mask is not None:
+ attn_weights = jnp.einsum("...hqk,h->...hqk", attn_weights, layer_head_mask)
+
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
+ attn_output = attn_output.reshape(attn_output.shape[:2] + (-1,))
+
+ outputs = (attn_output, attn_weights) if output_attentions else (attn_output,)
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertSelfOutput with Bert->XLMRoberta
+class FlaxXLMRobertaSelfOutput(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
+
+ def setup(self):
+ self.dense = nn.Dense(
+ self.config.hidden_size,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ dtype=self.dtype,
+ )
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
+
+ def __call__(self, hidden_states, input_tensor, deterministic: bool = True):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertAttention with Bert->XLMRoberta
+class FlaxXLMRobertaAttention(nn.Module):
+ config: XLMRobertaConfig
+ causal: bool = False
+ dtype: jnp.dtype = jnp.float32
+
+ def setup(self):
+ self.self = FlaxXLMRobertaSelfAttention(self.config, causal=self.causal, dtype=self.dtype)
+ self.output = FlaxXLMRobertaSelfOutput(self.config, dtype=self.dtype)
+
+ def __call__(
+ self,
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ key_value_states=None,
+ init_cache=False,
+ deterministic=True,
+ output_attentions: bool = False,
+ ):
+ # Attention mask comes in as attention_mask.shape == (*batch_sizes, kv_length)
+ # FLAX expects: attention_mask.shape == (*batch_sizes, 1, 1, kv_length) such that it is broadcastable
+ # with attn_weights.shape == (*batch_sizes, num_heads, q_length, kv_length)
+ attn_outputs = self.self(
+ hidden_states,
+ attention_mask,
+ layer_head_mask=layer_head_mask,
+ key_value_states=key_value_states,
+ init_cache=init_cache,
+ deterministic=deterministic,
+ output_attentions=output_attentions,
+ )
+ attn_output = attn_outputs[0]
+ hidden_states = self.output(attn_output, hidden_states, deterministic=deterministic)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (attn_outputs[1],)
+
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertIntermediate with Bert->XLMRoberta
+class FlaxXLMRobertaIntermediate(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
+
+ def setup(self):
+ self.dense = nn.Dense(
+ self.config.intermediate_size,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ dtype=self.dtype,
+ )
+ self.activation = ACT2FN[self.config.hidden_act]
+
+ def __call__(self, hidden_states):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertOutput with Bert->XLMRoberta
+class FlaxXLMRobertaOutput(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
+
+ def setup(self):
+ self.dense = nn.Dense(
+ self.config.hidden_size,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ dtype=self.dtype,
+ )
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
+ self.LayerNorm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
+
+ def __call__(self, hidden_states, attention_output, deterministic: bool = True):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
+ hidden_states = self.LayerNorm(hidden_states + attention_output)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertLayer with Bert->XLMRoberta
+class FlaxXLMRobertaLayer(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
+
+ def setup(self):
+ self.attention = FlaxXLMRobertaAttention(self.config, causal=self.config.is_decoder, dtype=self.dtype)
+ self.intermediate = FlaxXLMRobertaIntermediate(self.config, dtype=self.dtype)
+ self.output = FlaxXLMRobertaOutput(self.config, dtype=self.dtype)
+ if self.config.add_cross_attention:
+ self.crossattention = FlaxXLMRobertaAttention(self.config, causal=False, dtype=self.dtype)
+
+ def __call__(
+ self,
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
+ init_cache: bool = False,
+ deterministic: bool = True,
+ output_attentions: bool = False,
+ ):
+ # Self Attention
+ attention_outputs = self.attention(
+ hidden_states,
+ attention_mask,
+ layer_head_mask=layer_head_mask,
+ init_cache=init_cache,
+ deterministic=deterministic,
+ output_attentions=output_attentions,
+ )
+ attention_output = attention_outputs[0]
+
+ # Cross-Attention Block
+ if encoder_hidden_states is not None:
+ cross_attention_outputs = self.crossattention(
+ attention_output,
+ attention_mask=encoder_attention_mask,
+ layer_head_mask=layer_head_mask,
+ key_value_states=encoder_hidden_states,
+ deterministic=deterministic,
+ output_attentions=output_attentions,
+ )
+ attention_output = cross_attention_outputs[0]
+
+ hidden_states = self.intermediate(attention_output)
+ hidden_states = self.output(hidden_states, attention_output, deterministic=deterministic)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (attention_outputs[1],)
+ if encoder_hidden_states is not None:
+ outputs += (cross_attention_outputs[1],)
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertLayerCollection with Bert->XLMRoberta
+class FlaxXLMRobertaLayerCollection(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
+ gradient_checkpointing: bool = False
+
+ def setup(self):
+ if self.gradient_checkpointing:
+ FlaxXLMRobertaCheckpointLayer = remat(FlaxXLMRobertaLayer, static_argnums=(5, 6, 7))
+ self.layers = [
+ FlaxXLMRobertaCheckpointLayer(self.config, name=str(i), dtype=self.dtype)
+ for i in range(self.config.num_hidden_layers)
+ ]
+ else:
+ self.layers = [
+ FlaxXLMRobertaLayer(self.config, name=str(i), dtype=self.dtype)
+ for i in range(self.config.num_hidden_layers)
+ ]
+
+ def __call__(
+ self,
+ hidden_states,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
+ init_cache: bool = False,
+ deterministic: bool = True,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ all_attentions = () if output_attentions else None
+ all_hidden_states = () if output_hidden_states else None
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
+
+ # Check if head_mask has a correct number of layers specified if desired
+ if head_mask is not None:
+ if head_mask.shape[0] != (len(self.layers)):
+ raise ValueError(
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for "
+ f" {head_mask.shape[0]}."
+ )
+
+ for i, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ layer_outputs = layer(
+ hidden_states,
+ attention_mask,
+ head_mask[i] if head_mask is not None else None,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ init_cache,
+ deterministic,
+ output_attentions,
+ )
+
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ all_attentions += (layer_outputs[1],)
+
+ if encoder_hidden_states is not None:
+ all_cross_attentions += (layer_outputs[2],)
+
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ outputs = (hidden_states, all_hidden_states, all_attentions, all_cross_attentions)
+
+ if not return_dict:
+ return tuple(v for v in outputs if v is not None)
+
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertEncoder with Bert->XLMRoberta
+class FlaxXLMRobertaEncoder(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
+ gradient_checkpointing: bool = False
+
+ def setup(self):
+ self.layer = FlaxXLMRobertaLayerCollection(
+ self.config,
+ dtype=self.dtype,
+ gradient_checkpointing=self.gradient_checkpointing,
+ )
+
+ def __call__(
+ self,
+ hidden_states,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
+ init_cache: bool = False,
+ deterministic: bool = True,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ return self.layer(
+ hidden_states,
+ attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ init_cache=init_cache,
+ deterministic=deterministic,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertPooler with Bert->XLMRoberta
+class FlaxXLMRobertaPooler(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
+
+ def setup(self):
+ self.dense = nn.Dense(
+ self.config.hidden_size,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ dtype=self.dtype,
+ )
+
+ def __call__(self, hidden_states):
+ cls_hidden_state = hidden_states[:, 0]
+ cls_hidden_state = self.dense(cls_hidden_state)
+ return nn.tanh(cls_hidden_state)
+
+
+# Copied from transformers.models.roberta.modeling_flax_roberta.FlaxRobertaLMHead with Roberta->XLMRoberta
+class FlaxXLMRobertaLMHead(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32
+ bias_init: Callable[..., np.ndarray] = jax.nn.initializers.zeros
+
+ def setup(self):
+ self.dense = nn.Dense(
+ self.config.hidden_size,
+ dtype=self.dtype,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ )
+ self.layer_norm = nn.LayerNorm(epsilon=self.config.layer_norm_eps, dtype=self.dtype)
+ self.decoder = nn.Dense(
+ self.config.vocab_size,
+ dtype=self.dtype,
+ use_bias=False,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ )
+ self.bias = self.param("bias", self.bias_init, (self.config.vocab_size,))
+
+ def __call__(self, hidden_states, shared_embedding=None):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = ACT2FN["gelu"](hidden_states)
+ hidden_states = self.layer_norm(hidden_states)
+
+ if shared_embedding is not None:
+ hidden_states = self.decoder.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
+ else:
+ hidden_states = self.decoder(hidden_states)
+
+ bias = jnp.asarray(self.bias, self.dtype)
+ hidden_states += bias
+ return hidden_states
+
+
+# Copied from transformers.models.roberta.modeling_flax_roberta.FlaxRobertaClassificationHead with Roberta->XLMRoberta
+class FlaxXLMRobertaClassificationHead(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32
+
+ def setup(self):
+ self.dense = nn.Dense(
+ self.config.hidden_size,
+ dtype=self.dtype,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ )
+ classifier_dropout = (
+ self.config.classifier_dropout
+ if self.config.classifier_dropout is not None
+ else self.config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(rate=classifier_dropout)
+ self.out_proj = nn.Dense(
+ self.config.num_labels,
+ dtype=self.dtype,
+ kernel_init=jax.nn.initializers.normal(self.config.initializer_range),
+ )
+
+ def __call__(self, hidden_states, deterministic=True):
+ hidden_states = hidden_states[:, 0, :] # take token (equiv. to [CLS])
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
+ hidden_states = self.dense(hidden_states)
+ hidden_states = nn.tanh(hidden_states)
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
+ hidden_states = self.out_proj(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.roberta.modeling_flax_roberta.FlaxRobertaPreTrainedModel with Roberta->XLMRoberta, roberta->xlm-roberta, ROBERTA->XLM_ROBERTA
+class FlaxXLMRobertaPreTrainedModel(FlaxPreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config_class = XLMRobertaConfig
+ base_model_prefix = "xlm-roberta"
+
+ module_class: nn.Module = None
+
+ def __init__(
+ self,
+ config: XLMRobertaConfig,
+ input_shape: tuple = (1, 1),
+ seed: int = 0,
+ dtype: jnp.dtype = jnp.float32,
+ _do_init: bool = True,
+ gradient_checkpointing: bool = False,
+ **kwargs,
+ ):
+ module = self.module_class(config=config, dtype=dtype, gradient_checkpointing=gradient_checkpointing, **kwargs)
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
+
+ # Copied from transformers.models.bert.modeling_flax_bert.FlaxBertPreTrainedModel.enable_gradient_checkpointing
+ def enable_gradient_checkpointing(self):
+ self._module = self.module_class(
+ config=self.config,
+ dtype=self.dtype,
+ gradient_checkpointing=True,
+ )
+
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: tuple, params: FrozenDict = None) -> FrozenDict:
+ # init input tensors
+ input_ids = jnp.zeros(input_shape, dtype="i4")
+ token_type_ids = jnp.ones_like(input_ids)
+ position_ids = create_position_ids_from_input_ids(input_ids, self.config.pad_token_id)
+ attention_mask = jnp.ones_like(input_ids)
+ head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))
+
+ params_rng, dropout_rng = jax.random.split(rng)
+ rngs = {"params": params_rng, "dropout": dropout_rng}
+
+ if self.config.add_cross_attention:
+ encoder_hidden_states = jnp.zeros(input_shape + (self.config.hidden_size,))
+ encoder_attention_mask = attention_mask
+ module_init_outputs = self.module.init(
+ rngs,
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ return_dict=False,
+ )
+ else:
+ module_init_outputs = self.module.init(
+ rngs, input_ids, attention_mask, token_type_ids, position_ids, head_mask, return_dict=False
+ )
+
+ random_params = module_init_outputs["params"]
+
+ if params is not None:
+ random_params = flatten_dict(unfreeze(random_params))
+ params = flatten_dict(unfreeze(params))
+ for missing_key in self._missing_keys:
+ params[missing_key] = random_params[missing_key]
+ self._missing_keys = set()
+ return freeze(unflatten_dict(params))
+ else:
+ return random_params
+
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderPreTrainedModel.init_cache
+ def init_cache(self, batch_size, max_length):
+ r"""
+ Args:
+ batch_size (`int`):
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
+ max_length (`int`):
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
+ cache.
+ """
+ # init input variables to retrieve cache
+ input_ids = jnp.ones((batch_size, max_length), dtype="i4")
+ attention_mask = jnp.ones_like(input_ids, dtype="i4")
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
+
+ init_variables = self.module.init(
+ jax.random.PRNGKey(0), input_ids, attention_mask, position_ids, return_dict=False, init_cache=True
+ )
+ return unfreeze(init_variables["cache"])
+
+ @add_start_docstrings_to_model_forward(XLM_ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ def __call__(
+ self,
+ input_ids,
+ attention_mask=None,
+ token_type_ids=None,
+ position_ids=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ params: Optional[dict] = None,
+ dropout_rng: jax.random.PRNGKey = None,
+ train: bool = False,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ past_key_values: Optional[dict] = None,
+ ):
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
+
+ # init input tensors if not passed
+ if token_type_ids is None:
+ token_type_ids = jnp.zeros_like(input_ids)
+
+ if position_ids is None:
+ position_ids = create_position_ids_from_input_ids(input_ids, self.config.pad_token_id)
+
+ if attention_mask is None:
+ attention_mask = jnp.ones_like(input_ids)
+
+ if head_mask is None:
+ head_mask = jnp.ones((self.config.num_hidden_layers, self.config.num_attention_heads))
+
+ # Handle any PRNG if needed
+ rngs = {}
+ if dropout_rng is not None:
+ rngs["dropout"] = dropout_rng
+
+ inputs = {"params": params or self.params}
+
+ if self.config.add_cross_attention:
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be passed
+ # down to ensure cache is used. It has to be made sure that cache is marked as mutable so that it can be
+ # changed by FlaxXLMRobertaAttention module
+ if past_key_values:
+ inputs["cache"] = past_key_values
+ mutable = ["cache"]
+ else:
+ mutable = False
+
+ outputs = self.module.apply(
+ inputs,
+ jnp.array(input_ids, dtype="i4"),
+ jnp.array(attention_mask, dtype="i4"),
+ token_type_ids=jnp.array(token_type_ids, dtype="i4"),
+ position_ids=jnp.array(position_ids, dtype="i4"),
+ head_mask=jnp.array(head_mask, dtype="i4"),
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ deterministic=not train,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ rngs=rngs,
+ mutable=mutable,
+ )
+
+ # add updated cache to model output
+ if past_key_values is not None and return_dict:
+ outputs, past_key_values = outputs
+ outputs["past_key_values"] = unfreeze(past_key_values["cache"])
+ return outputs
+ elif past_key_values is not None and not return_dict:
+ outputs, past_key_values = outputs
+ outputs = outputs[:1] + (unfreeze(past_key_values["cache"]),) + outputs[1:]
+
+ else:
+ outputs = self.module.apply(
+ inputs,
+ jnp.array(input_ids, dtype="i4"),
+ jnp.array(attention_mask, dtype="i4"),
+ token_type_ids=jnp.array(token_type_ids, dtype="i4"),
+ position_ids=jnp.array(position_ids, dtype="i4"),
+ head_mask=jnp.array(head_mask, dtype="i4"),
+ deterministic=not train,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ rngs=rngs,
+ )
+
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertModule with Bert->XLMRoberta
+class FlaxXLMRobertaModule(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
+ add_pooling_layer: bool = True
+ gradient_checkpointing: bool = False
+
+ def setup(self):
+ self.embeddings = FlaxXLMRobertaEmbeddings(self.config, dtype=self.dtype)
+ self.encoder = FlaxXLMRobertaEncoder(
+ self.config,
+ dtype=self.dtype,
+ gradient_checkpointing=self.gradient_checkpointing,
+ )
+ self.pooler = FlaxXLMRobertaPooler(self.config, dtype=self.dtype)
+
+ def __call__(
+ self,
+ input_ids,
+ attention_mask,
+ token_type_ids: Optional[jnp.ndarray] = None,
+ position_ids: Optional[jnp.ndarray] = None,
+ head_mask: Optional[jnp.ndarray] = None,
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
+ init_cache: bool = False,
+ deterministic: bool = True,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ # make sure `token_type_ids` is correctly initialized when not passed
+ if token_type_ids is None:
+ token_type_ids = jnp.zeros_like(input_ids)
+
+ # make sure `position_ids` is correctly initialized when not passed
+ if position_ids is None:
+ position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape)
+
+ hidden_states = self.embeddings(
+ input_ids, token_type_ids, position_ids, attention_mask, deterministic=deterministic
+ )
+ outputs = self.encoder(
+ hidden_states,
+ attention_mask,
+ head_mask=head_mask,
+ deterministic=deterministic,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ init_cache=init_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ hidden_states = outputs[0]
+ pooled = self.pooler(hidden_states) if self.add_pooling_layer else None
+
+ if not return_dict:
+ # if pooled is None, don't return it
+ if pooled is None:
+ return (hidden_states,) + outputs[1:]
+ return (hidden_states, pooled) + outputs[1:]
+
+ return FlaxBaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ pooler_output=pooled,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@add_start_docstrings(
+ "The bare XLM RoBERTa Model transformer outputting raw hidden-states without any specific head on top.",
+ XLM_ROBERTA_START_DOCSTRING,
+)
+class FlaxXLMRobertaModel(FlaxXLMRobertaPreTrainedModel):
+ module_class = FlaxXLMRobertaModule
+
+
+append_call_sample_docstring(FlaxXLMRobertaModel, _CHECKPOINT_FOR_DOC, FlaxBaseModelOutputWithPooling, _CONFIG_FOR_DOC)
+
+
+# Copied from transformers.models.roberta.modeling_flax_roberta.FlaxRobertaForMaskedLMModule with Roberta->XLMRoberta
+class FlaxXLMRobertaForMaskedLMModule(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32
+ gradient_checkpointing: bool = False
+
+ def setup(self):
+ self.roberta = FlaxXLMRobertaModule(
+ config=self.config,
+ add_pooling_layer=False,
+ dtype=self.dtype,
+ gradient_checkpointing=self.gradient_checkpointing,
+ )
+ self.lm_head = FlaxXLMRobertaLMHead(config=self.config, dtype=self.dtype)
+
+ def __call__(
+ self,
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ deterministic: bool = True,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ # Model
+ outputs = self.roberta(
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ deterministic=deterministic,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ if self.config.tie_word_embeddings:
+ shared_embedding = self.roberta.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
+ else:
+ shared_embedding = None
+
+ # Compute the prediction scores
+ logits = self.lm_head(hidden_states, shared_embedding=shared_embedding)
+
+ if not return_dict:
+ return (logits,) + outputs[1:]
+
+ return FlaxMaskedLMOutput(
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings("""XLM RoBERTa Model with a `language modeling` head on top.""", XLM_ROBERTA_START_DOCSTRING)
+class FlaxXLMRobertaForMaskedLM(FlaxXLMRobertaPreTrainedModel):
+ module_class = FlaxXLMRobertaForMaskedLMModule
+
+
+append_call_sample_docstring(
+ FlaxXLMRobertaForMaskedLM,
+ _CHECKPOINT_FOR_DOC,
+ FlaxBaseModelOutputWithPooling,
+ _CONFIG_FOR_DOC,
+ mask="",
+)
+
+
+# Copied from transformers.models.roberta.modeling_flax_roberta.FlaxRobertaForSequenceClassificationModule with Roberta->XLMRoberta
+class FlaxXLMRobertaForSequenceClassificationModule(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32
+ gradient_checkpointing: bool = False
+
+ def setup(self):
+ self.roberta = FlaxXLMRobertaModule(
+ config=self.config,
+ dtype=self.dtype,
+ add_pooling_layer=False,
+ gradient_checkpointing=self.gradient_checkpointing,
+ )
+ self.classifier = FlaxXLMRobertaClassificationHead(config=self.config, dtype=self.dtype)
+
+ def __call__(
+ self,
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ deterministic: bool = True,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ # Model
+ outputs = self.roberta(
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ deterministic=deterministic,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output, deterministic=deterministic)
+
+ if not return_dict:
+ return (logits,) + outputs[1:]
+
+ return FlaxSequenceClassifierOutput(
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ XLM Roberta Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """,
+ XLM_ROBERTA_START_DOCSTRING,
+)
+class FlaxXLMRobertaForSequenceClassification(FlaxXLMRobertaPreTrainedModel):
+ module_class = FlaxXLMRobertaForSequenceClassificationModule
+
+
+append_call_sample_docstring(
+ FlaxXLMRobertaForSequenceClassification,
+ _CHECKPOINT_FOR_DOC,
+ FlaxSequenceClassifierOutput,
+ _CONFIG_FOR_DOC,
+)
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertForMultipleChoiceModule with Bert->XLMRoberta, with self.bert->self.roberta
+class FlaxXLMRobertaForMultipleChoiceModule(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32
+ gradient_checkpointing: bool = False
+
+ def setup(self):
+ self.roberta = FlaxXLMRobertaModule(
+ config=self.config,
+ dtype=self.dtype,
+ gradient_checkpointing=self.gradient_checkpointing,
+ )
+ self.dropout = nn.Dropout(rate=self.config.hidden_dropout_prob)
+ self.classifier = nn.Dense(1, dtype=self.dtype)
+
+ def __call__(
+ self,
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ deterministic: bool = True,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ num_choices = input_ids.shape[1]
+ input_ids = input_ids.reshape(-1, input_ids.shape[-1]) if input_ids is not None else None
+ attention_mask = attention_mask.reshape(-1, attention_mask.shape[-1]) if attention_mask is not None else None
+ token_type_ids = token_type_ids.reshape(-1, token_type_ids.shape[-1]) if token_type_ids is not None else None
+ position_ids = position_ids.reshape(-1, position_ids.shape[-1]) if position_ids is not None else None
+
+ # Model
+ outputs = self.roberta(
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ deterministic=deterministic,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ pooled_output = outputs[1]
+ pooled_output = self.dropout(pooled_output, deterministic=deterministic)
+ logits = self.classifier(pooled_output)
+
+ reshaped_logits = logits.reshape(-1, num_choices)
+
+ if not return_dict:
+ return (reshaped_logits,) + outputs[2:]
+
+ return FlaxMultipleChoiceModelOutput(
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ XLM Roberta Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
+ a softmax) e.g. for RocStories/SWAG tasks.
+ """,
+ XLM_ROBERTA_START_DOCSTRING,
+)
+class FlaxXLMRobertaForMultipleChoice(FlaxXLMRobertaPreTrainedModel):
+ module_class = FlaxXLMRobertaForMultipleChoiceModule
+
+
+overwrite_call_docstring(
+ FlaxXLMRobertaForMultipleChoice, XLM_ROBERTA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
+)
+append_call_sample_docstring(
+ FlaxXLMRobertaForMultipleChoice,
+ _CHECKPOINT_FOR_DOC,
+ FlaxMultipleChoiceModelOutput,
+ _CONFIG_FOR_DOC,
+)
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertForTokenClassificationModule with Bert->XLMRoberta, with self.bert->self.roberta
+class FlaxXLMRobertaForTokenClassificationModule(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32
+ gradient_checkpointing: bool = False
+
+ def setup(self):
+ self.roberta = FlaxXLMRobertaModule(
+ config=self.config,
+ dtype=self.dtype,
+ add_pooling_layer=False,
+ gradient_checkpointing=self.gradient_checkpointing,
+ )
+ classifier_dropout = (
+ self.config.classifier_dropout
+ if self.config.classifier_dropout is not None
+ else self.config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(rate=classifier_dropout)
+ self.classifier = nn.Dense(self.config.num_labels, dtype=self.dtype)
+
+ def __call__(
+ self,
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ deterministic: bool = True,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ # Model
+ outputs = self.roberta(
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ deterministic=deterministic,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ hidden_states = self.dropout(hidden_states, deterministic=deterministic)
+ logits = self.classifier(hidden_states)
+
+ if not return_dict:
+ return (logits,) + outputs[1:]
+
+ return FlaxTokenClassifierOutput(
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ XLM Roberta Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
+ for Named-Entity-Recognition (NER) tasks.
+ """,
+ XLM_ROBERTA_START_DOCSTRING,
+)
+class FlaxXLMRobertaForTokenClassification(FlaxXLMRobertaPreTrainedModel):
+ module_class = FlaxXLMRobertaForTokenClassificationModule
+
+
+append_call_sample_docstring(
+ FlaxXLMRobertaForTokenClassification,
+ _CHECKPOINT_FOR_DOC,
+ FlaxTokenClassifierOutput,
+ _CONFIG_FOR_DOC,
+)
+
+
+# Copied from transformers.models.bert.modeling_flax_bert.FlaxBertForQuestionAnsweringModule with Bert->XLMRoberta, with self.bert->self.roberta
+class FlaxXLMRobertaForQuestionAnsweringModule(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32
+ gradient_checkpointing: bool = False
+
+ def setup(self):
+ self.roberta = FlaxXLMRobertaModule(
+ config=self.config,
+ dtype=self.dtype,
+ add_pooling_layer=False,
+ gradient_checkpointing=self.gradient_checkpointing,
+ )
+ self.qa_outputs = nn.Dense(self.config.num_labels, dtype=self.dtype)
+
+ def __call__(
+ self,
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ deterministic: bool = True,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ # Model
+ outputs = self.roberta(
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ deterministic=deterministic,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+
+ logits = self.qa_outputs(hidden_states)
+ start_logits, end_logits = jnp.split(logits, self.config.num_labels, axis=-1)
+ start_logits = start_logits.squeeze(-1)
+ end_logits = end_logits.squeeze(-1)
+
+ if not return_dict:
+ return (start_logits, end_logits) + outputs[1:]
+
+ return FlaxQuestionAnsweringModelOutput(
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ XLM Roberta Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
+ linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """,
+ XLM_ROBERTA_START_DOCSTRING,
+)
+class FlaxXLMRobertaForQuestionAnswering(FlaxXLMRobertaPreTrainedModel):
+ module_class = FlaxXLMRobertaForQuestionAnsweringModule
+
+
+append_call_sample_docstring(
+ FlaxXLMRobertaForQuestionAnswering,
+ _CHECKPOINT_FOR_DOC,
+ FlaxQuestionAnsweringModelOutput,
+ _CONFIG_FOR_DOC,
+)
+
+
+# Copied from transformers.models.roberta.modeling_flax_roberta.FlaxRobertaForCausalLMModule with Roberta->XLMRoberta
+class FlaxXLMRobertaForCausalLMModule(nn.Module):
+ config: XLMRobertaConfig
+ dtype: jnp.dtype = jnp.float32
+ gradient_checkpointing: bool = False
+
+ def setup(self):
+ self.roberta = FlaxXLMRobertaModule(
+ config=self.config,
+ add_pooling_layer=False,
+ dtype=self.dtype,
+ gradient_checkpointing=self.gradient_checkpointing,
+ )
+ self.lm_head = FlaxXLMRobertaLMHead(config=self.config, dtype=self.dtype)
+
+ def __call__(
+ self,
+ input_ids,
+ attention_mask,
+ position_ids,
+ token_type_ids: Optional[jnp.ndarray] = None,
+ head_mask: Optional[jnp.ndarray] = None,
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
+ init_cache: bool = False,
+ deterministic: bool = True,
+ output_attentions: bool = False,
+ output_hidden_states: bool = False,
+ return_dict: bool = True,
+ ):
+ # Model
+ outputs = self.roberta(
+ input_ids,
+ attention_mask,
+ token_type_ids,
+ position_ids,
+ head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ init_cache=init_cache,
+ deterministic=deterministic,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ if self.config.tie_word_embeddings:
+ shared_embedding = self.roberta.variables["params"]["embeddings"]["word_embeddings"]["embedding"]
+ else:
+ shared_embedding = None
+
+ # Compute the prediction scores
+ logits = self.lm_head(hidden_states, shared_embedding=shared_embedding)
+
+ if not return_dict:
+ return (logits,) + outputs[1:]
+
+ return FlaxCausalLMOutputWithCrossAttentions(
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@add_start_docstrings(
+ """
+ XLM Roberta Model with a language modeling head on top (a linear layer on top of the hidden-states output) e.g for
+ autoregressive tasks.
+ """,
+ XLM_ROBERTA_START_DOCSTRING,
+)
+# Copied from transformers.models.roberta.modeling_flax_roberta.FlaxRobertaForCausalLM with Roberta->XLMRoberta
+class FlaxXLMRobertaForCausalLM(FlaxXLMRobertaPreTrainedModel):
+ module_class = FlaxXLMRobertaForCausalLMModule
+
+ def prepare_inputs_for_generation(self, input_ids, max_length, attention_mask: Optional[jax.Array] = None):
+ # initializing the cache
+ batch_size, seq_length = input_ids.shape
+
+ past_key_values = self.init_cache(batch_size, max_length)
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
+ # But since the decoder uses a causal mask, those positions are masked anyway.
+ # Thus, we can create a single static attention_mask here, which is more efficient for compilation
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
+ if attention_mask is not None:
+ position_ids = attention_mask.cumsum(axis=-1) - 1
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, attention_mask, (0, 0))
+ else:
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
+
+ return {
+ "past_key_values": past_key_values,
+ "attention_mask": extended_attention_mask,
+ "position_ids": position_ids,
+ }
+
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
+ model_kwargs["position_ids"] = model_kwargs["position_ids"][:, -1:] + 1
+ return model_kwargs
+
+
+append_call_sample_docstring(
+ FlaxXLMRobertaForCausalLM,
+ _CHECKPOINT_FOR_DOC,
+ FlaxCausalLMOutputWithCrossAttentions,
+ _CONFIG_FOR_DOC,
+)
+
+
+__all__ = [
+ "FlaxXLMRobertaForMaskedLM",
+ "FlaxXLMRobertaForCausalLM",
+ "FlaxXLMRobertaForMultipleChoice",
+ "FlaxXLMRobertaForQuestionAnswering",
+ "FlaxXLMRobertaForSequenceClassification",
+ "FlaxXLMRobertaForTokenClassification",
+ "FlaxXLMRobertaModel",
+ "FlaxXLMRobertaPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_tf_xlm_roberta.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_tf_xlm_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..0def1bfdb00da7422d0957f330936ebc74e99e38
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_tf_xlm_roberta.py
@@ -0,0 +1,1790 @@
+# coding=utf-8
+# Copyright 2019 Facebook AI Research and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""TF 2.0 XLM-RoBERTa model."""
+
+from __future__ import annotations
+
+import math
+import warnings
+
+import numpy as np
+import tensorflow as tf
+
+from ...activations_tf import get_tf_activation
+from ...modeling_tf_outputs import (
+ TFBaseModelOutputWithPastAndCrossAttentions,
+ TFBaseModelOutputWithPoolingAndCrossAttentions,
+ TFCausalLMOutputWithCrossAttentions,
+ TFMaskedLMOutput,
+ TFMultipleChoiceModelOutput,
+ TFQuestionAnsweringModelOutput,
+ TFSequenceClassifierOutput,
+ TFTokenClassifierOutput,
+)
+from ...modeling_tf_utils import (
+ TFCausalLanguageModelingLoss,
+ TFMaskedLanguageModelingLoss,
+ TFModelInputType,
+ TFMultipleChoiceLoss,
+ TFPreTrainedModel,
+ TFQuestionAnsweringLoss,
+ TFSequenceClassificationLoss,
+ TFTokenClassificationLoss,
+ get_initializer,
+ keras,
+ keras_serializable,
+ unpack_inputs,
+)
+from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
+from ...utils import (
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+)
+from .configuration_xlm_roberta import XLMRobertaConfig
+
+
+logger = logging.get_logger(__name__)
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "FacebookAI/xlm-roberta-base"
+_CONFIG_FOR_DOC = "XLMRobertaConfig"
+
+
+XLM_ROBERTA_START_DOCSTRING = r"""
+
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
+ behavior.
+
+
+
+ TensorFlow models and layers in `transformers` accept two formats as input:
+
+ - having all inputs as keyword arguments (like PyTorch models), or
+ - having all inputs as a list, tuple or dict in the first positional argument.
+
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
+ positional argument:
+
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
+
+ Note that when creating models and layers with
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
+ about any of this, as you can just pass inputs like you would to any other Python function!
+
+
+
+ Parameters:
+ config ([`XLMRobertaConfig`]): Model configuration class with all the parameters of the
+ model. Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+XLM_ROBERTA_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`Numpy array` or `tf.Tensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
+ [`PreTrainedTokenizer.__call__`] and [`PreTrainedTokenizer.encode`] for details. [What are input
+ IDs?](../glossary#input-ids)
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ [What are attention masks?](../glossary#attention-mask)
+ token_type_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`Numpy array` or `tf.Tensor` of shape `({0})`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids)
+ head_mask (`Numpy array` or `tf.Tensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+ inputs_embeds (`tf.Tensor` of shape `({0}, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
+ config will be used instead.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
+ used instead.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
+ eager mode, in graph mode the value will always be set to True.
+ training (`bool`, *optional*, defaults to `False`):
+ Whether or not to use the model in training mode (some modules like dropout modules have different
+ behaviors between training and evaluation).
+"""
+
+
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaEmbeddings with Roberta->XLMRoberta
+class TFXLMRobertaEmbeddings(keras.layers.Layer):
+ """
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
+ """
+
+ def __init__(self, config, **kwargs):
+ super().__init__(**kwargs)
+
+ self.padding_idx = 1
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.max_position_embeddings = config.max_position_embeddings
+ self.initializer_range = config.initializer_range
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
+
+ def build(self, input_shape=None):
+ with tf.name_scope("word_embeddings"):
+ self.weight = self.add_weight(
+ name="weight",
+ shape=[self.config.vocab_size, self.hidden_size],
+ initializer=get_initializer(self.initializer_range),
+ )
+
+ with tf.name_scope("token_type_embeddings"):
+ self.token_type_embeddings = self.add_weight(
+ name="embeddings",
+ shape=[self.config.type_vocab_size, self.hidden_size],
+ initializer=get_initializer(self.initializer_range),
+ )
+
+ with tf.name_scope("position_embeddings"):
+ self.position_embeddings = self.add_weight(
+ name="embeddings",
+ shape=[self.max_position_embeddings, self.hidden_size],
+ initializer=get_initializer(self.initializer_range),
+ )
+
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "LayerNorm", None) is not None:
+ with tf.name_scope(self.LayerNorm.name):
+ self.LayerNorm.build([None, None, self.config.hidden_size])
+
+ def create_position_ids_from_input_ids(self, input_ids, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
+ symbols are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ input_ids: tf.Tensor
+ Returns: tf.Tensor
+ """
+ mask = tf.cast(tf.math.not_equal(input_ids, self.padding_idx), dtype=input_ids.dtype)
+ incremental_indices = (tf.math.cumsum(mask, axis=1) + past_key_values_length) * mask
+
+ return incremental_indices + self.padding_idx
+
+ def call(
+ self,
+ input_ids=None,
+ position_ids=None,
+ token_type_ids=None,
+ inputs_embeds=None,
+ past_key_values_length=0,
+ training=False,
+ ):
+ """
+ Applies embedding based on inputs tensor.
+
+ Returns:
+ final_embeddings (`tf.Tensor`): output embedding tensor.
+ """
+ assert not (input_ids is None and inputs_embeds is None)
+
+ if input_ids is not None:
+ check_embeddings_within_bounds(input_ids, self.config.vocab_size)
+ inputs_embeds = tf.gather(params=self.weight, indices=input_ids)
+
+ input_shape = shape_list(inputs_embeds)[:-1]
+
+ if token_type_ids is None:
+ token_type_ids = tf.fill(dims=input_shape, value=0)
+
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = self.create_position_ids_from_input_ids(
+ input_ids=input_ids, past_key_values_length=past_key_values_length
+ )
+ else:
+ position_ids = tf.expand_dims(
+ tf.range(start=self.padding_idx + 1, limit=input_shape[-1] + self.padding_idx + 1), axis=0
+ )
+
+ position_embeds = tf.gather(params=self.position_embeddings, indices=position_ids)
+ token_type_embeds = tf.gather(params=self.token_type_embeddings, indices=token_type_ids)
+ final_embeddings = inputs_embeds + position_embeds + token_type_embeds
+ final_embeddings = self.LayerNorm(inputs=final_embeddings)
+ final_embeddings = self.dropout(inputs=final_embeddings, training=training)
+
+ return final_embeddings
+
+
+# Copied from transformers.models.bert.modeling_tf_bert.TFBertPooler with Bert->XLMRoberta
+class TFXLMRobertaPooler(keras.layers.Layer):
+ def __init__(self, config: XLMRobertaConfig, **kwargs):
+ super().__init__(**kwargs)
+
+ self.dense = keras.layers.Dense(
+ units=config.hidden_size,
+ kernel_initializer=get_initializer(config.initializer_range),
+ activation="tanh",
+ name="dense",
+ )
+ self.config = config
+
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(inputs=first_token_tensor)
+
+ return pooled_output
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "dense", None) is not None:
+ with tf.name_scope(self.dense.name):
+ self.dense.build([None, None, self.config.hidden_size])
+
+
+# Copied from transformers.models.bert.modeling_tf_bert.TFBertSelfAttention with Bert->XLMRoberta
+class TFXLMRobertaSelfAttention(keras.layers.Layer):
+ def __init__(self, config: XLMRobertaConfig, **kwargs):
+ super().__init__(**kwargs)
+
+ if config.hidden_size % config.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number "
+ f"of attention heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.sqrt_att_head_size = math.sqrt(self.attention_head_size)
+
+ self.query = keras.layers.Dense(
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="query"
+ )
+ self.key = keras.layers.Dense(
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="key"
+ )
+ self.value = keras.layers.Dense(
+ units=self.all_head_size, kernel_initializer=get_initializer(config.initializer_range), name="value"
+ )
+ self.dropout = keras.layers.Dropout(rate=config.attention_probs_dropout_prob)
+
+ self.is_decoder = config.is_decoder
+ self.config = config
+
+ def transpose_for_scores(self, tensor: tf.Tensor, batch_size: int) -> tf.Tensor:
+ # Reshape from [batch_size, seq_length, all_head_size] to [batch_size, seq_length, num_attention_heads, attention_head_size]
+ tensor = tf.reshape(tensor=tensor, shape=(batch_size, -1, self.num_attention_heads, self.attention_head_size))
+
+ # Transpose the tensor from [batch_size, seq_length, num_attention_heads, attention_head_size] to [batch_size, num_attention_heads, seq_length, attention_head_size]
+ return tf.transpose(tensor, perm=[0, 2, 1, 3])
+
+ def call(
+ self,
+ hidden_states: tf.Tensor,
+ attention_mask: tf.Tensor,
+ head_mask: tf.Tensor,
+ encoder_hidden_states: tf.Tensor,
+ encoder_attention_mask: tf.Tensor,
+ past_key_value: tuple[tf.Tensor],
+ output_attentions: bool,
+ training: bool = False,
+ ) -> tuple[tf.Tensor]:
+ batch_size = shape_list(hidden_states)[0]
+ mixed_query_layer = self.query(inputs=hidden_states)
+
+ # If this is instantiated as a cross-attention module, the keys
+ # and values come from an encoder; the attention mask needs to be
+ # such that the encoder's padding tokens are not attended to.
+ is_cross_attention = encoder_hidden_states is not None
+
+ if is_cross_attention and past_key_value is not None:
+ # reuse k,v, cross_attentions
+ key_layer = past_key_value[0]
+ value_layer = past_key_value[1]
+ attention_mask = encoder_attention_mask
+ elif is_cross_attention:
+ key_layer = self.transpose_for_scores(self.key(inputs=encoder_hidden_states), batch_size)
+ value_layer = self.transpose_for_scores(self.value(inputs=encoder_hidden_states), batch_size)
+ attention_mask = encoder_attention_mask
+ elif past_key_value is not None:
+ key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
+ value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
+ key_layer = tf.concat([past_key_value[0], key_layer], axis=2)
+ value_layer = tf.concat([past_key_value[1], value_layer], axis=2)
+ else:
+ key_layer = self.transpose_for_scores(self.key(inputs=hidden_states), batch_size)
+ value_layer = self.transpose_for_scores(self.value(inputs=hidden_states), batch_size)
+
+ query_layer = self.transpose_for_scores(mixed_query_layer, batch_size)
+
+ if self.is_decoder:
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
+ # Further calls to cross_attention layer can then reuse all cross-attention
+ # key/value_states (first "if" case)
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
+ past_key_value = (key_layer, value_layer)
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ # (batch size, num_heads, seq_len_q, seq_len_k)
+ attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
+ dk = tf.cast(self.sqrt_att_head_size, dtype=attention_scores.dtype)
+ attention_scores = tf.divide(attention_scores, dk)
+
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in TFXLMRobertaModel call() function)
+ attention_scores = tf.add(attention_scores, attention_mask)
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = stable_softmax(logits=attention_scores, axis=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(inputs=attention_probs, training=training)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = tf.multiply(attention_probs, head_mask)
+
+ attention_output = tf.matmul(attention_probs, value_layer)
+ attention_output = tf.transpose(attention_output, perm=[0, 2, 1, 3])
+
+ # (batch_size, seq_len_q, all_head_size)
+ attention_output = tf.reshape(tensor=attention_output, shape=(batch_size, -1, self.all_head_size))
+ outputs = (attention_output, attention_probs) if output_attentions else (attention_output,)
+
+ if self.is_decoder:
+ outputs = outputs + (past_key_value,)
+ return outputs
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "query", None) is not None:
+ with tf.name_scope(self.query.name):
+ self.query.build([None, None, self.config.hidden_size])
+ if getattr(self, "key", None) is not None:
+ with tf.name_scope(self.key.name):
+ self.key.build([None, None, self.config.hidden_size])
+ if getattr(self, "value", None) is not None:
+ with tf.name_scope(self.value.name):
+ self.value.build([None, None, self.config.hidden_size])
+
+
+# Copied from transformers.models.bert.modeling_tf_bert.TFBertSelfOutput with Bert->XLMRoberta
+class TFXLMRobertaSelfOutput(keras.layers.Layer):
+ def __init__(self, config: XLMRobertaConfig, **kwargs):
+ super().__init__(**kwargs)
+
+ self.dense = keras.layers.Dense(
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
+ )
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
+ self.config = config
+
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
+ hidden_states = self.dense(inputs=hidden_states)
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
+
+ return hidden_states
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "dense", None) is not None:
+ with tf.name_scope(self.dense.name):
+ self.dense.build([None, None, self.config.hidden_size])
+ if getattr(self, "LayerNorm", None) is not None:
+ with tf.name_scope(self.LayerNorm.name):
+ self.LayerNorm.build([None, None, self.config.hidden_size])
+
+
+# Copied from transformers.models.bert.modeling_tf_bert.TFBertAttention with Bert->XLMRoberta
+class TFXLMRobertaAttention(keras.layers.Layer):
+ def __init__(self, config: XLMRobertaConfig, **kwargs):
+ super().__init__(**kwargs)
+
+ self.self_attention = TFXLMRobertaSelfAttention(config, name="self")
+ self.dense_output = TFXLMRobertaSelfOutput(config, name="output")
+
+ def prune_heads(self, heads):
+ raise NotImplementedError
+
+ def call(
+ self,
+ input_tensor: tf.Tensor,
+ attention_mask: tf.Tensor,
+ head_mask: tf.Tensor,
+ encoder_hidden_states: tf.Tensor,
+ encoder_attention_mask: tf.Tensor,
+ past_key_value: tuple[tf.Tensor],
+ output_attentions: bool,
+ training: bool = False,
+ ) -> tuple[tf.Tensor]:
+ self_outputs = self.self_attention(
+ hidden_states=input_tensor,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_value=past_key_value,
+ output_attentions=output_attentions,
+ training=training,
+ )
+ attention_output = self.dense_output(
+ hidden_states=self_outputs[0], input_tensor=input_tensor, training=training
+ )
+ # add attentions (possibly with past_key_value) if we output them
+ outputs = (attention_output,) + self_outputs[1:]
+
+ return outputs
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "self_attention", None) is not None:
+ with tf.name_scope(self.self_attention.name):
+ self.self_attention.build(None)
+ if getattr(self, "dense_output", None) is not None:
+ with tf.name_scope(self.dense_output.name):
+ self.dense_output.build(None)
+
+
+# Copied from transformers.models.bert.modeling_tf_bert.TFBertIntermediate with Bert->XLMRoberta
+class TFXLMRobertaIntermediate(keras.layers.Layer):
+ def __init__(self, config: XLMRobertaConfig, **kwargs):
+ super().__init__(**kwargs)
+
+ self.dense = keras.layers.Dense(
+ units=config.intermediate_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
+ )
+
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = get_tf_activation(config.hidden_act)
+ else:
+ self.intermediate_act_fn = config.hidden_act
+ self.config = config
+
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
+ hidden_states = self.dense(inputs=hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+
+ return hidden_states
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "dense", None) is not None:
+ with tf.name_scope(self.dense.name):
+ self.dense.build([None, None, self.config.hidden_size])
+
+
+# Copied from transformers.models.bert.modeling_tf_bert.TFBertOutput with Bert->XLMRoberta
+class TFXLMRobertaOutput(keras.layers.Layer):
+ def __init__(self, config: XLMRobertaConfig, **kwargs):
+ super().__init__(**kwargs)
+
+ self.dense = keras.layers.Dense(
+ units=config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
+ )
+ self.LayerNorm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="LayerNorm")
+ self.dropout = keras.layers.Dropout(rate=config.hidden_dropout_prob)
+ self.config = config
+
+ def call(self, hidden_states: tf.Tensor, input_tensor: tf.Tensor, training: bool = False) -> tf.Tensor:
+ hidden_states = self.dense(inputs=hidden_states)
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
+ hidden_states = self.LayerNorm(inputs=hidden_states + input_tensor)
+
+ return hidden_states
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "dense", None) is not None:
+ with tf.name_scope(self.dense.name):
+ self.dense.build([None, None, self.config.intermediate_size])
+ if getattr(self, "LayerNorm", None) is not None:
+ with tf.name_scope(self.LayerNorm.name):
+ self.LayerNorm.build([None, None, self.config.hidden_size])
+
+
+# Copied from transformers.models.bert.modeling_tf_bert.TFBertLayer with Bert->XLMRoberta
+class TFXLMRobertaLayer(keras.layers.Layer):
+ def __init__(self, config: XLMRobertaConfig, **kwargs):
+ super().__init__(**kwargs)
+
+ self.attention = TFXLMRobertaAttention(config, name="attention")
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = TFXLMRobertaAttention(config, name="crossattention")
+ self.intermediate = TFXLMRobertaIntermediate(config, name="intermediate")
+ self.bert_output = TFXLMRobertaOutput(config, name="output")
+
+ def call(
+ self,
+ hidden_states: tf.Tensor,
+ attention_mask: tf.Tensor,
+ head_mask: tf.Tensor,
+ encoder_hidden_states: tf.Tensor | None,
+ encoder_attention_mask: tf.Tensor | None,
+ past_key_value: tuple[tf.Tensor] | None,
+ output_attentions: bool,
+ training: bool = False,
+ ) -> tuple[tf.Tensor]:
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
+ self_attention_outputs = self.attention(
+ input_tensor=hidden_states,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_value=self_attn_past_key_value,
+ output_attentions=output_attentions,
+ training=training,
+ )
+ attention_output = self_attention_outputs[0]
+
+ # if decoder, the last output is tuple of self-attn cache
+ if self.is_decoder:
+ outputs = self_attention_outputs[1:-1]
+ present_key_value = self_attention_outputs[-1]
+ else:
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ cross_attn_present_key_value = None
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
+ cross_attention_outputs = self.crossattention(
+ input_tensor=attention_output,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_value=cross_attn_past_key_value,
+ output_attentions=output_attentions,
+ training=training,
+ )
+ attention_output = cross_attention_outputs[0]
+ outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
+
+ # add cross-attn cache to positions 3,4 of present_key_value tuple
+ cross_attn_present_key_value = cross_attention_outputs[-1]
+ present_key_value = present_key_value + cross_attn_present_key_value
+
+ intermediate_output = self.intermediate(hidden_states=attention_output)
+ layer_output = self.bert_output(
+ hidden_states=intermediate_output, input_tensor=attention_output, training=training
+ )
+ outputs = (layer_output,) + outputs # add attentions if we output them
+
+ # if decoder, return the attn key/values as the last output
+ if self.is_decoder:
+ outputs = outputs + (present_key_value,)
+
+ return outputs
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "attention", None) is not None:
+ with tf.name_scope(self.attention.name):
+ self.attention.build(None)
+ if getattr(self, "intermediate", None) is not None:
+ with tf.name_scope(self.intermediate.name):
+ self.intermediate.build(None)
+ if getattr(self, "bert_output", None) is not None:
+ with tf.name_scope(self.bert_output.name):
+ self.bert_output.build(None)
+ if getattr(self, "crossattention", None) is not None:
+ with tf.name_scope(self.crossattention.name):
+ self.crossattention.build(None)
+
+
+# Copied from transformers.models.bert.modeling_tf_bert.TFBertEncoder with Bert->XLMRoberta
+class TFXLMRobertaEncoder(keras.layers.Layer):
+ def __init__(self, config: XLMRobertaConfig, **kwargs):
+ super().__init__(**kwargs)
+ self.config = config
+ self.layer = [TFXLMRobertaLayer(config, name=f"layer_._{i}") for i in range(config.num_hidden_layers)]
+
+ def call(
+ self,
+ hidden_states: tf.Tensor,
+ attention_mask: tf.Tensor,
+ head_mask: tf.Tensor,
+ encoder_hidden_states: tf.Tensor | None,
+ encoder_attention_mask: tf.Tensor | None,
+ past_key_values: tuple[tuple[tf.Tensor]] | None,
+ use_cache: bool | None,
+ output_attentions: bool,
+ output_hidden_states: bool,
+ return_dict: bool,
+ training: bool = False,
+ ) -> TFBaseModelOutputWithPastAndCrossAttentions | tuple[tf.Tensor]:
+ all_hidden_states = () if output_hidden_states else None
+ all_attentions = () if output_attentions else None
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
+
+ next_decoder_cache = () if use_cache else None
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ past_key_value = past_key_values[i] if past_key_values is not None else None
+
+ layer_outputs = layer_module(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ head_mask=head_mask[i],
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_value=past_key_value,
+ output_attentions=output_attentions,
+ training=training,
+ )
+ hidden_states = layer_outputs[0]
+
+ if use_cache:
+ next_decoder_cache += (layer_outputs[-1],)
+
+ if output_attentions:
+ all_attentions = all_attentions + (layer_outputs[1],)
+ if self.config.add_cross_attention and encoder_hidden_states is not None:
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
+
+ # Add last layer
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v for v in [hidden_states, all_hidden_states, all_attentions, all_cross_attentions] if v is not None
+ )
+
+ return TFBaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=next_decoder_cache,
+ hidden_states=all_hidden_states,
+ attentions=all_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "layer", None) is not None:
+ for layer in self.layer:
+ with tf.name_scope(layer.name):
+ layer.build(None)
+
+
+@keras_serializable
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaMainLayer with Roberta->XLMRoberta
+class TFXLMRobertaMainLayer(keras.layers.Layer):
+ config_class = XLMRobertaConfig
+
+ def __init__(self, config, add_pooling_layer=True, **kwargs):
+ super().__init__(**kwargs)
+
+ self.config = config
+ self.is_decoder = config.is_decoder
+
+ self.num_hidden_layers = config.num_hidden_layers
+ self.initializer_range = config.initializer_range
+ self.output_attentions = config.output_attentions
+ self.output_hidden_states = config.output_hidden_states
+ self.return_dict = config.use_return_dict
+ self.encoder = TFXLMRobertaEncoder(config, name="encoder")
+ self.pooler = TFXLMRobertaPooler(config, name="pooler") if add_pooling_layer else None
+ # The embeddings must be the last declaration in order to follow the weights order
+ self.embeddings = TFXLMRobertaEmbeddings(config, name="embeddings")
+
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.get_input_embeddings
+ def get_input_embeddings(self) -> keras.layers.Layer:
+ return self.embeddings
+
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.set_input_embeddings
+ def set_input_embeddings(self, value: tf.Variable):
+ self.embeddings.weight = value
+ self.embeddings.vocab_size = shape_list(value)[0]
+
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer._prune_heads
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ raise NotImplementedError
+
+ @unpack_inputs
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertMainLayer.call
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
+ past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ training: bool = False,
+ ) -> TFBaseModelOutputWithPoolingAndCrossAttentions | tuple[tf.Tensor]:
+ if not self.config.is_decoder:
+ use_cache = False
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_shape = shape_list(input_ids)
+ elif inputs_embeds is not None:
+ input_shape = shape_list(inputs_embeds)[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ batch_size, seq_length = input_shape
+
+ if past_key_values is None:
+ past_key_values_length = 0
+ past_key_values = [None] * len(self.encoder.layer)
+ else:
+ past_key_values_length = shape_list(past_key_values[0][0])[-2]
+
+ if attention_mask is None:
+ attention_mask = tf.fill(dims=(batch_size, seq_length + past_key_values_length), value=1)
+
+ if token_type_ids is None:
+ token_type_ids = tf.fill(dims=input_shape, value=0)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ training=training,
+ )
+
+ # We create a 3D attention mask from a 2D tensor mask.
+ # Sizes are [batch_size, 1, 1, to_seq_length]
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
+ # this attention mask is more simple than the triangular masking of causal attention
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
+ attention_mask_shape = shape_list(attention_mask)
+
+ mask_seq_length = seq_length + past_key_values_length
+ # Copied from `modeling_tf_t5.py`
+ # Provided a padding mask of dimensions [batch_size, mask_seq_length]
+ # - if the model is a decoder, apply a causal mask in addition to the padding mask
+ # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
+ if self.is_decoder:
+ seq_ids = tf.range(mask_seq_length)
+ causal_mask = tf.less_equal(
+ tf.tile(seq_ids[None, None, :], (batch_size, mask_seq_length, 1)),
+ seq_ids[None, :, None],
+ )
+ causal_mask = tf.cast(causal_mask, dtype=attention_mask.dtype)
+ extended_attention_mask = causal_mask * attention_mask[:, None, :]
+ attention_mask_shape = shape_list(extended_attention_mask)
+ extended_attention_mask = tf.reshape(
+ extended_attention_mask, (attention_mask_shape[0], 1, attention_mask_shape[1], attention_mask_shape[2])
+ )
+ if past_key_values[0] is not None:
+ # attention_mask needs to be sliced to the shape `[batch_size, 1, from_seq_length - cached_seq_length, to_seq_length]
+ extended_attention_mask = extended_attention_mask[:, :, -seq_length:, :]
+ else:
+ extended_attention_mask = tf.reshape(
+ attention_mask, (attention_mask_shape[0], 1, 1, attention_mask_shape[1])
+ )
+
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
+ # masked positions, this operation will create a tensor which is 0.0 for
+ # positions we want to attend and -10000.0 for masked positions.
+ # Since we are adding it to the raw scores before the softmax, this is
+ # effectively the same as removing these entirely.
+ extended_attention_mask = tf.cast(extended_attention_mask, dtype=embedding_output.dtype)
+ one_cst = tf.constant(1.0, dtype=embedding_output.dtype)
+ ten_thousand_cst = tf.constant(-10000.0, dtype=embedding_output.dtype)
+ extended_attention_mask = tf.multiply(tf.subtract(one_cst, extended_attention_mask), ten_thousand_cst)
+
+ # Copied from `modeling_tf_t5.py` with -1e9 -> -10000
+ if self.is_decoder and encoder_attention_mask is not None:
+ # If a 2D ou 3D attention mask is provided for the cross-attention
+ # we need to make broadcastable to [batch_size, num_heads, mask_seq_length, mask_seq_length]
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ encoder_attention_mask = tf.cast(encoder_attention_mask, dtype=extended_attention_mask.dtype)
+ num_dims_encoder_attention_mask = len(shape_list(encoder_attention_mask))
+ if num_dims_encoder_attention_mask == 3:
+ encoder_extended_attention_mask = encoder_attention_mask[:, None, :, :]
+ if num_dims_encoder_attention_mask == 2:
+ encoder_extended_attention_mask = encoder_attention_mask[:, None, None, :]
+
+ # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
+ # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow/transformer/transformer_layers.py#L270
+ # encoder_extended_attention_mask = tf.math.equal(encoder_extended_attention_mask,
+ # tf.transpose(encoder_extended_attention_mask, perm=(-1, -2)))
+
+ encoder_extended_attention_mask = (1.0 - encoder_extended_attention_mask) * -10000.0
+ else:
+ encoder_extended_attention_mask = None
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ if head_mask is not None:
+ raise NotImplementedError
+ else:
+ head_mask = [None] * self.config.num_hidden_layers
+
+ encoder_outputs = self.encoder(
+ hidden_states=embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(hidden_states=sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ return (
+ sequence_output,
+ pooled_output,
+ ) + encoder_outputs[1:]
+
+ return TFBaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "encoder", None) is not None:
+ with tf.name_scope(self.encoder.name):
+ self.encoder.build(None)
+ if getattr(self, "pooler", None) is not None:
+ with tf.name_scope(self.pooler.name):
+ self.pooler.build(None)
+ if getattr(self, "embeddings", None) is not None:
+ with tf.name_scope(self.embeddings.name):
+ self.embeddings.build(None)
+
+
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaPreTrainedModel with Roberta->XLMRoberta
+class TFXLMRobertaPreTrainedModel(TFPreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config_class = XLMRobertaConfig
+ base_model_prefix = "roberta"
+
+
+@add_start_docstrings(
+ "The bare XLM RoBERTa Model transformer outputting raw hidden-states without any specific head on top.",
+ XLM_ROBERTA_START_DOCSTRING,
+)
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaModel with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class TFXLMRobertaModel(TFXLMRobertaPreTrainedModel):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.roberta = TFXLMRobertaMainLayer(config, name="roberta")
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFBaseModelOutputWithPoolingAndCrossAttentions,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
+ past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ training: bool | None = False,
+ ) -> tuple | TFBaseModelOutputWithPoolingAndCrossAttentions:
+ r"""
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ past_key_values (`tuple[tuple[tf.Tensor]]` of length `config.n_layers`)
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`). Set to `False` during training, `True` during generation
+ """
+ outputs = self.roberta(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ return outputs
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "roberta", None) is not None:
+ with tf.name_scope(self.roberta.name):
+ self.roberta.build(None)
+
+
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaLMHead with Roberta->XLMRoberta
+class TFXLMRobertaLMHead(keras.layers.Layer):
+ """XLMRoberta Head for masked language modeling."""
+
+ def __init__(self, config, input_embeddings, **kwargs):
+ super().__init__(**kwargs)
+
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.dense = keras.layers.Dense(
+ config.hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="dense"
+ )
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
+ self.act = get_tf_activation("gelu")
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = input_embeddings
+
+ def build(self, input_shape=None):
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
+
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "dense", None) is not None:
+ with tf.name_scope(self.dense.name):
+ self.dense.build([None, None, self.config.hidden_size])
+ if getattr(self, "layer_norm", None) is not None:
+ with tf.name_scope(self.layer_norm.name):
+ self.layer_norm.build([None, None, self.config.hidden_size])
+
+ def get_output_embeddings(self):
+ return self.decoder
+
+ def set_output_embeddings(self, value):
+ self.decoder.weight = value
+ self.decoder.vocab_size = shape_list(value)[0]
+
+ def get_bias(self):
+ return {"bias": self.bias}
+
+ def set_bias(self, value):
+ self.bias = value["bias"]
+ self.config.vocab_size = shape_list(value["bias"])[0]
+
+ def call(self, hidden_states):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.act(hidden_states)
+ hidden_states = self.layer_norm(hidden_states)
+
+ # project back to size of vocabulary with bias
+ seq_length = shape_list(tensor=hidden_states)[1]
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, self.hidden_size])
+ hidden_states = tf.matmul(a=hidden_states, b=self.decoder.weight, transpose_b=True)
+ hidden_states = tf.reshape(tensor=hidden_states, shape=[-1, seq_length, self.config.vocab_size])
+ hidden_states = tf.nn.bias_add(value=hidden_states, bias=self.bias)
+
+ return hidden_states
+
+
+@add_start_docstrings("""XLM RoBERTa Model with a `language modeling` head on top.""", XLM_ROBERTA_START_DOCSTRING)
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForMaskedLM with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class TFXLMRobertaForMaskedLM(TFXLMRobertaPreTrainedModel, TFMaskedLanguageModelingLoss):
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
+ _keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head.decoder.weight"]
+
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+
+ self.roberta = TFXLMRobertaMainLayer(config, add_pooling_layer=False, name="roberta")
+ self.lm_head = TFXLMRobertaLMHead(config, self.roberta.embeddings, name="lm_head")
+
+ def get_lm_head(self):
+ return self.lm_head
+
+ def get_prefix_bias_name(self):
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
+ return self.name + "/" + self.lm_head.name
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFMaskedLMOutput,
+ config_class=_CONFIG_FOR_DOC,
+ mask="",
+ expected_output="' Paris'",
+ expected_loss=0.1,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool | None = False,
+ ) -> TFMaskedLMOutput | tuple[tf.Tensor]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ loss = None if labels is None else self.hf_compute_loss(labels, prediction_scores)
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFMaskedLMOutput(
+ loss=loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "roberta", None) is not None:
+ with tf.name_scope(self.roberta.name):
+ self.roberta.build(None)
+ if getattr(self, "lm_head", None) is not None:
+ with tf.name_scope(self.lm_head.name):
+ self.lm_head.build(None)
+
+
+@add_start_docstrings(
+ "XLM-RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.",
+ XLM_ROBERTA_START_DOCSTRING,
+)
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForCausalLM with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class TFXLMRobertaForCausalLM(TFXLMRobertaPreTrainedModel, TFCausalLanguageModelingLoss):
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
+ _keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head.decoder.weight"]
+
+ def __init__(self, config: XLMRobertaConfig, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `TFXLMRobertaLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.roberta = TFXLMRobertaMainLayer(config, add_pooling_layer=False, name="roberta")
+ self.lm_head = TFXLMRobertaLMHead(config, input_embeddings=self.roberta.embeddings, name="lm_head")
+
+ def get_lm_head(self):
+ return self.lm_head
+
+ def get_prefix_bias_name(self):
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
+ return self.name + "/" + self.lm_head.name
+
+ # Copied from transformers.models.bert.modeling_tf_bert.TFBertLMHeadModel.prepare_inputs_for_generation
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
+ input_shape = input_ids.shape
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
+ if attention_mask is None:
+ attention_mask = tf.ones(input_shape)
+
+ # cut decoder_input_ids if past is used
+ if past_key_values is not None:
+ input_ids = input_ids[:, -1:]
+
+ return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFCausalLMOutputWithCrossAttentions,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
+ past_key_values: tuple[tuple[np.ndarray | tf.Tensor]] | None = None,
+ use_cache: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool | None = False,
+ ) -> TFCausalLMOutputWithCrossAttentions | tuple[tf.Tensor]:
+ r"""
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ past_key_values (`tuple[tuple[tf.Tensor]]` of length `config.n_layers`)
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`). Set to `False` during training, `True` during generation
+ labels (`tf.Tensor` or `np.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
+ config.vocab_size - 1]`.
+ """
+ outputs = self.roberta(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ sequence_output = outputs[0]
+ logits = self.lm_head(hidden_states=sequence_output, training=training)
+ loss = None
+
+ if labels is not None:
+ # shift labels to the left and cut last logit token
+ shifted_logits = logits[:, :-1]
+ labels = labels[:, 1:]
+ loss = self.hf_compute_loss(labels=labels, logits=shifted_logits)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFCausalLMOutputWithCrossAttentions(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "roberta", None) is not None:
+ with tf.name_scope(self.roberta.name):
+ self.roberta.build(None)
+ if getattr(self, "lm_head", None) is not None:
+ with tf.name_scope(self.lm_head.name):
+ self.lm_head.build(None)
+
+
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaClassificationHead with Roberta->XLMRoberta
+class TFXLMRobertaClassificationHead(keras.layers.Layer):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config, **kwargs):
+ super().__init__(**kwargs)
+ self.dense = keras.layers.Dense(
+ config.hidden_size,
+ kernel_initializer=get_initializer(config.initializer_range),
+ activation="tanh",
+ name="dense",
+ )
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = keras.layers.Dropout(classifier_dropout)
+ self.out_proj = keras.layers.Dense(
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="out_proj"
+ )
+ self.config = config
+
+ def call(self, features, training=False):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x, training=training)
+ x = self.dense(x)
+ x = self.dropout(x, training=training)
+ x = self.out_proj(x)
+ return x
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "dense", None) is not None:
+ with tf.name_scope(self.dense.name):
+ self.dense.build([None, None, self.config.hidden_size])
+ if getattr(self, "out_proj", None) is not None:
+ with tf.name_scope(self.out_proj.name):
+ self.out_proj.build([None, None, self.config.hidden_size])
+
+
+@add_start_docstrings(
+ """
+ XLM RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """,
+ XLM_ROBERTA_START_DOCSTRING,
+)
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForSequenceClassification with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class TFXLMRobertaForSequenceClassification(TFXLMRobertaPreTrainedModel, TFSequenceClassificationLoss):
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
+ _keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head"]
+
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.num_labels = config.num_labels
+
+ self.roberta = TFXLMRobertaMainLayer(config, add_pooling_layer=False, name="roberta")
+ self.classifier = TFXLMRobertaClassificationHead(config, name="classifier")
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint="cardiffnlp/twitter-roberta-base-emotion",
+ output_type=TFSequenceClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output="'optimism'",
+ expected_loss=0.08,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool | None = False,
+ ) -> TFSequenceClassifierOutput | tuple[tf.Tensor]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output, training=training)
+
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFSequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "roberta", None) is not None:
+ with tf.name_scope(self.roberta.name):
+ self.roberta.build(None)
+ if getattr(self, "classifier", None) is not None:
+ with tf.name_scope(self.classifier.name):
+ self.classifier.build(None)
+
+
+@add_start_docstrings(
+ """
+ XLM Roberta Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
+ a softmax) e.g. for RocStories/SWAG tasks.
+ """,
+ XLM_ROBERTA_START_DOCSTRING,
+)
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForMultipleChoice with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class TFXLMRobertaForMultipleChoice(TFXLMRobertaPreTrainedModel, TFMultipleChoiceLoss):
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
+ _keys_to_ignore_on_load_unexpected = [r"lm_head"]
+ _keys_to_ignore_on_load_missing = [r"dropout"]
+
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+
+ self.roberta = TFXLMRobertaMainLayer(config, name="roberta")
+ self.dropout = keras.layers.Dropout(config.hidden_dropout_prob)
+ self.classifier = keras.layers.Dense(
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
+ )
+ self.config = config
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(
+ XLM_ROBERTA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
+ )
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFMultipleChoiceModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool | None = False,
+ ) -> TFMultipleChoiceModelOutput | tuple[tf.Tensor]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
+ """
+
+ if input_ids is not None:
+ num_choices = shape_list(input_ids)[1]
+ seq_length = shape_list(input_ids)[2]
+ else:
+ num_choices = shape_list(inputs_embeds)[1]
+ seq_length = shape_list(inputs_embeds)[2]
+
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
+ flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
+ flat_position_ids = tf.reshape(position_ids, (-1, seq_length)) if position_ids is not None else None
+ outputs = self.roberta(
+ flat_input_ids,
+ flat_attention_mask,
+ flat_token_type_ids,
+ flat_position_ids,
+ head_mask,
+ inputs_embeds,
+ output_attentions,
+ output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ pooled_output = outputs[1]
+ pooled_output = self.dropout(pooled_output, training=training)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
+
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFMultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "roberta", None) is not None:
+ with tf.name_scope(self.roberta.name):
+ self.roberta.build(None)
+ if getattr(self, "classifier", None) is not None:
+ with tf.name_scope(self.classifier.name):
+ self.classifier.build([None, None, self.config.hidden_size])
+
+
+@add_start_docstrings(
+ """
+ XLM RoBERTa Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
+ for Named-Entity-Recognition (NER) tasks.
+ """,
+ XLM_ROBERTA_START_DOCSTRING,
+)
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForTokenClassification with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class TFXLMRobertaForTokenClassification(TFXLMRobertaPreTrainedModel, TFTokenClassificationLoss):
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
+ _keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head"]
+ _keys_to_ignore_on_load_missing = [r"dropout"]
+
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.num_labels = config.num_labels
+
+ self.roberta = TFXLMRobertaMainLayer(config, add_pooling_layer=False, name="roberta")
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = keras.layers.Dropout(classifier_dropout)
+ self.classifier = keras.layers.Dense(
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
+ )
+ self.config = config
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint="ydshieh/roberta-large-ner-english",
+ output_type=TFTokenClassifierOutput,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output="['O', 'ORG', 'ORG', 'O', 'O', 'O', 'O', 'O', 'LOC', 'O', 'LOC', 'LOC']",
+ expected_loss=0.01,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool | None = False,
+ ) -> TFTokenClassifierOutput | tuple[tf.Tensor]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output, training=training)
+ logits = self.classifier(sequence_output)
+
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFTokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "roberta", None) is not None:
+ with tf.name_scope(self.roberta.name):
+ self.roberta.build(None)
+ if getattr(self, "classifier", None) is not None:
+ with tf.name_scope(self.classifier.name):
+ self.classifier.build([None, None, self.config.hidden_size])
+
+
+@add_start_docstrings(
+ """
+ XLM RoBERTa Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
+ linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """,
+ XLM_ROBERTA_START_DOCSTRING,
+)
+# Copied from transformers.models.roberta.modeling_tf_roberta.TFRobertaForQuestionAnswering with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class TFXLMRobertaForQuestionAnswering(TFXLMRobertaPreTrainedModel, TFQuestionAnsweringLoss):
+ # names with a '.' represents the authorized unexpected/missing layers when a TF model is loaded from a PT model
+ _keys_to_ignore_on_load_unexpected = [r"pooler", r"lm_head"]
+
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.num_labels = config.num_labels
+
+ self.roberta = TFXLMRobertaMainLayer(config, add_pooling_layer=False, name="roberta")
+ self.qa_outputs = keras.layers.Dense(
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
+ )
+ self.config = config
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLM_ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint="ydshieh/roberta-base-squad2",
+ output_type=TFQuestionAnsweringModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ expected_output="' puppet'",
+ expected_loss=0.86,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ position_ids: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ start_positions: np.ndarray | tf.Tensor | None = None,
+ end_positions: np.ndarray | tf.Tensor | None = None,
+ training: bool | None = False,
+ ) -> TFQuestionAnsweringModelOutput | tuple[tf.Tensor]:
+ r"""
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ """
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
+ start_logits = tf.squeeze(start_logits, axis=-1)
+ end_logits = tf.squeeze(end_logits, axis=-1)
+
+ loss = None
+ if start_positions is not None and end_positions is not None:
+ labels = {"start_position": start_positions}
+ labels["end_position"] = end_positions
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFQuestionAnsweringModelOutput(
+ loss=loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "roberta", None) is not None:
+ with tf.name_scope(self.roberta.name):
+ self.roberta.build(None)
+ if getattr(self, "qa_outputs", None) is not None:
+ with tf.name_scope(self.qa_outputs.name):
+ self.qa_outputs.build([None, None, self.config.hidden_size])
+
+
+__all__ = [
+ "TFXLMRobertaForCausalLM",
+ "TFXLMRobertaForMaskedLM",
+ "TFXLMRobertaForMultipleChoice",
+ "TFXLMRobertaForQuestionAnswering",
+ "TFXLMRobertaForSequenceClassification",
+ "TFXLMRobertaForTokenClassification",
+ "TFXLMRobertaModel",
+ "TFXLMRobertaPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_xlm_roberta.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_xlm_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..facfd3a6003914d2cef9a4606067131631392871
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/modeling_xlm_roberta.py
@@ -0,0 +1,1561 @@
+# coding=utf-8
+# Copyright 2019 Facebook AI Research and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch XLM-RoBERTa model."""
+
+import math
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import ACT2FN, gelu
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa, _prepare_4d_causal_attention_mask_for_sdpa
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
+from ...utils import auto_docstring, logging
+from ...utils.deprecation import deprecate_kwarg
+from .configuration_xlm_roberta import XLMRobertaConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->XLMRoberta
+class XLMRobertaEmbeddings(nn.Module):
+ """
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
+ """
+
+ # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
+ # any TensorFlow checkpoint file
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ # End copy
+ self.padding_idx = config.pad_token_id
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+
+ def forward(
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
+ ):
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+
+ embeddings = inputs_embeds + token_type_embeddings
+ if self.position_embedding_type == "absolute":
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings += position_embeddings
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->XLMRoberta
+class XLMRobertaSelfAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.position_embedding_type = position_embedding_type or getattr(
+ config, "position_embedding_type", "absolute"
+ )
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ self.max_position_embeddings = config.max_position_embeddings
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
+
+ self.is_decoder = config.is_decoder
+ self.layer_idx = layer_idx
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor]:
+ batch_size, seq_length, _ = hidden_states.shape
+ query_layer = self.query(hidden_states)
+ query_layer = query_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
+ 1, 2
+ )
+
+ is_cross_attention = encoder_hidden_states is not None
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_layer from cache
+ curr_past_key_value = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_value = past_key_values.self_attention_cache
+ else:
+ curr_past_key_value = past_key_values
+
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = curr_past_key_value.layers[self.layer_idx].keys
+ value_layer = curr_past_key_value.layers[self.layer_idx].values
+ else:
+ key_layer = self.key(current_states)
+ key_layer = key_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
+ 1, 2
+ )
+ value_layer = self.value(current_states)
+ value_layer = value_layer.view(
+ batch_size, -1, self.num_attention_heads, self.attention_head_size
+ ).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ cache_position = cache_position if not is_cross_attention else None
+ key_layer, value_layer = curr_past_key_value.update(
+ key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention:
+ past_key_values.is_updated[self.layer_idx] = True
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
+ if past_key_values is not None:
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
+ -1, 1
+ )
+ else:
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
+ distance = position_ids_l - position_ids_r
+
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
+
+ if self.position_embedding_type == "relative_key":
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores
+ elif self.position_embedding_type == "relative_key_query":
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in XLMRobertaModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = attention_probs * head_mask
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ return context_layer, attention_probs
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaSdpaSelfAttention with Roberta->XLMRoberta
+class XLMRobertaSdpaSelfAttention(XLMRobertaSelfAttention):
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
+ super().__init__(config, position_embedding_type=position_embedding_type, layer_idx=layer_idx)
+ self.dropout_prob = config.attention_probs_dropout_prob
+
+ # Adapted from XLMRobertaSelfAttention
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor]:
+ if self.position_embedding_type != "absolute" or output_attentions or head_mask is not None:
+ # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once implemented.
+ logger.warning_once(
+ "XLMRobertaSdpaSelfAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
+ "non-absolute `position_embedding_type` or `output_attentions=True` or `head_mask`. Falling back to "
+ "the manual attention implementation, but specifying the manual implementation will be required from "
+ "Transformers version v5.0.0 onwards. This warning can be removed using the argument "
+ '`attn_implementation="eager"` when loading the model.'
+ )
+ return super().forward(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ past_key_values,
+ output_attentions,
+ cache_position,
+ )
+
+ bsz, tgt_len, _ = hidden_states.size()
+
+ query_layer = (
+ self.query(hidden_states).view(bsz, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
+ )
+
+ is_cross_attention = encoder_hidden_states is not None
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_value = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_value = past_key_values.self_attention_cache
+ else:
+ curr_past_key_value = past_key_values
+
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = curr_past_key_value.layers[self.layer_idx].keys
+ value_layer = curr_past_key_value.layers[self.layer_idx].values
+ else:
+ key_layer = (
+ self.key(current_states)
+ .view(bsz, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ value_layer = (
+ self.value(current_states)
+ .view(bsz, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+
+ if past_key_values is not None:
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ cache_position = cache_position if not is_cross_attention else None
+ key_layer, value_layer = curr_past_key_value.update(
+ key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention:
+ past_key_values.is_updated[self.layer_idx] = True
+
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
+ # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create
+ # a causal mask in case tgt_len == 1.
+ is_causal = self.is_decoder and not is_cross_attention and attention_mask is None and tgt_len > 1
+
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
+ query_layer,
+ key_layer,
+ value_layer,
+ attn_mask=attention_mask,
+ dropout_p=self.dropout_prob if self.training else 0.0,
+ is_causal=is_causal,
+ )
+
+ attn_output = attn_output.transpose(1, 2)
+ attn_output = attn_output.reshape(bsz, tgt_len, self.all_head_size)
+
+ return attn_output, None
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput with Roberta->XLMRoberta
+class XLMRobertaSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+XLM_ROBERTA_SELF_ATTENTION_CLASSES = {
+ "eager": XLMRobertaSelfAttention,
+ "sdpa": XLMRobertaSdpaSelfAttention,
+}
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaAttention with Roberta->XLMRoberta,ROBERTA->XLM_ROBERTA
+class XLMRobertaAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
+ super().__init__()
+ self.self = XLM_ROBERTA_SELF_ATTENTION_CLASSES[config._attn_implementation](
+ config,
+ position_embedding_type=position_embedding_type,
+ layer_idx=layer_idx,
+ )
+ self.output = XLMRobertaSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.self.query = prune_linear_layer(self.self.query, index)
+ self.self.key = prune_linear_layer(self.self.key, index)
+ self.self.value = prune_linear_layer(self.self.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor]:
+ self_outputs = self.self(
+ hidden_states,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ cache_position=cache_position,
+ )
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaIntermediate with Roberta->XLMRoberta
+class XLMRobertaIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaOutput with Roberta->XLMRoberta
+class XLMRobertaOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaLayer with Roberta->XLMRoberta
+class XLMRobertaLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = XLMRobertaAttention(config, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = XLMRobertaAttention(config, position_embedding_type="absolute", layer_idx=layer_idx)
+ self.intermediate = XLMRobertaIntermediate(config)
+ self.output = XLMRobertaOutput(config)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor]:
+ self_attention_outputs = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ past_key_values=past_key_values,
+ cache_position=cache_position,
+ )
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_outputs = self.crossattention(
+ attention_output,
+ attention_mask=encoder_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ cache_position=cache_position,
+ )
+ attention_output = cross_attention_outputs[0]
+ outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaEncoder with Roberta->XLMRoberta
+class XLMRobertaEncoder(nn.Module):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([XLMRobertaLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = False,
+ output_hidden_states: Optional[bool] = False,
+ return_dict: Optional[bool] = True,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
+
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ if use_cache and self.config.is_decoder and past_key_values is None:
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+
+ if use_cache and self.config.is_decoder and isinstance(past_key_values, tuple):
+ logger.warning_once(
+ "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
+ "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
+ "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
+ )
+ past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
+
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+
+ layer_outputs = layer_module(
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ encoder_hidden_states, # as a positional argument for gradient checkpointing
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ cache_position=cache_position,
+ )
+
+ hidden_states = layer_outputs[0]
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+ if self.config.add_cross_attention:
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ hidden_states,
+ past_key_values,
+ all_hidden_states,
+ all_self_attentions,
+ all_cross_attentions,
+ ]
+ if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaPooler with Roberta->XLMRoberta
+class XLMRobertaPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@auto_docstring
+# Copied from transformers.models.roberta.modeling_roberta.RobertaPreTrainedModel with Roberta->XLMRoberta
+class XLMRobertaPreTrainedModel(PreTrainedModel):
+ config: XLMRobertaConfig
+ base_model_prefix = "roberta"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["XLMRobertaEmbeddings", "XLMRobertaSelfAttention", "XLMRobertaSdpaSelfAttention"]
+ _supports_sdpa = True
+
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights with BertLMPredictionHead->XLMRobertaLMHead
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ elif isinstance(module, XLMRobertaLMHead):
+ module.bias.data.zero_()
+
+
+@auto_docstring
+# Copied from transformers.models.roberta.modeling_roberta.RobertaModel with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class XLMRobertaModel(XLMRobertaPreTrainedModel):
+ _no_split_modules = ["XLMRobertaEmbeddings", "XLMRobertaLayer"]
+
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = XLMRobertaEmbeddings(config)
+ self.encoder = XLMRobertaEncoder(config)
+
+ self.pooler = XLMRobertaPooler(config) if add_pooling_layer else None
+
+ self.attn_implementation = config._attn_implementation
+ self.position_embedding_type = config.position_embedding_type
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ batch_size, seq_length = input_shape
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ past_key_values_length = 0
+ if past_key_values is not None:
+ past_key_values_length = (
+ past_key_values[0][0].shape[-2]
+ if not isinstance(past_key_values, Cache)
+ else past_key_values.get_seq_length()
+ )
+
+ if token_type_ids is None:
+ if hasattr(self.embeddings, "token_type_ids"):
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ if attention_mask is None:
+ attention_mask = torch.ones((batch_size, seq_length + past_key_values_length), device=device)
+
+ use_sdpa_attention_masks = (
+ self.attn_implementation == "sdpa"
+ and self.position_embedding_type == "absolute"
+ and head_mask is None
+ and not output_attentions
+ )
+
+ # Expand the attention mask
+ if use_sdpa_attention_masks and attention_mask.dim() == 2:
+ # Expand the attention mask for SDPA.
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
+ if self.config.is_decoder:
+ extended_attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
+ attention_mask,
+ input_shape,
+ embedding_output,
+ past_key_values_length,
+ )
+ else:
+ extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
+ attention_mask, embedding_output.dtype, tgt_len=seq_length
+ )
+ else:
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
+ # ourselves in which case we just need to make it broadcastable to all heads.
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
+
+ # If a 2D or 3D attention mask is provided for the cross-attention
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ if self.config.is_decoder and encoder_hidden_states is not None:
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
+ if encoder_attention_mask is None:
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
+
+ if use_sdpa_attention_masks and encoder_attention_mask.dim() == 2:
+ # Expand the attention mask for SDPA.
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
+ encoder_extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
+ encoder_attention_mask, embedding_output.dtype, tgt_len=seq_length
+ )
+ else:
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
+ else:
+ encoder_extended_attention_mask = None
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+# Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class XLMRobertaForCausalLM(XLMRobertaPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `XLMRobertaLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+ self.lm_head = XLMRobertaLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs,
+ ) -> Union[tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLMRobertaForCausalLM, AutoConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base")
+ >>> config = AutoConfig.from_pretrained("FacebookAI/roberta-base")
+ >>> config.is_decoder = True
+ >>> model = XLMRobertaForCausalLM.from_pretrained("FacebookAI/roberta-base", config=config)
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ if labels is not None:
+ use_cache = False
+
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ lm_loss = None
+ if labels is not None:
+ # move labels to correct device to enable model parallelism
+ labels = labels.to(prediction_scores.device)
+ lm_loss = self.loss_function(
+ prediction_scores,
+ labels,
+ vocab_size=self.config.vocab_size,
+ **kwargs,
+ )
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((lm_loss,) + output) if lm_loss is not None else output
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=lm_loss,
+ logits=prediction_scores,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+# Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class XLMRobertaForMaskedLM(XLMRobertaPreTrainedModel):
+ _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `XLMRobertaForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+ self.lm_head = XLMRobertaLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], MaskedLMOutput]:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ # move labels to correct device to enable model parallelism
+ labels = labels.to(prediction_scores.device)
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaLMHead
+class XLMRobertaLMHead(nn.Module):
+ """Roberta Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+ self.decoder.bias = self.bias
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+ def _tie_weights(self):
+ # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
+ # For accelerate compatibility and to not break backward compatibility
+ if self.decoder.bias.device.type == "meta":
+ self.decoder.bias = self.bias
+ else:
+ self.bias = self.decoder.bias
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the
+ pooled output) e.g. for GLUE tasks.
+ """
+)
+# Copied from transformers.models.roberta.modeling_roberta.RobertaForSequenceClassification with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class XLMRobertaForSequenceClassification(XLMRobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+ self.classifier = XLMRobertaClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device to enable model parallelism
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+# Copied from transformers.models.roberta.modeling_roberta.RobertaForMultipleChoice with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class XLMRobertaForMultipleChoice(XLMRobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.roberta = XLMRobertaModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], MultipleChoiceModelOutput]:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ head_mask=head_mask,
+ inputs_embeds=flat_inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device to enable model parallelism
+ labels = labels.to(reshaped_logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+# Copied from transformers.models.roberta.modeling_roberta.RobertaForTokenClassification with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class XLMRobertaForTokenClassification(XLMRobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device to enable model parallelism
+ labels = labels.to(logits.device)
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead with Roberta->XLMRoberta
+class XLMRobertaClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring
+# Copied from transformers.models.roberta.modeling_roberta.RobertaForQuestionAnswering with Roberta->XLMRoberta, ROBERTA->XLM_ROBERTA
+class XLMRobertaForQuestionAnswering(XLMRobertaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XLMRobertaModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ start_positions: Optional[torch.LongTensor] = None,
+ end_positions: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
+ r"""
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value
+ >= 2. All the value in this tensor should be always < type_vocab_size.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[2:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
+def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+__all__ = [
+ "XLMRobertaForCausalLM",
+ "XLMRobertaForMaskedLM",
+ "XLMRobertaForMultipleChoice",
+ "XLMRobertaForQuestionAnswering",
+ "XLMRobertaForSequenceClassification",
+ "XLMRobertaForTokenClassification",
+ "XLMRobertaModel",
+ "XLMRobertaPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/tokenization_xlm_roberta.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/tokenization_xlm_roberta.py
new file mode 100644
index 0000000000000000000000000000000000000000..149a09f5ed61a67e52f7f0a1170b5d70b99a6bb6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/tokenization_xlm_roberta.py
@@ -0,0 +1,301 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License
+"""Tokenization classes for XLM-RoBERTa model."""
+
+import os
+from shutil import copyfile
+from typing import Any, Optional
+
+import sentencepiece as spm
+
+from ...tokenization_utils import AddedToken, PreTrainedTokenizer
+from ...utils import logging
+from ...utils.import_utils import requires
+
+
+logger = logging.get_logger(__name__)
+
+SPIECE_UNDERLINE = "▁"
+
+VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model"}
+
+
+@requires(backends=("sentencepiece",))
+class XLMRobertaTokenizer(PreTrainedTokenizer):
+ """
+ Adapted from [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
+ [SentencePiece](https://github.com/google/sentencepiece).
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Path to the vocabulary file.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ sp_model_kwargs (`dict`, *optional*):
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
+ to set:
+
+ - `enable_sampling`: Enable subword regularization.
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
+
+ - `nbest_size = {0,1}`: No sampling is performed.
+ - `nbest_size > 1`: samples from the nbest_size results.
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
+ using forward-filtering-and-backward-sampling algorithm.
+
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
+ BPE-dropout.
+
+ Attributes:
+ sp_model (`SentencePieceProcessor`):
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+
+ def __init__(
+ self,
+ vocab_file,
+ bos_token="",
+ eos_token="",
+ sep_token="",
+ cls_token="",
+ unk_token="",
+ pad_token="",
+ mask_token="",
+ sp_model_kwargs: Optional[dict[str, Any]] = None,
+ **kwargs,
+ ) -> None:
+ # Mask token behave like a normal word, i.e. include the space before it
+ mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
+
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.Load(str(vocab_file))
+ self.vocab_file = vocab_file
+
+ # Original fairseq vocab and spm vocab must be "aligned":
+ # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
+ # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
+ # fairseq | '' | '' | '' | '' | ',' | '.' | '▁' | 's' | '▁de' | '-'
+ # spm | '' | '' | '' | ',' | '.' | '▁' | 's' | '▁de' | '-' | '▁a'
+
+ # Mimic fairseq token-to-id alignment for the first 4 token
+ self.fairseq_tokens_to_ids = {"": 0, "": 1, "": 2, "": 3}
+
+ # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
+ self.fairseq_offset = 1
+
+ self.fairseq_tokens_to_ids[""] = len(self.sp_model) + self.fairseq_offset
+ self.fairseq_ids_to_tokens = {v: k for k, v in self.fairseq_tokens_to_ids.items()}
+
+ super().__init__(
+ bos_token=bos_token,
+ eos_token=eos_token,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ pad_token=pad_token,
+ mask_token=mask_token,
+ sp_model_kwargs=self.sp_model_kwargs,
+ **kwargs,
+ )
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state["sp_model"] = None
+ state["sp_model_proto"] = self.sp_model.serialized_model_proto()
+ return state
+
+ def __setstate__(self, d):
+ self.__dict__ = d
+
+ # for backward compatibility
+ if not hasattr(self, "sp_model_kwargs"):
+ self.sp_model_kwargs = {}
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.LoadFromSerializedProto(self.sp_model_proto)
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An XLM-RoBERTa sequence has the following format:
+
+ - single sequence: ` X `
+ - pair of sequences: ` A B `
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+
+ if token_ids_1 is None:
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
+ cls = [self.cls_token_id]
+ sep = [self.sep_token_id]
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is None:
+ return [1] + ([0] * len(token_ids_0)) + [1]
+ return [1] + ([0] * len(token_ids_0)) + [1, 1] + ([0] * len(token_ids_1)) + [1]
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does
+ not make use of token type ids, therefore a list of zeros is returned.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of zeros.
+
+ """
+
+ sep = [self.sep_token_id]
+ cls = [self.cls_token_id]
+
+ if token_ids_1 is None:
+ return len(cls + token_ids_0 + sep) * [0]
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
+
+ @property
+ def vocab_size(self):
+ return len(self.sp_model) + self.fairseq_offset + 1 # Add the token
+
+ def get_vocab(self):
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
+ vocab.update(self.added_tokens_encoder)
+ return vocab
+
+ def _tokenize(self, text: str) -> list[str]:
+ # TODO check if the t5/llama PR also applies here
+ return self.sp_model.encode(text, out_type=str)
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ if token in self.fairseq_tokens_to_ids:
+ return self.fairseq_tokens_to_ids[token]
+ spm_id = self.sp_model.PieceToId(token)
+
+ # Need to return unknown token if the SP model returned 0
+ return spm_id + self.fairseq_offset if spm_id else self.unk_token_id
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ if index in self.fairseq_ids_to_tokens:
+ return self.fairseq_ids_to_tokens[index]
+ return self.sp_model.IdToPiece(index - self.fairseq_offset)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (strings for sub-words) in a single string."""
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
+ return out_string
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ out_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
+ copyfile(self.vocab_file, out_vocab_file)
+ elif not os.path.isfile(self.vocab_file):
+ with open(out_vocab_file, "wb") as fi:
+ content_spiece_model = self.sp_model.serialized_model_proto()
+ fi.write(content_spiece_model)
+
+ return (out_vocab_file,)
+
+
+__all__ = ["XLMRobertaTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/tokenization_xlm_roberta_fast.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/tokenization_xlm_roberta_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..bcdea2325fc1ed14bd1b152f06ed619582e5e65c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta/tokenization_xlm_roberta_fast.py
@@ -0,0 +1,194 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License
+"""Tokenization classes for XLM-RoBERTa model."""
+
+import os
+from shutil import copyfile
+from typing import Optional
+
+from ...tokenization_utils import AddedToken
+from ...tokenization_utils_fast import PreTrainedTokenizerFast
+from ...utils import is_sentencepiece_available, logging
+
+
+if is_sentencepiece_available():
+ from .tokenization_xlm_roberta import XLMRobertaTokenizer
+else:
+ XLMRobertaTokenizer = None
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "sentencepiece.bpe.model", "tokenizer_file": "tokenizer.json"}
+
+
+class XLMRobertaTokenizerFast(PreTrainedTokenizerFast):
+ """
+ Construct a "fast" XLM-RoBERTa tokenizer (backed by HuggingFace's *tokenizers* library). Adapted from
+ [`RobertaTokenizer`] and [`XLNetTokenizer`]. Based on
+ [BPE](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=BPE#models).
+
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ Path to the vocabulary file.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["NOTUSED", "NOTUSED"]`):
+ Additional special tokens used by the tokenizer.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ slow_tokenizer_class = XLMRobertaTokenizer
+
+ def __init__(
+ self,
+ vocab_file=None,
+ tokenizer_file=None,
+ bos_token="",
+ eos_token="",
+ sep_token="",
+ cls_token="",
+ unk_token="",
+ pad_token="",
+ mask_token="",
+ **kwargs,
+ ):
+ # Mask token behave like a normal word, i.e. include the space before it
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
+
+ super().__init__(
+ vocab_file,
+ tokenizer_file=tokenizer_file,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ sep_token=sep_token,
+ cls_token=cls_token,
+ unk_token=unk_token,
+ pad_token=pad_token,
+ mask_token=mask_token,
+ **kwargs,
+ )
+
+ self.vocab_file = vocab_file
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An XLM-RoBERTa sequence has the following format:
+
+ - single sequence: ` X `
+ - pair of sequences: ` A B `
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+
+ if token_ids_1 is None:
+ return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
+ cls = [self.cls_token_id]
+ sep = [self.sep_token_id]
+ return cls + token_ids_0 + sep + sep + token_ids_1 + sep
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. XLM-RoBERTa does
+ not make use of token type ids, therefore a list of zeros is returned.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of zeros.
+
+ """
+
+ sep = [self.sep_token_id]
+ cls = [self.cls_token_id]
+
+ if token_ids_1 is None:
+ return len(cls + token_ids_0 + sep) * [0]
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if not self.can_save_slow_tokenizer:
+ raise ValueError(
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
+ "tokenizer."
+ )
+
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory.")
+ return
+ out_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
+ copyfile(self.vocab_file, out_vocab_file)
+
+ return (out_vocab_file,)
+
+
+__all__ = ["XLMRobertaTokenizerFast"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..57aaceadacea8342c64364f5b712089228a0ab66
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xlm_roberta_xl import *
+ from .modeling_xlm_roberta_xl import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py
new file mode 100644
index 0000000000000000000000000000000000000000..4111a61d4e26b6756a7b439bcdd390dc85227f6b
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py
@@ -0,0 +1,153 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""XLM_ROBERTa_XL configuration"""
+
+from collections import OrderedDict
+from collections.abc import Mapping
+
+from ...configuration_utils import PretrainedConfig
+from ...onnx import OnnxConfig
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class XLMRobertaXLConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`XLMRobertaXLModel`] or a [`TFXLMRobertaXLModel`].
+ It is used to instantiate a XLM_ROBERTA_XL model according to the specified arguments, defining the model
+ architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the
+ XLM_ROBERTA_XL [facebook/xlm-roberta-xl](https://huggingface.co/facebook/xlm-roberta-xl) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 250880):
+ Vocabulary size of the XLM_ROBERTA_XL model. Defines the number of different tokens that can be represented
+ by the `inputs_ids` passed when calling [`XLMRobertaXLModel`].
+ hidden_size (`int`, *optional*, defaults to 2560):
+ Dimensionality of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 36):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 32):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 10240):
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention probabilities.
+ max_position_embeddings (`int`, *optional*, defaults to 514):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ type_vocab_size (`int`, *optional*, defaults to 1):
+ The vocabulary size of the `token_type_ids` passed when calling [`XLMRobertaXLModel`] or
+ [`TFXLMRobertaXLModel`].
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-5):
+ The epsilon used by the layer normalization layers.
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
+ with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+ classifier_dropout (`float`, *optional*):
+ The dropout ratio for the classification head.
+
+ Examples:
+
+ ```python
+ >>> from transformers import XLMRobertaXLConfig, XLMRobertaXLModel
+
+ >>> # Initializing a XLM_ROBERTA_XL google-bert/bert-base-uncased style configuration
+ >>> configuration = XLMRobertaXLConfig()
+
+ >>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
+ >>> model = XLMRobertaXLModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xlm-roberta-xl"
+
+ def __init__(
+ self,
+ vocab_size=250880,
+ hidden_size=2560,
+ num_hidden_layers=36,
+ num_attention_heads=32,
+ intermediate_size=10240,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=514,
+ type_vocab_size=1,
+ initializer_range=0.02,
+ layer_norm_eps=1e-05,
+ pad_token_id=1,
+ bos_token_id=0,
+ eos_token_id=2,
+ position_embedding_type="absolute",
+ use_cache=True,
+ classifier_dropout=None,
+ **kwargs,
+ ):
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.hidden_act = hidden_act
+ self.intermediate_size = intermediate_size
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.max_position_embeddings = max_position_embeddings
+ self.type_vocab_size = type_vocab_size
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.position_embedding_type = position_embedding_type
+ self.use_cache = use_cache
+ self.classifier_dropout = classifier_dropout
+
+
+# Copied from transformers.models.roberta.configuration_roberta.RobertaOnnxConfig with Roberta->XLMRobertaXL
+class XLMRobertaXLOnnxConfig(OnnxConfig):
+ @property
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
+ if self.task == "multiple-choice":
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
+ else:
+ dynamic_axis = {0: "batch", 1: "sequence"}
+ return OrderedDict(
+ [
+ ("input_ids", dynamic_axis),
+ ("attention_mask", dynamic_axis),
+ ]
+ )
+
+
+__all__ = ["XLMRobertaXLConfig", "XLMRobertaXLOnnxConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bbe7591f779293eafba4d650778f72037d06ee6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py
@@ -0,0 +1,1522 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch XLM RoBERTa xl,xxl model."""
+
+import math
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import ACT2FN, gelu
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...modeling_attn_mask_utils import _prepare_4d_attention_mask_for_sdpa, _prepare_4d_causal_attention_mask_for_sdpa
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
+from ...utils import auto_docstring, logging
+from ...utils.deprecation import deprecate_kwarg
+from .configuration_xlm_roberta_xl import XLMRobertaXLConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+class XLMRobertaXLEmbeddings(nn.Module):
+ """
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
+ # any TensorFlow checkpoint file
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ # End copy
+ self.padding_idx = config.pad_token_id
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+
+ def forward(
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
+ ):
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+
+ embeddings = inputs_embeds + token_type_embeddings
+ if self.position_embedding_type == "absolute":
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings += position_embeddings
+
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings.create_position_ids_from_inputs_embeds
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->XLMRobertaXL
+class XLMRobertaXLSelfAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.position_embedding_type = position_embedding_type or getattr(
+ config, "position_embedding_type", "absolute"
+ )
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ self.max_position_embeddings = config.max_position_embeddings
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
+
+ self.is_decoder = config.is_decoder
+ self.layer_idx = layer_idx
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor]:
+ batch_size, seq_length, _ = hidden_states.shape
+ query_layer = self.query(hidden_states)
+ query_layer = query_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
+ 1, 2
+ )
+
+ is_cross_attention = encoder_hidden_states is not None
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_layer from cache
+ curr_past_key_value = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_value = past_key_values.self_attention_cache
+ else:
+ curr_past_key_value = past_key_values
+
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = curr_past_key_value.layers[self.layer_idx].keys
+ value_layer = curr_past_key_value.layers[self.layer_idx].values
+ else:
+ key_layer = self.key(current_states)
+ key_layer = key_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
+ 1, 2
+ )
+ value_layer = self.value(current_states)
+ value_layer = value_layer.view(
+ batch_size, -1, self.num_attention_heads, self.attention_head_size
+ ).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ cache_position = cache_position if not is_cross_attention else None
+ key_layer, value_layer = curr_past_key_value.update(
+ key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention:
+ past_key_values.is_updated[self.layer_idx] = True
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
+ if past_key_values is not None:
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
+ -1, 1
+ )
+ else:
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
+ distance = position_ids_l - position_ids_r
+
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
+
+ if self.position_embedding_type == "relative_key":
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores
+ elif self.position_embedding_type == "relative_key_query":
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in XLMRobertaXLModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = attention_probs * head_mask
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ return context_layer, attention_probs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSdpaSelfAttention with Bert->XLMRobertaXL
+class XLMRobertaXLSdpaSelfAttention(XLMRobertaXLSelfAttention):
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
+ super().__init__(config, position_embedding_type=position_embedding_type, layer_idx=layer_idx)
+ self.dropout_prob = config.attention_probs_dropout_prob
+
+ # Adapted from XLMRobertaXLSelfAttention
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor]:
+ if self.position_embedding_type != "absolute" or output_attentions or head_mask is not None:
+ # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once implemented.
+ logger.warning_once(
+ "XLMRobertaXLSdpaSelfAttention is used but `torch.nn.functional.scaled_dot_product_attention` does not support "
+ "non-absolute `position_embedding_type` or `output_attentions=True` or `head_mask`. Falling back to "
+ "the manual attention implementation, but specifying the manual implementation will be required from "
+ "Transformers version v5.0.0 onwards. This warning can be removed using the argument "
+ '`attn_implementation="eager"` when loading the model.'
+ )
+ return super().forward(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ past_key_values,
+ output_attentions,
+ cache_position,
+ )
+
+ bsz, tgt_len, _ = hidden_states.size()
+
+ query_layer = (
+ self.query(hidden_states).view(bsz, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
+ )
+
+ is_cross_attention = encoder_hidden_states is not None
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_states from cache
+ curr_past_key_value = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_value = past_key_values.self_attention_cache
+ else:
+ curr_past_key_value = past_key_values
+
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = curr_past_key_value.layers[self.layer_idx].keys
+ value_layer = curr_past_key_value.layers[self.layer_idx].values
+ else:
+ key_layer = (
+ self.key(current_states)
+ .view(bsz, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ value_layer = (
+ self.value(current_states)
+ .view(bsz, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+
+ if past_key_values is not None:
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ cache_position = cache_position if not is_cross_attention else None
+ key_layer, value_layer = curr_past_key_value.update(
+ key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention:
+ past_key_values.is_updated[self.layer_idx] = True
+
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
+ # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create
+ # a causal mask in case tgt_len == 1.
+ is_causal = self.is_decoder and not is_cross_attention and attention_mask is None and tgt_len > 1
+
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
+ query_layer,
+ key_layer,
+ value_layer,
+ attn_mask=attention_mask,
+ dropout_p=self.dropout_prob if self.training else 0.0,
+ is_causal=is_causal,
+ )
+
+ attn_output = attn_output.transpose(1, 2)
+ attn_output = attn_output.reshape(bsz, tgt_len, self.all_head_size)
+
+ return attn_output, None
+
+
+class XLMRobertaXLSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+XLMROBERTAXL_SELF_ATTENTION_CLASSES = {
+ "eager": XLMRobertaXLSelfAttention,
+ "sdpa": XLMRobertaXLSdpaSelfAttention,
+}
+
+
+class XLMRobertaXLAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
+ super().__init__()
+ self.self_attn_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.self = XLMROBERTAXL_SELF_ATTENTION_CLASSES[config._attn_implementation](
+ config,
+ position_embedding_type=position_embedding_type,
+ layer_idx=layer_idx,
+ )
+ self.output = XLMRobertaXLSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.self.query = prune_linear_layer(self.self.query, index)
+ self.self.key = prune_linear_layer(self.self.key, index)
+ self.self.value = prune_linear_layer(self.self.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ past_key_values=None,
+ output_attentions=False,
+ cache_position=None,
+ ):
+ intermediate = self.self_attn_layer_norm(hidden_states)
+ self_outputs = self.self(
+ intermediate,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ past_key_values,
+ output_attentions,
+ cache_position,
+ )
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertIntermediate
+class XLMRobertaXLIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class XLMRobertaXLOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states, input_tensor):
+ hidden_states = self.dense(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+class XLMRobertaXLLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = XLMRobertaXLAttention(config, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = XLMRobertaXLAttention(
+ config, position_embedding_type="absolute", layer_idx=layer_idx
+ )
+ self.intermediate = XLMRobertaXLIntermediate(config)
+ self.output = XLMRobertaXLOutput(config)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ output_attentions=False,
+ cache_position=None,
+ ):
+ self_attention_outputs = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ past_key_values=past_key_values,
+ cache_position=cache_position,
+ )
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_outputs = self.crossattention(
+ attention_output,
+ attention_mask=encoder_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ cache_position=cache_position,
+ )
+ attention_output = cross_attention_outputs[0]
+ outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ return (layer_output,) + outputs
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.LayerNorm(attention_output)
+ intermediate_output = self.intermediate(intermediate_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class XLMRobertaXLEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([XLMRobertaXLLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ use_cache=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ cache_position=None,
+ ):
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ if use_cache and past_key_values is None:
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if use_cache and isinstance(past_key_values, tuple):
+ logger.warning_once(
+ "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
+ "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
+ "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
+ )
+ past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
+
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
+
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+
+ layer_outputs = layer_module(
+ hidden_states,
+ attention_mask,
+ layer_head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values,
+ output_attentions,
+ cache_position,
+ )
+
+ hidden_states = layer_outputs[0]
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+ if self.config.add_cross_attention:
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
+
+ hidden_states = self.LayerNorm(hidden_states)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ hidden_states,
+ past_key_values,
+ all_hidden_states,
+ all_self_attentions,
+ all_cross_attentions,
+ ]
+ if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+# Copied from transformers.models.bert.modeling_bert.BertPooler
+class XLMRobertaXLPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@auto_docstring
+class XLMRobertaXLPreTrainedModel(PreTrainedModel):
+ config: XLMRobertaXLConfig
+ base_model_prefix = "roberta"
+ _no_split_modules = ["XLMRobertaXLEmbeddings", "XLMRobertaXLLayer"]
+ _supports_sdpa = True
+
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights with BertLMPredictionHead->XLMRobertaXLLMHead
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ elif isinstance(module, XLMRobertaXLLMHead):
+ module.bias.data.zero_()
+
+
+@auto_docstring
+# Copied from transformers.models.bert.modeling_bert.BertModel with Bert->XLMRobertaXL, BERT->XLM_ROBERTA_XL
+class XLMRobertaXLModel(XLMRobertaXLPreTrainedModel):
+ _no_split_modules = ["XLMRobertaXLEmbeddings", "XLMRobertaXLLayer"]
+
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = XLMRobertaXLEmbeddings(config)
+ self.encoder = XLMRobertaXLEncoder(config)
+
+ self.pooler = XLMRobertaXLPooler(config) if add_pooling_layer else None
+
+ self.attn_implementation = config._attn_implementation
+ self.position_embedding_type = config.position_embedding_type
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ batch_size, seq_length = input_shape
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ past_key_values_length = 0
+ if past_key_values is not None:
+ past_key_values_length = (
+ past_key_values[0][0].shape[-2]
+ if not isinstance(past_key_values, Cache)
+ else past_key_values.get_seq_length()
+ )
+
+ if token_type_ids is None:
+ if hasattr(self.embeddings, "token_type_ids"):
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ if attention_mask is None:
+ attention_mask = torch.ones((batch_size, seq_length + past_key_values_length), device=device)
+
+ use_sdpa_attention_masks = (
+ self.attn_implementation == "sdpa"
+ and self.position_embedding_type == "absolute"
+ and head_mask is None
+ and not output_attentions
+ )
+
+ # Expand the attention mask
+ if use_sdpa_attention_masks and attention_mask.dim() == 2:
+ # Expand the attention mask for SDPA.
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
+ if self.config.is_decoder:
+ extended_attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
+ attention_mask,
+ input_shape,
+ embedding_output,
+ past_key_values_length,
+ )
+ else:
+ extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
+ attention_mask, embedding_output.dtype, tgt_len=seq_length
+ )
+ else:
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
+ # ourselves in which case we just need to make it broadcastable to all heads.
+ extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape)
+
+ # If a 2D or 3D attention mask is provided for the cross-attention
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ if self.config.is_decoder and encoder_hidden_states is not None:
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
+ if encoder_attention_mask is None:
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
+
+ if use_sdpa_attention_masks and encoder_attention_mask.dim() == 2:
+ # Expand the attention mask for SDPA.
+ # [bsz, seq_len] -> [bsz, 1, seq_len, seq_len]
+ encoder_extended_attention_mask = _prepare_4d_attention_mask_for_sdpa(
+ encoder_attention_mask, embedding_output.dtype, tgt_len=seq_length
+ )
+ else:
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
+ else:
+ encoder_extended_attention_mask = None
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa-XL Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class XLMRobertaXLForCausalLM(XLMRobertaXLPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `RobertaLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.lm_head = XLMRobertaXLLMHead(config)
+
+ self.init_weights()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+ self.lm_head.bias = new_embeddings.bias
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs,
+ ) -> Union[tuple, CausalLMOutputWithCrossAttentions]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, RobertaForCausalLM, RobertaConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/roberta-base")
+ >>> config = RobertaConfig.from_pretrained("FacebookAI/roberta-base")
+ >>> config.is_decoder = True
+ >>> model = RobertaForCausalLM.from_pretrained("FacebookAI/roberta-base", config=config)
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+ >>> prediction_logits = outputs.logits
+ ```
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ if labels is not None:
+ use_cache = False
+
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ lm_loss = None
+ if labels is not None:
+ lm_loss = self.loss_function(
+ prediction_scores,
+ labels,
+ vocab_size=self.config.vocab_size,
+ **kwargs,
+ )
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((lm_loss,) + output) if lm_loss is not None else output
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=lm_loss,
+ logits=prediction_scores,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
+ # Overwritten -- model logic breaks when `inputs_embeds` are passed from this function
+
+ input_shape = input_ids.shape
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
+ if attention_mask is None:
+ attention_mask = input_ids.new_ones(input_shape)
+
+ # Create missing `position_ids` on the fly
+ position_ids = None
+ if model_kwargs.get("position_ids") is None:
+ position_ids = create_position_ids_from_input_ids(
+ input_ids, padding_idx=self.config.pad_token_id
+ ) # placed in kwargs for further processing (see below)
+
+ # cut decoder_input_ids if past_key_values is used
+ if past_key_values is not None:
+ past_length = past_key_values.get_seq_length()
+
+ # Some generation methods already pass only the last input ID
+ if input_ids.shape[1] > past_length:
+ remove_prefix_length = past_length
+ else:
+ # Default to old behavior: keep only final ID
+ remove_prefix_length = input_ids.shape[1] - 1
+
+ input_ids = input_ids[:, remove_prefix_length:]
+ if position_ids is not None:
+ position_ids = position_ids[:, remove_prefix_length:]
+
+ return {
+ "input_ids": input_ids,
+ "attention_mask": attention_mask,
+ "position_ids": position_ids,
+ "past_key_values": past_key_values,
+ }
+
+
+@auto_docstring
+class XLMRobertaXLForMaskedLM(XLMRobertaXLPreTrainedModel):
+ _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.lm_head = XLMRobertaXLLMHead(config)
+
+ self.init_weights()
+
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+ self.lm_head.bias = new_embeddings.bias
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, MaskedLMOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class XLMRobertaXLLMHead(nn.Module):
+ """XLM-RoBERTa-XL Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+ self.decoder.bias = self.bias
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+ def _tie_weights(self) -> None:
+ # For accelerate compatibility and to not break backward compatibility
+ if self.decoder.bias.device.type == "meta":
+ self.decoder.bias = self.bias
+ else:
+ # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
+ self.bias = self.decoder.bias
+
+
+@auto_docstring(
+ custom_intro="""
+ XLM-RoBERTa-XL Model transformer with a sequence classification/regression head on top (a linear layer on top
+ of the pooled output) e.g. for GLUE tasks.
+ """
+)
+class XLMRobertaXLForSequenceClassification(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.classifier = XLMRobertaXLClassificationHead(config)
+
+ self.init_weights()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, SequenceClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLForMultipleChoice(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.roberta = XLMRobertaXLModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ self.init_weights()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, MultipleChoiceModelOutput]:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary. Indices can be obtained using [`AutoTokenizer`]. See
+ [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input
+ IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ head_mask=head_mask,
+ inputs_embeds=flat_inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLMRobertaXLForTokenClassification(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.init_weights()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, TokenClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ # Only keep active parts of the loss
+ if attention_mask is not None:
+ active_loss = attention_mask.view(-1) == 1
+ active_logits = logits.view(-1, self.num_labels)
+ active_labels = torch.where(
+ active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
+ )
+ loss = loss_fct(active_logits, active_labels)
+ else:
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class XLMRobertaXLClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring
+class XLMRobertaXLForQuestionAnswering(XLMRobertaXLPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XLMRobertaXLModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.init_weights()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ start_positions: Optional[torch.LongTensor] = None,
+ end_positions: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, QuestionAnsweringModelOutput]:
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[2:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
+def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+__all__ = [
+ "XLMRobertaXLForCausalLM",
+ "XLMRobertaXLForMaskedLM",
+ "XLMRobertaXLForMultipleChoice",
+ "XLMRobertaXLForQuestionAnswering",
+ "XLMRobertaXLForSequenceClassification",
+ "XLMRobertaXLForTokenClassification",
+ "XLMRobertaXLModel",
+ "XLMRobertaXLPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f453455925328db06bf86ecc85c5acc8762dd26
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/__init__.py
@@ -0,0 +1,30 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xlnet import *
+ from .modeling_tf_xlnet import *
+ from .modeling_xlnet import *
+ from .tokenization_xlnet import *
+ from .tokenization_xlnet_fast import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/configuration_xlnet.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/configuration_xlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a7238eb4c098b93c7aa911bb958ebe771a4539c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/configuration_xlnet.py
@@ -0,0 +1,240 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""XLNet configuration"""
+
+import warnings
+
+from ...configuration_utils import PretrainedConfig
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class XLNetConfig(PretrainedConfig):
+ """
+ This is the configuration class to store the configuration of a [`XLNetModel`] or a [`TFXLNetModel`]. It is used to
+ instantiate a XLNet model according to the specified arguments, defining the model architecture. Instantiating a
+ configuration with the defaults will yield a similar configuration to that of the
+ [xlnet/xlnet-large-cased](https://huggingface.co/xlnet/xlnet-large-cased) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 32000):
+ Vocabulary size of the XLNet model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`XLNetModel`] or [`TFXLNetModel`].
+ d_model (`int`, *optional*, defaults to 1024):
+ Dimensionality of the encoder layers and the pooler layer.
+ n_layer (`int`, *optional*, defaults to 24):
+ Number of hidden layers in the Transformer encoder.
+ n_head (`int`, *optional*, defaults to 16):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ d_inner (`int`, *optional*, defaults to 4096):
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
+ ff_activation (`str` or `Callable`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the If string, `"gelu"`, `"relu"`, `"silu"` and
+ `"gelu_new"` are supported.
+ untie_r (`bool`, *optional*, defaults to `True`):
+ Whether or not to untie relative position biases
+ attn_type (`str`, *optional*, defaults to `"bi"`):
+ The attention type used by the model. Set `"bi"` for XLNet, `"uni"` for Transformer-XL.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ dropout (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ mem_len (`int` or `None`, *optional*):
+ The number of tokens to cache. The key/value pairs that have already been pre-computed in a previous
+ forward pass won't be re-computed. See the
+ [quickstart](https://huggingface.co/transformers/quickstart.html#using-the-past) for more information.
+ reuse_len (`int`, *optional*):
+ The number of tokens in the current batch to be cached and reused in the future.
+ bi_data (`bool`, *optional*, defaults to `False`):
+ Whether or not to use bidirectional input pipeline. Usually set to `True` during pretraining and `False`
+ during finetuning.
+ clamp_len (`int`, *optional*, defaults to -1):
+ Clamp all relative distances larger than clamp_len. Setting this attribute to -1 means no clamping.
+ same_length (`bool`, *optional*, defaults to `False`):
+ Whether or not to use the same attention length for each token.
+ summary_type (`str`, *optional*, defaults to "last"):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+
+ Has to be one of the following options:
+
+ - `"last"`: Take the last token hidden state (like XLNet).
+ - `"first"`: Take the first token hidden state (like BERT).
+ - `"mean"`: Take the mean of all tokens hidden states.
+ - `"cls_index"`: Supply a Tensor of classification token position (like GPT/GPT-2).
+ - `"attn"`: Not implemented now, use multi-head attention.
+ summary_use_proj (`bool`, *optional*, defaults to `True`):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+
+ Whether or not to add a projection after the vector extraction.
+ summary_activation (`str`, *optional*):
+ Argument used when doing sequence summary. Used in the sequence classification and multiple choice models.
+
+ Pass `"tanh"` for a tanh activation to the output, any other value will result in no activation.
+ summary_proj_to_labels (`boo`, *optional*, defaults to `True`):
+ Used in the sequence classification and multiple choice models.
+
+ Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
+ summary_last_dropout (`float`, *optional*, defaults to 0.1):
+ Used in the sequence classification and multiple choice models.
+
+ The dropout ratio to be used after the projection and activation.
+ start_n_top (`int`, *optional*, defaults to 5):
+ Used in the SQuAD evaluation script.
+ end_n_top (`int`, *optional*, defaults to 5):
+ Used in the SQuAD evaluation script.
+ use_mems_eval (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should make use of the recurrent memory mechanism in evaluation mode.
+ use_mems_train (`bool`, *optional*, defaults to `False`):
+ Whether or not the model should make use of the recurrent memory mechanism in train mode.
+
+
+
+ For pretraining, it is recommended to set `use_mems_train` to `True`. For fine-tuning, it is recommended to
+ set `use_mems_train` to `False` as discussed
+ [here](https://github.com/zihangdai/xlnet/issues/41#issuecomment-505102587). If `use_mems_train` is set to
+ `True`, one has to make sure that the train batches are correctly pre-processed, *e.g.* `batch_1 = [[This
+ line is], [This is the]]` and `batch_2 = [[ the first line], [ second line]]` and that all batches are of
+ equal size.
+
+
+
+ Examples:
+
+ ```python
+ >>> from transformers import XLNetConfig, XLNetModel
+
+ >>> # Initializing a XLNet configuration
+ >>> configuration = XLNetConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = XLNetModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xlnet"
+ keys_to_ignore_at_inference = ["mems"]
+ attribute_map = {
+ "n_token": "vocab_size", # Backward compatibility
+ "hidden_size": "d_model",
+ "num_attention_heads": "n_head",
+ "num_hidden_layers": "n_layer",
+ }
+
+ def __init__(
+ self,
+ vocab_size=32000,
+ d_model=1024,
+ n_layer=24,
+ n_head=16,
+ d_inner=4096,
+ ff_activation="gelu",
+ untie_r=True,
+ attn_type="bi",
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ dropout=0.1,
+ mem_len=512,
+ reuse_len=None,
+ use_mems_eval=True,
+ use_mems_train=False,
+ bi_data=False,
+ clamp_len=-1,
+ same_length=False,
+ summary_type="last",
+ summary_use_proj=True,
+ summary_activation="tanh",
+ summary_last_dropout=0.1,
+ start_n_top=5,
+ end_n_top=5,
+ pad_token_id=5,
+ bos_token_id=1,
+ eos_token_id=2,
+ **kwargs,
+ ):
+ """Constructs XLNetConfig."""
+ self.vocab_size = vocab_size
+ self.d_model = d_model
+ self.n_layer = n_layer
+ self.n_head = n_head
+ if d_model % n_head != 0:
+ raise ValueError(f"'d_model % n_head' ({d_model % n_head}) should be equal to 0")
+ if "d_head" in kwargs:
+ if kwargs["d_head"] != d_model // n_head:
+ raise ValueError(
+ f"`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})"
+ )
+ self.d_head = d_model // n_head
+ self.ff_activation = ff_activation
+ self.d_inner = d_inner
+ self.untie_r = untie_r
+ self.attn_type = attn_type
+
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+
+ self.dropout = dropout
+ self.mem_len = mem_len
+ self.reuse_len = reuse_len
+ self.bi_data = bi_data
+ self.clamp_len = clamp_len
+ self.same_length = same_length
+
+ self.summary_type = summary_type
+ self.summary_use_proj = summary_use_proj
+ self.summary_activation = summary_activation
+ self.summary_last_dropout = summary_last_dropout
+ self.start_n_top = start_n_top
+ self.end_n_top = end_n_top
+
+ self.bos_token_id = bos_token_id
+ self.pad_token_id = pad_token_id
+ self.eos_token_id = eos_token_id
+
+ if "use_cache" in kwargs:
+ warnings.warn(
+ "The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`"
+ " instead.",
+ FutureWarning,
+ )
+ use_mems_eval = kwargs["use_cache"]
+
+ self.use_mems_eval = use_mems_eval
+ self.use_mems_train = use_mems_train
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
+
+ @property
+ def max_position_embeddings(self):
+ logger.info(f"The model {self.model_type} is one of the few models that has no sequence length limit.")
+ return -1
+
+ @max_position_embeddings.setter
+ def max_position_embeddings(self, value):
+ # Message copied from Transformer-XL documentation
+ raise NotImplementedError(
+ f"The model {self.model_type} is one of the few models that has no sequence length limit."
+ )
+
+
+__all__ = ["XLNetConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/modeling_tf_xlnet.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/modeling_tf_xlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..451d26c844d8dc3c054a26c532e070e00460e22c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/modeling_tf_xlnet.py
@@ -0,0 +1,1820 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+TF 2.0 XLNet model.
+"""
+
+from __future__ import annotations
+
+import warnings
+from dataclasses import dataclass
+
+import numpy as np
+import tensorflow as tf
+
+from ...activations_tf import get_tf_activation
+from ...modeling_tf_utils import (
+ TFCausalLanguageModelingLoss,
+ TFModelInputType,
+ TFMultipleChoiceLoss,
+ TFPreTrainedModel,
+ TFQuestionAnsweringLoss,
+ TFSequenceClassificationLoss,
+ TFSequenceSummary,
+ TFSharedEmbeddings,
+ TFTokenClassificationLoss,
+ get_initializer,
+ keras,
+ keras_serializable,
+ unpack_inputs,
+)
+from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
+from ...utils import (
+ ModelOutput,
+ add_code_sample_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ logging,
+ replace_return_docstrings,
+)
+from .configuration_xlnet import XLNetConfig
+
+
+logger = logging.get_logger(__name__)
+
+_CHECKPOINT_FOR_DOC = "xlnet/xlnet-base-cased"
+_CONFIG_FOR_DOC = "XLNetConfig"
+
+
+class TFXLNetRelativeAttention(keras.layers.Layer):
+ def __init__(self, config, **kwargs):
+ super().__init__(**kwargs)
+
+ if config.d_model % config.n_head != 0:
+ raise ValueError(
+ f"The hidden size ({config.d_model}) is not a multiple of the number of attention "
+ f"heads ({config.n_head}"
+ )
+
+ self.n_head = config.n_head
+ self.d_head = config.d_head
+ self.d_model = config.d_model
+ self.scale = 1 / (config.d_head**0.5)
+ self.initializer_range = config.initializer_range
+ self.output_attentions = config.output_attentions
+
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
+ self.dropout = keras.layers.Dropout(config.dropout)
+ self.config = config
+
+ def build(self, input_shape=None):
+ initializer = get_initializer(self.initializer_range)
+ self.q = self.add_weight(
+ shape=(self.d_model, self.n_head, self.d_head), initializer=initializer, trainable=True, name="q"
+ )
+ self.k = self.add_weight(
+ shape=(self.d_model, self.n_head, self.d_head), initializer=initializer, trainable=True, name="k"
+ )
+ self.v = self.add_weight(
+ shape=(self.d_model, self.n_head, self.d_head), initializer=initializer, trainable=True, name="v"
+ )
+ self.o = self.add_weight(
+ shape=(self.d_model, self.n_head, self.d_head), initializer=initializer, trainable=True, name="o"
+ )
+ self.r = self.add_weight(
+ shape=(self.d_model, self.n_head, self.d_head), initializer=initializer, trainable=True, name="r"
+ )
+ self.r_r_bias = self.add_weight(
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_r_bias"
+ )
+ self.r_s_bias = self.add_weight(
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_s_bias"
+ )
+ self.r_w_bias = self.add_weight(
+ shape=(self.n_head, self.d_head), initializer="zeros", trainable=True, name="r_w_bias"
+ )
+ self.seg_embed = self.add_weight(
+ shape=(2, self.n_head, self.d_head), initializer=initializer, trainable=True, name="seg_embed"
+ )
+
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "layer_norm", None) is not None:
+ with tf.name_scope(self.layer_norm.name):
+ self.layer_norm.build([None, None, self.config.d_model])
+
+ def prune_heads(self, heads):
+ raise NotImplementedError
+
+ def rel_shift(self, x, klen=-1):
+ """perform relative shift to form the relative attention score."""
+ x_size = shape_list(x)
+
+ x = tf.reshape(x, (x_size[1], x_size[0], x_size[2], x_size[3]))
+ x = x[1:, ...]
+ x = tf.reshape(x, (x_size[0], x_size[1] - 1, x_size[2], x_size[3]))
+ x = x[:, 0:klen, :, :]
+ # x = torch.index_select(x, 1, torch.arange(klen, device=x.device, dtype=torch.long))
+
+ return x
+
+ def rel_attn_core(
+ self, q_head, k_head_h, v_head_h, k_head_r, seg_mat, attn_mask, head_mask, output_attentions, training=False
+ ):
+ """Core relative positional attention operations."""
+ # content based attention score
+ ac = tf.einsum("ibnd,jbnd->ijbn", q_head + self.r_w_bias, k_head_h)
+
+ # position based attention score
+ bd = tf.einsum("ibnd,jbnd->ijbn", q_head + self.r_r_bias, k_head_r)
+ bd = self.rel_shift(bd, klen=shape_list(ac)[1])
+
+ # segment based attention score
+ if seg_mat is None:
+ ef = 0
+ else:
+ ef = tf.einsum("ibnd,snd->ibns", q_head + self.r_s_bias, self.seg_embed)
+ ef = tf.einsum("ijbs,ibns->ijbn", seg_mat, ef)
+
+ # merge attention scores and perform masking
+ attn_score = (ac + bd + ef) * self.scale
+ if attn_mask is not None:
+ # attn_score = attn_score * (1 - attn_mask) - 1e30 * attn_mask
+ if attn_mask.dtype == tf.float16 or attn_mask.dtype == tf.bfloat16:
+ attn_score = attn_score - 65500 * attn_mask
+ else:
+ attn_score = attn_score - 1e30 * attn_mask
+
+ # attention probability
+ attn_prob = stable_softmax(attn_score, axis=1)
+
+ attn_prob = self.dropout(attn_prob, training=training)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attn_prob = attn_prob * head_mask
+
+ # attention output
+ attn_vec = tf.einsum("ijbn,jbnd->ibnd", attn_prob, v_head_h)
+
+ if output_attentions:
+ return attn_vec, attn_prob
+
+ return attn_vec
+
+ def post_attention(self, h, attn_vec, residual=True, training=False):
+ """Post-attention processing."""
+ # post-attention projection (back to `d_model`)
+ attn_out = tf.einsum("ibnd,hnd->ibh", attn_vec, self.o)
+
+ attn_out = self.dropout(attn_out, training=training)
+
+ if residual:
+ attn_out = attn_out + h
+ output = self.layer_norm(attn_out)
+
+ return output
+
+ def call(
+ self,
+ h,
+ g,
+ attn_mask_h,
+ attn_mask_g,
+ r,
+ seg_mat,
+ mems: np.ndarray | tf.Tensor | None = None,
+ target_mapping: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = False,
+ training: bool = False,
+ ):
+ if g is not None:
+ # Two-stream attention with relative positional encoding.
+ # content based attention score
+ if mems is not None and len(shape_list(mems)) > 1:
+ cat = tf.concat([mems, h], axis=0)
+ else:
+ cat = h
+
+ # content-based key head
+ k_head_h = tf.einsum("ibh,hnd->ibnd", cat, self.k)
+
+ # content-based value head
+ v_head_h = tf.einsum("ibh,hnd->ibnd", cat, self.v)
+
+ # position-based key head
+ k_head_r = tf.einsum("ibh,hnd->ibnd", r, self.r)
+
+ # h-stream
+ # content-stream query head
+ q_head_h = tf.einsum("ibh,hnd->ibnd", h, self.q)
+
+ # core attention ops
+ attn_vec_h = self.rel_attn_core(
+ q_head_h,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat,
+ attn_mask_h,
+ head_mask,
+ output_attentions,
+ training=training,
+ )
+
+ if output_attentions:
+ attn_vec_h, attn_prob_h = attn_vec_h
+
+ # post processing
+ output_h = self.post_attention(h, attn_vec_h, training=training)
+
+ # g-stream
+ # query-stream query head
+ q_head_g = tf.einsum("ibh,hnd->ibnd", g, self.q)
+
+ # core attention ops
+ if target_mapping is not None:
+ q_head_g = tf.einsum("mbnd,mlb->lbnd", q_head_g, target_mapping)
+ attn_vec_g = self.rel_attn_core(
+ q_head_g,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat,
+ attn_mask_g,
+ head_mask,
+ output_attentions,
+ training=training,
+ )
+
+ if output_attentions:
+ attn_vec_g, attn_prob_g = attn_vec_g
+
+ attn_vec_g = tf.einsum("lbnd,mlb->mbnd", attn_vec_g, target_mapping)
+ else:
+ attn_vec_g = self.rel_attn_core(
+ q_head_g,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat,
+ attn_mask_g,
+ head_mask,
+ output_attentions,
+ training=training,
+ )
+
+ if output_attentions:
+ attn_vec_g, attn_prob_g = attn_vec_g
+
+ # post processing
+ output_g = self.post_attention(g, attn_vec_g, training=training)
+
+ if output_attentions:
+ attn_prob = attn_prob_h, attn_prob_g
+
+ else:
+ # Multi-head attention with relative positional encoding
+ if mems is not None and len(shape_list(mems)) > 1:
+ cat = tf.concat([mems, h], axis=0)
+ else:
+ cat = h
+
+ # content heads
+ q_head_h = tf.einsum("ibh,hnd->ibnd", h, self.q)
+ k_head_h = tf.einsum("ibh,hnd->ibnd", cat, self.k)
+ v_head_h = tf.einsum("ibh,hnd->ibnd", cat, self.v)
+
+ # positional heads
+ k_head_r = tf.einsum("ibh,hnd->ibnd", r, self.r)
+
+ # core attention ops
+ attn_vec = self.rel_attn_core(
+ q_head_h,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat,
+ attn_mask_h,
+ head_mask,
+ output_attentions,
+ training=training,
+ )
+
+ if output_attentions:
+ attn_vec, attn_prob = attn_vec
+
+ # post processing
+ output_h = self.post_attention(h, attn_vec, training=training)
+ output_g = None
+
+ outputs = (output_h, output_g)
+ if output_attentions:
+ outputs = outputs + (attn_prob,)
+ return outputs
+
+
+class TFXLNetFeedForward(keras.layers.Layer):
+ def __init__(self, config, **kwargs):
+ super().__init__(**kwargs)
+ self.layer_norm = keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layer_norm")
+ self.layer_1 = keras.layers.Dense(
+ config.d_inner, kernel_initializer=get_initializer(config.initializer_range), name="layer_1"
+ )
+ self.layer_2 = keras.layers.Dense(
+ config.d_model, kernel_initializer=get_initializer(config.initializer_range), name="layer_2"
+ )
+ self.dropout = keras.layers.Dropout(config.dropout)
+ if isinstance(config.ff_activation, str):
+ self.activation_function = get_tf_activation(config.ff_activation)
+ else:
+ self.activation_function = config.ff_activation
+ self.config = config
+
+ def call(self, inp, training=False):
+ output = inp
+ output = self.layer_1(output)
+ output = self.activation_function(output)
+ output = self.dropout(output, training=training)
+ output = self.layer_2(output)
+ output = self.dropout(output, training=training)
+ output = self.layer_norm(output + inp)
+ return output
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "layer_norm", None) is not None:
+ with tf.name_scope(self.layer_norm.name):
+ self.layer_norm.build([None, None, self.config.d_model])
+ if getattr(self, "layer_1", None) is not None:
+ with tf.name_scope(self.layer_1.name):
+ self.layer_1.build([None, None, self.config.d_model])
+ if getattr(self, "layer_2", None) is not None:
+ with tf.name_scope(self.layer_2.name):
+ self.layer_2.build([None, None, self.config.d_inner])
+
+
+class TFXLNetLayer(keras.layers.Layer):
+ def __init__(self, config, **kwargs):
+ super().__init__(**kwargs)
+ self.rel_attn = TFXLNetRelativeAttention(config, name="rel_attn")
+ self.ff = TFXLNetFeedForward(config, name="ff")
+ self.dropout = keras.layers.Dropout(config.dropout)
+
+ def call(
+ self,
+ output_h,
+ output_g,
+ non_tgt_mask,
+ attn_mask,
+ pos_emb,
+ seg_mat,
+ mems: np.ndarray | tf.Tensor | None = None,
+ target_mapping: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ output_attentions: bool | None = False,
+ training: bool = False,
+ ):
+ outputs = self.rel_attn(
+ output_h,
+ output_g,
+ non_tgt_mask,
+ attn_mask,
+ pos_emb,
+ seg_mat,
+ mems,
+ target_mapping,
+ head_mask,
+ output_attentions,
+ training=training,
+ )
+ output_h, output_g = outputs[:2]
+
+ if output_g is not None:
+ output_g = self.ff(output_g, training=training)
+ output_h = self.ff(output_h, training=training)
+
+ outputs = (output_h, output_g) + outputs[2:] # Add again attentions if there are there
+ return outputs
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "rel_attn", None) is not None:
+ with tf.name_scope(self.rel_attn.name):
+ self.rel_attn.build(None)
+ if getattr(self, "ff", None) is not None:
+ with tf.name_scope(self.ff.name):
+ self.ff.build(None)
+
+
+class TFXLNetLMHead(keras.layers.Layer):
+ def __init__(self, config, input_embeddings, **kwargs):
+ super().__init__(**kwargs)
+ self.config = config
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.input_embeddings = input_embeddings
+
+ def build(self, input_shape):
+ self.bias = self.add_weight(shape=(self.config.vocab_size,), initializer="zeros", trainable=True, name="bias")
+ super().build(input_shape)
+
+ def get_output_embeddings(self):
+ return self.input_embeddings
+
+ def set_output_embeddings(self, value):
+ self.input_embeddings.weight = value
+ self.input_embeddings.vocab_size = shape_list(value)[0]
+
+ def get_bias(self):
+ return {"bias": self.bias}
+
+ def set_bias(self, value):
+ self.bias = value["bias"]
+ self.config.vocab_size = shape_list(value["bias"])[0]
+
+ def call(self, hidden_states):
+ hidden_states = self.input_embeddings(hidden_states, mode="linear")
+ hidden_states = hidden_states + self.bias
+ return hidden_states
+
+
+@keras_serializable
+class TFXLNetMainLayer(keras.layers.Layer):
+ config_class = XLNetConfig
+
+ def __init__(self, config, **kwargs):
+ super().__init__(**kwargs)
+
+ self.config = config
+ self.output_hidden_states = config.output_hidden_states
+ self.output_attentions = config.output_attentions
+ self.return_dict = config.return_dict
+
+ self.mem_len = config.mem_len
+ self.reuse_len = config.reuse_len
+ self.d_model = config.d_model
+ self.same_length = config.same_length
+ self.attn_type = config.attn_type
+ self.bi_data = config.bi_data
+ self.clamp_len = config.clamp_len
+ self.n_layer = config.n_layer
+ self.use_bfloat16 = config.use_bfloat16
+ self.initializer_range = config.initializer_range
+
+ self.word_embedding = TFSharedEmbeddings(
+ config.vocab_size, config.d_model, initializer_range=config.initializer_range, name="word_embedding"
+ )
+ self.layer = [TFXLNetLayer(config, name=f"layer_._{i}") for i in range(config.n_layer)]
+ self.dropout = keras.layers.Dropout(config.dropout)
+
+ self.use_mems_eval = config.use_mems_eval
+ self.use_mems_train = config.use_mems_train
+
+ def get_input_embeddings(self):
+ return self.word_embedding
+
+ def set_input_embeddings(self, value):
+ self.word_embedding.weight = value
+ self.word_embedding.vocab_size = shape_list(value)[0]
+
+ def build(self, input_shape=None):
+ initializer = get_initializer(self.initializer_range)
+ self.mask_emb = self.add_weight(
+ shape=(1, 1, self.d_model), initializer=initializer, trainable=True, name="mask_emb"
+ )
+
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "word_embedding", None) is not None:
+ with tf.name_scope(self.word_embedding.name):
+ self.word_embedding.build(None)
+ if getattr(self, "layer", None) is not None:
+ for layer in self.layer:
+ with tf.name_scope(layer.name):
+ layer.build(None)
+
+ def _prune_heads(self, heads_to_prune):
+ raise NotImplementedError
+
+ def create_mask(self, qlen, mlen):
+ """
+ Creates causal attention mask. Float mask where 1.0 indicates masked, 0.0 indicates not-masked.
+
+ Args:
+ qlen: TODO Lysandre didn't fill
+ mlen: TODO Lysandre didn't fill
+
+ ```
+
+ same_length=False: same_length=True:
+ < qlen > < qlen >
+ ^ [0 0 0 0 0 1 1 1 1] [0 0 0 0 0 1 1 1 1]
+ [0 0 0 0 0 0 1 1 1] [1 0 0 0 0 0 1 1 1]
+ qlen [0 0 0 0 0 0 0 1 1] [1 1 0 0 0 0 0 1 1]
+ [0 0 0 0 0 0 0 0 1] [1 1 1 0 0 0 0 0 1]
+ v [0 0 0 0 0 0 0 0 0] [1 1 1 1 0 0 0 0 0]
+ ```
+ """
+ attn_mask = tf.ones([qlen, qlen])
+ mask_u = tf.linalg.band_part(attn_mask, 0, -1)
+ mask_dia = tf.linalg.band_part(attn_mask, 0, 0)
+ attn_mask_pad = tf.zeros([qlen, mlen])
+ ret = tf.concat([attn_mask_pad, mask_u - mask_dia], 1)
+ if self.same_length:
+ mask_l = tf.linalg.band_part(attn_mask, -1, 0)
+ ret = tf.concat([ret[:, :qlen] + mask_l - mask_dia, ret[:, qlen:]], 1)
+ return ret
+
+ def cache_mem(self, curr_out, prev_mem):
+ # cache hidden states into memory.
+ if self.reuse_len is not None and self.reuse_len > 0:
+ curr_out = curr_out[: self.reuse_len]
+
+ if self.mem_len is None or self.mem_len == 0:
+ # If `use_mems` is active but no `mem_len` is defined, the model behaves like GPT-2 at inference time
+ # and returns all of the past and current hidden states.
+ cutoff = 0
+ else:
+ # If `use_mems` is active and `mem_len` is defined, the model returns the last `mem_len` hidden
+ # states. This is the preferred setting for training and long-form generation.
+ cutoff = -self.mem_len
+ if prev_mem is None:
+ # if `use_mems` is active and `mem_len` is defined, the model
+ new_mem = curr_out[cutoff:]
+ else:
+ new_mem = tf.concat([prev_mem, curr_out], 0)[cutoff:]
+
+ return tf.stop_gradient(new_mem)
+
+ @staticmethod
+ def positional_embedding(pos_seq, inv_freq, bsz=None):
+ sinusoid_inp = tf.einsum("i,d->id", pos_seq, inv_freq)
+ pos_emb = tf.concat([tf.sin(sinusoid_inp), tf.cos(sinusoid_inp)], axis=-1)
+ pos_emb = pos_emb[:, None, :]
+
+ if bsz is not None:
+ pos_emb = tf.tile(pos_emb, [1, bsz, 1])
+
+ return pos_emb
+
+ def relative_positional_encoding(self, qlen, klen, bsz=None):
+ """create relative positional encoding."""
+ freq_seq = tf.range(0, self.d_model, 2.0)
+ inv_freq = 1 / (10000 ** (freq_seq / self.d_model))
+
+ if self.attn_type == "bi":
+ # beg, end = klen - 1, -qlen
+ beg, end = klen, -qlen
+ elif self.attn_type == "uni":
+ # beg, end = klen - 1, -1
+ beg, end = klen, -1
+ else:
+ raise ValueError(f"Unknown `attn_type` {self.attn_type}.")
+
+ if self.bi_data:
+ fwd_pos_seq = tf.range(beg, end, -1.0)
+ bwd_pos_seq = tf.range(-beg, -end, 1.0)
+
+ if self.clamp_len > 0:
+ fwd_pos_seq = tf.clip_by_value(fwd_pos_seq, -self.clamp_len, self.clamp_len)
+ bwd_pos_seq = tf.clip_by_value(bwd_pos_seq, -self.clamp_len, self.clamp_len)
+
+ if bsz is not None:
+ if bsz % 2 != 0:
+ raise ValueError(f"With bi_data, the batch size {bsz} should be divisible by 2")
+ fwd_pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq, bsz // 2)
+ bwd_pos_emb = self.positional_embedding(bwd_pos_seq, inv_freq, bsz // 2)
+ else:
+ fwd_pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq)
+ bwd_pos_emb = self.positional_embedding(bwd_pos_seq, inv_freq)
+
+ pos_emb = tf.concat([fwd_pos_emb, bwd_pos_emb], axis=1)
+ else:
+ fwd_pos_seq = tf.range(beg, end, -1.0)
+ if self.clamp_len > 0:
+ fwd_pos_seq = tf.clip_by_value(fwd_pos_seq, -self.clamp_len, self.clamp_len)
+ pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq, bsz)
+
+ return pos_emb
+
+ @unpack_inputs
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ mems: np.ndarray | tf.Tensor | None = None,
+ perm_mask: np.ndarray | tf.Tensor | None = None,
+ target_mapping: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ input_mask: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ training: bool = False,
+ ):
+ if training and use_mems is None:
+ use_mems = self.use_mems_train
+ else:
+ use_mems = self.use_mems_eval
+
+ # the original code for XLNet uses shapes [len, bsz] with the batch dimension at the end
+ # but we want a unified interface in the library with the batch size on the first dimension
+ # so we move here the first dimension (batch) to the end
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_ids = tf.transpose(input_ids, perm=(1, 0))
+ qlen, bsz = shape_list(input_ids)[:2]
+ elif inputs_embeds is not None:
+ inputs_embeds = tf.transpose(inputs_embeds, perm=(1, 0, 2))
+ qlen, bsz = shape_list(inputs_embeds)[:2]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ token_type_ids = tf.transpose(token_type_ids, perm=(1, 0)) if token_type_ids is not None else None
+ input_mask = tf.transpose(input_mask, perm=(1, 0)) if input_mask is not None else None
+ attention_mask = tf.transpose(attention_mask, perm=(1, 0)) if attention_mask is not None else None
+ perm_mask = tf.transpose(perm_mask, perm=(1, 2, 0)) if perm_mask is not None else None
+ target_mapping = tf.transpose(target_mapping, perm=(1, 2, 0)) if target_mapping is not None else None
+
+ mlen = shape_list(mems[0])[0] if mems is not None and mems[0] is not None else 0
+ klen = mlen + qlen
+
+ # Attention mask
+ # causal attention mask
+ if self.attn_type == "uni":
+ attn_mask = self.create_mask(qlen, mlen)
+ attn_mask = attn_mask[:, :, None, None]
+ elif self.attn_type == "bi":
+ attn_mask = None
+ else:
+ raise ValueError(f"Unsupported attention type: {self.attn_type}")
+
+ # data mask: input mask & perm mask
+ assert input_mask is None or attention_mask is None, (
+ "You can only use one of input_mask (uses 1 for padding) "
+ "or attention_mask (uses 0 for padding, added for compatibility with BERT). Please choose one."
+ )
+ if input_mask is None and attention_mask is not None:
+ one_cst = tf.constant(1.0)
+ input_mask = 1.0 - tf.cast(attention_mask, dtype=one_cst.dtype)
+ if input_mask is not None and perm_mask is not None:
+ data_mask = input_mask[None] + perm_mask
+ elif input_mask is not None and perm_mask is None:
+ data_mask = input_mask[None]
+ elif input_mask is None and perm_mask is not None:
+ data_mask = perm_mask
+ else:
+ data_mask = None
+
+ if data_mask is not None:
+ # all mems can be attended to
+ if mlen > 0:
+ mems_mask = tf.zeros([shape_list(data_mask)[0], mlen, bsz])
+ data_mask = tf.concat([mems_mask, data_mask], axis=1)
+ if attn_mask is None:
+ attn_mask = data_mask[:, :, :, None]
+ else:
+ attn_mask += data_mask[:, :, :, None]
+
+ if attn_mask is not None:
+ attn_mask = tf.cast(attn_mask > 0, dtype=attn_mask.dtype)
+
+ if attn_mask is not None:
+ non_tgt_mask = -tf.eye(qlen)
+ if mlen > 0:
+ non_tgt_mask = tf.concat([tf.zeros([qlen, mlen]), non_tgt_mask], axis=-1)
+ non_tgt_mask = tf.cast((attn_mask + non_tgt_mask[:, :, None, None]) > 0, dtype=non_tgt_mask.dtype)
+ else:
+ non_tgt_mask = None
+
+ # Word embeddings and prepare h & g hidden states
+ if inputs_embeds is not None:
+ word_emb_k = inputs_embeds
+ else:
+ check_embeddings_within_bounds(input_ids, self.word_embedding.vocab_size)
+ word_emb_k = self.word_embedding(input_ids)
+ output_h = self.dropout(word_emb_k, training=training)
+ if target_mapping is not None:
+ word_emb_q = tf.tile(self.mask_emb, [shape_list(target_mapping)[0], bsz, 1])
+ # else: # We removed the inp_q input which was same as target mapping
+ # inp_q_ext = inp_q[:, :, None]
+ # word_emb_q = inp_q_ext * self.mask_emb + (1 - inp_q_ext) * word_emb_k
+ output_g = self.dropout(word_emb_q, training=training)
+ else:
+ output_g = None
+
+ # Segment embedding
+ if token_type_ids is not None:
+ # Convert `token_type_ids` to one-hot `seg_mat`
+ if mlen > 0:
+ mem_pad = tf.zeros([mlen, bsz], dtype=token_type_ids.dtype)
+ cat_ids = tf.concat([mem_pad, token_type_ids], 0)
+ else:
+ cat_ids = token_type_ids
+
+ # `1` indicates not in the same segment [qlen x klen x bsz]
+ seg_mat = tf.cast(
+ tf.logical_not(tf.equal(token_type_ids[:, None], cat_ids[None, :])),
+ dtype=token_type_ids.dtype,
+ )
+ seg_mat = tf.one_hot(seg_mat, 2)
+ else:
+ seg_mat = None
+
+ # Positional encoding
+ pos_emb = self.relative_positional_encoding(qlen, klen, bsz=bsz)
+ pos_emb = self.dropout(pos_emb, training=training)
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
+ # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
+ if head_mask is not None:
+ raise NotImplementedError
+ else:
+ head_mask = [None] * self.n_layer
+
+ new_mems = ()
+ if mems is None:
+ mems = [None] * len(self.layer)
+
+ attentions = [] if output_attentions else None
+ hidden_states = [] if output_hidden_states else None
+ for i, layer_module in enumerate(self.layer):
+ # cache new mems
+ if use_mems:
+ new_mems = new_mems + (self.cache_mem(output_h, mems[i]),)
+ if output_hidden_states:
+ hidden_states.append((output_h, output_g) if output_g is not None else output_h)
+
+ outputs = layer_module(
+ output_h,
+ output_g,
+ non_tgt_mask,
+ attn_mask,
+ pos_emb,
+ seg_mat,
+ mems[i],
+ target_mapping,
+ head_mask[i],
+ output_attentions,
+ training=training,
+ )
+ output_h, output_g = outputs[:2]
+ if output_attentions:
+ attentions.append(outputs[2])
+
+ # Add last hidden state
+ if output_hidden_states:
+ hidden_states.append((output_h, output_g) if output_g is not None else output_h)
+
+ output = self.dropout(output_g if output_g is not None else output_h, training=training)
+
+ # Prepare outputs, we transpose back here to shape [bsz, len, hidden_dim] (cf. beginning of forward() method)
+ output = tf.transpose(output, perm=(1, 0, 2))
+
+ if not use_mems:
+ new_mems = None
+ if output_hidden_states:
+ if output_g is not None:
+ hidden_states = tuple(tf.transpose(h, perm=(1, 0, 2)) for hs in hidden_states for h in hs)
+ else:
+ hidden_states = tuple(tf.transpose(hs, perm=(1, 0, 2)) for hs in hidden_states)
+ if output_attentions:
+ if target_mapping is not None:
+ # when target_mapping is provided, there are 2-tuple of attentions
+ attentions = tuple(
+ tuple(tf.transpose(attn_stream, perm=(2, 3, 0, 1)) for attn_stream in t) for t in attentions
+ )
+ else:
+ attentions = tuple(tf.transpose(t, perm=(2, 3, 0, 1)) for t in attentions)
+
+ if not return_dict:
+ return tuple(v for v in [output, new_mems, hidden_states, attentions] if v is not None)
+
+ return TFXLNetModelOutput(
+ last_hidden_state=output, mems=new_mems, hidden_states=hidden_states, attentions=attentions
+ )
+
+
+class TFXLNetPreTrainedModel(TFPreTrainedModel):
+ """
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
+ models.
+ """
+
+ config_class = XLNetConfig
+ base_model_prefix = "transformer"
+
+
+@dataclass
+class TFXLNetModelOutput(ModelOutput):
+ """
+ Output type of [`TFXLNetModel`].
+
+ Args:
+ last_hidden_state (`tf.Tensor` of shape `(batch_size, num_predict, hidden_size)`):
+ Sequence of hidden-states at the last layer of the model.
+
+ `num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
+ corresponds to `sequence_length`.
+ mems (`list[tf.Tensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ last_hidden_state: tf.Tensor | None = None
+ mems: list[tf.Tensor] | None = None
+ hidden_states: tuple[tf.Tensor, ...] | None = None
+ attentions: tuple[tf.Tensor, ...] | None = None
+
+
+@dataclass
+class TFXLNetLMHeadModelOutput(ModelOutput):
+ """
+ Output type of [`TFXLNetLMHeadModel`].
+
+ Args:
+ loss (`tf.Tensor` of shape *(1,)*, *optional*, returned when `labels` is provided)
+ Language modeling loss (for next-token prediction).
+ logits (`tf.Tensor` of shape `(batch_size, num_predict, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+
+ `num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
+ corresponds to `sequence_length`.
+ mems (`list[tf.Tensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: tf.Tensor | None = None
+ logits: tf.Tensor | None = None
+ mems: list[tf.Tensor] | None = None
+ hidden_states: tuple[tf.Tensor, ...] | None = None
+ attentions: tuple[tf.Tensor, ...] | None = None
+
+
+@dataclass
+class TFXLNetForSequenceClassificationOutput(ModelOutput):
+ """
+ Output type of [`TFXLNetForSequenceClassification`].
+
+ Args:
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `label` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
+ mems (`list[tf.Tensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: tf.Tensor | None = None
+ logits: tf.Tensor | None = None
+ mems: list[tf.Tensor] | None = None
+ hidden_states: tuple[tf.Tensor, ...] | None = None
+ attentions: tuple[tf.Tensor, ...] | None = None
+
+
+@dataclass
+class TFXLNetForTokenClassificationOutput(ModelOutput):
+ """
+ Output type of [`TFXLNetForTokenClassificationOutput`].
+
+ Args:
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided) :
+ Classification loss.
+ logits (`tf.Tensor` of shape `(batch_size, sequence_length, config.num_labels)`):
+ Classification scores (before SoftMax).
+ mems (`list[tf.Tensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: tf.Tensor | None = None
+ logits: tf.Tensor | None = None
+ mems: list[tf.Tensor] | None = None
+ hidden_states: tuple[tf.Tensor, ...] | None = None
+ attentions: tuple[tf.Tensor, ...] | None = None
+
+
+@dataclass
+class TFXLNetForMultipleChoiceOutput(ModelOutput):
+ """
+ Output type of [`TFXLNetForMultipleChoice`].
+
+ Args:
+ loss (`tf.Tensor` of shape *(1,)*, *optional*, returned when `labels` is provided):
+ Classification loss.
+ logits (`tf.Tensor` of shape `(batch_size, num_choices)`):
+ *num_choices* is the second dimension of the input tensors. (see *input_ids* above).
+
+ Classification scores (before SoftMax).
+ mems (`list[tf.Tensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: tf.Tensor | None = None
+ logits: tf.Tensor | None = None
+ mems: list[tf.Tensor] | None = None
+ hidden_states: tuple[tf.Tensor, ...] | None = None
+ attentions: tuple[tf.Tensor, ...] | None = None
+
+
+@dataclass
+class TFXLNetForQuestionAnsweringSimpleOutput(ModelOutput):
+ """
+ Output type of [`TFXLNetForQuestionAnsweringSimple`].
+
+ Args:
+ loss (`tf.Tensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
+ start_logits (`tf.Tensor` of shape `(batch_size, sequence_length,)`):
+ Span-start scores (before SoftMax).
+ end_logits (`tf.Tensor` of shape `(batch_size, sequence_length,)`):
+ Span-end scores (before SoftMax).
+ mems (`list[tf.Tensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
+ `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads.
+ """
+
+ loss: tf.Tensor | None = None
+ start_logits: tf.Tensor | None = None
+ end_logits: tf.Tensor | None = None
+ mems: list[tf.Tensor] | None = None
+ hidden_states: tuple[tf.Tensor, ...] | None = None
+ attentions: tuple[tf.Tensor, ...] | None = None
+
+
+XLNET_START_DOCSTRING = r"""
+
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
+ etc.)
+
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
+ behavior.
+
+
+
+ TensorFlow models and layers in `transformers` accept two formats as input:
+
+ - having all inputs as keyword arguments (like PyTorch models), or
+ - having all inputs as a list, tuple or dict in the first positional argument.
+
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
+ positional argument:
+
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
+
+ Note that when creating models and layers with
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
+ about any of this, as you can just pass inputs like you would to any other Python function!
+
+
+
+ Parameters:
+ config ([`XLNetConfig`]): Model configuration class with all the parameters of the model.
+ Initializing with a config file does not load the weights associated with the model, only the
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
+"""
+
+XLNET_INPUTS_DOCSTRING = r"""
+ Args:
+ input_ids (`torch.LongTensor` of shape `({0})`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+
+ [What are attention masks?](../glossary#attention-mask)
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ input_mask (`torch.FloatTensor` of shape `{0}`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
+
+ - 1 indicates the head is **not masked**,
+ - 0 indicates the head is **masked**.
+
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ output_hidden_states (`bool`, *optional*):
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ return_dict (`bool`, *optional*):
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+"""
+
+
+@add_start_docstrings(
+ "The bare XLNet Model transformer outputting raw hidden-states without any specific head on top.",
+ XLNET_START_DOCSTRING,
+)
+class TFXLNetModel(TFXLNetPreTrainedModel):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.transformer = TFXLNetMainLayer(config, name="transformer")
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFXLNetModelOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ mems: np.ndarray | tf.Tensor | None = None,
+ perm_mask: np.ndarray | tf.Tensor | None = None,
+ target_mapping: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ input_mask: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ training: bool = False,
+ ) -> TFXLNetModelOutput | tuple[tf.Tensor]:
+ outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+
+ return outputs
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+
+
+@add_start_docstrings(
+ """
+ XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
+ """,
+ XLNET_START_DOCSTRING,
+)
+class TFXLNetLMHeadModel(TFXLNetPreTrainedModel, TFCausalLanguageModelingLoss):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.transformer = TFXLNetMainLayer(config, name="transformer")
+ self.lm_loss = TFXLNetLMHead(config, self.transformer.word_embedding, name="lm_loss")
+ # generate fails to convert to a graph with XLNet
+ self.supports_xla_generation = False
+
+ def get_lm_head(self):
+ return self.lm_loss
+
+ def get_prefix_bias_name(self):
+ warnings.warn("The method get_prefix_bias_name is deprecated. Please use `get_bias` instead.", FutureWarning)
+ return self.name + "/" + self.lm_loss.name
+
+ def prepare_inputs_for_generation(self, inputs, past_key_values=None, use_mems=None, **kwargs):
+ # Add dummy token at the end (no attention on this one)
+ effective_batch_size = inputs.shape[0]
+ dummy_token = tf.zeros((effective_batch_size, 1), dtype=inputs.dtype)
+
+ # At every pass, the attention values for the new token and the two last generated tokens
+ # are computed, the rest is reloaded from the `past` cache. A purely auto-regressive model would have
+ # offset = 1; offset = 2 seems to have slightly better computation.
+ offset = 2
+
+ if past_key_values:
+ input_ids = tf.concat([inputs[:, -offset:], dummy_token], axis=1)
+ else:
+ input_ids = tf.concat([inputs, dummy_token], axis=1)
+
+ # Build permutation mask so that previous tokens don't see last token
+ sequence_length = input_ids.shape[1]
+ perm_mask = tf.zeros((effective_batch_size, sequence_length, sequence_length - 1))
+ perm_mask_seq_end = tf.ones((effective_batch_size, sequence_length, 1))
+ perm_mask = tf.concat([perm_mask, perm_mask_seq_end], axis=-1)
+
+ # We'll only predict the last token
+ target_mapping = tf.zeros((effective_batch_size, 1, sequence_length - 1))
+ target_mapping_seq_end = tf.ones((effective_batch_size, 1, 1))
+ target_mapping = tf.concat([target_mapping, target_mapping_seq_end], axis=-1)
+
+ inputs = {
+ "input_ids": input_ids,
+ "perm_mask": perm_mask,
+ "target_mapping": target_mapping,
+ "use_mems": use_mems,
+ }
+
+ # if past is defined in model kwargs then use it for faster decoding
+ if past_key_values:
+ inputs["mems"] = tuple(layer_past[:-offset, :, :] for layer_past in past_key_values)
+
+ return inputs
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @replace_return_docstrings(output_type=TFXLNetLMHeadModelOutput, config_class=_CONFIG_FOR_DOC)
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ mems: np.ndarray | tf.Tensor | None = None,
+ perm_mask: np.ndarray | tf.Tensor | None = None,
+ target_mapping: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ input_mask: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ) -> TFXLNetLMHeadModelOutput | tuple[tf.Tensor]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the cross entropy classification loss. Indices should be in `[0, ...,
+ config.vocab_size - 1]`.
+
+ Return:
+
+ Examples:
+
+ ```python
+ >>> import tensorflow as tf
+ >>> import numpy as np
+ >>> from transformers import AutoTokenizer, TFXLNetLMHeadModel
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-large-cased")
+ >>> model = TFXLNetLMHeadModel.from_pretrained("xlnet/xlnet-large-cased")
+
+ >>> # We show how to setup inputs to predict a next token using a bi-directional context.
+ >>> input_ids = tf.constant(tokenizer.encode("Hello, my dog is very ", add_special_tokens=True))[
+ ... None, :
+ ... ] # We will predict the masked token
+
+ >>> perm_mask = np.zeros((1, input_ids.shape[1], input_ids.shape[1]))
+ >>> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token
+
+ >>> target_mapping = np.zeros(
+ ... (1, 1, input_ids.shape[1])
+ ... ) # Shape [1, 1, seq_length] => let's predict one token
+ >>> target_mapping[
+ ... 0, 0, -1
+ ... ] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token)
+
+ >>> outputs = model(
+ ... input_ids,
+ ... perm_mask=tf.constant(perm_mask, dtype=tf.float32),
+ ... target_mapping=tf.constant(target_mapping, dtype=tf.float32),
+ ... )
+
+ >>> next_token_logits = outputs[
+ ... 0
+ ... ] # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
+ ```"""
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ hidden_state = transformer_outputs[0]
+ logits = self.lm_loss(hidden_state, training=training)
+
+ loss = None
+ if labels is not None:
+ loss = self.hf_compute_loss(labels, logits)
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFXLNetLMHeadModelOutput(
+ loss=loss,
+ logits=logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+ if getattr(self, "lm_loss", None) is not None:
+ with tf.name_scope(self.lm_loss.name):
+ self.lm_loss.build(None)
+
+
+@add_start_docstrings(
+ """
+ XLNet Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g.
+ for GLUE tasks.
+ """,
+ XLNET_START_DOCSTRING,
+)
+class TFXLNetForSequenceClassification(TFXLNetPreTrainedModel, TFSequenceClassificationLoss):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.num_labels = config.num_labels
+
+ self.transformer = TFXLNetMainLayer(config, name="transformer")
+ self.sequence_summary = TFSequenceSummary(
+ config, initializer_range=config.initializer_range, name="sequence_summary"
+ )
+ self.logits_proj = keras.layers.Dense(
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="logits_proj"
+ )
+ self.config = config
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFXLNetForSequenceClassificationOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ mems: np.ndarray | tf.Tensor | None = None,
+ perm_mask: np.ndarray | tf.Tensor | None = None,
+ target_mapping: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ input_mask: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ) -> TFXLNetForSequenceClassificationOutput | tuple[tf.Tensor]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ output = transformer_outputs[0]
+
+ output = self.sequence_summary(output)
+ logits = self.logits_proj(output)
+
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFXLNetForSequenceClassificationOutput(
+ loss=loss,
+ logits=logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+ if getattr(self, "sequence_summary", None) is not None:
+ with tf.name_scope(self.sequence_summary.name):
+ self.sequence_summary.build(None)
+ if getattr(self, "logits_proj", None) is not None:
+ with tf.name_scope(self.logits_proj.name):
+ self.logits_proj.build([None, None, self.config.d_model])
+
+
+@add_start_docstrings(
+ """
+ XLNET Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
+ softmax) e.g. for RocStories/SWAG tasks.
+ """,
+ XLNET_START_DOCSTRING,
+)
+class TFXLNetForMultipleChoice(TFXLNetPreTrainedModel, TFMultipleChoiceLoss):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+
+ self.transformer = TFXLNetMainLayer(config, name="transformer")
+ self.sequence_summary = TFSequenceSummary(
+ config, initializer_range=config.initializer_range, name="sequence_summary"
+ )
+ self.logits_proj = keras.layers.Dense(
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="logits_proj"
+ )
+ self.config = config
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFXLNetForMultipleChoiceOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ input_mask: np.ndarray | tf.Tensor | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ mems: np.ndarray | tf.Tensor | None = None,
+ perm_mask: np.ndarray | tf.Tensor | None = None,
+ target_mapping: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ) -> TFXLNetForMultipleChoiceOutput | tuple[tf.Tensor]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
+ where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above)
+ """
+
+ if input_ids is not None:
+ num_choices = shape_list(input_ids)[1]
+ seq_length = shape_list(input_ids)[2]
+ else:
+ num_choices = shape_list(inputs_embeds)[1]
+ seq_length = shape_list(inputs_embeds)[2]
+
+ flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None
+ flat_attention_mask = tf.reshape(attention_mask, (-1, seq_length)) if attention_mask is not None else None
+ flat_token_type_ids = tf.reshape(token_type_ids, (-1, seq_length)) if token_type_ids is not None else None
+ flat_input_mask = tf.reshape(input_mask, (-1, seq_length)) if input_mask is not None else None
+ flat_inputs_embeds = (
+ tf.reshape(inputs_embeds, (-1, seq_length, shape_list(inputs_embeds)[3]))
+ if inputs_embeds is not None
+ else None
+ )
+ transformer_outputs = self.transformer(
+ flat_input_ids,
+ flat_attention_mask,
+ mems,
+ perm_mask,
+ target_mapping,
+ flat_token_type_ids,
+ flat_input_mask,
+ head_mask,
+ flat_inputs_embeds,
+ use_mems,
+ output_attentions,
+ output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ output = transformer_outputs[0]
+ logits = self.sequence_summary(output)
+ logits = self.logits_proj(logits)
+ reshaped_logits = tf.reshape(logits, (-1, num_choices))
+ loss = None if labels is None else self.hf_compute_loss(labels, reshaped_logits)
+
+ if not return_dict:
+ output = (reshaped_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFXLNetForMultipleChoiceOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+ if getattr(self, "sequence_summary", None) is not None:
+ with tf.name_scope(self.sequence_summary.name):
+ self.sequence_summary.build(None)
+ if getattr(self, "logits_proj", None) is not None:
+ with tf.name_scope(self.logits_proj.name):
+ self.logits_proj.build([None, None, self.config.d_model])
+
+
+@add_start_docstrings(
+ """
+ XLNet Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
+ Named-Entity-Recognition (NER) tasks.
+ """,
+ XLNET_START_DOCSTRING,
+)
+class TFXLNetForTokenClassification(TFXLNetPreTrainedModel, TFTokenClassificationLoss):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.num_labels = config.num_labels
+
+ self.transformer = TFXLNetMainLayer(config, name="transformer")
+ self.classifier = keras.layers.Dense(
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier"
+ )
+ self.config = config
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFXLNetForTokenClassificationOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ mems: np.ndarray | tf.Tensor | None = None,
+ perm_mask: np.ndarray | tf.Tensor | None = None,
+ target_mapping: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ input_mask: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ labels: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ) -> TFXLNetForTokenClassificationOutput | tuple[tf.Tensor]:
+ r"""
+ labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ output = transformer_outputs[0]
+ logits = self.classifier(output)
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFXLNetForTokenClassificationOutput(
+ loss=loss,
+ logits=logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+ if getattr(self, "classifier", None) is not None:
+ with tf.name_scope(self.classifier.name):
+ self.classifier.build([None, None, self.config.hidden_size])
+
+
+@add_start_docstrings(
+ """
+ XLNet Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """,
+ XLNET_START_DOCSTRING,
+)
+class TFXLNetForQuestionAnsweringSimple(TFXLNetPreTrainedModel, TFQuestionAnsweringLoss):
+ def __init__(self, config, *inputs, **kwargs):
+ super().__init__(config, *inputs, **kwargs)
+ self.transformer = TFXLNetMainLayer(config, name="transformer")
+ self.qa_outputs = keras.layers.Dense(
+ config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
+ )
+ self.config = config
+
+ @unpack_inputs
+ @add_start_docstrings_to_model_forward(XLNET_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
+ @add_code_sample_docstrings(
+ checkpoint=_CHECKPOINT_FOR_DOC,
+ output_type=TFXLNetForQuestionAnsweringSimpleOutput,
+ config_class=_CONFIG_FOR_DOC,
+ )
+ def call(
+ self,
+ input_ids: TFModelInputType | None = None,
+ attention_mask: np.ndarray | tf.Tensor | None = None,
+ mems: np.ndarray | tf.Tensor | None = None,
+ perm_mask: np.ndarray | tf.Tensor | None = None,
+ target_mapping: np.ndarray | tf.Tensor | None = None,
+ token_type_ids: np.ndarray | tf.Tensor | None = None,
+ input_mask: np.ndarray | tf.Tensor | None = None,
+ head_mask: np.ndarray | tf.Tensor | None = None,
+ inputs_embeds: np.ndarray | tf.Tensor | None = None,
+ use_mems: bool | None = None,
+ output_attentions: bool | None = None,
+ output_hidden_states: bool | None = None,
+ return_dict: bool | None = None,
+ start_positions: np.ndarray | tf.Tensor | None = None,
+ end_positions: np.ndarray | tf.Tensor | None = None,
+ training: bool = False,
+ ) -> TFXLNetForQuestionAnsweringSimpleOutput | tuple[tf.Tensor]:
+ r"""
+ start_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ end_positions (`tf.Tensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
+ are not taken into account for computing the loss.
+ """
+ transformer_outputs = self.transformer(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ training=training,
+ )
+ sequence_output = transformer_outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
+ start_logits = tf.squeeze(start_logits, axis=-1)
+ end_logits = tf.squeeze(end_logits, axis=-1)
+
+ loss = None
+ if start_positions is not None and end_positions is not None:
+ labels = {"start_position": start_positions}
+ labels["end_position"] = end_positions
+ loss = self.hf_compute_loss(labels, (start_logits, end_logits))
+
+ if not return_dict:
+ output = (start_logits, end_logits) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TFXLNetForQuestionAnsweringSimpleOutput(
+ loss=loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ def build(self, input_shape=None):
+ if self.built:
+ return
+ self.built = True
+ if getattr(self, "transformer", None) is not None:
+ with tf.name_scope(self.transformer.name):
+ self.transformer.build(None)
+ if getattr(self, "qa_outputs", None) is not None:
+ with tf.name_scope(self.qa_outputs.name):
+ self.qa_outputs.build([None, None, self.config.hidden_size])
+
+
+__all__ = [
+ "TFXLNetForMultipleChoice",
+ "TFXLNetForQuestionAnsweringSimple",
+ "TFXLNetForSequenceClassification",
+ "TFXLNetForTokenClassification",
+ "TFXLNetLMHeadModel",
+ "TFXLNetMainLayer",
+ "TFXLNetModel",
+ "TFXLNetPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/modeling_xlnet.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/modeling_xlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..736521ee9561d985a2e17eb41246f0e3ff6615e3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/modeling_xlnet.py
@@ -0,0 +1,2380 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""
+PyTorch XLNet model.
+"""
+
+import warnings
+from dataclasses import dataclass
+from typing import Callable, Optional, Union
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import ACT2FN, get_activation
+from ...generation import GenerationMixin
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward
+from ...utils import ModelOutput, auto_docstring, logging
+from .configuration_xlnet import XLNetConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+def build_tf_xlnet_to_pytorch_map(model, config, tf_weights=None):
+ """
+ A map of modules from TF to PyTorch. I use a map to keep the PyTorch model as identical to the original PyTorch
+ model as possible.
+ """
+
+ tf_to_pt_map = {}
+
+ if hasattr(model, "transformer"):
+ if hasattr(model, "lm_loss"):
+ # We will load also the output bias
+ tf_to_pt_map["model/lm_loss/bias"] = model.lm_loss.bias
+ if hasattr(model, "sequence_summary") and "model/sequnece_summary/summary/kernel" in tf_weights:
+ # We will load also the sequence summary
+ tf_to_pt_map["model/sequnece_summary/summary/kernel"] = model.sequence_summary.summary.weight
+ tf_to_pt_map["model/sequnece_summary/summary/bias"] = model.sequence_summary.summary.bias
+ if (
+ hasattr(model, "logits_proj")
+ and config.finetuning_task is not None
+ and f"model/regression_{config.finetuning_task}/logit/kernel" in tf_weights
+ ):
+ tf_to_pt_map[f"model/regression_{config.finetuning_task}/logit/kernel"] = model.logits_proj.weight
+ tf_to_pt_map[f"model/regression_{config.finetuning_task}/logit/bias"] = model.logits_proj.bias
+
+ # Now load the rest of the transformer
+ model = model.transformer
+
+ # Embeddings and output
+ tf_to_pt_map.update(
+ {
+ "model/transformer/word_embedding/lookup_table": model.word_embedding.weight,
+ "model/transformer/mask_emb/mask_emb": model.mask_emb,
+ }
+ )
+
+ # Transformer blocks
+ for i, b in enumerate(model.layer):
+ layer_str = f"model/transformer/layer_{i}/"
+ tf_to_pt_map.update(
+ {
+ layer_str + "rel_attn/LayerNorm/gamma": b.rel_attn.layer_norm.weight,
+ layer_str + "rel_attn/LayerNorm/beta": b.rel_attn.layer_norm.bias,
+ layer_str + "rel_attn/o/kernel": b.rel_attn.o,
+ layer_str + "rel_attn/q/kernel": b.rel_attn.q,
+ layer_str + "rel_attn/k/kernel": b.rel_attn.k,
+ layer_str + "rel_attn/r/kernel": b.rel_attn.r,
+ layer_str + "rel_attn/v/kernel": b.rel_attn.v,
+ layer_str + "ff/LayerNorm/gamma": b.ff.layer_norm.weight,
+ layer_str + "ff/LayerNorm/beta": b.ff.layer_norm.bias,
+ layer_str + "ff/layer_1/kernel": b.ff.layer_1.weight,
+ layer_str + "ff/layer_1/bias": b.ff.layer_1.bias,
+ layer_str + "ff/layer_2/kernel": b.ff.layer_2.weight,
+ layer_str + "ff/layer_2/bias": b.ff.layer_2.bias,
+ }
+ )
+
+ # Relative positioning biases
+ if config.untie_r:
+ r_r_list = []
+ r_w_list = []
+ r_s_list = []
+ seg_embed_list = []
+ for b in model.layer:
+ r_r_list.append(b.rel_attn.r_r_bias)
+ r_w_list.append(b.rel_attn.r_w_bias)
+ r_s_list.append(b.rel_attn.r_s_bias)
+ seg_embed_list.append(b.rel_attn.seg_embed)
+ else:
+ r_r_list = [model.r_r_bias]
+ r_w_list = [model.r_w_bias]
+ r_s_list = [model.r_s_bias]
+ seg_embed_list = [model.seg_embed]
+ tf_to_pt_map.update(
+ {
+ "model/transformer/r_r_bias": r_r_list,
+ "model/transformer/r_w_bias": r_w_list,
+ "model/transformer/r_s_bias": r_s_list,
+ "model/transformer/seg_embed": seg_embed_list,
+ }
+ )
+ return tf_to_pt_map
+
+
+def load_tf_weights_in_xlnet(model, config, tf_path):
+ """Load tf checkpoints in a pytorch model"""
+ try:
+ import numpy as np
+ import tensorflow as tf
+ except ImportError:
+ logger.error(
+ "Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see "
+ "https://www.tensorflow.org/install/ for installation instructions."
+ )
+ raise
+ # Load weights from TF model
+ init_vars = tf.train.list_variables(tf_path)
+ tf_weights = {}
+ for name, shape in init_vars:
+ logger.info(f"Loading TF weight {name} with shape {shape}")
+ array = tf.train.load_variable(tf_path, name)
+ tf_weights[name] = array
+
+ # Build TF to PyTorch weights loading map
+ tf_to_pt_map = build_tf_xlnet_to_pytorch_map(model, config, tf_weights)
+
+ for name, pointer in tf_to_pt_map.items():
+ logger.info(f"Importing {name}")
+ if name not in tf_weights:
+ logger.info(f"{name} not in tf pre-trained weights, skipping")
+ continue
+ array = tf_weights[name]
+ # adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
+ # which are not required for using pretrained model
+ if "kernel" in name and ("ff" in name or "summary" in name or "logit" in name):
+ logger.info("Transposing")
+ array = np.transpose(array)
+ if isinstance(pointer, list):
+ # Here we will split the TF weights
+ assert len(pointer) == array.shape[0], (
+ f"Pointer length {len(pointer)} and array length {array.shape[0]} mismatched"
+ )
+ for i, p_i in enumerate(pointer):
+ arr_i = array[i, ...]
+ try:
+ assert p_i.shape == arr_i.shape, (
+ f"Pointer shape {p_i.shape} and array shape {arr_i.shape} mismatched"
+ )
+ except AssertionError as e:
+ e.args += (p_i.shape, arr_i.shape)
+ raise
+ logger.info(f"Initialize PyTorch weight {name} for layer {i}")
+ p_i.data = torch.from_numpy(arr_i)
+ else:
+ try:
+ assert pointer.shape == array.shape, (
+ f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
+ )
+ except AssertionError as e:
+ e.args += (pointer.shape, array.shape)
+ raise
+ logger.info(f"Initialize PyTorch weight {name}")
+ pointer.data = torch.from_numpy(array)
+ tf_weights.pop(name, None)
+ tf_weights.pop(name + "/Adam", None)
+ tf_weights.pop(name + "/Adam_1", None)
+
+ logger.info(f"Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}")
+ return model
+
+
+class XLNetRelativeAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ if config.d_model % config.n_head != 0:
+ raise ValueError(
+ f"The hidden size ({config.d_model}) is not a multiple of the number of attention "
+ f"heads ({config.n_head}"
+ )
+
+ self.n_head = config.n_head
+ self.d_head = config.d_head
+ self.d_model = config.d_model
+ self.scale = 1 / (config.d_head**0.5)
+
+ self.q = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
+ self.k = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
+ self.v = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
+ self.o = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
+ self.r = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
+
+ self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
+ self.r_s_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
+ self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
+ self.seg_embed = nn.Parameter(torch.FloatTensor(2, self.n_head, self.d_head))
+
+ self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.dropout)
+
+ def prune_heads(self, heads):
+ raise NotImplementedError
+
+ @staticmethod
+ def rel_shift(x, klen=-1):
+ """perform relative shift to form the relative attention score."""
+ x_size = x.shape
+
+ x = x.reshape(x_size[1], x_size[0], x_size[2], x_size[3])
+ x = x[1:, ...]
+ x = x.reshape(x_size[0], x_size[1] - 1, x_size[2], x_size[3])
+ # x = x[:, 0:klen, :, :]
+ x = torch.index_select(x, 1, torch.arange(klen, device=x.device, dtype=torch.long))
+
+ return x
+
+ @staticmethod
+ def rel_shift_bnij(x, klen=-1):
+ x_size = x.shape
+
+ x = x.reshape(x_size[0], x_size[1], x_size[3], x_size[2])
+ x = x[:, :, 1:, :]
+ x = x.reshape(x_size[0], x_size[1], x_size[2], x_size[3] - 1)
+ # Note: the tensor-slice form was faster in my testing than torch.index_select
+ # However, tracing doesn't like the nature of the slice, and if klen changes
+ # during the run then it'll fail, whereas index_select will be fine.
+ x = torch.index_select(x, 3, torch.arange(klen, device=x.device, dtype=torch.long))
+ # x = x[:, :, :, :klen]
+
+ return x
+
+ def rel_attn_core(
+ self,
+ q_head,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat=None,
+ attn_mask=None,
+ head_mask=None,
+ output_attentions=False,
+ ):
+ """Core relative positional attention operations."""
+
+ # content based attention score
+ ac = torch.einsum("ibnd,jbnd->bnij", q_head + self.r_w_bias, k_head_h)
+
+ # position based attention score
+ bd = torch.einsum("ibnd,jbnd->bnij", q_head + self.r_r_bias, k_head_r)
+ bd = self.rel_shift_bnij(bd, klen=ac.shape[3])
+
+ # segment based attention score
+ if seg_mat is None:
+ ef = 0
+ else:
+ ef = torch.einsum("ibnd,snd->ibns", q_head + self.r_s_bias, self.seg_embed)
+ ef = torch.einsum("ijbs,ibns->bnij", seg_mat, ef)
+
+ # merge attention scores and perform masking
+ attn_score = (ac + bd + ef) * self.scale
+ if attn_mask is not None:
+ # attn_score = attn_score * (1 - attn_mask) - 1e30 * attn_mask
+ if attn_mask.dtype == torch.float16:
+ attn_score = attn_score - 65500 * torch.einsum("ijbn->bnij", attn_mask)
+ else:
+ attn_score = attn_score - 1e30 * torch.einsum("ijbn->bnij", attn_mask)
+
+ # attention probability
+ attn_prob = nn.functional.softmax(attn_score, dim=3)
+ attn_prob = self.dropout(attn_prob)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attn_prob = attn_prob * torch.einsum("ijbn->bnij", head_mask)
+
+ # attention output
+ attn_vec = torch.einsum("bnij,jbnd->ibnd", attn_prob, v_head_h)
+
+ if output_attentions:
+ return attn_vec, torch.einsum("bnij->ijbn", attn_prob)
+
+ return attn_vec
+
+ def post_attention(self, h, attn_vec, residual=True):
+ """Post-attention processing."""
+ # post-attention projection (back to `d_model`)
+ attn_out = torch.einsum("ibnd,hnd->ibh", attn_vec, self.o)
+
+ attn_out = self.dropout(attn_out)
+ if residual:
+ attn_out = attn_out + h
+ output = self.layer_norm(attn_out)
+
+ return output
+
+ def forward(
+ self,
+ h,
+ g,
+ attn_mask_h,
+ attn_mask_g,
+ r,
+ seg_mat,
+ mems=None,
+ target_mapping=None,
+ head_mask=None,
+ output_attentions=False,
+ ):
+ if g is not None:
+ # Two-stream attention with relative positional encoding.
+ # content based attention score
+ if mems is not None and mems.dim() > 1:
+ cat = torch.cat([mems, h], dim=0)
+ else:
+ cat = h
+
+ # content-based key head
+ k_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.k)
+
+ # content-based value head
+ v_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.v)
+
+ # position-based key head
+ k_head_r = torch.einsum("ibh,hnd->ibnd", r, self.r)
+
+ # h-stream
+ # content-stream query head
+ q_head_h = torch.einsum("ibh,hnd->ibnd", h, self.q)
+
+ # core attention ops
+ attn_vec_h = self.rel_attn_core(
+ q_head_h,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat=seg_mat,
+ attn_mask=attn_mask_h,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ )
+
+ if output_attentions:
+ attn_vec_h, attn_prob_h = attn_vec_h
+
+ # post processing
+ output_h = self.post_attention(h, attn_vec_h)
+
+ # g-stream
+ # query-stream query head
+ q_head_g = torch.einsum("ibh,hnd->ibnd", g, self.q)
+
+ # core attention ops
+ if target_mapping is not None:
+ q_head_g = torch.einsum("mbnd,mlb->lbnd", q_head_g, target_mapping)
+ attn_vec_g = self.rel_attn_core(
+ q_head_g,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat=seg_mat,
+ attn_mask=attn_mask_g,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ )
+
+ if output_attentions:
+ attn_vec_g, attn_prob_g = attn_vec_g
+
+ attn_vec_g = torch.einsum("lbnd,mlb->mbnd", attn_vec_g, target_mapping)
+ else:
+ attn_vec_g = self.rel_attn_core(
+ q_head_g,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat=seg_mat,
+ attn_mask=attn_mask_g,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ )
+
+ if output_attentions:
+ attn_vec_g, attn_prob_g = attn_vec_g
+
+ # post processing
+ output_g = self.post_attention(g, attn_vec_g)
+
+ if output_attentions:
+ attn_prob = attn_prob_h, attn_prob_g
+
+ else:
+ # Multi-head attention with relative positional encoding
+ if mems is not None and mems.dim() > 1:
+ cat = torch.cat([mems, h], dim=0)
+ else:
+ cat = h
+
+ # content heads
+ q_head_h = torch.einsum("ibh,hnd->ibnd", h, self.q)
+ k_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.k)
+ v_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.v)
+
+ # positional heads
+ # type casting for fp16 support
+ k_head_r = torch.einsum("ibh,hnd->ibnd", r.type(self.r.dtype), self.r)
+
+ # core attention ops
+ attn_vec = self.rel_attn_core(
+ q_head_h,
+ k_head_h,
+ v_head_h,
+ k_head_r,
+ seg_mat=seg_mat,
+ attn_mask=attn_mask_h,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ )
+
+ if output_attentions:
+ attn_vec, attn_prob = attn_vec
+
+ # post processing
+ output_h = self.post_attention(h, attn_vec)
+ output_g = None
+
+ outputs = (output_h, output_g)
+ if output_attentions:
+ outputs = outputs + (attn_prob,)
+ return outputs
+
+
+class XLNetFeedForward(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps)
+ self.layer_1 = nn.Linear(config.d_model, config.d_inner)
+ self.layer_2 = nn.Linear(config.d_inner, config.d_model)
+ self.dropout = nn.Dropout(config.dropout)
+ if isinstance(config.ff_activation, str):
+ self.activation_function = ACT2FN[config.ff_activation]
+ else:
+ self.activation_function = config.ff_activation
+
+ def forward(self, inp):
+ output = inp
+ output = self.layer_1(output)
+ output = self.activation_function(output)
+ output = self.dropout(output)
+ output = self.layer_2(output)
+ output = self.dropout(output)
+ output = self.layer_norm(output + inp)
+ return output
+
+
+class XLNetLayer(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.rel_attn = XLNetRelativeAttention(config)
+ self.ff = XLNetFeedForward(config)
+ self.dropout = nn.Dropout(config.dropout)
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+
+ def forward(
+ self,
+ output_h,
+ output_g,
+ attn_mask_h,
+ attn_mask_g,
+ r,
+ seg_mat,
+ mems=None,
+ target_mapping=None,
+ head_mask=None,
+ output_attentions=False,
+ ):
+ outputs = self.rel_attn(
+ output_h,
+ output_g,
+ attn_mask_h,
+ attn_mask_g,
+ r,
+ seg_mat,
+ mems=mems,
+ target_mapping=target_mapping,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ )
+ output_h, output_g = outputs[:2]
+
+ if output_g is not None:
+ output_g = apply_chunking_to_forward(
+ self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, output_g
+ )
+ output_h = apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, output_h)
+
+ outputs = (output_h, output_g) + outputs[2:] # Add again attentions if there are there
+ return outputs
+
+ def ff_chunk(self, output_x):
+ output_x = self.ff(output_x)
+ return output_x
+
+
+# Copied from transformers.models.xlm.modeling_xlm.XLMPoolerStartLogits with XLM->XLNet
+class XLNetPoolerStartLogits(nn.Module):
+ """
+ Compute SQuAD start logits from sequence hidden states.
+
+ Args:
+ config ([`XLNetConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model.
+ """
+
+ def __init__(self, config: XLNetConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, 1)
+
+ def forward(
+ self, hidden_states: torch.FloatTensor, p_mask: Optional[torch.FloatTensor] = None
+ ) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
+ Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
+ should be masked.
+
+ Returns:
+ `torch.FloatTensor`: The start logits for SQuAD.
+ """
+ x = self.dense(hidden_states).squeeze(-1)
+
+ if p_mask is not None:
+ if p_mask.dtype == torch.float16:
+ x = x * (1 - p_mask) - 65500 * p_mask
+ else:
+ x = x * (1 - p_mask) - 1e30 * p_mask
+
+ return x
+
+
+# Copied from transformers.models.xlm.modeling_xlm.XLMPoolerEndLogits with XLM->XLNet
+class XLNetPoolerEndLogits(nn.Module):
+ """
+ Compute SQuAD end logits from sequence hidden states.
+
+ Args:
+ config ([`XLNetConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
+ to use.
+ """
+
+ def __init__(self, config: XLNetConfig):
+ super().__init__()
+ self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
+ self.activation = nn.Tanh()
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dense_1 = nn.Linear(config.hidden_size, 1)
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ start_states: Optional[torch.FloatTensor] = None,
+ start_positions: Optional[torch.LongTensor] = None,
+ p_mask: Optional[torch.FloatTensor] = None,
+ ) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
+ The hidden states of the first tokens for the labeled span.
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ The position of the first token for the labeled span.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
+ Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
+ should be masked.
+
+
+
+ One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
+ `start_states`.
+
+
+
+ Returns:
+ `torch.FloatTensor`: The end logits for SQuAD.
+ """
+ assert start_states is not None or start_positions is not None, (
+ "One of start_states, start_positions should be not None"
+ )
+ if start_positions is not None:
+ slen, hsz = hidden_states.shape[-2:]
+ start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ start_states = hidden_states.gather(-2, start_positions) # shape (bsz, 1, hsz)
+ start_states = start_states.expand(-1, slen, -1) # shape (bsz, slen, hsz)
+
+ x = self.dense_0(torch.cat([hidden_states, start_states], dim=-1))
+ x = self.activation(x)
+ x = self.LayerNorm(x)
+ x = self.dense_1(x).squeeze(-1)
+
+ if p_mask is not None:
+ if p_mask.dtype == torch.float16:
+ x = x * (1 - p_mask) - 65500 * p_mask
+ else:
+ x = x * (1 - p_mask) - 1e30 * p_mask
+
+ return x
+
+
+# Copied from transformers.models.xlm.modeling_xlm.XLMPoolerAnswerClass with XLM->XLNet
+class XLNetPoolerAnswerClass(nn.Module):
+ """
+ Compute SQuAD 2.0 answer class from classification and start tokens hidden states.
+
+ Args:
+ config ([`XLNetConfig`]):
+ The config used by the model, will be used to grab the `hidden_size` of the model.
+ """
+
+ def __init__(self, config: XLNetConfig):
+ super().__init__()
+ self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
+ self.activation = nn.Tanh()
+ self.dense_1 = nn.Linear(config.hidden_size, 1, bias=False)
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ start_states: Optional[torch.FloatTensor] = None,
+ start_positions: Optional[torch.LongTensor] = None,
+ cls_index: Optional[torch.LongTensor] = None,
+ ) -> torch.FloatTensor:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
+ The final hidden states of the model.
+ start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
+ The hidden states of the first tokens for the labeled span.
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ The position of the first token for the labeled span.
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
+
+
+
+ One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
+ `start_states`.
+
+
+
+ Returns:
+ `torch.FloatTensor`: The SQuAD 2.0 answer class.
+ """
+ # No dependency on end_feature so that we can obtain one single `cls_logits` for each sample.
+ hsz = hidden_states.shape[-1]
+ assert start_states is not None or start_positions is not None, (
+ "One of start_states, start_positions should be not None"
+ )
+ if start_positions is not None:
+ start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ start_states = hidden_states.gather(-2, start_positions).squeeze(-2) # shape (bsz, hsz)
+
+ if cls_index is not None:
+ cls_index = cls_index[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
+ cls_token_state = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, hsz)
+ else:
+ cls_token_state = hidden_states[:, -1, :] # shape (bsz, hsz)
+
+ x = self.dense_0(torch.cat([start_states, cls_token_state], dim=-1))
+ x = self.activation(x)
+ x = self.dense_1(x).squeeze(-1)
+
+ return x
+
+
+# Copied from transformers.models.xlm.modeling_xlm.XLMSequenceSummary with XLM->XLNet
+class XLNetSequenceSummary(nn.Module):
+ r"""
+ Compute a single vector summary of a sequence hidden states.
+
+ Args:
+ config ([`XLNetConfig`]):
+ The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
+ config class of your model for the default values it uses):
+
+ - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
+
+ - `"last"` -- Take the last token hidden state (like XLNet)
+ - `"first"` -- Take the first token hidden state (like Bert)
+ - `"mean"` -- Take the mean of all tokens hidden states
+ - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
+ - `"attn"` -- Not implemented now, use multi-head attention
+
+ - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
+ - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
+ (otherwise to `config.hidden_size`).
+ - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
+ another string or `None` will add no activation.
+ - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
+ - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
+ """
+
+ def __init__(self, config: XLNetConfig):
+ super().__init__()
+
+ self.summary_type = getattr(config, "summary_type", "last")
+ if self.summary_type == "attn":
+ # We should use a standard multi-head attention module with absolute positional embedding for that.
+ # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
+ # We can probably just use the multi-head attention module of PyTorch >=1.1.0
+ raise NotImplementedError
+
+ self.summary = nn.Identity()
+ if hasattr(config, "summary_use_proj") and config.summary_use_proj:
+ if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
+ num_classes = config.num_labels
+ else:
+ num_classes = config.hidden_size
+ self.summary = nn.Linear(config.hidden_size, num_classes)
+
+ activation_string = getattr(config, "summary_activation", None)
+ self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
+
+ self.first_dropout = nn.Identity()
+ if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
+ self.first_dropout = nn.Dropout(config.summary_first_dropout)
+
+ self.last_dropout = nn.Identity()
+ if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
+ self.last_dropout = nn.Dropout(config.summary_last_dropout)
+
+ def forward(
+ self, hidden_states: torch.FloatTensor, cls_index: Optional[torch.LongTensor] = None
+ ) -> torch.FloatTensor:
+ """
+ Compute a single vector summary of a sequence hidden states.
+
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
+ The hidden states of the last layer.
+ cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
+ Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
+
+ Returns:
+ `torch.FloatTensor`: The summary of the sequence hidden states.
+ """
+ if self.summary_type == "last":
+ output = hidden_states[:, -1]
+ elif self.summary_type == "first":
+ output = hidden_states[:, 0]
+ elif self.summary_type == "mean":
+ output = hidden_states.mean(dim=1)
+ elif self.summary_type == "cls_index":
+ if cls_index is None:
+ cls_index = torch.full_like(
+ hidden_states[..., :1, :],
+ hidden_states.shape[-2] - 1,
+ dtype=torch.long,
+ )
+ else:
+ cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
+ cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
+ # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
+ output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
+ elif self.summary_type == "attn":
+ raise NotImplementedError
+
+ output = self.first_dropout(output)
+ output = self.summary(output)
+ output = self.activation(output)
+ output = self.last_dropout(output)
+
+ return output
+
+
+@auto_docstring
+class XLNetPreTrainedModel(PreTrainedModel):
+ config: XLNetConfig
+ load_tf_weights = load_tf_weights_in_xlnet
+ base_model_prefix = "transformer"
+
+ def _init_weights(self, module):
+ """Initialize the weights."""
+ if isinstance(module, nn.Linear):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ elif isinstance(module, XLNetRelativeAttention):
+ for param in [
+ module.q,
+ module.k,
+ module.v,
+ module.o,
+ module.r,
+ module.r_r_bias,
+ module.r_s_bias,
+ module.r_w_bias,
+ module.seg_embed,
+ ]:
+ param.data.normal_(mean=0.0, std=self.config.initializer_range)
+ elif isinstance(module, XLNetModel):
+ module.mask_emb.data.normal_(mean=0.0, std=self.config.initializer_range)
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetModel`].
+ """
+)
+class XLNetModelOutput(ModelOutput):
+ r"""
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_predict, hidden_size)`):
+ Sequence of hidden-states at the last layer of the model.
+
+ `num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
+ corresponds to `sequence_length`.
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ last_hidden_state: torch.FloatTensor
+ mems: Optional[list[torch.FloatTensor]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetLMHeadModel`].
+ """
+)
+class XLNetLMHeadModelOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, num_predict, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+
+ `num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
+ corresponds to `sequence_length`.
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ mems: Optional[list[torch.FloatTensor]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetForSequenceClassification`].
+ """
+)
+class XLNetForSequenceClassificationOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `label` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
+ Classification (or regression if config.num_labels==1) scores (before SoftMax).
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ mems: Optional[list[torch.FloatTensor]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetForTokenClassificationOutput`].
+ """
+)
+class XLNetForTokenClassificationOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`):
+ Classification scores (before SoftMax).
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ mems: Optional[list[torch.FloatTensor]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetForMultipleChoice`].
+ """
+)
+class XLNetForMultipleChoiceOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided):
+ Classification loss.
+ logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
+ *num_choices* is the second dimension of the input tensors. (see *input_ids* above).
+
+ Classification scores (before SoftMax).
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ mems: Optional[list[torch.FloatTensor]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetForQuestionAnsweringSimple`].
+ """
+)
+class XLNetForQuestionAnsweringSimpleOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
+ start_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length,)`):
+ Span-start scores (before SoftMax).
+ end_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length,)`):
+ Span-end scores (before SoftMax).
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ start_logits: Optional[torch.FloatTensor] = None
+ end_logits: Optional[torch.FloatTensor] = None
+ mems: Optional[list[torch.FloatTensor]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Output type of [`XLNetForQuestionAnswering`].
+ """
+)
+class XLNetForQuestionAnsweringOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
+ Classification loss as the sum of start token, end token (and is_impossible if provided) classification
+ losses.
+ start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top config.start_n_top start token possibilities (beam-search).
+ start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top config.start_n_top start token possibilities (beam-search).
+ end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
+ (beam-search).
+ end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
+ cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
+ Log probabilities for the `is_impossible` label of the answers.
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
+ token ids which have their past given to this model should not be passed as `input_ids` as they have
+ already been computed.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ start_top_log_probs: Optional[torch.FloatTensor] = None
+ start_top_index: Optional[torch.LongTensor] = None
+ end_top_log_probs: Optional[torch.FloatTensor] = None
+ end_top_index: Optional[torch.LongTensor] = None
+ cls_logits: Optional[torch.FloatTensor] = None
+ mems: Optional[list[torch.FloatTensor]] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+@auto_docstring
+class XLNetModel(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.mem_len = config.mem_len
+ self.reuse_len = config.reuse_len
+ self.d_model = config.d_model
+ self.same_length = config.same_length
+ self.attn_type = config.attn_type
+ self.bi_data = config.bi_data
+ self.clamp_len = config.clamp_len
+ self.n_layer = config.n_layer
+
+ self.word_embedding = nn.Embedding(config.vocab_size, config.d_model)
+ self.mask_emb = nn.Parameter(torch.FloatTensor(1, 1, config.d_model))
+ self.layer = nn.ModuleList([XLNetLayer(config) for _ in range(config.n_layer)])
+ self.dropout = nn.Dropout(config.dropout)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.word_embedding
+
+ def set_input_embeddings(self, new_embeddings):
+ self.word_embedding = new_embeddings
+
+ def _prune_heads(self, heads_to_prune):
+ raise NotImplementedError
+
+ def create_mask(self, qlen, mlen):
+ """
+ Creates causal attention mask. Float mask where 1.0 indicates masked, 0.0 indicates not-masked.
+
+ Args:
+ qlen: Sequence length
+ mlen: Mask length
+
+ ::
+
+ same_length=False: same_length=True: < qlen > < qlen >
+ ^ [0 0 0 0 0 1 1 1 1] [0 0 0 0 0 1 1 1 1]
+ [0 0 0 0 0 0 1 1 1] [1 0 0 0 0 0 1 1 1]
+ qlen [0 0 0 0 0 0 0 1 1] [1 1 0 0 0 0 0 1 1]
+ [0 0 0 0 0 0 0 0 1] [1 1 1 0 0 0 0 0 1]
+ v [0 0 0 0 0 0 0 0 0] [1 1 1 1 0 0 0 0 0]
+
+ """
+ mask = torch.ones((qlen, qlen + mlen), device=self.device)
+ if self.same_length:
+ mask_lo = mask[:, :qlen].tril(-1)
+ mask.triu_(mlen + 1)
+ mask[:, :qlen] += mask_lo
+ else:
+ mask.triu_(mlen + 1)
+
+ return mask
+
+ def cache_mem(self, curr_out, prev_mem):
+ # cache hidden states into memory.
+ if self.reuse_len is not None and self.reuse_len > 0:
+ curr_out = curr_out[: self.reuse_len]
+
+ if self.mem_len is None or self.mem_len == 0:
+ # If `use_mems` is active but no `mem_len` is defined, the model behaves like GPT-2 at inference time
+ # and returns all of the past and current hidden states.
+ cutoff = 0
+ else:
+ # If `use_mems` is active and `mem_len` is defined, the model returns the last `mem_len` hidden
+ # states. This is the preferred setting for training and long-form generation.
+ cutoff = -self.mem_len
+ if prev_mem is None:
+ # if `use_mems` is active and `mem_len` is defined, the model
+ new_mem = curr_out[cutoff:]
+ else:
+ new_mem = torch.cat([prev_mem, curr_out], dim=0)[cutoff:]
+
+ return new_mem.detach()
+
+ @staticmethod
+ def positional_embedding(pos_seq, inv_freq, bsz=None):
+ sinusoid_inp = torch.einsum("i,d->id", pos_seq, inv_freq)
+ pos_emb = torch.cat([torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)], dim=-1)
+ pos_emb = pos_emb[:, None, :]
+
+ if bsz is not None:
+ pos_emb = pos_emb.expand(-1, bsz, -1)
+
+ return pos_emb
+
+ def relative_positional_encoding(self, qlen, klen, bsz=None):
+ # create relative positional encoding.
+ freq_seq = torch.arange(0, self.d_model, 2.0, dtype=torch.int64).float()
+ inv_freq = 1 / torch.pow(10000, (freq_seq / self.d_model))
+
+ if self.attn_type == "bi":
+ # beg, end = klen - 1, -qlen
+ beg, end = klen, -qlen
+ elif self.attn_type == "uni":
+ # beg, end = klen - 1, -1
+ beg, end = klen, -1
+ else:
+ raise ValueError(f"Unknown `attn_type` {self.attn_type}.")
+
+ if self.bi_data:
+ fwd_pos_seq = torch.arange(beg, end, -1.0, dtype=torch.int64).float()
+ bwd_pos_seq = torch.arange(-beg, -end, 1.0, dtype=torch.int64).float()
+
+ if self.clamp_len > 0:
+ fwd_pos_seq = fwd_pos_seq.clamp(-self.clamp_len, self.clamp_len)
+ bwd_pos_seq = bwd_pos_seq.clamp(-self.clamp_len, self.clamp_len)
+
+ if bsz is not None:
+ fwd_pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq, bsz // 2)
+ bwd_pos_emb = self.positional_embedding(bwd_pos_seq, inv_freq, bsz // 2)
+ else:
+ fwd_pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq)
+ bwd_pos_emb = self.positional_embedding(bwd_pos_seq, inv_freq)
+
+ pos_emb = torch.cat([fwd_pos_emb, bwd_pos_emb], dim=1)
+ else:
+ fwd_pos_seq = torch.arange(beg, end, -1.0, dtype=torch.int64).float()
+ if self.clamp_len > 0:
+ fwd_pos_seq = fwd_pos_seq.clamp(-self.clamp_len, self.clamp_len)
+ pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq, bsz)
+
+ return pos_emb
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ mems: Optional[torch.Tensor] = None,
+ perm_mask: Optional[torch.Tensor] = None,
+ target_mapping: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ input_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ use_mems: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs, # delete after depreciation warning is removed
+ ) -> Union[tuple, XLNetModelOutput]:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if "use_cache" in kwargs:
+ warnings.warn(
+ "The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems`"
+ " instead.",
+ FutureWarning,
+ )
+ use_mems = kwargs["use_cache"]
+
+ if self.training:
+ use_mems = use_mems if use_mems is not None else self.config.use_mems_train
+ else:
+ use_mems = use_mems if use_mems is not None else self.config.use_mems_eval
+
+ # the original code for XLNet uses shapes [len, bsz] with the batch dimension at the end
+ # but we want a unified interface in the library with the batch size on the first dimension
+ # so we move here the first dimension (batch) to the end
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_ids = input_ids.transpose(0, 1).contiguous()
+ qlen, bsz = input_ids.shape[0], input_ids.shape[1]
+ elif inputs_embeds is not None:
+ inputs_embeds = inputs_embeds.transpose(0, 1).contiguous()
+ qlen, bsz = inputs_embeds.shape[0], inputs_embeds.shape[1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ token_type_ids = token_type_ids.transpose(0, 1).contiguous() if token_type_ids is not None else None
+ input_mask = input_mask.transpose(0, 1).contiguous() if input_mask is not None else None
+ attention_mask = attention_mask.transpose(0, 1).contiguous() if attention_mask is not None else None
+ perm_mask = perm_mask.permute(1, 2, 0).contiguous() if perm_mask is not None else None
+ target_mapping = target_mapping.permute(1, 2, 0).contiguous() if target_mapping is not None else None
+
+ mlen = mems[0].shape[0] if mems is not None and mems[0] is not None else 0
+ klen = mlen + qlen
+
+ dtype_float = self.dtype
+ device = self.device
+
+ # Attention mask
+ # causal attention mask
+ if self.attn_type == "uni":
+ attn_mask = self.create_mask(qlen, mlen)
+ attn_mask = attn_mask[:, :, None, None]
+ elif self.attn_type == "bi":
+ attn_mask = None
+ else:
+ raise ValueError(f"Unsupported attention type: {self.attn_type}")
+
+ # data mask: input mask & perm mask
+ assert input_mask is None or attention_mask is None, "You can only use one of input_mask (uses 1 for padding) "
+ "or attention_mask (uses 0 for padding, added for compatibility with BERT). Please choose one."
+ if input_mask is None and attention_mask is not None:
+ input_mask = 1.0 - attention_mask
+ if input_mask is not None and perm_mask is not None:
+ data_mask = input_mask[None] + perm_mask
+ elif input_mask is not None and perm_mask is None:
+ data_mask = input_mask[None]
+ elif input_mask is None and perm_mask is not None:
+ data_mask = perm_mask
+ else:
+ data_mask = None
+
+ if data_mask is not None:
+ # all mems can be attended to
+ if mlen > 0:
+ mems_mask = torch.zeros([data_mask.shape[0], mlen, bsz]).to(data_mask)
+ data_mask = torch.cat([mems_mask, data_mask], dim=1)
+ if attn_mask is None:
+ attn_mask = data_mask[:, :, :, None]
+ else:
+ attn_mask += data_mask[:, :, :, None]
+
+ if attn_mask is not None:
+ attn_mask = (attn_mask > 0).to(dtype_float)
+
+ if attn_mask is not None:
+ non_tgt_mask = -torch.eye(qlen).to(attn_mask)
+ if mlen > 0:
+ non_tgt_mask = torch.cat([torch.zeros([qlen, mlen]).to(attn_mask), non_tgt_mask], dim=-1)
+ non_tgt_mask = ((attn_mask + non_tgt_mask[:, :, None, None]) > 0).to(attn_mask)
+ else:
+ non_tgt_mask = None
+
+ # Word embeddings and prepare h & g hidden states
+ if inputs_embeds is not None:
+ word_emb_k = inputs_embeds
+ else:
+ word_emb_k = self.word_embedding(input_ids)
+ output_h = self.dropout(word_emb_k)
+ if target_mapping is not None:
+ word_emb_q = self.mask_emb.expand(target_mapping.shape[0], bsz, -1)
+ # else: # We removed the inp_q input which was same as target mapping
+ # inp_q_ext = inp_q[:, :, None]
+ # word_emb_q = inp_q_ext * self.mask_emb + (1 - inp_q_ext) * word_emb_k
+ output_g = self.dropout(word_emb_q)
+ else:
+ output_g = None
+
+ # Segment embedding
+ if token_type_ids is not None:
+ # Convert `token_type_ids` to one-hot `seg_mat`
+ if mlen > 0:
+ mem_pad = torch.zeros([mlen, bsz], dtype=torch.long, device=device)
+ cat_ids = torch.cat([mem_pad, token_type_ids], dim=0)
+ else:
+ cat_ids = token_type_ids
+
+ # `1` indicates not in the same segment [qlen x klen x bsz]
+ seg_mat = (token_type_ids[:, None] != cat_ids[None, :]).long()
+ seg_mat = nn.functional.one_hot(seg_mat, num_classes=2).to(dtype_float)
+ else:
+ seg_mat = None
+
+ # Positional encoding
+ pos_emb = self.relative_positional_encoding(qlen, klen, bsz=bsz)
+ pos_emb = pos_emb.to(output_h.device)
+ pos_emb = self.dropout(pos_emb)
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] (a head_mask for each layer)
+ # and head_mask is converted to shape [num_hidden_layers x qlen x klen x bsz x n_head]
+ if head_mask is not None:
+ if head_mask.dim() == 1:
+ head_mask = head_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0).unsqueeze(0)
+ head_mask = head_mask.expand(self.n_layer, -1, -1, -1, -1)
+ elif head_mask.dim() == 2:
+ head_mask = head_mask.unsqueeze(1).unsqueeze(1).unsqueeze(1)
+ head_mask = head_mask.to(
+ dtype=next(self.parameters()).dtype
+ ) # switch to float if need + fp16 compatibility
+ else:
+ head_mask = [None] * self.n_layer
+
+ new_mems = ()
+ if mems is None:
+ mems = [None] * len(self.layer)
+
+ attentions = [] if output_attentions else None
+ hidden_states = [] if output_hidden_states else None
+ for i, layer_module in enumerate(self.layer):
+ if use_mems:
+ # cache new mems
+ new_mems = new_mems + (self.cache_mem(output_h, mems[i]),)
+ if output_hidden_states:
+ hidden_states.append((output_h, output_g) if output_g is not None else output_h)
+
+ outputs = layer_module(
+ output_h,
+ output_g,
+ attn_mask_h=non_tgt_mask,
+ attn_mask_g=attn_mask,
+ r=pos_emb,
+ seg_mat=seg_mat,
+ mems=mems[i],
+ target_mapping=target_mapping,
+ head_mask=head_mask[i],
+ output_attentions=output_attentions,
+ )
+ output_h, output_g = outputs[:2]
+ if output_attentions:
+ attentions.append(outputs[2])
+
+ # Add last hidden state
+ if output_hidden_states:
+ hidden_states.append((output_h, output_g) if output_g is not None else output_h)
+
+ output = self.dropout(output_g if output_g is not None else output_h)
+
+ # Prepare outputs, we transpose back here to shape [bsz, len, hidden_dim] (cf. beginning of forward() method)
+ output = output.permute(1, 0, 2).contiguous()
+
+ if not use_mems:
+ new_mems = None
+
+ if output_hidden_states:
+ if output_g is not None:
+ hidden_states = tuple(h.permute(1, 0, 2).contiguous() for hs in hidden_states for h in hs)
+ else:
+ hidden_states = tuple(hs.permute(1, 0, 2).contiguous() for hs in hidden_states)
+
+ if output_attentions:
+ if target_mapping is not None:
+ # when target_mapping is provided, there are 2-tuple of attentions
+ attentions = tuple(
+ tuple(att_stream.permute(2, 3, 0, 1).contiguous() for att_stream in t) for t in attentions
+ )
+ else:
+ attentions = tuple(t.permute(2, 3, 0, 1).contiguous() for t in attentions)
+
+ if not return_dict:
+ return tuple(v for v in [output, new_mems, hidden_states, attentions] if v is not None)
+
+ return XLNetModelOutput(
+ last_hidden_state=output, mems=new_mems, hidden_states=hidden_states, attentions=attentions
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
+ """
+)
+class XLNetLMHeadModel(XLNetPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = ["lm_loss.weight"]
+
+ def __init__(self, config):
+ super().__init__(config)
+ self.attn_type = config.attn_type
+ self.same_length = config.same_length
+
+ self.transformer = XLNetModel(config)
+ self.lm_loss = nn.Linear(config.d_model, config.vocab_size, bias=True)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_loss
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_loss = new_embeddings
+
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, use_mems=None, **kwargs):
+ # Overwritten -- this model has unique input preparation
+
+ # Add dummy token at the end (no attention on this one)
+
+ effective_batch_size = input_ids.shape[0]
+ dummy_token = torch.zeros((effective_batch_size, 1), dtype=torch.long, device=input_ids.device)
+
+ # At every pass, the attention values for the new token and the two last generated tokens
+ # are computed, the rest is reloaded from the `past` cache. A purely auto-regressive model would have
+ # offset = 1; offset = 2 seems to have slightly better computation.
+ offset = 2
+
+ if past_key_values:
+ input_ids = torch.cat([input_ids[:, -offset:], dummy_token], dim=1)
+ else:
+ input_ids = torch.cat([input_ids, dummy_token], dim=1)
+
+ # Build permutation mask so that previous tokens don't see last token
+ sequence_length = input_ids.shape[1]
+ perm_mask = torch.zeros(
+ (effective_batch_size, sequence_length, sequence_length), dtype=torch.float, device=input_ids.device
+ )
+ perm_mask[:, :, -1] = 1.0
+
+ # We'll only predict the last token
+ target_mapping = torch.zeros(
+ (effective_batch_size, 1, sequence_length), dtype=torch.float, device=input_ids.device
+ )
+ target_mapping[:, 0, -1] = 1.0
+
+ inputs = {
+ "input_ids": input_ids,
+ "perm_mask": perm_mask,
+ "target_mapping": target_mapping,
+ "use_mems": use_mems,
+ }
+
+ # if past is defined in model kwargs then use it for faster decoding
+ if past_key_values:
+ inputs["mems"] = tuple(layer_past[:-offset, :, :] for layer_past in past_key_values)
+
+ return inputs
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ mems: Optional[torch.Tensor] = None,
+ perm_mask: Optional[torch.Tensor] = None,
+ target_mapping: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ input_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ use_mems: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> Union[tuple, XLNetLMHeadModelOutput]:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ labels (`torch.LongTensor` of shape `(batch_size, num_predict)`, *optional*):
+ Labels for masked language modeling. `num_predict` corresponds to `target_mapping.shape[1]`. If
+ `target_mapping` is `None`, then `num_predict` corresponds to `sequence_length`.
+
+ The labels should correspond to the masked input words that should be predicted and depends on
+ `target_mapping`. Note in order to perform standard auto-regressive language modeling a ** token has
+ to be added to the `input_ids` (see the `prepare_inputs_for_generation` function and examples below)
+
+ Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored, the loss
+ is only computed for labels in `[0, ..., config.vocab_size]`
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLNetLMHeadModel
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-large-cased")
+ >>> model = XLNetLMHeadModel.from_pretrained("xlnet/xlnet-large-cased")
+
+ >>> # We show how to setup inputs to predict a next token using a bi-directional context.
+ >>> input_ids = torch.tensor(
+ ... tokenizer.encode("Hello, my dog is very ", add_special_tokens=False)
+ ... ).unsqueeze(
+ ... 0
+ ... ) # We will predict the masked token
+ >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
+ >>> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token
+ >>> target_mapping = torch.zeros(
+ ... (1, 1, input_ids.shape[1]), dtype=torch.float
+ ... ) # Shape [1, 1, seq_length] => let's predict one token
+ >>> target_mapping[
+ ... 0, 0, -1
+ ... ] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token)
+
+ >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping)
+ >>> next_token_logits = outputs[
+ ... 0
+ ... ] # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
+
+ >>> # The same way can the XLNetLMHeadModel be used to be trained by standard auto-regressive language modeling.
+ >>> input_ids = torch.tensor(
+ ... tokenizer.encode("Hello, my dog is very ", add_special_tokens=False)
+ ... ).unsqueeze(
+ ... 0
+ ... ) # We will predict the masked token
+ >>> labels = torch.tensor(tokenizer.encode("cute", add_special_tokens=False)).unsqueeze(0)
+ >>> assert labels.shape[0] == 1, "only one word will be predicted"
+ >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
+ >>> perm_mask[
+ ... :, :, -1
+ ... ] = 1.0 # Previous tokens don't see last token as is done in standard auto-regressive lm training
+ >>> target_mapping = torch.zeros(
+ ... (1, 1, input_ids.shape[1]), dtype=torch.float
+ ... ) # Shape [1, 1, seq_length] => let's predict one token
+ >>> target_mapping[
+ ... 0, 0, -1
+ ... ] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token)
+
+ >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping, labels=labels)
+ >>> loss = outputs.loss
+ >>> next_token_logits = (
+ ... outputs.logits
+ ... ) # Logits have shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+
+ logits = self.lm_loss(transformer_outputs[0])
+
+ loss = None
+ if labels is not None:
+ # Flatten the tokens
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XLNetLMHeadModelOutput(
+ loss=loss,
+ logits=logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ @staticmethod
+ def _reorder_cache(mems: list[torch.Tensor], beam_idx: torch.Tensor) -> list[torch.Tensor]:
+ """
+ This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or
+ [`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every
+ generation step.
+ """
+ return [layer_past.index_select(1, beam_idx.to(layer_past.device)) for layer_past in mems]
+
+
+@auto_docstring(
+ custom_intro="""
+ XLNet Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g.
+ for GLUE tasks.
+ """
+)
+class XLNetForSequenceClassification(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.transformer = XLNetModel(config)
+ self.sequence_summary = XLNetSequenceSummary(config)
+ self.logits_proj = nn.Linear(config.d_model, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ mems: Optional[torch.Tensor] = None,
+ perm_mask: Optional[torch.Tensor] = None,
+ target_mapping: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ input_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ use_mems: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> Union[tuple, XLNetForSequenceClassificationOutput]:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+ output = transformer_outputs[0]
+
+ output = self.sequence_summary(output)
+ logits = self.logits_proj(output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XLNetForSequenceClassificationOutput(
+ loss=loss,
+ logits=logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLNetForTokenClassification(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.transformer = XLNetModel(config)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ mems: Optional[torch.Tensor] = None,
+ perm_mask: Optional[torch.Tensor] = None,
+ target_mapping: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ input_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ use_mems: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> Union[tuple, XLNetForTokenClassificationOutput]:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
+ where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.emory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XLNetForTokenClassificationOutput(
+ loss=loss,
+ logits=logits,
+ mems=outputs.mems,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLNetForMultipleChoice(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.transformer = XLNetModel(config)
+ self.sequence_summary = XLNetSequenceSummary(config)
+ self.logits_proj = nn.Linear(config.d_model, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ input_mask: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ mems: Optional[torch.Tensor] = None,
+ perm_mask: Optional[torch.Tensor] = None,
+ target_mapping: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ use_mems: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> Union[tuple, XLNetForMultipleChoiceOutput]:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ input_mask (`torch.FloatTensor` of shape `batch_size, num_choices, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_input_mask = input_mask.view(-1, input_mask.size(-1)) if input_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ transformer_outputs = self.transformer(
+ flat_input_ids,
+ token_type_ids=flat_token_type_ids,
+ input_mask=flat_input_mask,
+ attention_mask=flat_attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ head_mask=head_mask,
+ inputs_embeds=flat_inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+
+ output = transformer_outputs[0]
+
+ output = self.sequence_summary(output)
+ logits = self.logits_proj(output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels.view(-1))
+
+ if not return_dict:
+ output = (reshaped_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return XLNetForMultipleChoiceOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ XLNet Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
+ layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
+ """
+)
+class XLNetForQuestionAnsweringSimple(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.transformer = XLNetModel(config)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ mems: Optional[torch.Tensor] = None,
+ perm_mask: Optional[torch.Tensor] = None,
+ target_mapping: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ input_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ start_positions: Optional[torch.Tensor] = None,
+ end_positions: Optional[torch.Tensor] = None,
+ use_mems: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> Union[tuple, XLNetForQuestionAnsweringSimpleOutput]:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[1:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return XLNetForQuestionAnsweringSimpleOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ mems=outputs.mems,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XLNetForQuestionAnswering(XLNetPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.start_n_top = config.start_n_top
+ self.end_n_top = config.end_n_top
+
+ self.transformer = XLNetModel(config)
+ self.start_logits = XLNetPoolerStartLogits(config)
+ self.end_logits = XLNetPoolerEndLogits(config)
+ self.answer_class = XLNetPoolerAnswerClass(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ mems: Optional[torch.Tensor] = None,
+ perm_mask: Optional[torch.Tensor] = None,
+ target_mapping: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ input_mask: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ start_positions: Optional[torch.Tensor] = None,
+ end_positions: Optional[torch.Tensor] = None,
+ is_impossible: Optional[torch.Tensor] = None,
+ cls_index: Optional[torch.Tensor] = None,
+ p_mask: Optional[torch.Tensor] = None,
+ use_mems: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ **kwargs, # delete when `use_cache` is removed in XLNetModel
+ ) -> Union[tuple, XLNetForQuestionAnsweringOutput]:
+ r"""
+ mems (`list[torch.FloatTensor]` of length `config.n_layers`):
+ Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
+ decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
+ they have already been computed.
+
+ `use_mems` has to be set to `True` to make use of `mems`.
+ perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
+ Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
+
+ - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
+ - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
+
+ If not set, each token attends to all the others (full bidirectional attention). Only used during
+ pretraining (to define factorization order) or for sequential decoding (generation).
+ target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
+ Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
+ on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
+ (generation).
+ input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
+ Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
+ real tokens and 1 for padding which is kept for compatibility with the original code base.
+
+ Mask values selected in `[0, 1]`:
+
+ - 1 for tokens that are **masked**,
+ - 0 for tokens that are **not masked**.
+
+ You can only uses one of `input_mask` and `attention_mask`.
+ is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels whether a question has an answer or no answer (SQuAD 2.0)
+ cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for position (index) of the classification token to use as input for computing plausibility of the
+ answer.
+ p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be
+ masked. 0.0 mean token is not masked.
+ use_mems (`bool`, *optional*):
+ Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
+ states from previous forward passes to compute attention, which can significantly improve performance for
+ sequential decoding tasks.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XLNetForQuestionAnswering
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
+ >>> model = XLNetForQuestionAnswering.from_pretrained("xlnet/xlnet-base-cased")
+
+ >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(
+ ... 0
+ ... ) # Batch size 1
+ >>> start_positions = torch.tensor([1])
+ >>> end_positions = torch.tensor([3])
+ >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
+
+ >>> loss = outputs.loss
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.transformer(
+ input_ids,
+ attention_mask=attention_mask,
+ mems=mems,
+ perm_mask=perm_mask,
+ target_mapping=target_mapping,
+ token_type_ids=token_type_ids,
+ input_mask=input_mask,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ use_mems=use_mems,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ **kwargs,
+ )
+ hidden_states = transformer_outputs[0]
+ start_logits = self.start_logits(hidden_states, p_mask=p_mask)
+
+ outputs = transformer_outputs[1:] # Keep mems, hidden states, attentions if there are in it
+
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, let's remove the dimension added by batch splitting
+ for x in (start_positions, end_positions, cls_index, is_impossible):
+ if x is not None and x.dim() > 1:
+ x.squeeze_(-1)
+
+ # during training, compute the end logits based on the ground truth of the start position
+ end_logits = self.end_logits(hidden_states, start_positions=start_positions, p_mask=p_mask)
+
+ loss_fct = CrossEntropyLoss()
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if cls_index is not None and is_impossible is not None:
+ # Predict answerability from the representation of CLS and START
+ cls_logits = self.answer_class(hidden_states, start_positions=start_positions, cls_index=cls_index)
+ loss_fct_cls = nn.BCEWithLogitsLoss()
+ cls_loss = loss_fct_cls(cls_logits, is_impossible)
+
+ # note(zhiliny): by default multiply the loss by 0.5 so that the scale is comparable to start_loss and end_loss
+ total_loss += cls_loss * 0.5
+
+ if not return_dict:
+ return (total_loss,) + transformer_outputs[1:]
+ else:
+ return XLNetForQuestionAnsweringOutput(
+ loss=total_loss,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+ else:
+ # during inference, compute the end logits based on beam search
+ bsz, slen, hsz = hidden_states.size()
+ start_log_probs = nn.functional.softmax(start_logits, dim=-1) # shape (bsz, slen)
+
+ start_top_log_probs, start_top_index = torch.topk(
+ start_log_probs, self.start_n_top, dim=-1
+ ) # shape (bsz, start_n_top)
+ start_top_index_exp = start_top_index.unsqueeze(-1).expand(-1, -1, hsz) # shape (bsz, start_n_top, hsz)
+ start_states = torch.gather(hidden_states, -2, start_top_index_exp) # shape (bsz, start_n_top, hsz)
+ start_states = start_states.unsqueeze(1).expand(-1, slen, -1, -1) # shape (bsz, slen, start_n_top, hsz)
+
+ hidden_states_expanded = hidden_states.unsqueeze(2).expand_as(
+ start_states
+ ) # shape (bsz, slen, start_n_top, hsz)
+ p_mask = p_mask.unsqueeze(-1) if p_mask is not None else None
+ end_logits = self.end_logits(hidden_states_expanded, start_states=start_states, p_mask=p_mask)
+ end_log_probs = nn.functional.softmax(end_logits, dim=1) # shape (bsz, slen, start_n_top)
+
+ end_top_log_probs, end_top_index = torch.topk(
+ end_log_probs, self.end_n_top, dim=1
+ ) # shape (bsz, end_n_top, start_n_top)
+ end_top_log_probs = end_top_log_probs.view(-1, self.start_n_top * self.end_n_top)
+ end_top_index = end_top_index.view(-1, self.start_n_top * self.end_n_top)
+
+ start_states = torch.einsum(
+ "blh,bl->bh", hidden_states, start_log_probs
+ ) # get the representation of START as weighted sum of hidden states
+ cls_logits = self.answer_class(
+ hidden_states, start_states=start_states, cls_index=cls_index
+ ) # Shape (batch size,): one single `cls_logits` for each sample
+
+ if not return_dict:
+ outputs = (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits)
+ return outputs + transformer_outputs[1:]
+ else:
+ return XLNetForQuestionAnsweringOutput(
+ start_top_log_probs=start_top_log_probs,
+ start_top_index=start_top_index,
+ end_top_log_probs=end_top_log_probs,
+ end_top_index=end_top_index,
+ cls_logits=cls_logits,
+ mems=transformer_outputs.mems,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = [
+ "XLNetForMultipleChoice",
+ "XLNetForQuestionAnswering",
+ "XLNetForQuestionAnsweringSimple",
+ "XLNetForSequenceClassification",
+ "XLNetForTokenClassification",
+ "XLNetLMHeadModel",
+ "XLNetModel",
+ "XLNetPreTrainedModel",
+ "load_tf_weights_in_xlnet",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/tokenization_xlnet.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/tokenization_xlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..9186db33d788e2766755c0d1ec51614e95173a0f
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/tokenization_xlnet.py
@@ -0,0 +1,387 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for XLNet model."""
+
+import os
+import unicodedata
+from shutil import copyfile
+from typing import Any, Optional
+
+import sentencepiece as spm
+
+from ...tokenization_utils import AddedToken, PreTrainedTokenizer
+from ...utils import SPIECE_UNDERLINE, logging
+from ...utils.import_utils import requires
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "spiece.model"}
+
+
+# Segments (not really needed)
+SEG_ID_A = 0
+SEG_ID_B = 1
+SEG_ID_CLS = 2
+SEG_ID_SEP = 3
+SEG_ID_PAD = 4
+
+
+@requires(backends=("sentencepiece",))
+class XLNetTokenizer(PreTrainedTokenizer):
+ """
+ Construct an XLNet tokenizer. Based on [SentencePiece](https://github.com/google/sentencepiece).
+
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
+ this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
+ contains the vocabulary necessary to instantiate a tokenizer.
+ do_lower_case (`bool`, *optional*, defaults to `False`):
+ Whether to lowercase the input when tokenizing.
+ remove_space (`bool`, *optional*, defaults to `True`):
+ Whether to strip the text when tokenizing (removing excess spaces before and after the string).
+ keep_accents (`bool`, *optional*, defaults to `False`):
+ Whether to keep accents when tokenizing.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ additional_special_tokens (`list[str]`, *optional*, defaults to `['', '']`):
+ Additional special tokens used by the tokenizer.
+ sp_model_kwargs (`dict`, *optional*):
+ Will be passed to the `SentencePieceProcessor.__init__()` method. The [Python wrapper for
+ SentencePiece](https://github.com/google/sentencepiece/tree/master/python) can be used, among other things,
+ to set:
+
+ - `enable_sampling`: Enable subword regularization.
+ - `nbest_size`: Sampling parameters for unigram. Invalid for BPE-Dropout.
+
+ - `nbest_size = {0,1}`: No sampling is performed.
+ - `nbest_size > 1`: samples from the nbest_size results.
+ - `nbest_size < 0`: assuming that nbest_size is infinite and samples from the all hypothesis (lattice)
+ using forward-filtering-and-backward-sampling algorithm.
+
+ - `alpha`: Smoothing parameter for unigram sampling, and dropout probability of merge operations for
+ BPE-dropout.
+
+ Attributes:
+ sp_model (`SentencePieceProcessor`):
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ padding_side = "left"
+
+ def __init__(
+ self,
+ vocab_file,
+ do_lower_case=False,
+ remove_space=True,
+ keep_accents=False,
+ bos_token="",
+ eos_token="",
+ unk_token="",
+ sep_token="",
+ pad_token="",
+ cls_token="",
+ mask_token="",
+ additional_special_tokens=["", ""],
+ sp_model_kwargs: Optional[dict[str, Any]] = None,
+ **kwargs,
+ ) -> None:
+ # Mask token behave like a normal word, i.e. include the space before it
+ mask_token = AddedToken(mask_token, lstrip=True, special=True) if isinstance(mask_token, str) else mask_token
+
+ self.sp_model_kwargs = {} if sp_model_kwargs is None else sp_model_kwargs
+
+ self.do_lower_case = do_lower_case
+ self.remove_space = remove_space
+ self.keep_accents = keep_accents
+ self.vocab_file = vocab_file
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.Load(vocab_file)
+
+ super().__init__(
+ do_lower_case=do_lower_case,
+ remove_space=remove_space,
+ keep_accents=keep_accents,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ additional_special_tokens=additional_special_tokens,
+ sp_model_kwargs=self.sp_model_kwargs,
+ **kwargs,
+ )
+
+ self._pad_token_type_id = 3
+
+ @property
+ def vocab_size(self):
+ return len(self.sp_model)
+
+ def get_vocab(self):
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size)}
+ vocab.update(self.added_tokens_encoder)
+ return vocab
+
+ def __getstate__(self):
+ state = self.__dict__.copy()
+ state["sp_model"] = None
+ return state
+
+ def __setstate__(self, d):
+ self.__dict__ = d
+
+ # for backward compatibility
+ if not hasattr(self, "sp_model_kwargs"):
+ self.sp_model_kwargs = {}
+
+ self.sp_model = spm.SentencePieceProcessor(**self.sp_model_kwargs)
+ self.sp_model.Load(self.vocab_file)
+
+ def preprocess_text(self, inputs):
+ if self.remove_space:
+ outputs = " ".join(inputs.strip().split())
+ else:
+ outputs = inputs
+ outputs = outputs.replace("``", '"').replace("''", '"')
+
+ if not self.keep_accents:
+ outputs = unicodedata.normalize("NFKD", outputs)
+ outputs = "".join([c for c in outputs if not unicodedata.combining(c)])
+ if self.do_lower_case:
+ outputs = outputs.lower()
+
+ return outputs
+
+ def _tokenize(self, text: str) -> list[str]:
+ """Tokenize a string."""
+ text = self.preprocess_text(text)
+ pieces = self.sp_model.encode(text, out_type=str)
+ new_pieces = []
+ for piece in pieces:
+ if len(piece) > 1 and piece[-1] == "," and piece[-2].isdigit():
+ cur_pieces = self.sp_model.EncodeAsPieces(piece[:-1].replace(SPIECE_UNDERLINE, ""))
+ if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
+ if len(cur_pieces[0]) == 1:
+ cur_pieces = cur_pieces[1:]
+ else:
+ cur_pieces[0] = cur_pieces[0][1:]
+ cur_pieces.append(piece[-1])
+ new_pieces.extend(cur_pieces)
+ else:
+ new_pieces.append(piece)
+
+ return new_pieces
+
+ def _convert_token_to_id(self, token):
+ """Converts a token (str) in an id using the vocab."""
+ return self.sp_model.PieceToId(token)
+
+ def _convert_id_to_token(self, index):
+ """Converts an index (integer) in a token (str) using the vocab."""
+ return self.sp_model.IdToPiece(index)
+
+ def convert_tokens_to_string(self, tokens):
+ """Converts a sequence of tokens (strings for sub-words) in a single string."""
+ out_string = "".join(tokens).replace(SPIECE_UNDERLINE, " ").strip()
+ return out_string
+
+ def _decode(
+ self,
+ token_ids: list[int],
+ skip_special_tokens: bool = False,
+ clean_up_tokenization_spaces: Optional[bool] = None,
+ spaces_between_special_tokens: bool = True,
+ **kwargs,
+ ) -> str:
+ self._decode_use_source_tokenizer = kwargs.pop("use_source_tokenizer", False)
+
+ filtered_tokens = self.convert_ids_to_tokens(token_ids, skip_special_tokens=skip_special_tokens)
+
+ # To avoid mixing byte-level and unicode for byte-level BPT
+ # we need to build string separately for added tokens and byte-level tokens
+ # cf. https://github.com/huggingface/transformers/issues/1133
+ sub_texts = []
+ current_sub_text = []
+ for token in filtered_tokens:
+ if skip_special_tokens and token in self.all_special_ids:
+ continue
+ if token in self.added_tokens_encoder:
+ if current_sub_text:
+ sub_texts.append(self.convert_tokens_to_string(current_sub_text))
+ current_sub_text = []
+ sub_texts.append(token)
+ else:
+ current_sub_text.append(token)
+ if current_sub_text:
+ sub_texts.append(self.convert_tokens_to_string(current_sub_text))
+
+ # Mimic the behavior of the Rust tokenizer:
+ # By default, there are no spaces between special tokens
+ text = "".join(sub_texts)
+
+ clean_up_tokenization_spaces = (
+ clean_up_tokenization_spaces
+ if clean_up_tokenization_spaces is not None
+ else self.clean_up_tokenization_spaces
+ )
+ if clean_up_tokenization_spaces:
+ clean_text = self.clean_up_tokenization(text)
+ return clean_text
+ else:
+ return text
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An XLNet sequence has the following format:
+
+ - single sequence: `X `
+ - pair of sequences: `A B `
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ sep = [self.sep_token_id]
+ cls = [self.cls_token_id]
+ if token_ids_1 is None:
+ return token_ids_0 + sep + cls
+ return token_ids_0 + sep + token_ids_1 + sep + cls
+
+ def get_special_tokens_mask(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None, already_has_special_tokens: bool = False
+ ) -> list[int]:
+ """
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
+ special tokens using the tokenizer `prepare_for_model` method.
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
+ Whether or not the token list is already formatted with special tokens for the model.
+
+ Returns:
+ `list[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
+ """
+
+ if already_has_special_tokens:
+ return super().get_special_tokens_mask(
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
+ )
+
+ if token_ids_1 is not None:
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1, 1]
+ return ([0] * len(token_ids_0)) + [1, 1]
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
+ sequence pair mask has the following format:
+
+ ```
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
+ | first sequence | second sequence |
+ ```
+
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
+ """
+ sep = [self.sep_token_id]
+ cls_segment_id = [2]
+
+ if token_ids_1 is None:
+ return len(token_ids_0 + sep) * [0] + cls_segment_id
+ return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ out_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file) and os.path.isfile(self.vocab_file):
+ copyfile(self.vocab_file, out_vocab_file)
+ elif not os.path.isfile(self.vocab_file):
+ with open(out_vocab_file, "wb") as fi:
+ content_spiece_model = self.sp_model.serialized_model_proto()
+ fi.write(content_spiece_model)
+
+ return (out_vocab_file,)
+
+
+__all__ = ["XLNetTokenizer"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/tokenization_xlnet_fast.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/tokenization_xlnet_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..56cd2a50e1b26552d60e4e41a86cd5780a766363
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlnet/tokenization_xlnet_fast.py
@@ -0,0 +1,230 @@
+# coding=utf-8
+# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Tokenization classes for XLNet model."""
+
+import os
+from shutil import copyfile
+from typing import Optional
+
+from ...tokenization_utils import AddedToken
+from ...tokenization_utils_fast import PreTrainedTokenizerFast
+from ...utils import is_sentencepiece_available, logging
+
+
+if is_sentencepiece_available():
+ from .tokenization_xlnet import XLNetTokenizer
+else:
+ XLNetTokenizer = None
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}
+
+
+SPIECE_UNDERLINE = "▁"
+
+# Segments (not really needed)
+SEG_ID_A = 0
+SEG_ID_B = 1
+SEG_ID_CLS = 2
+SEG_ID_SEP = 3
+SEG_ID_PAD = 4
+
+
+class XLNetTokenizerFast(PreTrainedTokenizerFast):
+ """
+ Construct a "fast" XLNet tokenizer (backed by HuggingFace's *tokenizers* library). Based on
+ [Unigram](https://huggingface.co/docs/tokenizers/python/latest/components.html?highlight=unigram#models).
+
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab_file (`str`):
+ [SentencePiece](https://github.com/google/sentencepiece) file (generally has a .spm extension) that
+ contains the vocabulary necessary to instantiate a tokenizer.
+ do_lower_case (`bool`, *optional*, defaults to `True`):
+ Whether to lowercase the input when tokenizing.
+ remove_space (`bool`, *optional*, defaults to `True`):
+ Whether to strip the text when tokenizing (removing excess spaces before and after the string).
+ keep_accents (`bool`, *optional*, defaults to `False`):
+ Whether to keep accents when tokenizing.
+ bos_token (`str`, *optional*, defaults to `""`):
+ The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the beginning of
+ sequence. The token used is the `cls_token`.
+
+
+
+ eos_token (`str`, *optional*, defaults to `""`):
+ The end of sequence token.
+
+
+
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
+ The token used is the `sep_token`.
+
+
+
+ unk_token (`str`, *optional*, defaults to `""`):
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
+ token instead.
+ sep_token (`str`, *optional*, defaults to `""`):
+ The separator token, which is used when building a sequence from multiple sequences, e.g. two sequences for
+ sequence classification or for a text and a question for question answering. It is also used as the last
+ token of a sequence built with special tokens.
+ pad_token (`str`, *optional*, defaults to `""`):
+ The token used for padding, for example when batching sequences of different lengths.
+ cls_token (`str`, *optional*, defaults to `""`):
+ The classifier token which is used when doing sequence classification (classification of the whole sequence
+ instead of per-token classification). It is the first token of the sequence when built with special tokens.
+ mask_token (`str`, *optional*, defaults to `""`):
+ The token used for masking values. This is the token used when training this model with masked language
+ modeling. This is the token which the model will try to predict.
+ additional_special_tokens (`list[str]`, *optional*, defaults to `["", ""]`):
+ Additional special tokens used by the tokenizer.
+
+ Attributes:
+ sp_model (`SentencePieceProcessor`):
+ The *SentencePiece* processor that is used for every conversion (string, tokens and IDs).
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ padding_side = "left"
+ slow_tokenizer_class = XLNetTokenizer
+
+ def __init__(
+ self,
+ vocab_file=None,
+ tokenizer_file=None,
+ do_lower_case=False,
+ remove_space=True,
+ keep_accents=False,
+ bos_token="",
+ eos_token="",
+ unk_token="",
+ sep_token="",
+ pad_token="",
+ cls_token="",
+ mask_token="",
+ additional_special_tokens=["", ""],
+ **kwargs,
+ ):
+ # Mask token behave like a normal word, i.e. include the space before it
+ mask_token = AddedToken(mask_token, lstrip=True, rstrip=False) if isinstance(mask_token, str) else mask_token
+
+ super().__init__(
+ vocab_file=vocab_file,
+ tokenizer_file=tokenizer_file,
+ do_lower_case=do_lower_case,
+ remove_space=remove_space,
+ keep_accents=keep_accents,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ unk_token=unk_token,
+ sep_token=sep_token,
+ pad_token=pad_token,
+ cls_token=cls_token,
+ mask_token=mask_token,
+ additional_special_tokens=additional_special_tokens,
+ **kwargs,
+ )
+
+ self._pad_token_type_id = 3
+ self.do_lower_case = do_lower_case
+ self.remove_space = remove_space
+ self.keep_accents = keep_accents
+ self.vocab_file = vocab_file
+
+ def build_inputs_with_special_tokens(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
+ adding special tokens. An XLNet sequence has the following format:
+
+ - single sequence: `X `
+ - pair of sequences: `A B `
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs to which the special tokens will be added.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
+ """
+ sep = [self.sep_token_id]
+ cls = [self.cls_token_id]
+ if token_ids_1 is None:
+ return token_ids_0 + sep + cls
+ return token_ids_0 + sep + token_ids_1 + sep + cls
+
+ def create_token_type_ids_from_sequences(
+ self, token_ids_0: list[int], token_ids_1: Optional[list[int]] = None
+ ) -> list[int]:
+ """
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. An XLNet
+ sequence pair mask has the following format:
+
+ ```
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
+ | first sequence | second sequence |
+ ```
+
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
+
+ Args:
+ token_ids_0 (`list[int]`):
+ List of IDs.
+ token_ids_1 (`list[int]`, *optional*):
+ Optional second list of IDs for sequence pairs.
+
+ Returns:
+ `list[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
+ """
+ sep = [self.sep_token_id]
+ cls_segment_id = [2]
+
+ if token_ids_1 is None:
+ return len(token_ids_0 + sep) * [0] + cls_segment_id
+ return len(token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] + cls_segment_id
+
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> tuple[str]:
+ if not self.can_save_slow_tokenizer:
+ raise ValueError(
+ "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
+ "tokenizer."
+ )
+
+ if not os.path.isdir(save_directory):
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
+ return
+ out_vocab_file = os.path.join(
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
+ )
+
+ if os.path.abspath(self.vocab_file) != os.path.abspath(out_vocab_file):
+ copyfile(self.vocab_file, out_vocab_file)
+
+ return (out_vocab_file,)
+
+
+__all__ = ["XLNetTokenizerFast"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..00e206973a908d82e9b8fe38a3d016fcced9ecd3
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlstm/__init__.py
@@ -0,0 +1,31 @@
+# Copyright 2025 NXAI GmbH. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import (
+ OptionalDependencyNotAvailable,
+ _LazyModule,
+ is_torch_available,
+)
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from configuration_xlstm import *
+ from modeling_xlstm import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlstm/configuration_xlstm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlstm/configuration_xlstm.py
new file mode 100644
index 0000000000000000000000000000000000000000..80c513adde69d3511bea2ede9c1834b45e1eb166
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlstm/configuration_xlstm.py
@@ -0,0 +1,302 @@
+# Copyright 2025 NXAI GmbH. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""xLSTM configuration."""
+
+from typing import Optional
+
+from ...configuration_utils import PretrainedConfig
+from ...utils import is_xlstm_available, logging
+
+
+if is_xlstm_available():
+ from xlstm.xlstm_large.model import (
+ BackendModeType,
+ ChunkwiseKernelType,
+ DtypeType,
+ SequenceKernelType,
+ StepKernelType,
+ WeightModeType,
+ round_up_to_next_multiple_of,
+ xLSTMLargeConfig,
+ )
+
+ external_xlstm = True
+else:
+ from typing import Literal
+
+ BackendModeType = Literal["train", "train_with_padding", "inference"]
+ ChunkwiseKernelType = Literal[
+ "chunkwise--native_autograd",
+ "parallel--native_autograd",
+ ]
+ DtypeType = Literal["float32", "bfloat16", "float16"]
+ SequenceKernelType = Literal["native_sequence__native"]
+ StepKernelType = Literal["native"]
+ WeightModeType = Literal["single", "fused"]
+
+ def round_up_to_next_multiple_of(x: int, multiple_of: int) -> int:
+ """Rounds up x to the next multiple of multiple_of."""
+ return int(((x + multiple_of - 1) // multiple_of) * multiple_of)
+
+ external_xlstm = False
+
+
+logger = logging.get_logger(__name__)
+
+
+class xLSTMConfig(PretrainedConfig):
+ """
+ This is the configuration class to store the configuration of a [`xLSTM`]. It is used to instantiate a xLSTM
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the xLSTM-7b [NX-AI/xLSTM-7b](https://huggingface.co/NX-AI/xLSTM-7b) model.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (int, optional, *optional*, defaults to 50304):
+ Vocabulary size of the xLSTM model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`xLSTMModel`]. Defaults to the GPT2-NeoX tokenizer size.
+ hidden_size (int, optional, *optional*, defaults to 4096):
+ Dimensionality of the embeddings or hidden states.
+ embedding_dim (int, optional, *optional*, defaults to 4096):
+ Dimensionality of the embeddings or hidden states, use hidde_size if None.
+ num_hidden_layers (int, optional, *optional*, defaults to 32):
+ Number of blocks of the xLSTM model.
+ num_blocks (int, optional, *optional*, defaults to 32):
+ Number of blocks of the xLSTM model, use num_hidden_layers if None.
+ num_heads (int, optional, *optional*, defaults to 8):
+ Number of heads for the xLSTM Layer/Cell.
+ use_bias (bool, optional, *optional*, defaults to `False`):
+ Whether to use biases in the xLSTM model.
+ norm_reduction_force_float32 (bool, optional, *optional*, defaults to `True`):
+ Whether to force the float32 norm reduction op to be done in fp32 precision.
+ tie_word_embeddings (bool, optional, *optional*, defaults to `False`):
+ Whether to tie word embeddings to the lm head weights.
+ add_out_norm (bool, optional, *optional*, defaults to `True`):
+ Whether to add an output norm after the blocks before the LMHead.
+ norm_eps (float, optional, *optional*, defaults to 1e-06):
+ Norm eps for RMSNorm and Layer Norm.
+ qk_dim_factor (float, optional, *optional*, defaults to 0.5):
+ Scale factor for the query and key dimension.
+ v_dim_factor (float, optional, *optional*, defaults to 1.0):
+ Scale factor for the value dimension.
+ chunkwise_kernel (ChunkwiseKernelType, optional, *optional*, defaults to `"chunkwise--native_autograd"`):
+ Kernel type for chunkwise processing mode.
+ sequence_kernel (SequenceKernelType, optional, *optional*, defaults to `"native_sequence__native"`):
+ Kernel type for sequence processing mode.
+ step_kernel (StepKernelType, optional, *optional*, defaults to `"native"`):
+ Kernel type for step processing mode.
+ mode (BackendModeType, optional, *optional*, defaults to `"inference"`):
+ Operation mode (inference is needed for generation).
+ chunk_size (int, optional, *optional*, defaults to 64):
+ Internal chunk size.
+ return_last_states (bool, optional, *optional*, defaults to `True`):
+ If to return the last states / cache internally. Needed as True for generation.
+ autocast_kernel_dtype (DtypeType, optional, *optional*, defaults to `"bfloat16"`):
+ Kernel dtype for the states.
+ eps (float, optional, *optional*, defaults to 1e-06):
+ Epsilon for the mLSTM cell post norm.
+ inference_state_dtype (DtypeType, optional, *optional*, defaults to `"float32"`):
+ Kernel dtype for states in inference.
+ ffn_proj_factor (float, optional, *optional*, defaults to 2.667):
+ Size factor of the post-up projection gated Feed Forward network.
+ ffn_round_up_to_multiple_of (int, optional, *optional*, defaults to 64):
+ Size factor round value of the post-up projection gated Feed Forward network.
+ gate_soft_cap (float, optional, *optional*, defaults to 15.0):
+ Gate soft cap scale.
+ output_logit_soft_cap (float, optional, *optional*, defaults to 30.0):
+ Output logit soft cap scale.
+ weight_mode (`Literal`, *optional*, defaults to `"single"`):
+ Whether parallel linear layers are separated or fused (single).
+ use_cache (bool, optional, *optional*, defaults to `True`):
+ Whether to use the cache (xLSTMCache).
+ pad_token_id (int, optional, *optional*, defaults to 1):
+ Pad token id needed for generation.
+ bos_token_id (int, optional, *optional*, defaults to 0):
+ BOS token id needed for generation.
+ eos_token_id (int, optional, *optional*, defaults to 2):
+ EOS token id needed for generation.
+ max_inference_chunksize (int, optional, *optional*, defaults to 16384):
+ Limit the chunk size for inference to save memory.
+
+ Example:
+
+ ```python
+ >>> from transformers import xLSTMConfig, xLSTMModel
+
+ >>> # Initializing a xLSTM configuration
+ >>> configuration = xLSTMConfig()
+
+ >>> # Initializing a model (with random weights) from the configuration
+ >>> model = xLSTMModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xlstm"
+
+ def __init__(
+ self,
+ vocab_size: int = 50304,
+ hidden_size: int = 4096,
+ embedding_dim: Optional[int] = None,
+ num_hidden_layers: Optional[int] = 32,
+ num_blocks: Optional[int] = None,
+ num_heads: int = 8,
+ use_bias: bool = False,
+ norm_reduction_force_float32: bool = True,
+ tie_word_embeddings: bool = False,
+ add_out_norm: bool = True,
+ norm_eps: float = 1e-6,
+ # mlstm_layer
+ qk_dim_factor: float = 0.5,
+ v_dim_factor: float = 1.0,
+ # mlstm backend
+ chunkwise_kernel: ChunkwiseKernelType = "chunkwise--native_autograd",
+ sequence_kernel: SequenceKernelType = "native_sequence__native",
+ step_kernel: StepKernelType = "native",
+ # nedded to enable generation
+ mode: BackendModeType = "inference",
+ chunk_size: int = 64,
+ # needed to be true for generation
+ return_last_states: bool = True,
+ autocast_kernel_dtype: DtypeType = "bfloat16",
+ eps: float = 1e-6,
+ inference_state_dtype: DtypeType = "float32",
+ # feedforward
+ ffn_proj_factor: float = 2.667,
+ ffn_round_up_to_multiple_of: int = 64,
+ # capping
+ gate_soft_cap: float = 15.0,
+ output_logit_soft_cap: float = 30.0,
+ # weights
+ weight_mode: WeightModeType = "single",
+ # HF interface
+ use_cache: bool = True,
+ pad_token_id: int = 1,
+ bos_token_id: int = 0,
+ eos_token_id: int = 2,
+ max_inference_chunksize: int = 16384,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size if hidden_size is not None else embedding_dim
+ self.embedding_dim = embedding_dim if embedding_dim is not None else hidden_size
+ self.num_hidden_layers = num_hidden_layers if num_hidden_layers is not None else num_blocks
+ self.num_blocks = num_blocks if num_blocks is not None else num_hidden_layers
+ self.num_heads = num_heads
+ self.use_bias = use_bias
+ self.tie_word_embeddings = tie_word_embeddings
+ self.add_out_norm = add_out_norm
+ self.norm_eps = norm_eps
+ self.norm_reduction_force_float32 = norm_reduction_force_float32
+ # mlstm_layer
+ self.qk_dim_factor = qk_dim_factor
+ self.v_dim_factor = v_dim_factor
+ # mlstm backend
+ self.chunkwise_kernel = chunkwise_kernel
+ self.sequence_kernel = sequence_kernel
+ self.step_kernel = step_kernel
+ self.mode = mode
+ self.chunk_size = chunk_size
+ self.return_last_states = return_last_states
+ self.autocast_kernel_dtype = autocast_kernel_dtype
+ self.eps = eps
+ self.inference_state_dtype = inference_state_dtype
+ # feedforward
+ self.ffn_proj_factor = ffn_proj_factor
+ self.ffn_round_up_to_multiple_of = ffn_round_up_to_multiple_of
+ # capping
+ self.gate_soft_cap = gate_soft_cap
+ self.output_logit_soft_cap = output_logit_soft_cap
+ self.weight_mode = weight_mode
+
+ self.use_cache = use_cache
+ self.pad_token_id = pad_token_id
+ self.bos_token_id = bos_token_id
+ self.eos_token_id = eos_token_id
+ self.max_inference_chunksize = max_inference_chunksize
+
+ super().__init__(
+ bos_token_id=bos_token_id,
+ eos_token_id=eos_token_id,
+ pad_token_id=pad_token_id,
+ tie_word_embeddings=tie_word_embeddings,
+ **kwargs,
+ )
+
+ @property
+ def qk_dim(self):
+ return round_up_to_next_multiple_of(
+ self.hidden_size * self.qk_dim_factor,
+ multiple_of=64,
+ )
+
+ @property
+ def v_dim(self):
+ return round_up_to_next_multiple_of(
+ self.hidden_size * self.v_dim_factor,
+ multiple_of=64,
+ )
+
+ @property
+ def qk_head_dim(self):
+ return self.qk_dim // self.num_heads
+
+ @property
+ def v_head_dim(self):
+ return self.v_dim // self.num_heads
+
+ def to_xlstm_block_config(self):
+ if external_xlstm:
+ return xLSTMLargeConfig(
+ vocab_size=self.vocab_size,
+ embedding_dim=self.hidden_size,
+ num_blocks=self.num_hidden_layers,
+ num_heads=self.num_heads,
+ use_bias=self.use_bias,
+ add_out_norm=self.add_out_norm,
+ norm_eps=self.norm_eps,
+ norm_reduction_force_float32=self.norm_reduction_force_float32,
+ # mlstm_layer
+ qk_dim_factor=self.qk_dim_factor,
+ v_dim_factor=self.v_dim_factor,
+ # mlstm backend
+ chunkwise_kernel=self.chunkwise_kernel,
+ sequence_kernel=self.sequence_kernel,
+ step_kernel=self.step_kernel,
+ mode=self.mode,
+ chunk_size=self.chunk_size,
+ return_last_states=self.return_last_states,
+ autocast_kernel_dtype=self.autocast_kernel_dtype,
+ eps=self.eps,
+ inference_state_dtype=self.inference_state_dtype,
+ # feedforward
+ ffn_proj_factor=self.ffn_proj_factor,
+ ffn_round_up_to_multiple_of=self.ffn_round_up_to_multiple_of,
+ # capping
+ gate_soft_cap=self.gate_soft_cap,
+ output_logit_soft_cap=self.output_logit_soft_cap,
+ weight_mode=self.weight_mode,
+ )
+ else:
+ return self
+
+
+__all__ = ["xLSTMConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlstm/modeling_xlstm.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlstm/modeling_xlstm.py
new file mode 100644
index 0000000000000000000000000000000000000000..14f189d2f1ccfe2b83a0dbeab4b34d05af5623a8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xlstm/modeling_xlstm.py
@@ -0,0 +1,1624 @@
+# Copyright 2025 NXAI GmbH. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch xLSTM Model."""
+
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+import torch.nn.functional as F
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import CrossEntropyLoss
+
+from ...generation import GenerationMixin
+from ...modeling_utils import PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, can_return_tuple, is_xlstm_available
+from .configuration_xlstm import xLSTMConfig
+
+
+if is_xlstm_available():
+ from xlstm.xlstm_large.model import RMSNorm as xLSTMRMSNorm
+ from xlstm.xlstm_large.model import mLSTMBlock as xLSTMBlock
+ from xlstm.xlstm_large.model import mLSTMStateType, soft_cap
+
+ external_xlstm = True
+else:
+ from functools import partial
+ from typing import Callable, Literal
+
+ from .configuration_xlstm import round_up_to_next_multiple_of
+
+ mLSTMLayerStateType = tuple[torch.Tensor, torch.Tensor, torch.Tensor]
+ mLSTMStateType = dict[int, mLSTMLayerStateType]
+
+ external_xlstm = False
+
+ def soft_cap(values: torch.Tensor, cap_value: Optional[Union[float, torch.Tensor]] = None) -> torch.Tensor:
+ """
+ Soft caps a tensor to a value.
+
+ Performs a tanh operation on the logits and scales the result to the cap value. Common technique in attention
+ and output language heads to prevent large logits from dominating the softmax. See for example Gemma2:
+ https://huggingface.co/papers/2408.00118
+
+ Args:
+ values: The tensor to cap.
+ cap_value: The value to cap the values to. If None, no cap is applied.
+
+ Returns:
+ The capped values.
+ """
+ if cap_value is None:
+ return values
+ return cap_value * torch.tanh(values / cap_value)
+
+ def mlstm_chunkwise_recurrent_fw_C(
+ matK: torch.Tensor,
+ matV: torch.Tensor,
+ vecB: torch.Tensor,
+ vecI: torch.Tensor,
+ matC_states: torch.Tensor = None,
+ vecN_states: torch.Tensor = None,
+ scaMinter_states: torch.Tensor = None,
+ matC_initial: torch.Tensor = None,
+ vecN_initial: torch.Tensor = None,
+ scaMinter_initial: torch.Tensor = None,
+ qk_scale: Optional[float] = None,
+ chunk_size: int = 64,
+ num_chunks: int = 1,
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ batch_size, nh, _, dhqk, dhhv = *matK.shape, matV.shape[-1]
+ nc = num_chunks
+ _dtype, _device = matK.dtype, matK.device
+
+ if qk_scale is None:
+ qk_scale = dhqk**-0.5
+
+ # initialize the states tensors
+ if matC_states is None:
+ matC_states = torch.zeros((batch_size, nh, (nc + 1) * dhqk, dhhv), dtype=_dtype, device=_device)
+ if vecN_states is None:
+ vecN_states = torch.zeros((batch_size, nh, (nc + 1) * dhqk), dtype=_dtype, device=_device)
+ if scaMinter_states is None:
+ scaMinter_states = torch.zeros((batch_size, nh, (nc + 1)), dtype=_dtype, device=_device)
+
+ # assign the initial states to the running states
+ matC_k = (
+ torch.zeros((batch_size, nh, dhqk, dhhv), dtype=_dtype, device=_device)
+ if matC_initial is None
+ else matC_initial
+ )
+ vecN_k = (
+ torch.zeros((batch_size, nh, dhqk), dtype=_dtype, device=_device) if vecN_initial is None else vecN_initial
+ )
+ scaM_inter_k = (
+ torch.zeros((batch_size, nh, 1), dtype=_dtype, device=_device)
+ if scaMinter_initial is None
+ else scaMinter_initial
+ )
+ vecA = vecB[..., -1, None] - vecB + vecI
+ scaG = vecB[..., -1]
+ scaA_max = vecA.max(-1).values
+
+ scaM_inter_k = scaM_inter_k.squeeze(-1)
+
+ for key in range(0, num_chunks):
+ # store the states from the previous iteration before updating them
+ # in the first iteration, these are the initial states
+ matC_states[:, :, key * dhqk : (key + 1) * dhqk, :] = matC_k
+ vecN_states[:, :, key * dhqk : (key + 1) * dhqk] = vecN_k
+ scaMinter_states[:, :, key] = scaM_inter_k
+
+ # m_k update
+ scaA_max_k = scaA_max[:, :, key]
+ scaG_k = scaG[:, :, key]
+ scaM_inter_k_next = torch.max(scaG_k + scaM_inter_k, scaA_max_k)
+ # C_k update
+ matK_chunk = matK[:, :, key * chunk_size : (key + 1) * chunk_size, :] # * qk_scale
+ matV_chunk = matV[:, :, key * chunk_size : (key + 1) * chunk_size, :]
+ vecA_k = vecA[:, :, key, :]
+
+ vecAbar_k = torch.exp(vecA_k - scaM_inter_k_next[..., None])[:, :, :, None]
+
+ matK_chunk_gated = matK_chunk * vecAbar_k
+
+ scaGbar_k = torch.exp(scaG_k + scaM_inter_k - scaM_inter_k_next)[:, :, None]
+
+ # NOTE: no update in-place (i.e. +=) as this gives error for autograd backward
+ matC_k_next = scaGbar_k[..., None] * matC_k + matK_chunk_gated.transpose(-2, -1) @ (matV_chunk)
+
+ # n_k update
+ vecN_k_next = scaGbar_k * vecN_k + matK_chunk_gated.transpose(-2, -1).sum(-1)
+
+ # move to the next iteration
+ scaM_inter_k = scaM_inter_k_next
+ matC_k = matC_k_next
+ vecN_k = vecN_k_next
+
+ # store the states from the last iteration
+ matC_states[:, :, -dhqk:, :] = matC_k
+ vecN_states[:, :, -dhqk:] = vecN_k
+ scaMinter_states[:, :, -1] = scaM_inter_k
+
+ return matC_states, vecN_states, scaMinter_states
+
+ def mlstm_chunkwise_parallel_fw_H(
+ matQ: torch.Tensor,
+ matK: torch.Tensor,
+ matV: torch.Tensor,
+ # these states must be all states up to the last chunk, i.e. :-1
+ matC_states: torch.Tensor,
+ vecN_states: torch.Tensor,
+ scaMinter_states: torch.Tensor,
+ vecI: torch.Tensor,
+ vecB: torch.Tensor,
+ qk_scale: float,
+ chunk_size: int = 64,
+ num_chunks: int = 1,
+ eps: float = 1e-6,
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ _device = matQ.device
+ nc, chunk_size = num_chunks, chunk_size
+ batch_size, nh, dqk, dhv = matC_states.shape
+ matC_k_states = matC_states.view(batch_size, nh, nc, dqk // nc, dhv)
+ vecN_k_states = vecN_states.view(batch_size, nh, nc, dqk // nc)
+ scaMinter_k_states = scaMinter_states
+
+ matQ = matQ.view(batch_size, nh, nc, chunk_size, dqk)
+ matK = matK.view(batch_size, nh, nc, chunk_size, dqk)
+ matV = matV.view(batch_size, nh, nc, chunk_size, dhv)
+
+ ltr = torch.tril(
+ torch.ones(
+ (chunk_size, chunk_size),
+ dtype=torch.bool,
+ device=_device,
+ )
+ )
+
+ # Compute intra chunk contribution: H_intra
+ matF_logsig_chunk = vecB[:, :, :, :, None] - vecB[:, :, :, None, :]
+
+ matF_logsig_mask_chunk = torch.where(ltr, matF_logsig_chunk, -float("inf"))
+
+ matLogD_chunk = matF_logsig_mask_chunk + vecI[:, :, :, None, :]
+
+ # max_state intra
+ vecMintra_k = torch.max(matLogD_chunk, dim=-1, keepdim=False).values
+
+ # max_state combined
+ vecM_b_inter = vecB + scaMinter_k_states[:, :, :, None]
+ vecM_k_combine = torch.maximum(vecM_b_inter, vecMintra_k)
+
+ vecM_k_combine = vecM_k_combine[:, :, :, :, None]
+ vecM_b_inter = vecM_b_inter[:, :, :, :, None]
+
+ matLogD_stabilized_chunk = matLogD_chunk - vecM_k_combine
+ matD_chunk = torch.exp(matLogD_stabilized_chunk)
+
+ matS_chunk = (matQ @ matK.transpose(-2, -1)) * qk_scale
+
+ matM_chunk = matS_chunk * matD_chunk
+
+ # ? Combine H_intra with H_inter
+ vecBbar = torch.exp(vecM_b_inter - vecM_k_combine)
+ matQ_chunk_gated = matQ * vecBbar * qk_scale
+
+ matNumerator_common = matQ_chunk_gated @ matC_k_states + matM_chunk @ matV
+
+ vecDenom_l_common = matQ_chunk_gated @ vecN_k_states.unsqueeze(-1) + matM_chunk.sum(dim=-1, keepdim=True)
+
+ vecDenom_max_common = torch.maximum(torch.abs(vecDenom_l_common), torch.exp(-vecM_k_combine))
+
+ matH_k_chunk = matNumerator_common / (vecDenom_max_common + eps)
+
+ matH_out = matH_k_chunk.view(batch_size, nh, nc * chunk_size, dhv)
+
+ # we need the denominator and the overall max state for the backward pass
+ vecN_out = vecDenom_max_common.reshape(batch_size, nh, nc * chunk_size)
+ vecM_out = vecM_k_combine(batch_size, nh, nc * chunk_size)
+ return matH_out, vecN_out, vecM_out
+
+ def mlstm_chunkwise_fw(
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ igate: torch.Tensor,
+ fgate: torch.Tensor,
+ cstate: torch.Tensor = None,
+ nstate: torch.Tensor = None,
+ mstate: torch.Tensor = None,
+ qk_scale: Optional[float] = None,
+ return_last_states: bool = False,
+ return_all_states: bool = False,
+ chunk_size: int = 64,
+ eps: float = 1e-6,
+ ) -> tuple[
+ torch.Tensor,
+ torch.Tensor,
+ torch.Tensor,
+ Optional[tuple[torch.Tensor, torch.Tensor, torch.Tensor]],
+ Optional[tuple[torch.Tensor, torch.Tensor, torch.Tensor]],
+ ]:
+ batch_size, nh, sequence_length, dhqk = query.shape
+ if sequence_length % chunk_size != 0:
+ raise ValueError(f"Sequence length {sequence_length} is not divisible by chunk size {chunk_size}.")
+ nc = sequence_length // chunk_size
+
+ vecI = igate.view(batch_size, nh, nc, chunk_size)
+ vecF = fgate.view(batch_size, nh, nc, chunk_size)
+
+ # compute the gates, the g and the a and b vectors
+ vecF_logsig = fgate.logsigmoid(vecF)
+ vecB = vecF_logsig.cumsum(-1)
+
+ if qk_scale is None:
+ qk_scale = dhqk**-0.5
+
+ #! materialize the C_k, n_k, m_k states for each chunk
+ matC_k_states, vecN_k_states, scaMinter_k_states = mlstm_chunkwise_recurrent_fw_C(
+ matK=key,
+ matV=value,
+ vecB=vecB,
+ vecI=vecI,
+ matC_initial=cstate,
+ vecN_initial=nstate,
+ scaMinter_initial=mstate,
+ qk_scale=qk_scale,
+ chunk_size=chunk_size,
+ num_chunks=nc,
+ )
+
+ #! compute the outputs within each chunk
+ matH_out, vecN_out, vecM_out = mlstm_chunkwise_parallel_fw_H(
+ matQ=query,
+ matK=key,
+ matV=value,
+ matC_states=matC_k_states[:, :, :-dhqk, :],
+ vecN_states=vecN_k_states[:, :, :-dhqk],
+ scaMinter_states=scaMinter_k_states[:, :, :-1],
+ vecI=vecI,
+ vecB=vecB,
+ qk_scale=qk_scale,
+ chunk_size=chunk_size,
+ num_chunks=nc,
+ eps=eps,
+ )
+
+ ret_tuple = (matH_out, vecN_out, vecM_out)
+ if return_last_states:
+ ret_tuple += (
+ (matC_k_states[:, :, -dhqk:, :], vecN_k_states[:, :, -dhqk:], scaMinter_k_states[:, :, -1:]),
+ )
+ else:
+ ret_tuple += (None,)
+
+ if return_all_states:
+ ret_tuple += ((matC_k_states, vecN_k_states, scaMinter_k_states),)
+ else:
+ ret_tuple += (None,)
+
+ return ret_tuple
+
+ def mlstm_chunkwise_native_autograd(
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ igate: torch.Tensor,
+ fgate: torch.Tensor,
+ c_initial: torch.Tensor = None,
+ n_initial: torch.Tensor = None,
+ m_initial: torch.Tensor = None,
+ return_last_states: bool = False,
+ eps: float = 1e-6,
+ chunk_size: int = 64,
+ **kwargs,
+ ) -> Union[torch.Tensor, tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor, torch.Tensor]]]:
+ batch_size, nh, sequence_length, dhqk = query.shape
+ if sequence_length % chunk_size != 0:
+ raise ValueError(f"Sequence length {sequence_length} is not divisible by chunk size {chunk_size}.")
+ nc = sequence_length // chunk_size
+
+ vecI = igate.view(batch_size, nh, nc, chunk_size)
+ vecF = fgate.view(batch_size, nh, nc, chunk_size)
+
+ # compute the gates, the g and the a and b vectors
+ vecF_logsig = F.logsigmoid(vecF)
+ vecB = vecF_logsig.cumsum(-1)
+
+ qk_scale = dhqk**-0.5
+
+ #! materialize the C_k, n_k, m_k states for each chunk
+ matC_k_states, vecN_k_states, scaMinter_k_states = mlstm_chunkwise_recurrent_fw_C(
+ matK=key,
+ matV=value,
+ vecB=vecB,
+ vecI=vecI,
+ matC_initial=c_initial,
+ vecN_initial=n_initial,
+ scaMinter_initial=m_initial,
+ qk_scale=qk_scale,
+ chunk_size=chunk_size,
+ num_chunks=nc,
+ )
+
+ #! compute the outputs within each chunk
+ matH_out, vecN_out, vecM_out = mlstm_chunkwise_parallel_fw_H(
+ matQ=query,
+ matK=key,
+ matV=value,
+ matC_states=matC_k_states[:, :, :-dhqk, :],
+ vecN_states=vecN_k_states[:, :, :-dhqk],
+ scaMinter_states=scaMinter_k_states[:, :, :-1],
+ vecI=vecI,
+ vecB=vecB,
+ qk_scale=qk_scale,
+ chunk_size=chunk_size,
+ num_chunks=nc,
+ eps=eps,
+ )
+
+ last_states = (matC_k_states[:, :, -dhqk:, :], vecN_k_states[:, :, -dhqk:], scaMinter_k_states[:, :, -1:])
+
+ if return_last_states:
+ return matH_out, last_states
+ else:
+ return matH_out
+
+ def mlstm_recurrent_step_native(
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ igate: torch.Tensor,
+ fgate: torch.Tensor,
+ cstate: torch.Tensor,
+ nstate: torch.Tensor,
+ mstate: torch.Tensor,
+ eps: float = 1e-6,
+ dtype_state: torch.dtype = torch.float32,
+ **kwargs,
+ ) -> tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
+ """This is a single step of the mLSTM operation in recurrent form."""
+ dtype_qkv = query.dtype
+ matC_old = cstate.to(dtype=dtype_state)
+ vecN_old = nstate.to(dtype=dtype_state)
+ scaM_old = mstate.to(dtype=dtype_state)
+
+ batch_size, nh, dhqk = query.shape
+ _, _, dhhv = value.shape
+ if query.shape != key.shape:
+ raise ValueError("query and key must have the same shape")
+ if matC_old.shape != (batch_size, nh, dhqk, dhhv):
+ raise ValueError(f"matC_old has wrong shape, got {matC_old.shape}")
+ if vecN_old.shape != (batch_size, nh, dhqk):
+ raise ValueError(f"vecN_old has wrong shape, got {vecN_old.shape}")
+ if scaM_old.shape != (batch_size, nh, 1):
+ raise ValueError(f"scaM_old has wrong shape, got {scaM_old.shape}")
+ if igate.shape != (batch_size, nh, 1):
+ raise ValueError(f"scaI has wrong shape, got {igate.shape}")
+ if fgate.shape != (batch_size, nh, 1):
+ raise ValueError(f"scaF has wrong shape, got {fgate.shape}")
+
+ # gates
+ scaF_log = torch.nn.functional.logsigmoid(fgate)
+
+ # update rule
+ scaM_state_new = torch.max(scaF_log + scaM_old, igate)
+
+ scaF_act = torch.exp(scaF_log + scaM_old - scaM_state_new)
+ scaI_act = torch.exp(igate - scaM_state_new)
+
+ vecQ_scaled = query * (dhqk ** (-0.5))
+ matC_state_new = scaF_act[:, :, :, None] * matC_old + scaI_act[:, :, :, None] * (
+ key[:, :, :, None] @ value[:, :, None, :]
+ )
+ vecN_state_new = scaF_act * vecN_old + scaI_act * key
+ h_num = vecQ_scaled[:, :, None, :] @ matC_state_new.to(dtype=dtype_qkv)
+ h_num = h_num.squeeze(2).to(dtype=dtype_state)
+
+ qn_dotproduct = vecQ_scaled[:, :, None, :] @ vecN_state_new[:, :, :, None].to(dtype=dtype_qkv)
+ qn_dotproduct = qn_dotproduct.squeeze(2)
+ max_val = torch.exp(-scaM_state_new)
+ h_denom = (torch.maximum(qn_dotproduct.abs(), max_val) + eps).to(dtype=dtype_state)
+ h = h_num / h_denom
+
+ h = h.to(dtype=dtype_qkv)
+ matC_state_new = matC_state_new.to(dtype=dtype_state)
+ vecN_state_new = vecN_state_new.to(dtype=dtype_state)
+ scaM_state_new = scaM_state_new.to(dtype=dtype_state)
+ return h, (matC_state_new, vecN_state_new, scaM_state_new)
+
+ def mlstm_recurrent_sequence_native(
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ igate: torch.Tensor,
+ fgate: torch.Tensor,
+ c_initial: torch.Tensor = None,
+ n_initial: torch.Tensor = None,
+ m_initial: torch.Tensor = None,
+ return_last_states: bool = False,
+ eps: float = 1e-6,
+ dtype_state: torch.dtype = torch.float32,
+ **kwargs,
+ ) -> tuple[
+ torch.Tensor,
+ torch.Tensor,
+ torch.Tensor,
+ Optional[tuple[torch.Tensor, torch.Tensor, torch.Tensor]],
+ Optional[tuple[torch.Tensor, torch.Tensor, torch.Tensor]],
+ ]:
+ batch_size, nh, sequence_length, dhqk = query.shape
+ dhv = value.shape[-1]
+ device = query.device
+
+ if c_initial is not None:
+ if n_initial is None or m_initial is None:
+ raise ValueError("Initial states must be provided together.")
+ if n_initial is None or m_initial is None:
+ raise ValueError("Initial states must be provided together.")
+ matC_state, vecN_state, vecM_state = (
+ c_initial.to(dtype=dtype_state),
+ n_initial.to(dtype=dtype_state),
+ m_initial.to(dtype=dtype_state),
+ )
+ else:
+ # memory state
+ matC_state = torch.zeros((batch_size, nh, dhqk, dhv), dtype=dtype_state, device=device)
+ # normalizer state
+ vecN_state = torch.zeros((batch_size, nh, dhqk), dtype=dtype_state, device=device)
+ # max state
+ vecM_state = torch.zeros((batch_size, nh, 1), dtype=dtype_state, device=device)
+
+ vecH_list = []
+ for t in range(sequence_length):
+ # gates
+ vecF_t, vecI_t = fgate[:, :, t, None], igate[:, :, t, None]
+
+ # projections
+ vecQ_t, vecK_t, vecV_t = query[:, :, t, :], key[:, :, t, :], value[:, :, t, :]
+
+ # step
+ vecH, (matC_state, vecN_state, vecM_state) = mlstm_recurrent_step_native(
+ cstate=matC_state,
+ nstate=vecN_state,
+ mstate=vecM_state,
+ query=vecQ_t,
+ key=vecK_t,
+ value=vecV_t,
+ igate=vecI_t,
+ fgate=vecF_t,
+ eps=eps,
+ dtype_state=dtype_state,
+ **kwargs,
+ )
+ vecH_list.append(vecH)
+
+ matH = torch.stack(vecH_list, dim=-2)
+
+ if return_last_states:
+ return matH, (matC_state, vecN_state, vecM_state)
+ else:
+ return matH
+
+ def wrap_chunkwise_pad_zeros(
+ mlstm_chunkwise_kernel: Callable,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ fgate: torch.Tensor,
+ igate: torch.Tensor,
+ c_initial: torch.Tensor = None,
+ n_initial: torch.Tensor = None,
+ m_initial: torch.Tensor = None,
+ return_last_states: bool = False,
+ eps: float = 1e-6,
+ autocast_kernel_dtype: torch.dtype = torch.bfloat16,
+ chunk_size: int = 64,
+ **kwargs,
+ ) -> Union[torch.Tensor, tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor, torch.Tensor]]]:
+ if return_last_states:
+ raise ValueError(
+ "We are padding zeros, so we cannot return last states,",
+ "as they would be not the true last states.",
+ )
+
+ batch_size, nh, sequence_length, dhqk = query.shape
+ S_unpadded = sequence_length
+ # padding to chunk size for kernels
+ if sequence_length % chunk_size != 0:
+ S_padded = ((sequence_length + chunk_size - 1) // chunk_size) * chunk_size
+ q_pad = query.new_zeros(batch_size, nh, S_padded, query.shape[3])
+ k_pad = key.new_zeros(batch_size, nh, S_padded, key.shape[3])
+ v_pad = value.new_zeros(batch_size, nh, S_padded, value.shape[3])
+ i_pad = igate.new_zeros(batch_size, nh, S_padded)
+ f_pad = fgate.new_zeros(batch_size, nh, S_padded)
+ q_pad[:, :, :S_unpadded, :] = query
+ k_pad[:, :, :S_unpadded, :] = key
+ v_pad[:, :, :S_unpadded, :] = value
+ i_pad[:, :, :S_unpadded] = igate
+ f_pad[:, :, :S_unpadded] = fgate
+ else:
+ q_pad = query
+ k_pad = key
+ v_pad = value
+ i_pad = igate
+ f_pad = fgate
+
+ matH = mlstm_chunkwise_kernel(
+ query=q_pad,
+ key=k_pad,
+ value=v_pad,
+ igate=i_pad,
+ fgate=f_pad,
+ c_initial=c_initial,
+ n_initial=n_initial,
+ m_initial=m_initial,
+ return_last_states=return_last_states,
+ eps=eps,
+ autocast_kernel_dtype=autocast_kernel_dtype,
+ chunk_size=chunk_size,
+ **kwargs,
+ )
+ matH = matH[:, :, :S_unpadded, :]
+ return matH
+
+ def wrap_chunkwise_arbitrary_sequence_length(
+ mlstm_chunkwise_kernel: Callable,
+ mlstm_sequence_kernel: Callable,
+ mlstm_step_kernel: Callable,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ fgate: torch.Tensor,
+ igate: torch.Tensor,
+ c_initial: torch.Tensor = None,
+ n_initial: torch.Tensor = None,
+ m_initial: torch.Tensor = None,
+ return_last_states: bool = True,
+ eps: float = 1e-6,
+ autocast_kernel_dtype: torch.dtype = torch.bfloat16,
+ chunk_size: int = 64,
+ enable_logging: bool = False,
+ ) -> Union[torch.Tensor, tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor, torch.Tensor]]]:
+ """This function computes the last hidden state and matH outputs of the mLSTM, independently of the sequence length.
+
+ For this it uses three kernels:
+ - mlstm_chunkwise_kernel: mlstm chunkwise kernels that processes chunks of a given chunk size in parallel.
+ - mlstm_sequence_kernel: mlstm kernel that processes the remaining sequence length in a single step recurrence.
+ - mlstm_step_kernel: mlstm kernel that processes a sequence length of 1 in a single step.
+
+ It tries to maximize the chunksizes to improve performance.
+ It will start with the given chunk size and then divides the chunksize by 2 until the chunk size is smaller than 16.
+ At every chunksize it will process the maximal number of chunks that fit into the remaining sequence length.
+
+ E.g. for chunk_size = 64, this function will try the chunksizes [64, 32, 16] if necessary.
+
+ For the remaining sequence length, which is smaller than 16, we use a different kernel that computes the mLSTM
+ in a single step and loop over this in pytorch.
+
+ Args:
+ mlstm_chunkwise_kernel: The mLSTM chunkwise kernel that processes chunks of a given chunk size in parallel
+ mlstm_sequence_kernel: The mLSTM kernel that processes the remaining sequence length in a single step recurrence
+ query: The query tensor (batch_size, nh, sequence_length, dhqk)
+ key: The key tensor (batch_size, nh, sequence_length, dhqk)
+ value: The value tensor (batch_size, nh, sequence_length, dhhv)
+ fgate: The forget gate tensor (batch_size, nh, sequence_length)
+ igate: The input gate tensor (batch_size, nh, sequence_length)
+ c_initial: The initial cell state tensor (batch_size, nh, dhqk, dhhv)
+ n_initial: The initial hidden state tensor (batch_size, nh, dhqk)
+ m_initial: The initial memory state tensor (batch_size, nh, 1)
+ return_last_states: If True, the function will return the last states of the mLSTM
+ eps: The epsilon value used for numerical stability
+ autocast_kernel_dtype: The dtype used for the kernel computation
+ chunk_size: The chunk size used for the chunkwise kernel
+ enable_logging: If True, the function will log debug information. Default is False.
+
+ Returns:
+ The last hidden state tensor (batch_size, nh, sequence_length, dhhv) or a tuple containing the last hidden state tensor and the last states of the mLSTM
+ Last states are (cstate (batch_size, nh, dhqk, dhhv), nstate (batch_size, nh, dhqk), mstate (batch_size, nh, 1)).
+ """
+
+ batch_size, nh, sequence_length, dhqk = key.shape
+ dhhv = value.shape[-1]
+
+ c_state = (
+ c_initial
+ if c_initial is not None
+ else torch.zeros(batch_size, nh, dhqk, dhhv, device=key.device, dtype=torch.float32)
+ )
+ n_state = (
+ n_initial
+ if n_initial is not None
+ else torch.zeros(batch_size, nh, dhqk, device=key.device, dtype=torch.float32)
+ )
+ m_state = (
+ m_initial
+ if m_initial is not None
+ else torch.zeros(batch_size, nh, 1, device=key.device, dtype=torch.float32)
+ )
+
+ if sequence_length > 1:
+ # process the sequence length in chunks
+ h_outs = []
+ seq_len_start_idx = 0
+ remaining_seq_len = sequence_length - seq_len_start_idx
+ num_chunks = remaining_seq_len // chunk_size
+ if num_chunks > 0:
+ iter_seq_len = chunk_size * num_chunks
+ seq_len_idx = seq_len_start_idx + iter_seq_len
+ h_out, (c_state, n_state, m_state) = mlstm_chunkwise_kernel(
+ query=query[..., seq_len_start_idx:seq_len_idx, :].contiguous(),
+ key=key[..., seq_len_start_idx:seq_len_idx, :].contiguous(),
+ value=value[..., seq_len_start_idx:seq_len_idx, :].contiguous(),
+ fgate=fgate[..., seq_len_start_idx:seq_len_idx].contiguous(),
+ igate=igate[..., seq_len_start_idx:seq_len_idx].contiguous(),
+ c_initial=c_state,
+ n_initial=n_state,
+ m_initial=m_state,
+ chunk_size=chunk_size,
+ return_last_states=True,
+ autocast_kernel_dtype=autocast_kernel_dtype,
+ eps=eps,
+ )
+ seq_len_start_idx += iter_seq_len
+ h_outs.append(h_out)
+
+ remaining_seq_len = sequence_length - seq_len_start_idx
+
+ if remaining_seq_len > 0:
+ # we use here matK as query as this kernel does not need a query, since we do not care about the outputs only about the last state
+ h_out, (c_state, n_state, m_state) = mlstm_sequence_kernel(
+ query=query[..., seq_len_start_idx:sequence_length, :].contiguous(),
+ key=key[..., seq_len_start_idx:sequence_length, :].contiguous(),
+ value=value[..., seq_len_start_idx:sequence_length, :].contiguous(),
+ igate=igate[..., seq_len_start_idx:sequence_length].contiguous(),
+ fgate=fgate[..., seq_len_start_idx:sequence_length].contiguous(),
+ c_initial=c_state,
+ n_initial=n_state,
+ m_initial=m_state,
+ return_last_states=True,
+ eps=eps,
+ )
+ h_outs.append(h_out)
+ h_out = torch.concatenate(h_outs, dim=2)
+
+ else:
+ if sequence_length != 1:
+ raise ValueError(
+ f"Received empty sequence (sequence_length={sequence_length}), require at least single element in the sequence."
+ )
+ # process the sequence length in a single step
+ # while this case is also captured by the regular mode above,
+ # it avoids the overhead of the loop and calls the step kernel directly
+ # The step function does not want a sequence dimension
+ # qkv shape is (batch_size, nh, dhqk/dhv)
+ # igate, fgate shape is (batch_size, nh, 1)
+ h_out, (c_state, n_state, m_state) = mlstm_step_kernel(
+ query=query.squeeze(2),
+ key=key.squeeze(2),
+ value=value.squeeze(2),
+ igate=igate,
+ fgate=fgate,
+ cstate=c_state,
+ nstate=n_state,
+ mstate=m_state,
+ eps=eps,
+ )
+ h_out = h_out[:, :, None, :]
+
+ if return_last_states:
+ return h_out, (c_state, n_state, m_state)
+ else:
+ return h_out
+
+ class xLSTMBackend(nn.Module):
+ """xLSTM Backend Module for PyTorch.
+
+ This module wraps the xLSTM kernels and provides a high-level interface for training and inference.
+ """
+
+ config_class = xLSTMConfig
+
+ def __init__(self, config: xLSTMConfig):
+ super().__init__()
+ self.config = config
+ self.chunkwise_kernel_fn = mlstm_chunkwise_native_autograd
+ self.sequence_kernel_fn = mlstm_recurrent_sequence_native
+ self.step_kernel_fn = mlstm_recurrent_step_native
+
+ self._inference_fn = partial(
+ wrap_chunkwise_arbitrary_sequence_length,
+ mlstm_chunkwise_kernel=self.chunkwise_kernel_fn,
+ mlstm_sequence_kernel=partial(
+ self.sequence_kernel_fn,
+ dtype_state=getattr(torch, config.inference_state_dtype),
+ ),
+ mlstm_step_kernel=partial(
+ self.step_kernel_fn,
+ dtype_state=getattr(torch, config.inference_state_dtype),
+ ),
+ chunk_size=config.chunk_size,
+ eps=config.eps,
+ autocast_kernel_dtype=getattr(torch, config.autocast_kernel_dtype),
+ return_last_states=True,
+ )
+
+ train_kernel_fn = partial(
+ self.chunkwise_kernel_fn,
+ autocast_kernel_dtype=getattr(torch, config.autocast_kernel_dtype),
+ eps=config.eps,
+ chunk_size=config.chunk_size,
+ )
+ if "with_padding" in config.mode:
+ train_kernel_fn = partial(wrap_chunkwise_pad_zeros, mlstm_chunkwise_kernel=train_kernel_fn)
+ self._train_fn = train_kernel_fn
+
+ def forward(
+ self,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ igate: torch.Tensor,
+ fgate: torch.Tensor,
+ c_initial: torch.Tensor = None,
+ n_initial: torch.Tensor = None,
+ m_initial: torch.Tensor = None,
+ return_last_states: bool = False,
+ mode: Optional[Literal["train", "inference"]] = None,
+ ) -> Union[torch.Tensor, tuple[torch.Tensor, tuple[torch.Tensor, torch.Tensor, torch.Tensor]]]:
+ """Forward pass of the mLSTM backend.
+
+ Depending on the configured mode, this method will call the appropriate kernel function.
+
+ Args:
+ query: The query tensor of shape (batch_size, nh, sequence_length, dhqk).
+ key: The key tensor of shape (batch_size, nh, sequence_length, dhqk).
+ value: The value tensor of shape (batch_size, nh, sequence_length, dhhv).
+ igate: The input gate preactivation tensor of shape (batch_size, nh, sequence_length).
+ fgate: The forget gate preactivation tensor of shape (batch_size, nh, sequence_length).
+ c_initial: The initial cell state tensor of shape (batch_size, nh, dhqk, dhhv).
+ Defaults to None.
+ n_initial: The initial hidden state tensor of shape (batch_size, nh, dhqk). Defaults to None.
+ m_initial: The initial memory tensor of shape (batch_size, nh, 1). Defaults to None.
+ return_last_states: Whether to return the last states of the sequence. Defaults to None.
+ If None, the value from the config is used.
+
+ Returns:
+ hidden states of shape (batch_size, nh, sequence_length, dhhv)
+ hidden states and last states the last states are the cell state cstate (batch_size, nh, dhqk, dhhv),
+ the normalizer state nstate (batch_size, nh, dhqk), and the max state mstate (batch_size, nh, 1)
+ """
+ if mode is None:
+ mode = self.config.mode
+
+ if "train" in mode:
+ if return_last_states is None:
+ return_last_states = self.config.return_last_states
+
+ if self.config.mode == "train_with_padding":
+ if return_last_states:
+ raise ValueError("return_last_states=True is not supported with train_with_padding mode.")
+
+ return self._train_fn(
+ query=query,
+ key=key,
+ value=value,
+ igate=igate,
+ fgate=fgate,
+ c_initial=c_initial,
+ n_initial=n_initial,
+ m_initial=m_initial,
+ return_last_states=return_last_states,
+ )
+
+ elif "inference" in mode:
+ # inference mode always returns the last states
+ return self._inference_fn(
+ query=query,
+ key=key,
+ value=value,
+ igate=igate,
+ fgate=fgate,
+ c_initial=c_initial,
+ n_initial=n_initial,
+ m_initial=m_initial,
+ )
+ else:
+ raise ValueError(f"Unknown mode: {self.config.mode}")
+
+ def extra_repr(self) -> str:
+ return f"{self.config}"
+
+ class xLSTMRMSNorm(nn.Module):
+ """Root mean square normalization layer implementation similar
+ to https://pytorch.org/docs/stable/generated/torch.nn.RMSNorm.html.
+
+ It normalizes the input tensor by the root mean square of the last dimension.
+
+ Args:
+ num_features: The number of features in the input tensor.
+ eps: A small value to avoid division by zero.
+ use_weight: Whether to use a learnable weight.
+ use_bias: Whether to use a learnable bias.
+ force_float32_reductions: Whether to force float32 reductions.
+ """
+
+ def __init__(
+ self,
+ num_features: int,
+ eps: float = 1e-6,
+ use_weight: bool = True,
+ use_bias: bool = False,
+ force_float32_reductions: bool = True,
+ ):
+ super().__init__()
+ self.num_features = num_features
+ self.eps = eps
+ self.force_float32_reductions = force_float32_reductions
+
+ if use_weight:
+ self.weight = nn.Parameter(torch.ones(num_features))
+ else:
+ self.weight = None
+
+ if use_bias:
+ self.bias = nn.Parameter(torch.zeros(num_features))
+ else:
+ self.bias = None
+
+ def _apply_weight_bias(self, x: torch.Tensor) -> torch.Tensor:
+ if self.weight is not None:
+ x = x * self.weight
+ if self.bias is not None:
+ x = x + self.bias
+ return x
+
+ def _rms_normalize(self, x: torch.Tensor) -> torch.Tensor:
+ # apply rms norm over the last dimension, i.e. HD dimension
+ in_dtype = x.dtype
+ if self.force_float32_reductions:
+ x = x.float()
+ x = x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
+ return x.to(in_dtype)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self._rms_normalize(x)
+ x = self._apply_weight_bias(x)
+ return x
+
+ class xLSTMMultiHeadLayerNorm(nn.Module):
+ """Multi-head version of the LayerNorm layer.
+
+ It normalizes the last dimension of the input tensor.
+
+ The input is assumed to have the shape (batch_size, sequence_length, nh, DH), where:
+ batch_size: batch size
+ sequence_length: sequence length
+ nh: number of heads
+ DH: head dimension
+
+ The normalization is applied over the last dimension (DH) of the input tensor.
+
+ Args:
+ num_heads: The number of heads.
+ head_dim: The head dimension.
+ eps: A small value to avoid division by zero.
+ use_weight: Whether to use a learnable weight.
+ use_bias: Whether to use a learnable bias.
+ force_float32_reductions: Whether to force float32 reductions
+
+ Returns:
+ The normalized tensor with the shape (batch_size, sequence_length, nh * DH).
+ """
+
+ def __init__(
+ self,
+ num_heads: int,
+ head_dim: int,
+ eps: float = 1e-6,
+ use_weight: bool = True,
+ use_bias: bool = False,
+ force_float32_reductions: bool = True,
+ ):
+ super().__init__()
+ self.num_features = num_heads * head_dim
+ self.eps = eps
+ self.force_float32_reductions = force_float32_reductions
+
+ if use_weight:
+ self.weight = nn.Parameter(torch.ones(self.num_features))
+ else:
+ self.weight = None
+
+ if use_bias:
+ self.bias = nn.Parameter(torch.zeros(self.num_features))
+ else:
+ self.bias = None
+ self.num_heads = num_heads
+ self.head_dim = head_dim
+
+ def _apply_weight_bias(self, x: torch.Tensor) -> torch.Tensor:
+ if self.weight is not None:
+ x = x * self.weight
+ if self.bias is not None:
+ x = x + self.bias
+ return x
+
+ def _layer_normalize(self, x: torch.Tensor) -> torch.Tensor:
+ # apply layer norm over the last dimension, i.e. HD dimension
+ in_dtype = x.dtype
+ if self.force_float32_reductions:
+ x = x.float()
+ x_centered = x - x.mean(dim=-1, keepdim=True)
+ y = x_centered * torch.rsqrt(x.var(dim=-1, keepdim=True, unbiased=False) + self.eps)
+ return y.to(in_dtype)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ ) -> torch.Tensor:
+ batch_size, sequence_length, nh, DH = x.shape
+ if nh != self.num_heads:
+ raise ValueError(f"Expected {self.num_heads} heads, got {nh}, input shape: {x.shape}")
+ if DH != self.head_dim:
+ raise ValueError(f"Expected {self.head_dim} head dimension, got {DH}, input shape: {x.shape}")
+
+ x = self._layer_normalize(x)
+ x = x.reshape(batch_size, sequence_length, -1)
+ x = self._apply_weight_bias(x)
+ return x
+
+ class xLSTMFeedForward(nn.Module):
+ def __init__(self, config: xLSTMConfig):
+ super().__init__()
+ self.config = config
+
+ self.up_proj_dim = round_up_to_next_multiple_of(
+ config.hidden_size * config.ffn_proj_factor,
+ config.ffn_round_up_to_multiple_of,
+ )
+
+ if self.config.weight_mode == "single":
+ self.proj_up_gate = nn.Linear(
+ in_features=config.hidden_size,
+ out_features=self.up_proj_dim,
+ bias=self.config.use_bias,
+ )
+ self.proj_up = nn.Linear(
+ in_features=config.hidden_size,
+ out_features=self.up_proj_dim,
+ bias=self.config.use_bias,
+ )
+ elif self.config.weight_mode == "fused":
+ self.proj_up_gate_z = nn.Linear(
+ in_features=config.hidden_size,
+ out_features=2 * self.up_proj_dim,
+ bias=self.config.use_bias,
+ )
+
+ self.proj_down = nn.Linear(
+ in_features=self.up_proj_dim,
+ out_features=config.hidden_size,
+ bias=self.config.use_bias,
+ )
+
+ self.act_fn = nn.SiLU()
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ if self.config.weight_mode == "single":
+ x = self.act_fn(self.proj_up_gate(x)) * self.proj_up(x)
+ elif self.config.weight_mode == "fused":
+ x = self.proj_up_gate_z(x)
+ gate, z = torch.tensor_split(x, (self.up_proj_dim,), dim=-1)
+ x = self.act_fn(gate) * z
+
+ y = self.proj_down(x)
+ return y
+
+ class xLSTMLayer(nn.Module):
+ def __init__(self, config: xLSTMConfig):
+ super().__init__()
+ self.config = config
+
+ self.v_dim = int(config.hidden_size * config.v_dim_factor)
+ self.qk_dim = int(config.hidden_size * config.qk_dim_factor)
+
+ if self.config.weight_mode == "single":
+ self.q = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.qk_dim,
+ bias=self.config.use_bias,
+ )
+ self.k = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.qk_dim,
+ bias=self.config.use_bias,
+ )
+ self.v = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.v_dim,
+ bias=self.config.use_bias,
+ )
+
+ self.ogate_preact = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.v_dim,
+ bias=self.config.use_bias,
+ )
+ self.igate_preact = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.config.num_heads,
+ bias=True,
+ )
+ self.fgate_preact = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=self.config.num_heads,
+ bias=True,
+ )
+ elif self.config.weight_mode == "fused":
+ self.qkv_opreact = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=2 * self.qk_dim + 2 * self.v_dim,
+ bias=self.config.use_bias,
+ )
+ self.ifgate_preact = nn.Linear(
+ in_features=self.config.hidden_size,
+ out_features=2 * self.config.num_heads,
+ bias=True,
+ )
+
+ self.ogate_act_fn = nn.Sigmoid()
+ self.mlstm_backend = xLSTMBackend(config=self.config)
+
+ self.multihead_norm = xLSTMMultiHeadLayerNorm(
+ num_heads=self.config.num_heads,
+ head_dim=self.v_dim // self.config.num_heads,
+ eps=self.config.norm_eps,
+ use_weight=True,
+ use_bias=self.config.use_bias,
+ force_float32_reductions=self.config.norm_reduction_force_float32,
+ )
+ self.out_proj = nn.Linear(
+ in_features=self.v_dim,
+ out_features=self.config.hidden_size,
+ bias=self.config.use_bias,
+ )
+
+ def forward(
+ self, x: torch.Tensor, state: Optional[mLSTMLayerStateType] = None
+ ) -> tuple[torch.Tensor, Optional[mLSTMLayerStateType]]:
+ if x.ndim != 3:
+ raise ValueError(f"Input must have shape [batch_size, sequence_length, HD], got {x.shape}")
+ batch_size, sequence_length, _ = x.shape
+ if self.config.weight_mode == "single":
+ query = self.q(x)
+ key = self.k(x)
+ value = self.v(x)
+ o_preact = self.ogate_preact(x)
+ i_preact = soft_cap(self.igate_preact(x), cap_value=self.config.gate_soft_cap)
+ f_preact = soft_cap(self.fgate_preact(x), cap_value=self.config.gate_soft_cap)
+
+ elif self.config.weight_mode == "fused":
+ qkv_opreact = self.qkv_opreact(x)
+ query, key, value, o_preact = torch.tensor_split(
+ qkv_opreact,
+ (
+ self.qk_dim,
+ 2 * self.qk_dim,
+ 2 * self.qk_dim + self.v_dim,
+ ),
+ dim=-1,
+ )
+
+ if_preact = soft_cap(self.ifgate_preact(x), cap_value=self.config.gate_soft_cap)
+ i_preact, f_preact = torch.tensor_split(if_preact, (self.config.num_heads,), dim=-1)
+
+ query = query.reshape(batch_size, sequence_length, self.config.num_heads, -1).transpose(1, 2)
+ key = key.reshape(batch_size, sequence_length, self.config.num_heads, -1).transpose(1, 2)
+ value = value.reshape(batch_size, sequence_length, self.config.num_heads, -1).transpose(1, 2)
+ i_preact = i_preact.transpose(1, 2)
+ f_preact = f_preact.transpose(1, 2)
+ if state is None:
+ c_initial, n_initial, m_initial = None, None, None
+ else:
+ c_initial, n_initial, m_initial = state
+
+ h, state = self.mlstm_backend(
+ query=query,
+ key=key,
+ value=value,
+ igate=i_preact,
+ fgate=f_preact,
+ c_initial=c_initial,
+ n_initial=n_initial,
+ m_initial=m_initial,
+ )
+ expected_h_shape = (
+ batch_size,
+ self.config.num_heads,
+ sequence_length,
+ self.v_dim // self.config.num_heads,
+ )
+ if h.shape != expected_h_shape:
+ raise ValueError(f"Got {h.shape}, expected {expected_h_shape}")
+
+ h = h.transpose(1, 2)
+ h_norm = self.multihead_norm(h)
+ h_norm = h_norm.reshape(batch_size, sequence_length, -1)
+
+ h_out = self.ogate_act_fn(o_preact) * h_norm
+
+ y = self.out_proj(h_out)
+ return y, state
+
+ class xLSTMBlock(nn.Module):
+ def __init__(self, config: xLSTMConfig):
+ super().__init__()
+ self.config = config
+ self.norm_mlstm = xLSTMRMSNorm(
+ num_features=config.hidden_size,
+ eps=config.norm_eps,
+ use_weight=True,
+ use_bias=config.use_bias,
+ force_float32_reductions=config.norm_reduction_force_float32,
+ )
+ self.mlstm_layer = xLSTMLayer(config)
+ self.norm_ffn = xLSTMRMSNorm(
+ num_features=config.hidden_size,
+ eps=config.norm_eps,
+ use_weight=True,
+ use_bias=config.use_bias,
+ force_float32_reductions=config.norm_reduction_force_float32,
+ )
+ self.ffn = xLSTMFeedForward(config)
+
+ def forward(
+ self, x: torch.Tensor, state: Optional[mLSTMStateType] = None
+ ) -> tuple[torch.Tensor, mLSTMStateType]:
+ x_mlstm = self.norm_mlstm(x)
+ x_mlstm, state = self.mlstm_layer(x_mlstm, state)
+ x = x + x_mlstm
+
+ x_ffn = self.norm_ffn(x)
+ x_ffn = self.ffn(x_ffn)
+ x = x + x_ffn
+
+ return x, state
+
+
+def small_init_method(dim):
+ """
+ Adapted from: https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/init_functions.py
+ Fills the input Tensor with values according to the method described in Transformers without Tears: Improving
+ the Normalization of Self-Attention - Nguyen, T. & Salazar, J. (2019), using a normal distribution."""
+ std = (2 / (5 * dim)) ** (1 / 2)
+
+ def init_(tensor):
+ return torch.nn.init.normal_(tensor, mean=0.0, std=std)
+
+ return init_
+
+
+def wang_init_method(n_layers, dim):
+ """
+ Adapted from https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/init_functions.py
+ """
+ std = 2 / n_layers / dim ** (1 / 2)
+
+ def init_(tensor):
+ return torch.nn.init.normal_(tensor, mean=0.0, std=std)
+
+ return init_
+
+
+class xLSTMPreTrainedModel(PreTrainedModel):
+ """
+ An abstract class for an interface to loading a pre-trained xLSTM model.
+ """
+
+ config_class = xLSTMConfig
+ base_model_prefix = "backbone"
+ _no_split_modules = ["xLSTMBlock"]
+ supports_gradient_checkpointing = True
+ _is_stateful = True
+
+ def _module_name_map(self, module):
+ for name, mod in self.named_modules():
+ if mod is module:
+ return name
+ return ""
+
+ def _init_weights(self, module):
+ if isinstance(module, nn.Embedding):
+ small_init_method(self.config.hidden_size)(self.embeddings.weight)
+ elif isinstance(module, nn.Linear):
+ if module.bias is not None:
+ torch.nn.init.zeros_(module.bias)
+ if self.config.weight_mode == "single" and "gate" in self._module_name_map(module):
+ torch.nn.init.zeros_(module.weight)
+ with torch.no_grad():
+ if "igate" in self._module_name_map(module):
+ module.bias.copy_(-10.0 * torch.ones_like(module.bias))
+ elif "fgate" in self._module_name_map(module):
+ module.bias.copy_(
+ torch.linspace(
+ 3.0,
+ 6.0,
+ module.bias.shape[-1],
+ ).to(
+ device=module.bias.device,
+ dtype=module.bias.dtype,
+ )
+ )
+ elif self.config.weight_mode == "fused" and "gate" in self._module_name_map(module):
+ torch.nn.init.zeros_(module.weight)
+ with torch.no_grad():
+ module.bias[: self.config.num_heads] += -module.bias[
+ : self.config.num_heads
+ ] - 10.0 * torch.ones_like(module.bias)
+ module.bias[: self.config.num_heads] += -module.bias[self.config.num_heads :] + torch.linspace(
+ 3.0,
+ 6.0,
+ module.bias.shape[-1],
+ ).to(
+ device=module.bias.device,
+ dtype=module.bias.dtype,
+ )
+ elif "proj_down" in self._module_name_map(module):
+ wang_init_method(dim=module.weight.shape[1], n_layers=self.config.num_hidden_layers)(module.weight)
+ elif "out_proj" in self._module_name_map(module):
+ wang_init_method(dim=self.config.hidden_size, n_layers=self.config.num_hidden_layers)(module.weight)
+ elif module.weight is not None:
+ small_init_method(self.config.hidden_size)(module.weight)
+ elif isinstance(module, xLSTMRMSNorm) or hasattr(module, "_layer_normalize"):
+ torch.nn.init.ones_(module.weight)
+ if hasattr(module, "bias") and module.bias is not None:
+ torch.nn.init.zeros_(module.bias)
+
+
+class xLSTMCache:
+ """
+ Cache for xLSTM model which does not have attention mechanism and key value states.
+
+ Arguments:
+ config (`PretrainedConfig):
+ The configuration file defining the shape-related attributes required to initialize the static cache.
+ max_batch_size (`int`):
+ The batch size with which the model will be used.
+ dtype (`torch.dtype`, *optional*, defaults to `torch.bfloat16`):
+ The default `dtype` to use when initializing the layer.
+ device (`torch.device` or `str`, *optional*):
+ The device on which the cache should be initialized. Should be the same as the layer.
+
+ Attributes:
+ seqlen_offset: int
+ dtype: torch.dtype
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, xLSTMForCausalLM, xLSTMCache
+
+ >>> model = xLSTMForCausalLM.from_pretrained("NX-AI/xLSTM-7b")
+ >>> tokenizer = xLSTMTokenizer.from_pretrained("NX-AI/xLSTM-7b")
+
+ >>> inputs = tokenizer(text="I am an xLSTM", return_tensors="pt")
+
+ >>> # Prepare a cache class and pass it to model's forward
+ >>> cache_params = xLSTMCache(config=model.config, max_batch_size=1, device=model.device, dtype=model.dtype)
+ >>> outputs = model(**inputs, cache_params=cache_params, use_cache=True)
+ >>> outputs.cache_params
+ xLSTMCache()
+ """
+
+ def __init__(
+ self,
+ config: xLSTMConfig,
+ max_batch_size: int,
+ dtype: torch.dtype = torch.bfloat16,
+ device: Optional[str] = None,
+ **kwargs,
+ ):
+ self.seqlen_offset = 0
+ self.dtype = dtype
+ self.config = config
+ self.rnn_state = {
+ layer: (
+ torch.zeros(
+ [max_batch_size, config.num_heads, config.qk_head_dim, config.v_head_dim],
+ dtype=dtype,
+ device=device,
+ ),
+ torch.zeros([max_batch_size, config.num_heads, config.qk_head_dim], dtype=dtype, device=device),
+ torch.zeros([max_batch_size, config.num_heads, 1], dtype=dtype, device=device),
+ )
+ for layer in range(config.num_hidden_layers)
+ }
+
+ def reset(self):
+ self.rnn_state = {
+ layer: (
+ torch.zeros_like(self.rnn_state[layer][0]),
+ torch.zeros_like(self.rnn_state[layer][1]),
+ torch.zeros_like(self.rnn_state[layer][2]),
+ )
+ for layer in self.rnn_state
+ }
+
+
+@dataclass
+@auto_docstring
+class xLSTMOutput(ModelOutput):
+ r"""
+ cache_params (`xLSTMCache`):
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
+ avoid providing the old `input_ids`.
+ """
+
+ last_hidden_state: Optional[torch.FloatTensor]
+ cache_params: Optional[xLSTMCache] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+
+
+@auto_docstring
+class xLSTMModel(xLSTMPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ # use embbeding_dim and num_blocks once here to make use of them
+ self.embeddings = nn.Embedding(config.vocab_size, config.embedding_dim)
+ self.blocks = nn.ModuleList([xLSTMBlock(config) for _ in range(config.num_blocks)])
+ self.out_norm = xLSTMRMSNorm(config.hidden_size, eps=config.norm_eps)
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings
+
+ def set_input_embeddings(self, new_embedding):
+ self.embeddings = new_embedding
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.LongTensor] = None,
+ cache_params: Optional[xLSTMCache] = None,
+ use_cache: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ **kwargs,
+ ) -> Union[tuple, xLSTMOutput]:
+ r"""
+ cache_params (`xLSTMCache`, *optional*):
+ The xLSTMCache that carries the RNN states.
+ """
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else (self.config.use_cache if not self.training else False)
+ if self.gradient_checkpointing and self.training and use_cache:
+ use_cache = False
+
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embeddings(input_ids)
+
+ if use_cache and cache_params is None:
+ cache_params = xLSTMCache(
+ self.config, inputs_embeds.size(0), device=inputs_embeds.device, dtype=inputs_embeds.dtype
+ )
+
+ hidden_states = inputs_embeds
+
+ if (
+ not self.training
+ and self.config.max_inference_chunksize < hidden_states.shape[1]
+ and not output_hidden_states
+ ):
+ offset = 0
+ with torch.no_grad():
+ if cache_params is None:
+ cache_params = xLSTMCache(config=self.config, max_batch_size=hidden_states.shape[0])
+ final_state = torch.zeros_like(hidden_states)
+ while offset < hidden_states.shape[1]:
+ hidden_states_chunk = hidden_states[
+ :, offset : min(offset + self.config.max_inference_chunksize, hidden_states.shape[1])
+ ]
+ for layer_idx, xlstm_block in enumerate(self.blocks):
+ hidden_states_chunk, rnn_state = xlstm_block(
+ hidden_states_chunk,
+ state=cache_params.rnn_state[layer_idx],
+ )
+ for state_idx in range(len(cache_params.rnn_state[layer_idx])):
+ local_rnn_state = rnn_state[state_idx]
+ cache_params.rnn_state[layer_idx][state_idx].copy_(local_rnn_state)
+ cache_params.rnn_state_initial = False
+ final_state[
+ :, offset : min(offset + self.config.max_inference_chunksize, hidden_states.shape[1])
+ ] = hidden_states_chunk
+ offset += self.config.max_inference_chunksize
+ hidden_states = final_state
+ else:
+ all_hidden_states = () if output_hidden_states else None
+ for layer_idx, xlstm_block in enumerate(self.blocks):
+ if self.gradient_checkpointing and self.training:
+ hidden_states, rnn_state = self._gradient_checkpointing_func(
+ xlstm_block.__call__,
+ hidden_states,
+ cache_params.rnn_state[layer_idx] if cache_params is not None else None,
+ )
+ else:
+ hidden_states, rnn_state = xlstm_block(
+ hidden_states,
+ state=cache_params.rnn_state[layer_idx] if cache_params is not None else None,
+ )
+ if cache_params:
+ for state_idx in range(len(cache_params.rnn_state[layer_idx])):
+ local_rnn_state = rnn_state[state_idx]
+ cache_params.rnn_state[layer_idx][state_idx].copy_(local_rnn_state)
+ cache_params.rnn_state_initial = False
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if use_cache:
+ cache_params.seqlen_offset += inputs_embeds.shape[1]
+
+ hidden_states = self.out_norm(hidden_states)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ return xLSTMOutput(
+ last_hidden_state=hidden_states,
+ cache_params=cache_params,
+ hidden_states=all_hidden_states,
+ )
+
+
+@dataclass
+@auto_docstring
+class xLSTMCausalLMOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Language modeling loss (for next-token prediction).
+ logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
+ Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
+ cache_params (`xLSTMCache`, *optional*, carrying the RNN states):
+ The state of the model at the last time step. Can be used in a forward method with the next `input_ids` to
+ avoid providing the old `input_ids`.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ cache_params: Optional[xLSTMCache] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+
+
+@auto_docstring
+class xLSTMForCausalLM(xLSTMPreTrainedModel, GenerationMixin):
+ def __init__(self, config):
+ super().__init__(config)
+ self.backbone = xLSTMModel(config)
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.lm_head
+
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head = new_embeddings
+
+ def get_input_embeddings(self):
+ return self.backbone.get_input_embeddings()
+
+ def set_input_embeddings(self, new_embeddings):
+ return self.backbone.set_input_embeddings(new_embeddings)
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ attention_mask=None, # not used but needed, otherwise generate complains when passing tokenizer inputs
+ inputs_embeds=None,
+ use_cache=None,
+ cache_params: Optional[xLSTMCache] = None,
+ **kwargs,
+ ):
+ if use_cache and cache_params is not None:
+ # If the first cache position is non-zero, we assume we are in generation mode.
+ # Thus, the cache_params state is assumed to be the state before the last token
+ # (lastly generated token), and all previous tokens are already ingested.
+ # This should as well support generation from scratch with the [BOS] token inserted first.
+ input_ids = input_ids[:, -1:]
+ if inputs_embeds is not None:
+ inputs_embeds = inputs_embeds[:, -1:]
+
+ if inputs_embeds is not None and cache_params is None:
+ model_inputs = {"inputs_embeds": inputs_embeds}
+ else:
+ model_inputs = {"input_ids": input_ids}
+
+ model_inputs.update({"cache_params": cache_params, "use_cache": use_cache})
+ return model_inputs
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ cache_params: Optional[xLSTMCache] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ **kwargs,
+ ) -> Union[tuple, xLSTMCausalLMOutput]:
+ r"""
+ cache_params (`xLSTMCache`, *optional*):
+ The xLSTMCache that carries the RNN states.
+ """
+ xlstm_outputs = self.backbone(
+ input_ids,
+ cache_params=cache_params,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_hidden_states=output_hidden_states,
+ **kwargs,
+ )
+ hidden_states = xlstm_outputs[0]
+
+ logits = self.lm_head(hidden_states.to(self.lm_head.weight.dtype)).float()
+
+ if not self.training and self.config.max_inference_chunksize < logits.shape[1]:
+ offset = 0
+ with torch.no_grad():
+ while offset < logits.shape[1]:
+ logits[:, offset : min(offset + self.config.max_inference_chunksize, logits.shape[1])] = soft_cap(
+ logits[:, offset : min(offset + self.config.max_inference_chunksize, logits.shape[1])],
+ self.config.output_logit_soft_cap,
+ )
+ offset += self.config.max_inference_chunksize
+ else:
+ logits = soft_cap(logits, self.config.output_logit_soft_cap)
+
+ loss = None
+ if labels is not None:
+ # move labels to correct device to enable model parallelism
+ labels = labels.to(logits.device)
+ # Shift so that tokens < nstate predict nstate
+ shift_logits = logits[..., :-1, :].contiguous()
+ shift_labels = labels[..., 1:].contiguous()
+ # Flatten the tokens
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
+
+ return xLSTMCausalLMOutput(
+ loss=loss,
+ logits=logits,
+ cache_params=xlstm_outputs.cache_params,
+ hidden_states=xlstm_outputs.hidden_states,
+ )
+
+
+__all__ = [
+ "xLSTMForCausalLM",
+ "xLSTMModel",
+ "xLSTMPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xmod/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xmod/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..13cf20cbe49cbafadbcaa3b8aa8eba9d34238f14
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xmod/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_xmod import *
+ from .modeling_xmod import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xmod/configuration_xmod.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xmod/configuration_xmod.py
new file mode 100644
index 0000000000000000000000000000000000000000..41bad38a45deab92598a7af4b198031c4674505c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xmod/configuration_xmod.py
@@ -0,0 +1,185 @@
+# coding=utf-8
+# Copyright 2023 The Meta AI Team Authors and The HuggingFace Inc. team.
+# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""X-MOD configuration"""
+
+from collections import OrderedDict
+from collections.abc import Mapping
+
+from ...configuration_utils import PretrainedConfig
+from ...onnx import OnnxConfig
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class XmodConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`XmodModel`]. It is used to instantiate an X-MOD
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the
+ [facebook/xmod-base](https://huggingface.co/facebook/xmod-base) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 30522):
+ Vocabulary size of the X-MOD model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`XmodModel`].
+ hidden_size (`int`, *optional*, defaults to 768):
+ Dimensionality of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 3072):
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention probabilities.
+ max_position_embeddings (`int`, *optional*, defaults to 512):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ type_vocab_size (`int`, *optional*, defaults to 2):
+ The vocabulary size of the `token_type_ids` passed when calling [`XmodModel`].
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://huggingface.co/papers/1803.02155).
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
+ with Better Relative Position Embeddings (Huang et al.)](https://huggingface.co/papers/2009.13658).
+ is_decoder (`bool`, *optional*, defaults to `False`):
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+ classifier_dropout (`float`, *optional*):
+ The dropout ratio for the classification head.
+ pre_norm (`bool`, *optional*, defaults to `False`):
+ Whether to apply layer normalization before each block.
+ adapter_reduction_factor (`int` or `float`, *optional*, defaults to 2):
+ The factor by which the dimensionality of the adapter is reduced relative to `hidden_size`.
+ adapter_layer_norm (`bool`, *optional*, defaults to `False`):
+ Whether to apply a new layer normalization before the adapter modules (shared across all adapters).
+ adapter_reuse_layer_norm (`bool`, *optional*, defaults to `True`):
+ Whether to reuse the second layer normalization and apply it before the adapter modules as well.
+ ln_before_adapter (`bool`, *optional*, defaults to `True`):
+ Whether to apply the layer normalization before the residual connection around the adapter module.
+ languages (`Iterable[str]`, *optional*, defaults to `["en_XX"]`):
+ An iterable of language codes for which adapter modules should be initialized.
+ default_language (`str`, *optional*):
+ Language code of a default language. It will be assumed that the input is in this language if no language
+ codes are explicitly passed to the forward method.
+
+ Examples:
+
+ ```python
+ >>> from transformers import XmodConfig, XmodModel
+
+ >>> # Initializing an X-MOD facebook/xmod-base style configuration
+ >>> configuration = XmodConfig()
+
+ >>> # Initializing a model (with random weights) from the facebook/xmod-base style configuration
+ >>> model = XmodModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "xmod"
+
+ def __init__(
+ self,
+ vocab_size=30522,
+ hidden_size=768,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=512,
+ type_vocab_size=2,
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ pad_token_id=1,
+ bos_token_id=0,
+ eos_token_id=2,
+ position_embedding_type="absolute",
+ use_cache=True,
+ classifier_dropout=None,
+ pre_norm=False,
+ adapter_reduction_factor=2,
+ adapter_layer_norm=False,
+ adapter_reuse_layer_norm=True,
+ ln_before_adapter=True,
+ languages=("en_XX",),
+ default_language=None,
+ **kwargs,
+ ):
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
+
+ self.vocab_size = vocab_size
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.hidden_act = hidden_act
+ self.intermediate_size = intermediate_size
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.max_position_embeddings = max_position_embeddings
+ self.type_vocab_size = type_vocab_size
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.position_embedding_type = position_embedding_type
+ self.use_cache = use_cache
+ self.classifier_dropout = classifier_dropout
+ self.pre_norm = pre_norm
+ self.adapter_reduction_factor = adapter_reduction_factor
+ self.adapter_layer_norm = adapter_layer_norm
+ self.adapter_reuse_layer_norm = adapter_reuse_layer_norm
+ self.ln_before_adapter = ln_before_adapter
+ self.languages = list(languages)
+ self.default_language = default_language
+
+
+# Copied from transformers.models.roberta.configuration_roberta.RobertaOnnxConfig with Roberta->Xmod
+class XmodOnnxConfig(OnnxConfig):
+ @property
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
+ if self.task == "multiple-choice":
+ dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
+ else:
+ dynamic_axis = {0: "batch", 1: "sequence"}
+ return OrderedDict(
+ [
+ ("input_ids", dynamic_axis),
+ ("attention_mask", dynamic_axis),
+ ]
+ )
+
+
+__all__ = ["XmodConfig", "XmodOnnxConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xmod/modeling_xmod.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xmod/modeling_xmod.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ddf15bdb5963a3e5631bd02256704e7d48cba3e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/xmod/modeling_xmod.py
@@ -0,0 +1,1517 @@
+# coding=utf-8
+# Copyright 2023 Meta AI Team and the HuggingFace Inc. team.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch X-MOD model."""
+
+import math
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import ACT2FN, gelu
+from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
+from ...generation import GenerationMixin
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithPastAndCrossAttentions,
+ BaseModelOutputWithPoolingAndCrossAttentions,
+ CausalLMOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
+from ...utils import auto_docstring, logging
+from ...utils.deprecation import deprecate_kwarg
+from .configuration_xmod import XmodConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->Xmod
+class XmodEmbeddings(nn.Module):
+ """
+ Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
+ """
+
+ # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
+ # any TensorFlow checkpoint file
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
+ )
+
+ # End copy
+ self.padding_idx = config.pad_token_id
+ self.position_embeddings = nn.Embedding(
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
+ )
+
+ def forward(
+ self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
+ ):
+ if position_ids is None:
+ if input_ids is not None:
+ # Create the position ids from the input token ids. Any padded tokens remain padded.
+ position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+
+ embeddings = inputs_embeds + token_type_embeddings
+ if self.position_embedding_type == "absolute":
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings += position_embeddings
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ def create_position_ids_from_inputs_embeds(self, inputs_embeds):
+ """
+ We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
+
+ Args:
+ inputs_embeds: torch.Tensor
+
+ Returns: torch.Tensor
+ """
+ input_shape = inputs_embeds.size()[:-1]
+ sequence_length = input_shape[1]
+
+ position_ids = torch.arange(
+ self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->Xmod
+class XmodSelfAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.position_embedding_type = position_embedding_type or getattr(
+ config, "position_embedding_type", "absolute"
+ )
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ self.max_position_embeddings = config.max_position_embeddings
+ self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
+
+ self.is_decoder = config.is_decoder
+ self.layer_idx = layer_idx
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor]:
+ batch_size, seq_length, _ = hidden_states.shape
+ query_layer = self.query(hidden_states)
+ query_layer = query_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
+ 1, 2
+ )
+
+ is_cross_attention = encoder_hidden_states is not None
+ if past_key_values is not None:
+ if isinstance(past_key_values, EncoderDecoderCache):
+ is_updated = past_key_values.is_updated.get(self.layer_idx)
+ if is_cross_attention:
+ # after the first generated id, we can subsequently re-use all key/value_layer from cache
+ curr_past_key_value = past_key_values.cross_attention_cache
+ else:
+ curr_past_key_value = past_key_values.self_attention_cache
+ else:
+ curr_past_key_value = past_key_values
+
+ current_states = encoder_hidden_states if is_cross_attention else hidden_states
+ if is_cross_attention and past_key_values is not None and is_updated:
+ # reuse k,v, cross_attentions
+ key_layer = curr_past_key_value.layers[self.layer_idx].keys
+ value_layer = curr_past_key_value.layers[self.layer_idx].values
+ else:
+ key_layer = self.key(current_states)
+ key_layer = key_layer.view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(
+ 1, 2
+ )
+ value_layer = self.value(current_states)
+ value_layer = value_layer.view(
+ batch_size, -1, self.num_attention_heads, self.attention_head_size
+ ).transpose(1, 2)
+
+ if past_key_values is not None:
+ # save all key/value_layer to cache to be re-used for fast auto-regressive generation
+ cache_position = cache_position if not is_cross_attention else None
+ key_layer, value_layer = curr_past_key_value.update(
+ key_layer, value_layer, self.layer_idx, {"cache_position": cache_position}
+ )
+ # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
+ if is_cross_attention:
+ past_key_values.is_updated[self.layer_idx] = True
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
+ query_length, key_length = query_layer.shape[2], key_layer.shape[2]
+ if past_key_values is not None:
+ position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
+ -1, 1
+ )
+ else:
+ position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
+ position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
+ distance = position_ids_l - position_ids_r
+
+ positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
+ positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
+
+ if self.position_embedding_type == "relative_key":
+ relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores
+ elif self.position_embedding_type == "relative_key_query":
+ relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
+ relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
+ attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in XmodModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ # Mask heads if we want to
+ if head_mask is not None:
+ attention_probs = attention_probs * head_mask
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ return context_layer, attention_probs
+
+
+class XmodSelfOutput(nn.Module):
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfOutput.__init__
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+class XmodAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None, layer_idx=None):
+ super().__init__()
+ self.self = XmodSelfAttention(config, position_embedding_type=position_embedding_type, layer_idx=layer_idx)
+ self.output = XmodSelfOutput(config)
+ self.pruned_heads = set()
+ self.pre_norm = config.pre_norm
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaAttention.prune_heads
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.self.query = prune_linear_layer(self.self.query, index)
+ self.self.key = prune_linear_layer(self.self.key, index)
+ self.self.value = prune_linear_layer(self.self.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor]:
+ residual = hidden_states
+ if self.pre_norm:
+ hidden_states = self.output.LayerNorm(hidden_states)
+ self_outputs = self.self(
+ hidden_states,
+ attention_mask,
+ head_mask,
+ encoder_hidden_states,
+ past_key_values,
+ output_attentions,
+ cache_position,
+ )
+ attention_output = self.output(self_outputs[0], residual)
+ if not self.pre_norm:
+ attention_output = self.output.LayerNorm(attention_output)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaIntermediate
+class XmodIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+class XmodAdapter(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.bottleneck_size = config.hidden_size // config.adapter_reduction_factor
+ self.dense1 = nn.Linear(config.hidden_size, self.bottleneck_size)
+ self.dense2 = nn.Linear(self.bottleneck_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.adapter_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.adapter_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense1(hidden_states)
+ hidden_states = self.adapter_act_fn(hidden_states)
+ hidden_states = self.dense2(hidden_states)
+ return hidden_states
+
+
+class XmodOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.ln_before_adapter = config.ln_before_adapter
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ if config.adapter_layer_norm:
+ self.adapter_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ else:
+ self.adapter_layer_norm = None
+ self.adapter_reuse_layer_norm = config.adapter_reuse_layer_norm
+ self.adapter_modules = nn.ModuleDict({})
+ for language in config.languages:
+ self.adapter_modules[str(language)] = XmodAdapter(config)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor, lang_ids: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ hidden_states = self.lang_adapter(lang_ids, hidden_states)
+ return hidden_states
+
+ def lang_adapter(self, lang_ids: torch.Tensor, hidden_states: torch.Tensor):
+ # Process subsequent samples with the same lang_id in parallel
+ lang_ids, lang_lengths = torch.unique_consecutive(lang_ids, return_counts=True)
+
+ if not self.ln_before_adapter:
+ residual = hidden_states
+
+ if self.adapter_layer_norm is not None:
+ hidden_states = self.adapter_layer_norm(hidden_states)
+ elif self.adapter_reuse_layer_norm:
+ hidden_states = self.LayerNorm(hidden_states)
+
+ if self.ln_before_adapter:
+ residual = hidden_states
+
+ split_hidden_states = torch.split(hidden_states, lang_lengths.tolist(), 0)
+ lang_wise_outputs = []
+ for i, (lang_id, split_hidden_state) in enumerate(zip(lang_ids, split_hidden_states)):
+ lang = list(self.adapter_modules.keys())[int(lang_id.item())]
+ lang_wise_outputs.append(self.adapter_modules[lang](split_hidden_state))
+ hidden_states = torch.cat(lang_wise_outputs, 0)
+
+ hidden_states = self.dropout(hidden_states)
+ hidden_states += residual
+ return hidden_states
+
+
+class XmodLayer(GradientCheckpointingLayer):
+ def __init__(self, config, layer_idx=None):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = XmodAttention(config, layer_idx=layer_idx)
+ self.is_decoder = config.is_decoder
+ self.add_cross_attention = config.add_cross_attention
+ if self.add_cross_attention:
+ if not self.is_decoder:
+ raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
+ self.crossattention = XmodAttention(config, position_embedding_type="absolute", layer_idx=layer_idx)
+ self.intermediate = XmodIntermediate(config)
+ self.output = XmodOutput(config)
+ self.pre_norm = config.pre_norm
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ lang_ids: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[Cache] = None,
+ output_attentions: Optional[bool] = False,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> tuple[torch.Tensor]:
+ self_attention_outputs = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ past_key_values=past_key_values,
+ cache_position=cache_position,
+ )
+ attention_output = self_attention_outputs[0]
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ if self.is_decoder and encoder_hidden_states is not None:
+ if not hasattr(self, "crossattention"):
+ raise ValueError(
+ f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
+ " by setting `config.add_cross_attention=True`"
+ )
+
+ cross_attention_outputs = self.crossattention(
+ attention_output,
+ attention_mask=encoder_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ cache_position=cache_position,
+ )
+ attention_output = cross_attention_outputs[0]
+ outputs = outputs + cross_attention_outputs[1:] # add cross attentions if we output attention weights
+
+ residual = attention_output
+ if self.pre_norm:
+ attention_output = self.output.LayerNorm(attention_output)
+ intermediate_output = apply_chunking_to_forward(
+ self.feed_forward_chunk,
+ self.chunk_size_feed_forward,
+ self.seq_len_dim,
+ attention_output,
+ )
+ layer_output = self.output(intermediate_output, residual, lang_ids)
+ if not self.pre_norm:
+ layer_output = self.output.LayerNorm(layer_output)
+ return (layer_output,) + outputs
+
+ def feed_forward_chunk(self, attention_output):
+ return self.intermediate(attention_output)
+
+
+class XmodEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([XmodLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)])
+ self.is_pre_norm = config.pre_norm
+ if self.is_pre_norm:
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ lang_ids: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = False,
+ output_hidden_states: Optional[bool] = False,
+ return_dict: Optional[bool] = True,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
+ if self.gradient_checkpointing and self.training:
+ if use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
+ )
+ use_cache = False
+
+ if use_cache and past_key_values is None:
+ past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
+ if use_cache and isinstance(past_key_values, tuple):
+ logger.warning_once(
+ "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.58.0. "
+ "You should pass an instance of `EncoderDecoderCache` instead, e.g. "
+ "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`."
+ )
+ past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values)
+
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+ all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
+
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+
+ layer_outputs = layer_module(
+ hidden_states,
+ lang_ids,
+ attention_mask,
+ layer_head_mask,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ past_key_values,
+ output_attentions,
+ cache_position,
+ )
+
+ hidden_states = layer_outputs[0]
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+ if self.config.add_cross_attention:
+ all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
+
+ if self.is_pre_norm:
+ hidden_states = self.LayerNorm(hidden_states)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(
+ v
+ for v in [
+ hidden_states,
+ past_key_values,
+ all_hidden_states,
+ all_self_attentions,
+ all_cross_attentions,
+ ]
+ if v is not None
+ )
+ return BaseModelOutputWithPastAndCrossAttentions(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ cross_attentions=all_cross_attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaPooler
+class XmodPooler(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+@auto_docstring
+class XmodPreTrainedModel(PreTrainedModel):
+ config: XmodConfig
+ base_model_prefix = "roberta"
+ supports_gradient_checkpointing = True
+
+ # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights with BertLMPredictionHead->XmodLMHead
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, nn.Linear):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ elif isinstance(module, XmodLMHead):
+ module.bias.data.zero_()
+
+ def set_default_language(self, language: str):
+ """
+ Set the default language code for the model. This is used when the language is not specified in the input.
+
+ Args:
+ language (`str`): The language code, such as `"en_XX"` or `"de_DE"`.
+ """
+ if language not in self.config.languages:
+ raise ValueError(
+ f"{self} does not have an adapter for {language}. Supported languages: {list(self.config.languages)}"
+ )
+ self.config.default_language = language
+
+ def freeze_embeddings_and_language_adapters(self):
+ """
+ Freeze the embeddings and language adapters of the model. Usually, this is applied before the model is
+ fine-tuned on a downstream task.
+ """
+ logger.info("Freezing embeddings")
+ for parameter in self.roberta.embeddings.parameters():
+ parameter.requires_grad = False
+ logger.info("Freezing adapters")
+ for layer in self.roberta.encoder.layer:
+ if layer.output.adapter_layer_norm is not None:
+ for parameter in layer.output.adapter_layer_norm.parameters():
+ parameter.requires_grad = False
+ for parameter in layer.output.adapter_modules.parameters():
+ parameter.requires_grad = False
+
+
+@auto_docstring(
+ custom_intro="""
+ The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
+ cross-attention is added between the self-attention layers, following the architecture described in *Attention is
+ all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
+ Kaiser and Illia Polosukhin.
+
+ To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
+ to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
+ `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
+
+ .. _*Attention is all you need*: https://huggingface.co/papers/1706.03762
+ """
+)
+class XmodModel(XmodPreTrainedModel):
+ # Copied from transformers.models.clap.modeling_clap.ClapTextModel.__init__ with ClapText->Xmod
+ def __init__(self, config, add_pooling_layer=True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = XmodEmbeddings(config)
+ self.encoder = XmodEncoder(config)
+
+ self.pooler = XmodPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaModel.get_input_embeddings
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaModel.set_input_embeddings
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaModel._prune_heads
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ lang_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[list[torch.FloatTensor]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.Tensor] = None,
+ ) -> Union[tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ """
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ batch_size, seq_length = input_shape
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ past_key_values_length = 0
+ if past_key_values is not None:
+ past_key_values_length = (
+ past_key_values[0][0].shape[-2]
+ if not isinstance(past_key_values, Cache)
+ else past_key_values.get_seq_length()
+ )
+
+ if lang_ids is None:
+ if self.config.default_language is None:
+ raise ValueError("Input language unknown. Please call `XmodPreTrainedModel.set_default_language()`")
+ adapter_languages = list(self.encoder.layer[0].output.adapter_modules.keys())
+ default_lang_id = adapter_languages.index(self.config.default_language)
+ lang_ids = default_lang_id * torch.ones(batch_size, device=device)
+
+ if attention_mask is None:
+ attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
+
+ if token_type_ids is None:
+ if hasattr(self.embeddings, "token_type_ids"):
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
+ # ourselves in which case we just need to make it broadcastable to all heads.
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
+
+ # If a 2D or 3D attention mask is provided for the cross-attention
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ if self.config.is_decoder and encoder_hidden_states is not None:
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
+ if encoder_attention_mask is None:
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
+ else:
+ encoder_extended_attention_mask = None
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+ encoder_outputs = self.encoder(
+ embedding_output,
+ lang_ids=lang_ids,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ X-MOD Model with a `language modeling` head on top for CLM fine-tuning.
+ """
+)
+class XmodForCausalLM(XmodPreTrainedModel, GenerationMixin):
+ _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+
+ if not config.is_decoder:
+ logger.warning("If you want to use `XmodLMHeadModel` as a standalone, add `is_decoder=True.`")
+
+ self.roberta = XmodModel(config, add_pooling_layer=False)
+ self.lm_head = XmodLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.get_output_embeddings
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForCausalLM.set_output_embeddings
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ lang_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[tuple[tuple[torch.FloatTensor]]] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> Union[tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
+ ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, XmodForCausalLM, AutoConfig
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-roberta-base")
+ >>> config = AutoConfig.from_pretrained("facebook/xmod-base")
+ >>> config.is_decoder = True
+ >>> model = XmodForCausalLM.from_pretrained("facebook/xmod-base", config=config)
+ >>> model.set_default_language("en_XX")
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> prediction_logits = outputs.logits
+ ```"""
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ if labels is not None:
+ use_cache = False
+
+ outputs = self.roberta(
+ input_ids,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ cache_position=cache_position,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ lm_loss = None
+ if labels is not None:
+ lm_loss = self.loss_function(
+ prediction_scores,
+ labels,
+ vocab_size=self.config.vocab_size,
+ **kwargs,
+ )
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((lm_loss,) + output) if lm_loss is not None else output
+
+ return CausalLMOutputWithCrossAttentions(
+ loss=lm_loss,
+ logits=prediction_scores,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ cross_attentions=outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class XmodForMaskedLM(XmodPreTrainedModel):
+ _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+
+ if config.is_decoder:
+ logger.warning(
+ "If you want to use `XmodForMaskedLM` make sure `config.is_decoder=False` for "
+ "bi-directional self-attention."
+ )
+
+ self.roberta = XmodModel(config, add_pooling_layer=False)
+ self.lm_head = XmodLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM.get_output_embeddings
+ def get_output_embeddings(self):
+ return self.lm_head.decoder
+
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMaskedLM.set_output_embeddings
+ def set_output_embeddings(self, new_embeddings):
+ self.lm_head.decoder = new_embeddings
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ lang_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], MaskedLMOutput]:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+ prediction_scores = self.lm_head(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[2:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaLMHead
+class XmodLMHead(nn.Module):
+ """Roberta Head for masked language modeling."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+ self.decoder.bias = self.bias
+
+ def forward(self, features, **kwargs):
+ x = self.dense(features)
+ x = gelu(x)
+ x = self.layer_norm(x)
+
+ # project back to size of vocabulary with bias
+ x = self.decoder(x)
+
+ return x
+
+ def _tie_weights(self):
+ # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
+ # For accelerate compatibility and to not break backward compatibility
+ if self.decoder.bias.device.type == "meta":
+ self.decoder.bias = self.bias
+ else:
+ self.bias = self.decoder.bias
+
+
+@auto_docstring(
+ custom_intro="""
+ X-MOD Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
+ output) e.g. for GLUE tasks.
+ """
+)
+class XmodForSequenceClassification(XmodPreTrainedModel):
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForSequenceClassification.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.config = config
+
+ self.roberta = XmodModel(config, add_pooling_layer=False)
+ self.classifier = XmodClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ lang_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], SequenceClassifierOutput]:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XmodForMultipleChoice(XmodPreTrainedModel):
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForMultipleChoice.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.roberta = XmodModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ lang_ids: Optional[torch.LongTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], MultipleChoiceModelOutput]:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ lang_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ flat_lang_ids = lang_ids.repeat(input_ids.size(0) * input_ids.size(1)) if lang_ids is not None else None
+ flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ flat_inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.roberta(
+ flat_input_ids,
+ lang_ids=flat_lang_ids,
+ position_ids=flat_position_ids,
+ token_type_ids=flat_token_type_ids,
+ attention_mask=flat_attention_mask,
+ head_mask=head_mask,
+ inputs_embeds=flat_inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ pooled_output = outputs[1]
+
+ pooled_output = self.dropout(pooled_output)
+ logits = self.classifier(pooled_output)
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class XmodForTokenClassification(XmodPreTrainedModel):
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForTokenClassification.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XmodModel(config, add_pooling_layer=False)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ lang_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], TokenClassifierOutput]:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[2:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead
+class XmodClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ classifier_dropout = (
+ config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
+ )
+ self.dropout = nn.Dropout(classifier_dropout)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = torch.tanh(x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring
+class XmodForQuestionAnswering(XmodPreTrainedModel):
+ # Copied from transformers.models.roberta.modeling_roberta.RobertaForQuestionAnswering.__init__ with Roberta->Xmod
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.roberta = XmodModel(config, add_pooling_layer=False)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ lang_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ token_type_ids: Optional[torch.LongTensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ head_mask: Optional[torch.FloatTensor] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ start_positions: Optional[torch.LongTensor] = None,
+ end_positions: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], QuestionAnsweringModelOutput]:
+ r"""
+ lang_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Indices of the language adapters that should be activated for each sample, respectively. Default: the index
+ that corresponds to `self.config.default_language`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.roberta(
+ input_ids,
+ lang_ids=lang_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1).contiguous()
+ end_logits = end_logits.squeeze(-1).contiguous()
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[2:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+# Copied from transformers.models.roberta.modeling_roberta.create_position_ids_from_input_ids
+def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
+ """
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
+ are ignored. This is modified from fairseq's `utils.make_positions`.
+
+ Args:
+ x: torch.Tensor x:
+
+ Returns: torch.Tensor
+ """
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
+ mask = input_ids.ne(padding_idx).int()
+ incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
+ return incremental_indices.long() + padding_idx
+
+
+__all__ = [
+ "XmodForCausalLM",
+ "XmodForMaskedLM",
+ "XmodForMultipleChoice",
+ "XmodForQuestionAnswering",
+ "XmodForSequenceClassification",
+ "XmodForTokenClassification",
+ "XmodModel",
+ "XmodPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7ce96987e40700eb32f32e3aa0ae6c29d850b54
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/__init__.py
@@ -0,0 +1,30 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_yolos import *
+ from .feature_extraction_yolos import *
+ from .image_processing_yolos import *
+ from .image_processing_yolos_fast import *
+ from .modeling_yolos import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/configuration_yolos.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/configuration_yolos.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d2fdb2ba34c839dee6795481022551fa15f8545
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/configuration_yolos.py
@@ -0,0 +1,178 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""YOLOS model configuration"""
+
+from collections import OrderedDict
+from collections.abc import Mapping
+
+from packaging import version
+
+from ...configuration_utils import PretrainedConfig
+from ...onnx import OnnxConfig
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class YolosConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`YolosModel`]. It is used to instantiate a YOLOS
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the YOLOS
+ [hustvl/yolos-base](https://huggingface.co/hustvl/yolos-base) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ hidden_size (`int`, *optional*, defaults to 768):
+ Dimensionality of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 3072):
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ image_size (`list[int]`, *optional*, defaults to `[512, 864]`):
+ The size (resolution) of each image.
+ patch_size (`int`, *optional*, defaults to 16):
+ The size (resolution) of each patch.
+ num_channels (`int`, *optional*, defaults to 3):
+ The number of input channels.
+ qkv_bias (`bool`, *optional*, defaults to `True`):
+ Whether to add a bias to the queries, keys and values.
+ num_detection_tokens (`int`, *optional*, defaults to 100):
+ The number of detection tokens.
+ use_mid_position_embeddings (`bool`, *optional*, defaults to `True`):
+ Whether to use the mid-layer position encodings.
+ auxiliary_loss (`bool`, *optional*, defaults to `False`):
+ Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
+ class_cost (`float`, *optional*, defaults to 1):
+ Relative weight of the classification error in the Hungarian matching cost.
+ bbox_cost (`float`, *optional*, defaults to 5):
+ Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
+ giou_cost (`float`, *optional*, defaults to 2):
+ Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
+ bbox_loss_coefficient (`float`, *optional*, defaults to 5):
+ Relative weight of the L1 bounding box loss in the object detection loss.
+ giou_loss_coefficient (`float`, *optional*, defaults to 2):
+ Relative weight of the generalized IoU loss in the object detection loss.
+ eos_coefficient (`float`, *optional*, defaults to 0.1):
+ Relative classification weight of the 'no-object' class in the object detection loss.
+
+ Example:
+
+ ```python
+ >>> from transformers import YolosConfig, YolosModel
+
+ >>> # Initializing a YOLOS hustvl/yolos-base style configuration
+ >>> configuration = YolosConfig()
+
+ >>> # Initializing a model (with random weights) from the hustvl/yolos-base style configuration
+ >>> model = YolosModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "yolos"
+
+ def __init__(
+ self,
+ hidden_size=768,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.0,
+ attention_probs_dropout_prob=0.0,
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ image_size=[512, 864],
+ patch_size=16,
+ num_channels=3,
+ qkv_bias=True,
+ num_detection_tokens=100,
+ use_mid_position_embeddings=True,
+ auxiliary_loss=False,
+ class_cost=1,
+ bbox_cost=5,
+ giou_cost=2,
+ bbox_loss_coefficient=5,
+ giou_loss_coefficient=2,
+ eos_coefficient=0.1,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.initializer_range = initializer_range
+ self.layer_norm_eps = layer_norm_eps
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.qkv_bias = qkv_bias
+ self.num_detection_tokens = num_detection_tokens
+ self.use_mid_position_embeddings = use_mid_position_embeddings
+ self.auxiliary_loss = auxiliary_loss
+ # Hungarian matcher
+ self.class_cost = class_cost
+ self.bbox_cost = bbox_cost
+ self.giou_cost = giou_cost
+ # Loss coefficients
+ self.bbox_loss_coefficient = bbox_loss_coefficient
+ self.giou_loss_coefficient = giou_loss_coefficient
+ self.eos_coefficient = eos_coefficient
+
+
+class YolosOnnxConfig(OnnxConfig):
+ torch_onnx_minimum_version = version.parse("1.11")
+
+ @property
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
+ return OrderedDict(
+ [
+ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
+ ]
+ )
+
+ @property
+ def atol_for_validation(self) -> float:
+ return 1e-4
+
+ @property
+ def default_onnx_opset(self) -> int:
+ return 12
+
+
+__all__ = ["YolosConfig", "YolosOnnxConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/feature_extraction_yolos.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/feature_extraction_yolos.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1c9165832f7b181503e48af42eae559400f170a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/feature_extraction_yolos.py
@@ -0,0 +1,48 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Feature extractor class for YOLOS."""
+
+import warnings
+
+from ...image_transforms import rgb_to_id as _rgb_to_id
+from ...utils import logging
+from ...utils.import_utils import requires
+from .image_processing_yolos import YolosImageProcessor
+
+
+logger = logging.get_logger(__name__)
+
+
+def rgb_to_id(x):
+ warnings.warn(
+ "rgb_to_id has moved and will not be importable from this module from v5. "
+ "Please import from transformers.image_transforms instead.",
+ FutureWarning,
+ )
+ return _rgb_to_id(x)
+
+
+@requires(backends=("vision",))
+class YolosFeatureExtractor(YolosImageProcessor):
+ def __init__(self, *args, **kwargs) -> None:
+ warnings.warn(
+ "The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
+ " use YolosImageProcessor instead.",
+ FutureWarning,
+ )
+ super().__init__(*args, **kwargs)
+
+
+__all__ = ["YolosFeatureExtractor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_yolos.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_yolos.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a716036d4003ce8b63ebe917f2d79849fac780a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_yolos.py
@@ -0,0 +1,1537 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for YOLOS."""
+
+import pathlib
+from collections.abc import Iterable
+from typing import Any, Callable, Optional, Union
+
+import numpy as np
+
+from ...feature_extraction_utils import BatchFeature
+from ...image_processing_utils import BaseImageProcessor, get_size_dict
+from ...image_transforms import (
+ PaddingMode,
+ center_to_corners_format,
+ corners_to_center_format,
+ id_to_rgb,
+ pad,
+ rescale,
+ resize,
+ rgb_to_id,
+ to_channel_dimension_format,
+)
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ AnnotationFormat,
+ AnnotationType,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ get_image_size,
+ infer_channel_dimension_format,
+ is_scaled_image,
+ make_list_of_images,
+ to_numpy_array,
+ valid_images,
+ validate_annotations,
+ validate_kwargs,
+ validate_preprocess_arguments,
+)
+from ...utils import (
+ TensorType,
+ is_flax_available,
+ is_jax_tensor,
+ is_scipy_available,
+ is_tf_available,
+ is_tf_tensor,
+ is_torch_available,
+ is_torch_tensor,
+ is_vision_available,
+ logging,
+)
+from ...utils.import_utils import requires
+
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+
+if is_vision_available():
+ import PIL
+
+
+if is_scipy_available():
+ import scipy.special
+ import scipy.stats
+
+logger = logging.get_logger(__name__)
+
+SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
+
+
+# Copied from transformers.models.detr.image_processing_detr.get_max_height_width
+def get_max_height_width(
+ images: list[np.ndarray], input_data_format: Optional[Union[str, ChannelDimension]] = None
+) -> list[int]:
+ """
+ Get the maximum height and width across all images in a batch.
+ """
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(images[0])
+
+ if input_data_format == ChannelDimension.FIRST:
+ _, max_height, max_width = max_across_indices([img.shape for img in images])
+ elif input_data_format == ChannelDimension.LAST:
+ max_height, max_width, _ = max_across_indices([img.shape for img in images])
+ else:
+ raise ValueError(f"Invalid channel dimension format: {input_data_format}")
+ return (max_height, max_width)
+
+
+def get_size_with_aspect_ratio(
+ image_size: tuple[int, int], size: int, max_size: Optional[int] = None, mod_size: int = 16
+) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size with multiple of divisible_size.
+
+ Args:
+ image_size (`tuple[int, int]`):
+ The input image size.
+ size (`int`):
+ The desired output size.
+ max_size (`int`, *optional*):
+ The maximum allowed output size.
+ mod_size (`int`, *optional*):
+ The size to make multiple of mod_size.
+ """
+ height, width = image_size
+ raw_size = None
+ if max_size is not None:
+ min_original_size = float(min((height, width)))
+ max_original_size = float(max((height, width)))
+ if max_original_size / min_original_size * size > max_size:
+ raw_size = max_size * min_original_size / max_original_size
+ size = int(round(raw_size))
+
+ if width < height:
+ ow = size
+ if max_size is not None and raw_size is not None:
+ oh = int(raw_size * height / width)
+ else:
+ oh = int(size * height / width)
+ elif (height <= width and height == size) or (width <= height and width == size):
+ oh, ow = height, width
+ else:
+ oh = size
+ if max_size is not None and raw_size is not None:
+ ow = int(raw_size * width / height)
+ else:
+ ow = int(size * width / height)
+
+ if mod_size is not None:
+ ow_mod = np.mod(ow, mod_size)
+ oh_mod = np.mod(oh, mod_size)
+ ow = ow - ow_mod
+ oh = oh - oh_mod
+
+ return (oh, ow)
+
+
+# Copied from transformers.models.detr.image_processing_detr.get_image_size_for_max_height_width
+def get_image_size_for_max_height_width(
+ input_image: np.ndarray,
+ max_height: int,
+ max_width: int,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio.
+ Important, even if image_height < max_height and image_width < max_width, the image will be resized
+ to at least one of the edges be equal to max_height or max_width.
+
+ For example:
+ - input_size: (100, 200), max_height: 50, max_width: 50 -> output_size: (25, 50)
+ - input_size: (100, 200), max_height: 200, max_width: 500 -> output_size: (200, 400)
+
+ Args:
+ input_image (`np.ndarray`):
+ The image to resize.
+ max_height (`int`):
+ The maximum allowed height.
+ max_width (`int`):
+ The maximum allowed width.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
+ """
+ image_size = get_image_size(input_image, input_data_format)
+ height, width = image_size
+ height_scale = max_height / height
+ width_scale = max_width / width
+ min_scale = min(height_scale, width_scale)
+ new_height = int(height * min_scale)
+ new_width = int(width * min_scale)
+ return new_height, new_width
+
+
+# Copied from transformers.models.detr.image_processing_detr.get_resize_output_image_size
+def get_resize_output_image_size(
+ input_image: np.ndarray,
+ size: Union[int, tuple[int, int], list[int]],
+ max_size: Optional[int] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size. If the desired output size
+ is a tuple or list, the output image size is returned as is. If the desired output size is an integer, the output
+ image size is computed by keeping the aspect ratio of the input image size.
+
+ Args:
+ input_image (`np.ndarray`):
+ The image to resize.
+ size (`int` or `tuple[int, int]` or `list[int]`):
+ The desired output size.
+ max_size (`int`, *optional*):
+ The maximum allowed output size.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
+ """
+ image_size = get_image_size(input_image, input_data_format)
+ if isinstance(size, (list, tuple)):
+ return size
+
+ return get_size_with_aspect_ratio(image_size, size, max_size)
+
+
+# Copied from transformers.models.detr.image_processing_detr.get_numpy_to_framework_fn
+def get_numpy_to_framework_fn(arr) -> Callable:
+ """
+ Returns a function that converts a numpy array to the framework of the input array.
+
+ Args:
+ arr (`np.ndarray`): The array to convert.
+ """
+ if isinstance(arr, np.ndarray):
+ return np.array
+ if is_tf_available() and is_tf_tensor(arr):
+ import tensorflow as tf
+
+ return tf.convert_to_tensor
+ if is_torch_available() and is_torch_tensor(arr):
+ import torch
+
+ return torch.tensor
+ if is_flax_available() and is_jax_tensor(arr):
+ import jax.numpy as jnp
+
+ return jnp.array
+ raise ValueError(f"Cannot convert arrays of type {type(arr)}")
+
+
+# Copied from transformers.models.detr.image_processing_detr.safe_squeeze
+def safe_squeeze(arr: np.ndarray, axis: Optional[int] = None) -> np.ndarray:
+ """
+ Squeezes an array, but only if the axis specified has dim 1.
+ """
+ if axis is None:
+ return arr.squeeze()
+
+ try:
+ return arr.squeeze(axis=axis)
+ except ValueError:
+ return arr
+
+
+# Copied from transformers.models.detr.image_processing_detr.normalize_annotation
+def normalize_annotation(annotation: dict, image_size: tuple[int, int]) -> dict:
+ image_height, image_width = image_size
+ norm_annotation = {}
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ boxes = corners_to_center_format(boxes)
+ boxes /= np.asarray([image_width, image_height, image_width, image_height], dtype=np.float32)
+ norm_annotation[key] = boxes
+ else:
+ norm_annotation[key] = value
+ return norm_annotation
+
+
+# Copied from transformers.models.detr.image_processing_detr.max_across_indices
+def max_across_indices(values: Iterable[Any]) -> list[Any]:
+ """
+ Return the maximum value across all indices of an iterable of values.
+ """
+ return [max(values_i) for values_i in zip(*values)]
+
+
+# Copied from transformers.models.detr.image_processing_detr.make_pixel_mask
+def make_pixel_mask(
+ image: np.ndarray, output_size: tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None
+) -> np.ndarray:
+ """
+ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+
+ Args:
+ image (`np.ndarray`):
+ Image to make the pixel mask for.
+ output_size (`tuple[int, int]`):
+ Output size of the mask.
+ """
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
+ mask = np.zeros(output_size, dtype=np.int64)
+ mask[:input_height, :input_width] = 1
+ return mask
+
+
+# Copied from transformers.models.detr.image_processing_detr.convert_coco_poly_to_mask
+def convert_coco_poly_to_mask(segmentations, height: int, width: int) -> np.ndarray:
+ """
+ Convert a COCO polygon annotation to a mask.
+
+ Args:
+ segmentations (`list[list[float]]`):
+ List of polygons, each polygon represented by a list of x-y coordinates.
+ height (`int`):
+ Height of the mask.
+ width (`int`):
+ Width of the mask.
+ """
+ try:
+ from pycocotools import mask as coco_mask
+ except ImportError:
+ raise ImportError("Pycocotools is not installed in your environment.")
+
+ masks = []
+ for polygons in segmentations:
+ rles = coco_mask.frPyObjects(polygons, height, width)
+ mask = coco_mask.decode(rles)
+ if len(mask.shape) < 3:
+ mask = mask[..., None]
+ mask = np.asarray(mask, dtype=np.uint8)
+ mask = np.any(mask, axis=2)
+ masks.append(mask)
+ if masks:
+ masks = np.stack(masks, axis=0)
+ else:
+ masks = np.zeros((0, height, width), dtype=np.uint8)
+
+ return masks
+
+
+# Copied from transformers.models.detr.image_processing_detr.prepare_coco_detection_annotation
+def prepare_coco_detection_annotation(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: Optional[Union[ChannelDimension, str]] = None,
+):
+ """
+ Convert the target in COCO format into the format expected by DETR.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+
+ image_id = target["image_id"]
+ image_id = np.asarray([image_id], dtype=np.int64)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0]
+
+ classes = [obj["category_id"] for obj in annotations]
+ classes = np.asarray(classes, dtype=np.int64)
+
+ # for conversion to coco api
+ area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32)
+ iscrowd = np.asarray([obj.get("iscrowd", 0) for obj in annotations], dtype=np.int64)
+
+ boxes = [obj["bbox"] for obj in annotations]
+ # guard against no boxes via resizing
+ boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {}
+ new_target["image_id"] = image_id
+ new_target["class_labels"] = classes[keep]
+ new_target["boxes"] = boxes[keep]
+ new_target["area"] = area[keep]
+ new_target["iscrowd"] = iscrowd[keep]
+ new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64)
+
+ if annotations and "keypoints" in annotations[0]:
+ keypoints = [obj["keypoints"] for obj in annotations]
+ # Converting the filtered keypoints list to a numpy array
+ keypoints = np.asarray(keypoints, dtype=np.float32)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ if return_segmentation_masks:
+ segmentation_masks = [obj["segmentation"] for obj in annotations]
+ masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width)
+ new_target["masks"] = masks[keep]
+
+ return new_target
+
+
+# Copied from transformers.models.detr.image_processing_detr.masks_to_boxes
+def masks_to_boxes(masks: np.ndarray) -> np.ndarray:
+ """
+ Compute the bounding boxes around the provided panoptic segmentation masks.
+
+ Args:
+ masks: masks in format `[number_masks, height, width]` where N is the number of masks
+
+ Returns:
+ boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
+ """
+ if masks.size == 0:
+ return np.zeros((0, 4))
+
+ h, w = masks.shape[-2:]
+ y = np.arange(0, h, dtype=np.float32)
+ x = np.arange(0, w, dtype=np.float32)
+ # see https://github.com/pytorch/pytorch/issues/50276
+ y, x = np.meshgrid(y, x, indexing="ij")
+
+ x_mask = masks * np.expand_dims(x, axis=0)
+ x_max = x_mask.reshape(x_mask.shape[0], -1).max(-1)
+ x = np.ma.array(x_mask, mask=~(np.array(masks, dtype=bool)))
+ x_min = x.filled(fill_value=1e8)
+ x_min = x_min.reshape(x_min.shape[0], -1).min(-1)
+
+ y_mask = masks * np.expand_dims(y, axis=0)
+ y_max = y_mask.reshape(x_mask.shape[0], -1).max(-1)
+ y = np.ma.array(y_mask, mask=~(np.array(masks, dtype=bool)))
+ y_min = y.filled(fill_value=1e8)
+ y_min = y_min.reshape(y_min.shape[0], -1).min(-1)
+
+ return np.stack([x_min, y_min, x_max, y_max], 1)
+
+
+# Copied from transformers.models.detr.image_processing_detr.prepare_coco_panoptic_annotation with DETR->YOLOS
+def prepare_coco_panoptic_annotation(
+ image: np.ndarray,
+ target: dict,
+ masks_path: Union[str, pathlib.Path],
+ return_masks: bool = True,
+ input_data_format: Union[ChannelDimension, str] = None,
+) -> dict:
+ """
+ Prepare a coco panoptic annotation for YOLOS.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+ annotation_path = pathlib.Path(masks_path) / target["file_name"]
+
+ new_target = {}
+ new_target["image_id"] = np.asarray([target["image_id"] if "image_id" in target else target["id"]], dtype=np.int64)
+ new_target["size"] = np.asarray([image_height, image_width], dtype=np.int64)
+ new_target["orig_size"] = np.asarray([image_height, image_width], dtype=np.int64)
+
+ if "segments_info" in target:
+ masks = np.asarray(PIL.Image.open(annotation_path), dtype=np.uint32)
+ masks = rgb_to_id(masks)
+
+ ids = np.array([segment_info["id"] for segment_info in target["segments_info"]])
+ masks = masks == ids[:, None, None]
+ masks = masks.astype(np.uint8)
+ if return_masks:
+ new_target["masks"] = masks
+ new_target["boxes"] = masks_to_boxes(masks)
+ new_target["class_labels"] = np.array(
+ [segment_info["category_id"] for segment_info in target["segments_info"]], dtype=np.int64
+ )
+ new_target["iscrowd"] = np.asarray(
+ [segment_info["iscrowd"] for segment_info in target["segments_info"]], dtype=np.int64
+ )
+ new_target["area"] = np.asarray(
+ [segment_info["area"] for segment_info in target["segments_info"]], dtype=np.float32
+ )
+
+ return new_target
+
+
+# Copied from transformers.models.detr.image_processing_detr.get_segmentation_image
+def get_segmentation_image(
+ masks: np.ndarray, input_size: tuple, target_size: tuple, stuff_equiv_classes, deduplicate=False
+):
+ h, w = input_size
+ final_h, final_w = target_size
+
+ m_id = scipy.special.softmax(masks.transpose(0, 1), -1)
+
+ if m_id.shape[-1] == 0:
+ # We didn't detect any mask :(
+ m_id = np.zeros((h, w), dtype=np.int64)
+ else:
+ m_id = m_id.argmax(-1).reshape(h, w)
+
+ if deduplicate:
+ # Merge the masks corresponding to the same stuff class
+ for equiv in stuff_equiv_classes.values():
+ for eq_id in equiv:
+ m_id[m_id == eq_id] = equiv[0]
+
+ seg_img = id_to_rgb(m_id)
+ seg_img = resize(seg_img, (final_w, final_h), resample=PILImageResampling.NEAREST)
+ return seg_img
+
+
+# Copied from transformers.models.detr.image_processing_detr.get_mask_area
+def get_mask_area(seg_img: np.ndarray, target_size: tuple[int, int], n_classes: int) -> np.ndarray:
+ final_h, final_w = target_size
+ np_seg_img = seg_img.astype(np.uint8)
+ np_seg_img = np_seg_img.reshape(final_h, final_w, 3)
+ m_id = rgb_to_id(np_seg_img)
+ area = [(m_id == i).sum() for i in range(n_classes)]
+ return area
+
+
+# Copied from transformers.models.detr.image_processing_detr.score_labels_from_class_probabilities
+def score_labels_from_class_probabilities(logits: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ probs = scipy.special.softmax(logits, axis=-1)
+ labels = probs.argmax(-1, keepdims=True)
+ scores = np.take_along_axis(probs, labels, axis=-1)
+ scores, labels = scores.squeeze(-1), labels.squeeze(-1)
+ return scores, labels
+
+
+# Copied from transformers.models.detr.image_processing_detr.resize_annotation
+def resize_annotation(
+ annotation: dict[str, Any],
+ orig_size: tuple[int, int],
+ target_size: tuple[int, int],
+ threshold: float = 0.5,
+ resample: PILImageResampling = PILImageResampling.NEAREST,
+):
+ """
+ Resizes an annotation to a target size.
+
+ Args:
+ annotation (`dict[str, Any]`):
+ The annotation dictionary.
+ orig_size (`tuple[int, int]`):
+ The original size of the input image.
+ target_size (`tuple[int, int]`):
+ The target size of the image, as returned by the preprocessing `resize` step.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The threshold used to binarize the segmentation masks.
+ resample (`PILImageResampling`, defaults to `PILImageResampling.NEAREST`):
+ The resampling filter to use when resizing the masks.
+ """
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(target_size, orig_size))
+ ratio_height, ratio_width = ratios
+
+ new_annotation = {}
+ new_annotation["size"] = target_size
+
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ scaled_boxes = boxes * np.asarray([ratio_width, ratio_height, ratio_width, ratio_height], dtype=np.float32)
+ new_annotation["boxes"] = scaled_boxes
+ elif key == "area":
+ area = value
+ scaled_area = area * (ratio_width * ratio_height)
+ new_annotation["area"] = scaled_area
+ elif key == "masks":
+ masks = value[:, None]
+ masks = np.array([resize(mask, target_size, resample=resample) for mask in masks])
+ masks = masks.astype(np.float32)
+ masks = masks[:, 0] > threshold
+ new_annotation["masks"] = masks
+ elif key == "size":
+ new_annotation["size"] = target_size
+ else:
+ new_annotation[key] = value
+
+ return new_annotation
+
+
+# Copied from transformers.models.detr.image_processing_detr.binary_mask_to_rle
+def binary_mask_to_rle(mask):
+ """
+ Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format.
+
+ Args:
+ mask (`torch.Tensor` or `numpy.array`):
+ A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target
+ segment_id or class_id.
+ Returns:
+ `List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE
+ format.
+ """
+ if is_torch_tensor(mask):
+ mask = mask.numpy()
+
+ pixels = mask.flatten()
+ pixels = np.concatenate([[0], pixels, [0]])
+ runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
+ runs[1::2] -= runs[::2]
+ return list(runs)
+
+
+# Copied from transformers.models.detr.image_processing_detr.convert_segmentation_to_rle
+def convert_segmentation_to_rle(segmentation):
+ """
+ Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format.
+
+ Args:
+ segmentation (`torch.Tensor` or `numpy.array`):
+ A segmentation map of shape `(height, width)` where each value denotes a segment or class id.
+ Returns:
+ `list[List]`: A list of lists, where each list is the run-length encoding of a segment / class id.
+ """
+ segment_ids = torch.unique(segmentation)
+
+ run_length_encodings = []
+ for idx in segment_ids:
+ mask = torch.where(segmentation == idx, 1, 0)
+ rle = binary_mask_to_rle(mask)
+ run_length_encodings.append(rle)
+
+ return run_length_encodings
+
+
+# Copied from transformers.models.detr.image_processing_detr.remove_low_and_no_objects
+def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
+ """
+ Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
+ `labels`.
+
+ Args:
+ masks (`torch.Tensor`):
+ A tensor of shape `(num_queries, height, width)`.
+ scores (`torch.Tensor`):
+ A tensor of shape `(num_queries)`.
+ labels (`torch.Tensor`):
+ A tensor of shape `(num_queries)`.
+ object_mask_threshold (`float`):
+ A number between 0 and 1 used to binarize the masks.
+ Raises:
+ `ValueError`: Raised when the first dimension doesn't match in all input tensors.
+ Returns:
+ `tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
+ < `object_mask_threshold`.
+ """
+ if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
+ raise ValueError("mask, scores and labels must have the same shape!")
+
+ to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
+
+ return masks[to_keep], scores[to_keep], labels[to_keep]
+
+
+# Copied from transformers.models.detr.image_processing_detr.check_segment_validity
+def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
+ # Get the mask associated with the k class
+ mask_k = mask_labels == k
+ mask_k_area = mask_k.sum()
+
+ # Compute the area of all the stuff in query k
+ original_area = (mask_probs[k] >= mask_threshold).sum()
+ mask_exists = mask_k_area > 0 and original_area > 0
+
+ # Eliminate disconnected tiny segments
+ if mask_exists:
+ area_ratio = mask_k_area / original_area
+ if not area_ratio.item() > overlap_mask_area_threshold:
+ mask_exists = False
+
+ return mask_exists, mask_k
+
+
+# Copied from transformers.models.detr.image_processing_detr.compute_segments
+def compute_segments(
+ mask_probs,
+ pred_scores,
+ pred_labels,
+ mask_threshold: float = 0.5,
+ overlap_mask_area_threshold: float = 0.8,
+ label_ids_to_fuse: Optional[set[int]] = None,
+ target_size: Optional[tuple[int, int]] = None,
+):
+ height = mask_probs.shape[1] if target_size is None else target_size[0]
+ width = mask_probs.shape[2] if target_size is None else target_size[1]
+
+ segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device)
+ segments: list[dict] = []
+
+ if target_size is not None:
+ mask_probs = nn.functional.interpolate(
+ mask_probs.unsqueeze(0), size=target_size, mode="bilinear", align_corners=False
+ )[0]
+
+ current_segment_id = 0
+
+ # Weigh each mask by its prediction score
+ mask_probs *= pred_scores.view(-1, 1, 1)
+ mask_labels = mask_probs.argmax(0) # [height, width]
+
+ # Keep track of instances of each class
+ stuff_memory_list: dict[str, int] = {}
+ for k in range(pred_labels.shape[0]):
+ pred_class = pred_labels[k].item()
+ should_fuse = pred_class in label_ids_to_fuse
+
+ # Check if mask exists and large enough to be a segment
+ mask_exists, mask_k = check_segment_validity(
+ mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
+ )
+
+ if mask_exists:
+ if pred_class in stuff_memory_list:
+ current_segment_id = stuff_memory_list[pred_class]
+ else:
+ current_segment_id += 1
+
+ # Add current object segment to final segmentation map
+ segmentation[mask_k] = current_segment_id
+ segment_score = round(pred_scores[k].item(), 6)
+ segments.append(
+ {
+ "id": current_segment_id,
+ "label_id": pred_class,
+ "was_fused": should_fuse,
+ "score": segment_score,
+ }
+ )
+ if should_fuse:
+ stuff_memory_list[pred_class] = current_segment_id
+
+ return segmentation, segments
+
+
+@requires(backends=("vision",))
+class YolosImageProcessor(BaseImageProcessor):
+ r"""
+ Constructs a Detr image processor.
+
+ Args:
+ format (`str`, *optional*, defaults to `"coco_detection"`):
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
+ do_resize (`bool`, *optional*, defaults to `True`):
+ Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be
+ overridden by the `do_resize` parameter in the `preprocess` method.
+ size (`dict[str, int]` *optional*, defaults to `{"shortest_edge": 800, "longest_edge": 1333}`):
+ Size of the image's `(height, width)` dimensions after resizing. Can be overridden by the `size` parameter
+ in the `preprocess` method. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ do_rescale (`bool`, *optional*, defaults to `True`):
+ Controls whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
+ `do_rescale` parameter in the `preprocess` method.
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
+ `preprocess` method.
+ do_normalize:
+ Controls whether to normalize the image. Can be overridden by the `do_normalize` parameter in the
+ `preprocess` method.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
+ Mean values to use when normalizing the image. Can be a single value or a list of values, one for each
+ channel. Can be overridden by the `image_mean` parameter in the `preprocess` method.
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`):
+ Standard deviation values to use when normalizing the image. Can be a single value or a list of values, one
+ for each channel. Can be overridden by the `image_std` parameter in the `preprocess` method.
+ do_pad (`bool`, *optional*, defaults to `True`):
+ Controls whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess`
+ method. If `True`, padding will be applied to the bottom and right of the image with zeros.
+ If `pad_size` is provided, the image will be padded to the specified dimensions.
+ Otherwise, the image will be padded to the maximum height and width of the batch.
+ pad_size (`dict[str, int]`, *optional*):
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
+ height and width in the batch.
+ """
+
+ model_input_names = ["pixel_values", "pixel_mask"]
+
+ def __init__(
+ self,
+ format: Union[str, AnnotationFormat] = AnnotationFormat.COCO_DETECTION,
+ do_resize: bool = True,
+ size: Optional[dict[str, int]] = None,
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
+ do_rescale: bool = True,
+ rescale_factor: Union[int, float] = 1 / 255,
+ do_normalize: bool = True,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ do_convert_annotations: Optional[bool] = None,
+ do_pad: bool = True,
+ pad_size: Optional[dict[str, int]] = None,
+ **kwargs,
+ ) -> None:
+ if "pad_and_return_pixel_mask" in kwargs:
+ do_pad = kwargs.pop("pad_and_return_pixel_mask")
+
+ if "max_size" in kwargs:
+ logger.warning_once(
+ "The `max_size` parameter is deprecated and will be removed in v4.26. "
+ "Please specify in `size['longest_edge'] instead`.",
+ )
+ max_size = kwargs.pop("max_size")
+ else:
+ max_size = None if size is None else 1333
+
+ size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
+ size = get_size_dict(size, max_size=max_size, default_to_square=False)
+
+ # Backwards compatibility
+ if do_convert_annotations is None:
+ do_convert_annotations = do_normalize
+
+ super().__init__(**kwargs)
+ self.format = format
+ self.do_resize = do_resize
+ self.size = size
+ self.resample = resample
+ self.do_rescale = do_rescale
+ self.rescale_factor = rescale_factor
+ self.do_normalize = do_normalize
+ self.do_convert_annotations = do_convert_annotations
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
+ self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
+ self.do_pad = do_pad
+ self.pad_size = pad_size
+ self._valid_processor_keys = [
+ "images",
+ "annotations",
+ "return_segmentation_masks",
+ "masks_path",
+ "do_resize",
+ "size",
+ "resample",
+ "do_rescale",
+ "rescale_factor",
+ "do_normalize",
+ "image_mean",
+ "image_std",
+ "do_convert_annotations",
+ "do_pad",
+ "pad_size",
+ "format",
+ "return_tensors",
+ "data_format",
+ "input_data_format",
+ ]
+
+ @classmethod
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.from_dict with Detr->Yolos
+ def from_dict(cls, image_processor_dict: dict[str, Any], **kwargs):
+ """
+ Overrides the `from_dict` method from the base class to make sure parameters are updated if image processor is
+ created using from_dict and kwargs e.g. `YolosImageProcessor.from_pretrained(checkpoint, size=600,
+ max_size=800)`
+ """
+ image_processor_dict = image_processor_dict.copy()
+ if "max_size" in kwargs:
+ image_processor_dict["max_size"] = kwargs.pop("max_size")
+ if "pad_and_return_pixel_mask" in kwargs:
+ image_processor_dict["pad_and_return_pixel_mask"] = kwargs.pop("pad_and_return_pixel_mask")
+ return super().from_dict(image_processor_dict, **kwargs)
+
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.prepare_annotation
+ def prepare_annotation(
+ self,
+ image: np.ndarray,
+ target: dict,
+ format: Optional[AnnotationFormat] = None,
+ return_segmentation_masks: Optional[bool] = None,
+ masks_path: Optional[Union[str, pathlib.Path]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ ) -> dict:
+ """
+ Prepare an annotation for feeding into DETR model.
+ """
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ elif format == AnnotationFormat.COCO_PANOPTIC:
+ return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_panoptic_annotation(
+ image,
+ target,
+ masks_path=masks_path,
+ return_masks=return_segmentation_masks,
+ input_data_format=input_data_format,
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.resize
+ def resize(
+ self,
+ image: np.ndarray,
+ size: dict[str, int],
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
+ data_format: Optional[ChannelDimension] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ **kwargs,
+ ) -> np.ndarray:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`dict[str, int]`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred.
+ """
+ if "max_size" in kwargs:
+ logger.warning_once(
+ "The `max_size` parameter is deprecated and will be removed in v4.26. "
+ "Please specify in `size['longest_edge'] instead`.",
+ )
+ max_size = kwargs.pop("max_size")
+ else:
+ max_size = None
+ size = get_size_dict(size, max_size=max_size, default_to_square=False)
+ if "shortest_edge" in size and "longest_edge" in size:
+ new_size = get_resize_output_image_size(
+ image, size["shortest_edge"], size["longest_edge"], input_data_format=input_data_format
+ )
+ elif "max_height" in size and "max_width" in size:
+ new_size = get_image_size_for_max_height_width(
+ image, size["max_height"], size["max_width"], input_data_format=input_data_format
+ )
+ elif "height" in size and "width" in size:
+ new_size = (size["height"], size["width"])
+ else:
+ raise ValueError(
+ "Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got"
+ f" {size.keys()}."
+ )
+ image = resize(
+ image,
+ size=new_size,
+ resample=resample,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ **kwargs,
+ )
+ return image
+
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.resize_annotation
+ def resize_annotation(
+ self,
+ annotation,
+ orig_size,
+ size,
+ resample: PILImageResampling = PILImageResampling.NEAREST,
+ ) -> dict:
+ """
+ Resize the annotation to match the resized image. If size is an int, smaller edge of the mask will be matched
+ to this number.
+ """
+ return resize_annotation(annotation, orig_size=orig_size, target_size=size, resample=resample)
+
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.rescale
+ def rescale(
+ self,
+ image: np.ndarray,
+ rescale_factor: float,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ ) -> np.ndarray:
+ """
+ Rescale the image by the given factor. image = image * rescale_factor.
+
+ Args:
+ image (`np.ndarray`):
+ Image to rescale.
+ rescale_factor (`float`):
+ The value to use for rescaling.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
+ image is used. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ input_data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format for the input image. If unset, is inferred from the input image. Can be
+ one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ """
+ return rescale(image, rescale_factor, data_format=data_format, input_data_format=input_data_format)
+
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.normalize_annotation
+ def normalize_annotation(self, annotation: dict, image_size: tuple[int, int]) -> dict:
+ """
+ Normalize the boxes in the annotation from `[top_left_x, top_left_y, bottom_right_x, bottom_right_y]` to
+ `[center_x, center_y, width, height]` format and from absolute to relative pixel values.
+ """
+ return normalize_annotation(annotation, image_size=image_size)
+
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor._update_annotation_for_padded_image
+ def _update_annotation_for_padded_image(
+ self,
+ annotation: dict,
+ input_image_size: tuple[int, int],
+ output_image_size: tuple[int, int],
+ padding,
+ update_bboxes,
+ ) -> dict:
+ """
+ Update the annotation for a padded image.
+ """
+ new_annotation = {}
+ new_annotation["size"] = output_image_size
+
+ for key, value in annotation.items():
+ if key == "masks":
+ masks = value
+ masks = pad(
+ masks,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=0,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ masks = safe_squeeze(masks, 1)
+ new_annotation["masks"] = masks
+ elif key == "boxes" and update_bboxes:
+ boxes = value
+ boxes *= np.asarray(
+ [
+ input_image_size[1] / output_image_size[1],
+ input_image_size[0] / output_image_size[0],
+ input_image_size[1] / output_image_size[1],
+ input_image_size[0] / output_image_size[0],
+ ]
+ )
+ new_annotation["boxes"] = boxes
+ elif key == "size":
+ new_annotation["size"] = output_image_size
+ else:
+ new_annotation[key] = value
+ return new_annotation
+
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor._pad_image
+ def _pad_image(
+ self,
+ image: np.ndarray,
+ output_size: tuple[int, int],
+ annotation: Optional[dict[str, Any]] = None,
+ constant_values: Union[float, Iterable[float]] = 0,
+ data_format: Optional[ChannelDimension] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ update_bboxes: bool = True,
+ ) -> np.ndarray:
+ """
+ Pad an image with zeros to the given size.
+ """
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
+ output_height, output_width = output_size
+
+ pad_bottom = output_height - input_height
+ pad_right = output_width - input_width
+ padding = ((0, pad_bottom), (0, pad_right))
+ padded_image = pad(
+ image,
+ padding,
+ mode=PaddingMode.CONSTANT,
+ constant_values=constant_values,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ )
+ if annotation is not None:
+ annotation = self._update_annotation_for_padded_image(
+ annotation, (input_height, input_width), (output_height, output_width), padding, update_bboxes
+ )
+ return padded_image, annotation
+
+ def pad(
+ self,
+ images: list[np.ndarray],
+ annotations: Optional[list[dict[str, Any]]] = None,
+ constant_values: Union[float, Iterable[float]] = 0,
+ return_pixel_mask: bool = False,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ data_format: Optional[ChannelDimension] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ update_bboxes: bool = True,
+ pad_size: Optional[dict[str, int]] = None,
+ ) -> BatchFeature:
+ """
+ Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width
+ in the batch and optionally returns their corresponding pixel mask.
+
+ Args:
+ image (`np.ndarray`):
+ Image to pad.
+ annotations (`list[dict[str, any]]`, *optional*):
+ Annotations to pad along with the images. If provided, the bounding boxes will be updated to match the
+ padded images.
+ constant_values (`float` or `Iterable[float]`, *optional*):
+ The value to use for the padding if `mode` is `"constant"`.
+ return_pixel_mask (`bool`, *optional*, defaults to `True`):
+ Whether to return a pixel mask.
+ return_tensors (`str` or `TensorType`, *optional*):
+ The type of tensors to return. Can be one of:
+ - Unset: Return a list of `np.ndarray`.
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred.
+ update_bboxes (`bool`, *optional*, defaults to `True`):
+ Whether to update the bounding boxes in the annotations to match the padded images. If the
+ bounding boxes have not been converted to relative coordinates and `(centre_x, centre_y, width, height)`
+ format, the bounding boxes will not be updated.
+ pad_size (`dict[str, int]`, *optional*):
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
+ height and width in the batch.
+ """
+ pad_size = pad_size if pad_size is not None else self.pad_size
+ if pad_size is not None:
+ padded_size = (pad_size["height"], pad_size["width"])
+ else:
+ padded_size = get_max_height_width(images, input_data_format=input_data_format)
+
+ annotation_list = annotations if annotations is not None else [None] * len(images)
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotation_list):
+ padded_image, padded_annotation = self._pad_image(
+ image,
+ padded_size,
+ annotation,
+ constant_values=constant_values,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ update_bboxes=update_bboxes,
+ )
+ padded_images.append(padded_image)
+ padded_annotations.append(padded_annotation)
+
+ data = {"pixel_values": padded_images}
+
+ if return_pixel_mask:
+ masks = [
+ make_pixel_mask(image=image, output_size=padded_size, input_data_format=input_data_format)
+ for image in images
+ ]
+ data["pixel_mask"] = masks
+
+ encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
+
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in padded_annotations
+ ]
+
+ return encoded_inputs
+
+ def preprocess(
+ self,
+ images: ImageInput,
+ annotations: Optional[Union[AnnotationType, list[AnnotationType]]] = None,
+ return_segmentation_masks: Optional[bool] = None,
+ masks_path: Optional[Union[str, pathlib.Path]] = None,
+ do_resize: Optional[bool] = None,
+ size: Optional[dict[str, int]] = None,
+ resample=None, # PILImageResampling
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[Union[int, float]] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ do_convert_annotations: Optional[bool] = None,
+ do_pad: Optional[bool] = None,
+ format: Optional[Union[str, AnnotationFormat]] = None,
+ return_tensors: Optional[Union[TensorType, str]] = None,
+ data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ pad_size: Optional[dict[str, int]] = None,
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+
+ Args:
+ images (`ImageInput`):
+ Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging
+ from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
+ annotations (`AnnotationType` or `list[AnnotationType]`, *optional*):
+ List of annotations associated with the image or batch of images. If annotation is for object
+ detection, the annotations should be a dictionary with the following keys:
+ - "image_id" (`int`): The image id.
+ - "annotations" (`list[Dict]`): List of annotations for an image. Each annotation should be a
+ dictionary. An image can have no annotations, in which case the list should be empty.
+ If annotation is for segmentation, the annotations should be a dictionary with the following keys:
+ - "image_id" (`int`): The image id.
+ - "segments_info" (`list[Dict]`): List of segments for an image. Each segment should be a dictionary.
+ An image can have no segments, in which case the list should be empty.
+ - "file_name" (`str`): The file name of the image.
+ return_segmentation_masks (`bool`, *optional*, defaults to self.return_segmentation_masks):
+ Whether to return segmentation masks.
+ masks_path (`str` or `pathlib.Path`, *optional*):
+ Path to the directory containing the segmentation masks.
+ do_resize (`bool`, *optional*, defaults to self.do_resize):
+ Whether to resize the image.
+ size (`dict[str, int]`, *optional*, defaults to self.size):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ resample (`PILImageResampling`, *optional*, defaults to self.resample):
+ Resampling filter to use when resizing the image.
+ do_rescale (`bool`, *optional*, defaults to self.do_rescale):
+ Whether to rescale the image.
+ rescale_factor (`float`, *optional*, defaults to self.rescale_factor):
+ Rescale factor to use when rescaling the image.
+ do_normalize (`bool`, *optional*, defaults to self.do_normalize):
+ Whether to normalize the image.
+ image_mean (`float` or `list[float]`, *optional*, defaults to self.image_mean):
+ Mean to use when normalizing the image.
+ image_std (`float` or `list[float]`, *optional*, defaults to self.image_std):
+ Standard deviation to use when normalizing the image.
+ do_convert_annotations (`bool`, *optional*, defaults to self.do_convert_annotations):
+ Whether to convert the annotations to the format expected by the model. Converts the bounding
+ boxes from the format `(top_left_x, top_left_y, width, height)` to `(center_x, center_y, width, height)`
+ and in relative coordinates.
+ do_pad (`bool`, *optional*, defaults to self.do_pad):
+ Whether to pad the image. If `True`, padding will be applied to the bottom and right of
+ the image with zeros. If `pad_size` is provided, the image will be padded to the specified
+ dimensions. Otherwise, the image will be padded to the maximum height and width of the batch.
+ format (`str` or `AnnotationFormat`, *optional*, defaults to self.format):
+ Format of the annotations.
+ return_tensors (`str` or `TensorType`, *optional*, defaults to self.return_tensors):
+ Type of tensors to return. If `None`, will return the list of images.
+ data_format (`str` or `ChannelDimension`, *optional*, defaults to self.data_format):
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+ pad_size (`dict[str, int]`, *optional*):
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
+ height and width in the batch.
+ """
+ if "pad_and_return_pixel_mask" in kwargs:
+ logger.warning_once(
+ "The `pad_and_return_pixel_mask` argument is deprecated and will be removed in v4.33, "
+ "use `do_pad` instead.",
+ )
+ do_pad = kwargs.pop("pad_and_return_pixel_mask")
+
+ if "max_size" in kwargs:
+ logger.warning_once(
+ "The `max_size` argument is deprecated and will be removed in v4.33, use"
+ " `size['longest_edge']` instead.",
+ )
+ size = kwargs.pop("max_size")
+
+ do_resize = self.do_resize if do_resize is None else do_resize
+ size = self.size if size is None else size
+ size = get_size_dict(size=size, default_to_square=False)
+ resample = self.resample if resample is None else resample
+ do_rescale = self.do_rescale if do_rescale is None else do_rescale
+ rescale_factor = self.rescale_factor if rescale_factor is None else rescale_factor
+ do_normalize = self.do_normalize if do_normalize is None else do_normalize
+ image_mean = self.image_mean if image_mean is None else image_mean
+ image_std = self.image_std if image_std is None else image_std
+ do_convert_annotations = (
+ self.do_convert_annotations if do_convert_annotations is None else do_convert_annotations
+ )
+ do_pad = self.do_pad if do_pad is None else do_pad
+ pad_size = self.pad_size if pad_size is None else pad_size
+ format = self.format if format is None else format
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
+
+ images = make_list_of_images(images)
+
+ if not valid_images(images):
+ raise ValueError(
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
+ "torch.Tensor, tf.Tensor or jax.ndarray."
+ )
+ # Here the pad() method pads using the max of (width, height) and does not need to be validated.
+ validate_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ )
+
+ if annotations is not None and isinstance(annotations, dict):
+ annotations = [annotations]
+
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ if (
+ masks_path is not None
+ and format == AnnotationFormat.COCO_PANOPTIC
+ and not isinstance(masks_path, (pathlib.Path, str))
+ ):
+ raise ValueError(
+ "The path to the directory containing the mask PNG files should be provided as a"
+ f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
+ )
+
+ # All transformations expect numpy arrays
+ images = [to_numpy_array(image) for image in images]
+
+ if do_rescale and is_scaled_image(images[0]):
+ logger.warning_once(
+ "It looks like you are trying to rescale already rescaled images. If the input"
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
+ )
+
+ if input_data_format is None:
+ # We assume that all images have the same channel dimension format.
+ input_data_format = infer_channel_dimension_format(images[0])
+
+ # prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
+ if annotations is not None:
+ prepared_images = []
+ prepared_annotations = []
+ for image, target in zip(images, annotations):
+ target = self.prepare_annotation(
+ image,
+ target,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=input_data_format,
+ )
+ prepared_images.append(image)
+ prepared_annotations.append(target)
+ images = prepared_images
+ annotations = prepared_annotations
+ del prepared_images, prepared_annotations
+
+ # transformations
+ if do_resize:
+ if annotations is not None:
+ resized_images, resized_annotations = [], []
+ for image, target in zip(images, annotations):
+ orig_size = get_image_size(image, input_data_format)
+ resized_image = self.resize(
+ image, size=size, resample=resample, input_data_format=input_data_format
+ )
+ resized_annotation = self.resize_annotation(
+ target, orig_size, get_image_size(resized_image, input_data_format)
+ )
+ resized_images.append(resized_image)
+ resized_annotations.append(resized_annotation)
+ images = resized_images
+ annotations = resized_annotations
+ del resized_images, resized_annotations
+ else:
+ images = [
+ self.resize(image, size=size, resample=resample, input_data_format=input_data_format)
+ for image in images
+ ]
+
+ if do_rescale:
+ images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]
+
+ if do_normalize:
+ images = [
+ self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images
+ ]
+
+ if do_convert_annotations and annotations is not None:
+ annotations = [
+ self.normalize_annotation(annotation, get_image_size(image, input_data_format))
+ for annotation, image in zip(annotations, images)
+ ]
+
+ if do_pad:
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ encoded_inputs = self.pad(
+ images,
+ annotations=annotations,
+ return_pixel_mask=False,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ update_bboxes=do_convert_annotations,
+ return_tensors=return_tensors,
+ pad_size=pad_size,
+ )
+ else:
+ images = [
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
+ for image in images
+ ]
+ encoded_inputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+
+ return encoded_inputs
+
+ # POSTPROCESSING METHODS - TODO: add support for other frameworks
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.post_process with Detr->Yolos
+ def post_process(self, outputs, target_sizes):
+ """
+ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`YolosObjectDetectionOutput`]):
+ Raw outputs of the model.
+ target_sizes (`torch.Tensor` of shape `(batch_size, 2)`):
+ Tensor containing the size (height, width) of each image of the batch. For evaluation, this must be the
+ original image size (before any data augmentation). For visualization, this should be the image size
+ after data augment, but before padding.
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ logger.warning_once(
+ "`post_process` is deprecated and will be removed in v5 of Transformers, please use"
+ " `post_process_object_detection` instead, with `threshold=0.` for equivalent results.",
+ )
+
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if len(out_logits) != len(target_sizes):
+ raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the logits")
+ if target_sizes.shape[1] != 2:
+ raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch")
+
+ prob = nn.functional.softmax(out_logits, -1)
+ scores, labels = prob[..., :-1].max(-1)
+
+ # convert to [x0, y0, x1, y1] format
+ boxes = center_to_corners_format(out_bbox)
+ # and from relative [0, 1] to absolute [0, height] coordinates
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = [{"scores": s, "labels": l, "boxes": b} for s, l, b in zip(scores, labels, boxes)]
+ return results
+
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.post_process_object_detection with Detr->Yolos
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: Union[TensorType, list[tuple]] = None
+ ):
+ """
+ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x, top_left_y,
+ bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`YolosObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ `(height, width)` of each image in the batch. If unset, predictions will not be resized.
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = nn.functional.softmax(out_logits, -1)
+ scores, labels = prob[..., :-1].max(-1)
+
+ # Convert to [x0, y0, x1, y1] format
+ boxes = center_to_corners_format(out_bbox)
+
+ # Convert from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+
+__all__ = ["YolosImageProcessor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_yolos_fast.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_yolos_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..85aeba94bfcc5ab3f02ad39e83e89e91c0bfb0a7
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/image_processing_yolos_fast.py
@@ -0,0 +1,876 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/yolos/modular_yolos.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_yolos.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+import pathlib
+from typing import Any, Optional, Union
+
+from ...image_processing_utils import BatchFeature, get_size_dict
+from ...image_processing_utils_fast import (
+ BaseImageProcessorFast,
+ DefaultFastImageProcessorKwargs,
+ SizeDict,
+ get_image_size_for_max_height_width,
+ get_max_height_width,
+ safe_squeeze,
+)
+from ...image_transforms import center_to_corners_format, corners_to_center_format
+from ...image_utils import (
+ IMAGENET_DEFAULT_MEAN,
+ IMAGENET_DEFAULT_STD,
+ AnnotationFormat,
+ AnnotationType,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ get_image_size,
+ validate_annotations,
+)
+from ...processing_utils import Unpack
+from ...utils import (
+ TensorType,
+ auto_docstring,
+ is_torch_available,
+ is_torchvision_available,
+ is_torchvision_v2_available,
+ logging,
+)
+from ...utils.import_utils import requires
+
+
+if is_torch_available():
+ import torch
+
+
+if is_torchvision_v2_available():
+ from torchvision.io import read_image
+ from torchvision.transforms.v2 import functional as F
+
+elif is_torchvision_available():
+ from torchvision.io import read_image
+ from torchvision.transforms import functional as F
+
+
+logger = logging.get_logger(__name__)
+
+
+class YolosFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
+ r"""
+ format (`str`, *optional*, defaults to `AnnotationFormat.COCO_DETECTION`):
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
+ Controls whether to convert the annotations to the format expected by the YOLOS model. Converts the
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
+ do_pad (`bool`, *optional*, defaults to `True`):
+ Controls whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess`
+ method. If `True`, padding will be applied to the bottom and right of the image with zeros.
+ If `pad_size` is provided, the image will be padded to the specified dimensions.
+ Otherwise, the image will be padded to the maximum height and width of the batch.
+ pad_size (`dict[str, int]`, *optional*):
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
+ height and width in the batch.
+ return_segmentation_masks (`bool`, *optional*, defaults to `False`):
+ Whether to return segmentation masks.
+ """
+
+ format: Optional[Union[str, AnnotationFormat]]
+ do_convert_annotations: Optional[bool]
+ do_pad: Optional[bool]
+ pad_size: Optional[dict[str, int]]
+ return_segmentation_masks: Optional[bool]
+
+
+SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
+
+
+# inspired by https://github.com/facebookresearch/yolos/blob/master/datasets/coco.py#L33
+def convert_coco_poly_to_mask(segmentations, height: int, width: int, device: torch.device) -> torch.Tensor:
+ """
+ Convert a COCO polygon annotation to a mask.
+
+ Args:
+ segmentations (`list[list[float]]`):
+ List of polygons, each polygon represented by a list of x-y coordinates.
+ height (`int`):
+ Height of the mask.
+ width (`int`):
+ Width of the mask.
+ """
+ try:
+ from pycocotools import mask as coco_mask
+ except ImportError:
+ raise ImportError("Pycocotools is not installed in your environment.")
+
+ masks = []
+ for polygons in segmentations:
+ rles = coco_mask.frPyObjects(polygons, height, width)
+ mask = coco_mask.decode(rles)
+ if len(mask.shape) < 3:
+ mask = mask[..., None]
+ mask = torch.as_tensor(mask, dtype=torch.uint8, device=device)
+ mask = torch.any(mask, axis=2)
+ masks.append(mask)
+ if masks:
+ masks = torch.stack(masks, axis=0)
+ else:
+ masks = torch.zeros((0, height, width), dtype=torch.uint8, device=device)
+
+ return masks
+
+
+# inspired by https://github.com/facebookresearch/yolos/blob/master/datasets/coco.py#L50
+def prepare_coco_detection_annotation(
+ image,
+ target,
+ return_segmentation_masks: bool = False,
+ input_data_format: Optional[Union[ChannelDimension, str]] = None,
+):
+ """
+ Convert the target in COCO format into the format expected by YOLOS.
+ """
+ image_height, image_width = image.size()[-2:]
+
+ image_id = target["image_id"]
+ image_id = torch.as_tensor([image_id], dtype=torch.int64, device=image.device)
+
+ # Get all COCO annotations for the given image.
+ annotations = target["annotations"]
+ classes = []
+ area = []
+ boxes = []
+ keypoints = []
+ for obj in annotations:
+ if "iscrowd" not in obj or obj["iscrowd"] == 0:
+ classes.append(obj["category_id"])
+ area.append(obj["area"])
+ boxes.append(obj["bbox"])
+ if "keypoints" in obj:
+ keypoints.append(obj["keypoints"])
+
+ classes = torch.as_tensor(classes, dtype=torch.int64, device=image.device)
+ area = torch.as_tensor(area, dtype=torch.float32, device=image.device)
+ iscrowd = torch.zeros_like(classes, dtype=torch.int64, device=image.device)
+ # guard against no boxes via resizing
+ boxes = torch.as_tensor(boxes, dtype=torch.float32, device=image.device).reshape(-1, 4)
+ boxes[:, 2:] += boxes[:, :2]
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
+
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
+
+ new_target = {
+ "image_id": image_id,
+ "class_labels": classes[keep],
+ "boxes": boxes[keep],
+ "area": area[keep],
+ "iscrowd": iscrowd[keep],
+ "orig_size": torch.as_tensor([int(image_height), int(image_width)], dtype=torch.int64, device=image.device),
+ }
+
+ if keypoints:
+ keypoints = torch.as_tensor(keypoints, dtype=torch.float32, device=image.device)
+ # Apply the keep mask here to filter the relevant annotations
+ keypoints = keypoints[keep]
+ num_keypoints = keypoints.shape[0]
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
+ new_target["keypoints"] = keypoints
+
+ if return_segmentation_masks:
+ segmentation_masks = [obj["segmentation"] for obj in annotations]
+ masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width, device=image.device)
+ new_target["masks"] = masks[keep]
+
+ return new_target
+
+
+def masks_to_boxes(masks: torch.Tensor) -> torch.Tensor:
+ """
+ Compute the bounding boxes around the provided panoptic segmentation masks.
+
+ Args:
+ masks: masks in format `[number_masks, height, width]` where N is the number of masks
+
+ Returns:
+ boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
+ """
+ if masks.numel() == 0:
+ return torch.zeros((0, 4), device=masks.device)
+
+ h, w = masks.shape[-2:]
+ y = torch.arange(0, h, dtype=torch.float32, device=masks.device)
+ x = torch.arange(0, w, dtype=torch.float32, device=masks.device)
+ # see https://github.com/pytorch/pytorch/issues/50276
+ y, x = torch.meshgrid(y, x, indexing="ij")
+
+ x_mask = masks * torch.unsqueeze(x, 0)
+ x_max = x_mask.view(x_mask.shape[0], -1).max(-1)[0]
+ x_min = (
+ torch.where(masks, x.unsqueeze(0), torch.tensor(1e8, device=masks.device)).view(masks.shape[0], -1).min(-1)[0]
+ )
+
+ y_mask = masks * torch.unsqueeze(y, 0)
+ y_max = y_mask.view(y_mask.shape[0], -1).max(-1)[0]
+ y_min = (
+ torch.where(masks, y.unsqueeze(0), torch.tensor(1e8, device=masks.device)).view(masks.shape[0], -1).min(-1)[0]
+ )
+
+ return torch.stack([x_min, y_min, x_max, y_max], 1)
+
+
+# 2 functions below adapted from https://github.com/cocodataset/panopticapi/blob/master/panopticapi/utils.py
+# Copyright (c) 2018, Alexander Kirillov
+# All rights reserved.
+def rgb_to_id(color):
+ """
+ Converts RGB color to unique ID.
+ """
+ if isinstance(color, torch.Tensor) and len(color.shape) == 3:
+ if color.dtype == torch.uint8:
+ color = color.to(torch.int32)
+ return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
+ return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
+
+
+def prepare_coco_panoptic_annotation(
+ image: torch.Tensor,
+ target: dict,
+ masks_path: Union[str, pathlib.Path],
+ return_masks: bool = True,
+ input_data_format: Union[ChannelDimension, str] = None,
+) -> dict:
+ """
+ Prepare a coco panoptic annotation for YOLOS.
+ """
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
+ annotation_path = pathlib.Path(masks_path) / target["file_name"]
+
+ new_target = {}
+ new_target["image_id"] = torch.as_tensor(
+ [target["image_id"] if "image_id" in target else target["id"]], dtype=torch.int64, device=image.device
+ )
+ new_target["size"] = torch.as_tensor([image_height, image_width], dtype=torch.int64, device=image.device)
+ new_target["orig_size"] = torch.as_tensor([image_height, image_width], dtype=torch.int64, device=image.device)
+
+ if "segments_info" in target:
+ masks = read_image(annotation_path).permute(1, 2, 0).to(dtype=torch.int32, device=image.device)
+ masks = rgb_to_id(masks)
+
+ ids = torch.as_tensor([segment_info["id"] for segment_info in target["segments_info"]], device=image.device)
+ masks = masks == ids[:, None, None]
+ masks = masks.to(torch.bool)
+ if return_masks:
+ new_target["masks"] = masks
+ new_target["boxes"] = masks_to_boxes(masks)
+ new_target["class_labels"] = torch.as_tensor(
+ [segment_info["category_id"] for segment_info in target["segments_info"]],
+ dtype=torch.int64,
+ device=image.device,
+ )
+ new_target["iscrowd"] = torch.as_tensor(
+ [segment_info["iscrowd"] for segment_info in target["segments_info"]],
+ dtype=torch.int64,
+ device=image.device,
+ )
+ new_target["area"] = torch.as_tensor(
+ [segment_info["area"] for segment_info in target["segments_info"]],
+ dtype=torch.float32,
+ device=image.device,
+ )
+
+ return new_target
+
+
+def get_size_with_aspect_ratio(
+ image_size: tuple[int, int], size: int, max_size: Optional[int] = None, mod_size: int = 16
+) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size with multiple of divisible_size.
+
+ Args:
+ image_size (`tuple[int, int]`):
+ The input image size.
+ size (`int`):
+ The desired output size.
+ max_size (`int`, *optional*):
+ The maximum allowed output size.
+ mod_size (`int`, *optional*):
+ The size to make multiple of mod_size.
+ """
+ height, width = image_size
+ raw_size = None
+ if max_size is not None:
+ min_original_size = float(min((height, width)))
+ max_original_size = float(max((height, width)))
+ if max_original_size / min_original_size * size > max_size:
+ raw_size = max_size * min_original_size / max_original_size
+ size = int(round(raw_size))
+
+ if width < height:
+ ow = size
+ if max_size is not None and raw_size is not None:
+ oh = int(raw_size * height / width)
+ else:
+ oh = int(size * height / width)
+ elif (height <= width and height == size) or (width <= height and width == size):
+ oh, ow = height, width
+ else:
+ oh = size
+ if max_size is not None and raw_size is not None:
+ ow = int(raw_size * width / height)
+ else:
+ ow = int(size * width / height)
+
+ if mod_size is not None:
+ ow_mod = torch.remainder(torch.tensor(ow), mod_size).item()
+ oh_mod = torch.remainder(torch.tensor(oh), mod_size).item()
+ ow = ow - ow_mod
+ oh = oh - oh_mod
+
+ return (oh, ow)
+
+
+@auto_docstring
+@requires(backends=("torchvision", "torch"))
+class YolosImageProcessorFast(BaseImageProcessorFast):
+ resample = PILImageResampling.BILINEAR
+ image_mean = IMAGENET_DEFAULT_MEAN
+ image_std = IMAGENET_DEFAULT_STD
+ format = AnnotationFormat.COCO_DETECTION
+ do_resize = True
+ do_rescale = True
+ do_normalize = True
+ do_pad = True
+ size = {"shortest_edge": 800, "longest_edge": 1333}
+ default_to_square = False
+ model_input_names = ["pixel_values", "pixel_mask"]
+ valid_kwargs = YolosFastImageProcessorKwargs
+
+ def __init__(self, **kwargs: Unpack[YolosFastImageProcessorKwargs]) -> None:
+ if "pad_and_return_pixel_mask" in kwargs:
+ kwargs["do_pad"] = kwargs.pop("pad_and_return_pixel_mask")
+
+ size = kwargs.pop("size", None)
+ if "max_size" in kwargs:
+ logger.warning_once(
+ "The `max_size` parameter is deprecated and will be removed in v4.26. "
+ "Please specify in `size['longest_edge'] instead`.",
+ )
+ max_size = kwargs.pop("max_size")
+ else:
+ max_size = None if size is None else 1333
+
+ size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
+ self.size = get_size_dict(size, max_size=max_size, default_to_square=False)
+
+ # Backwards compatibility
+ do_convert_annotations = kwargs.get("do_convert_annotations")
+ do_normalize = kwargs.get("do_normalize")
+ if do_convert_annotations is None and getattr(self, "do_convert_annotations", None) is None:
+ self.do_convert_annotations = do_normalize if do_normalize is not None else self.do_normalize
+
+ super().__init__(**kwargs)
+
+ @classmethod
+ def from_dict(cls, image_processor_dict: dict[str, Any], **kwargs):
+ """
+ Overrides the `from_dict` method from the base class to make sure parameters are updated if image processor is
+ created using from_dict and kwargs e.g. `YolosImageProcessorFast.from_pretrained(checkpoint, size=600,
+ max_size=800)`
+ """
+ image_processor_dict = image_processor_dict.copy()
+ if "max_size" in kwargs:
+ image_processor_dict["max_size"] = kwargs.pop("max_size")
+ if "pad_and_return_pixel_mask" in kwargs:
+ image_processor_dict["pad_and_return_pixel_mask"] = kwargs.pop("pad_and_return_pixel_mask")
+ return super().from_dict(image_processor_dict, **kwargs)
+
+ def prepare_annotation(
+ self,
+ image: torch.Tensor,
+ target: dict,
+ format: Optional[AnnotationFormat] = None,
+ return_segmentation_masks: Optional[bool] = None,
+ masks_path: Optional[Union[str, pathlib.Path]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ ) -> dict:
+ """
+ Prepare an annotation for feeding into YOLOS model.
+ """
+ format = format if format is not None else self.format
+
+ if format == AnnotationFormat.COCO_DETECTION:
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_detection_annotation(
+ image, target, return_segmentation_masks, input_data_format=input_data_format
+ )
+ elif format == AnnotationFormat.COCO_PANOPTIC:
+ return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
+ target = prepare_coco_panoptic_annotation(
+ image,
+ target,
+ masks_path=masks_path,
+ return_masks=return_segmentation_masks,
+ input_data_format=input_data_format,
+ )
+ else:
+ raise ValueError(f"Format {format} is not supported.")
+ return target
+
+ def resize(
+ self,
+ image: torch.Tensor,
+ size: SizeDict,
+ interpolation: "F.InterpolationMode" = None,
+ **kwargs,
+ ) -> torch.Tensor:
+ """
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
+ int, smaller edge of the image will be matched to this number.
+
+ Args:
+ image (`torch.Tensor`):
+ Image to resize.
+ size (`SizeDict`):
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
+ Do NOT keep the aspect ratio.
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
+ less or equal to `longest_edge`.
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
+ `max_width`.
+ interpolation (`InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
+ Resampling filter to use if resizing the image.
+ """
+ interpolation = interpolation if interpolation is not None else F.InterpolationMode.BILINEAR
+ if size.shortest_edge and size.longest_edge:
+ # Resize the image so that the shortest edge or the longest edge is of the given size
+ # while maintaining the aspect ratio of the original image.
+ new_size = get_size_with_aspect_ratio(
+ image.size()[-2:],
+ size["shortest_edge"],
+ size["longest_edge"],
+ )
+ elif size.max_height and size.max_width:
+ new_size = get_image_size_for_max_height_width(image.size()[-2:], size["max_height"], size["max_width"])
+ elif size.height and size.width:
+ new_size = (size["height"], size["width"])
+ else:
+ raise ValueError(
+ "Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got"
+ f" {size.keys()}."
+ )
+
+ image = F.resize(
+ image,
+ size=new_size,
+ interpolation=interpolation,
+ **kwargs,
+ )
+ return image
+
+ def resize_annotation(
+ self,
+ annotation: dict[str, Any],
+ orig_size: tuple[int, int],
+ target_size: tuple[int, int],
+ threshold: float = 0.5,
+ interpolation: "F.InterpolationMode" = None,
+ ):
+ """
+ Resizes an annotation to a target size.
+
+ Args:
+ annotation (`dict[str, Any]`):
+ The annotation dictionary.
+ orig_size (`tuple[int, int]`):
+ The original size of the input image.
+ target_size (`tuple[int, int]`):
+ The target size of the image, as returned by the preprocessing `resize` step.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The threshold used to binarize the segmentation masks.
+ resample (`InterpolationMode`, defaults to `F.InterpolationMode.NEAREST_EXACT`):
+ The resampling filter to use when resizing the masks.
+ """
+ interpolation = (
+ interpolation
+ if interpolation is not None
+ else F.InterpolationMode.NEAREST_EXACT
+ if is_torchvision_v2_available()
+ else F.InterpolationMode.NEAREST
+ )
+ ratio_height, ratio_width = [target / orig for target, orig in zip(target_size, orig_size)]
+
+ new_annotation = {}
+ new_annotation["size"] = target_size
+
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ scaled_boxes = boxes * torch.as_tensor(
+ [ratio_width, ratio_height, ratio_width, ratio_height], dtype=torch.float32, device=boxes.device
+ )
+ new_annotation["boxes"] = scaled_boxes
+ elif key == "area":
+ area = value
+ scaled_area = area * (ratio_width * ratio_height)
+ new_annotation["area"] = scaled_area
+ elif key == "masks":
+ masks = value[:, None]
+ masks = [F.resize(mask, target_size, interpolation=interpolation) for mask in masks]
+ masks = torch.stack(masks).to(torch.float32)
+ masks = masks[:, 0] > threshold
+ new_annotation["masks"] = masks
+ elif key == "size":
+ new_annotation["size"] = target_size
+ else:
+ new_annotation[key] = value
+
+ return new_annotation
+
+ def normalize_annotation(self, annotation: dict, image_size: tuple[int, int]) -> dict:
+ image_height, image_width = image_size
+ norm_annotation = {}
+ for key, value in annotation.items():
+ if key == "boxes":
+ boxes = value
+ boxes = corners_to_center_format(boxes)
+ boxes /= torch.as_tensor(
+ [image_width, image_height, image_width, image_height], dtype=torch.float32, device=boxes.device
+ )
+ norm_annotation[key] = boxes
+ else:
+ norm_annotation[key] = value
+ return norm_annotation
+
+ def _update_annotation_for_padded_image(
+ self,
+ annotation: dict,
+ input_image_size: tuple[int, int],
+ output_image_size: tuple[int, int],
+ padding,
+ update_bboxes,
+ ) -> dict:
+ """
+ Update the annotation for a padded image.
+ """
+ new_annotation = {}
+ new_annotation["size"] = output_image_size
+ ratio_height, ratio_width = (input / output for output, input in zip(output_image_size, input_image_size))
+
+ for key, value in annotation.items():
+ if key == "masks":
+ masks = value
+ masks = F.pad(
+ masks,
+ padding,
+ fill=0,
+ )
+ masks = safe_squeeze(masks, 1)
+ new_annotation["masks"] = masks
+ elif key == "boxes" and update_bboxes:
+ boxes = value
+ boxes *= torch.as_tensor([ratio_width, ratio_height, ratio_width, ratio_height], device=boxes.device)
+ new_annotation["boxes"] = boxes
+ elif key == "size":
+ new_annotation["size"] = output_image_size
+ else:
+ new_annotation[key] = value
+ return new_annotation
+
+ def pad(
+ self,
+ image: torch.Tensor,
+ padded_size: tuple[int, int],
+ annotation: Optional[dict[str, Any]] = None,
+ update_bboxes: bool = True,
+ fill: int = 0,
+ ):
+ original_size = image.size()[-2:]
+ padding_bottom = padded_size[0] - original_size[0]
+ padding_right = padded_size[1] - original_size[1]
+ if padding_bottom < 0 or padding_right < 0:
+ raise ValueError(
+ f"Padding dimensions are negative. Please make sure that the padded size is larger than the "
+ f"original size. Got padded size: {padded_size}, original size: {original_size}."
+ )
+ if original_size != padded_size:
+ padding = [0, 0, padding_right, padding_bottom]
+ image = F.pad(image, padding, fill=fill)
+ if annotation is not None:
+ annotation = self._update_annotation_for_padded_image(
+ annotation, original_size, padded_size, padding, update_bboxes
+ )
+
+ # Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
+ pixel_mask = torch.zeros(padded_size, dtype=torch.int64, device=image.device)
+ pixel_mask[: original_size[0], : original_size[1]] = 1
+
+ return image, pixel_mask, annotation
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ annotations: Optional[Union[AnnotationType, list[AnnotationType]]] = None,
+ masks_path: Optional[Union[str, pathlib.Path]] = None,
+ **kwargs: Unpack[YolosFastImageProcessorKwargs],
+ ) -> BatchFeature:
+ r"""
+ annotations (`AnnotationType` or `list[AnnotationType]`, *optional*):
+ List of annotations associated with the image or batch of images. If annotation is for object
+ detection, the annotations should be a dictionary with the following keys:
+ - "image_id" (`int`): The image id.
+ - "annotations" (`list[Dict]`): List of annotations for an image. Each annotation should be a
+ dictionary. An image can have no annotations, in which case the list should be empty.
+ If annotation is for segmentation, the annotations should be a dictionary with the following keys:
+ - "image_id" (`int`): The image id.
+ - "segments_info" (`list[Dict]`): List of segments for an image. Each segment should be a dictionary.
+ An image can have no segments, in which case the list should be empty.
+ - "file_name" (`str`): The file name of the image.
+ masks_path (`str` or `pathlib.Path`, *optional*):
+ Path to the directory containing the segmentation masks.
+ """
+ if "pad_and_return_pixel_mask" in kwargs:
+ kwargs["do_pad"] = kwargs.pop("pad_and_return_pixel_mask")
+ logger.warning_once(
+ "The `pad_and_return_pixel_mask` argument is deprecated and will be removed in a future version, "
+ "use `do_pad` instead."
+ )
+
+ if "max_size" in kwargs:
+ logger.warning_once(
+ "The `max_size` argument is deprecated and will be removed in a future version, use"
+ " `size['longest_edge']` instead."
+ )
+ kwargs["size"] = kwargs.pop("max_size")
+
+ return super().preprocess(images, annotations, masks_path, **kwargs)
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ annotations: Optional[Union[AnnotationType, list[AnnotationType]]],
+ masks_path: Optional[Union[str, pathlib.Path]],
+ return_segmentation_masks: bool,
+ do_resize: bool,
+ size: SizeDict,
+ interpolation: Optional["F.InterpolationMode"],
+ do_rescale: bool,
+ rescale_factor: float,
+ do_normalize: bool,
+ do_convert_annotations: bool,
+ image_mean: Optional[Union[float, list[float]]],
+ image_std: Optional[Union[float, list[float]]],
+ do_pad: bool,
+ pad_size: Optional[dict[str, int]],
+ format: Optional[Union[str, AnnotationFormat]],
+ return_tensors: Optional[Union[str, TensorType]],
+ **kwargs,
+ ) -> BatchFeature:
+ """
+ Preprocess an image or a batch of images so that it can be used by the model.
+ """
+ if annotations is not None and isinstance(annotations, dict):
+ annotations = [annotations]
+
+ if annotations is not None and len(images) != len(annotations):
+ raise ValueError(
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
+ )
+
+ format = AnnotationFormat(format)
+ if annotations is not None:
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
+
+ if (
+ masks_path is not None
+ and format == AnnotationFormat.COCO_PANOPTIC
+ and not isinstance(masks_path, (pathlib.Path, str))
+ ):
+ raise ValueError(
+ "The path to the directory containing the mask PNG files should be provided as a"
+ f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
+ )
+
+ data = {}
+
+ processed_images = []
+ processed_annotations = []
+ pixel_masks = [] # Initialize pixel_masks here
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # prepare (COCO annotations as a list of Dict -> YOLOS target as a single Dict per image)
+ if annotations is not None:
+ annotation = self.prepare_annotation(
+ image,
+ annotation,
+ format,
+ return_segmentation_masks=return_segmentation_masks,
+ masks_path=masks_path,
+ input_data_format=ChannelDimension.FIRST,
+ )
+
+ if do_resize:
+ resized_image = self.resize(image, size=size, interpolation=interpolation)
+ if annotations is not None:
+ annotation = self.resize_annotation(
+ annotation,
+ orig_size=image.size()[-2:],
+ target_size=resized_image.size()[-2:],
+ )
+ image = resized_image
+ # Fused rescale and normalize
+ image = self.rescale_and_normalize(image, do_rescale, rescale_factor, do_normalize, image_mean, image_std)
+ if do_convert_annotations and annotations is not None:
+ annotation = self.normalize_annotation(annotation, get_image_size(image, ChannelDimension.FIRST))
+
+ processed_images.append(image)
+ processed_annotations.append(annotation)
+ images = processed_images
+ annotations = processed_annotations if annotations is not None else None
+
+ if do_pad:
+ # depends on all resized image shapes so we need another loop
+ if pad_size is not None:
+ padded_size = (pad_size["height"], pad_size["width"])
+ else:
+ padded_size = get_max_height_width(images)
+
+ padded_images = []
+ padded_annotations = []
+ for image, annotation in zip(images, annotations if annotations is not None else [None] * len(images)):
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
+ if padded_size == image.size()[-2:]:
+ padded_images.append(image)
+ pixel_masks.append(torch.ones(padded_size, dtype=torch.int64, device=image.device))
+ padded_annotations.append(annotation)
+ continue
+ image, pixel_mask, annotation = self.pad(
+ image, padded_size, annotation=annotation, update_bboxes=do_convert_annotations
+ )
+ padded_images.append(image)
+ padded_annotations.append(annotation)
+ pixel_masks.append(pixel_mask)
+ images = padded_images
+ annotations = padded_annotations if annotations is not None else None
+ data.update({"pixel_mask": torch.stack(pixel_masks, dim=0)})
+
+ data.update({"pixel_values": torch.stack(images, dim=0)})
+ encoded_inputs = BatchFeature(data, tensor_type=return_tensors)
+ if annotations is not None:
+ encoded_inputs["labels"] = [
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
+ ]
+ return encoded_inputs
+
+ def post_process(self, outputs, target_sizes):
+ """
+ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x,
+ top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`YolosObjectDetectionOutput`]):
+ Raw outputs of the model.
+ target_sizes (`torch.Tensor` of shape `(batch_size, 2)`):
+ Tensor containing the size (height, width) of each image of the batch. For evaluation, this must be the
+ original image size (before any data augmentation). For visualization, this should be the image size
+ after data augment, but before padding.
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ logger.warning_once(
+ "`post_process` is deprecated and will be removed in v5 of Transformers, please use"
+ " `post_process_object_detection` instead, with `threshold=0.` for equivalent results.",
+ )
+
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if len(out_logits) != len(target_sizes):
+ raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the logits")
+ if target_sizes.shape[1] != 2:
+ raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch")
+
+ prob = out_logits.sigmoid()
+ topk_values, topk_indexes = torch.topk(prob.view(out_logits.shape[0], -1), 100, dim=1)
+ scores = topk_values
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
+ labels = topk_indexes % out_logits.shape[2]
+ boxes = center_to_corners_format(out_bbox)
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
+
+ # and from relative [0, 1] to absolute [0, height] coordinates
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = [{"scores": s, "labels": l, "boxes": b} for s, l, b in zip(scores, labels, boxes)]
+
+ return results
+
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: Union[TensorType, list[tuple]] = None, top_k: int = 100
+ ):
+ """
+ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x,
+ top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`YolosObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ top_k (`int`, *optional*, defaults to 100):
+ Keep only top k bounding boxes before filtering by thresholding.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = out_logits.sigmoid()
+ prob = prob.view(out_logits.shape[0], -1)
+ k_value = min(top_k, prob.size(1))
+ topk_values, topk_indexes = torch.topk(prob, k_value, dim=1)
+ scores = topk_values
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
+ labels = topk_indexes % out_logits.shape[2]
+ boxes = center_to_corners_format(out_bbox)
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
+
+ # and from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+
+__all__ = ["YolosImageProcessorFast"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/modeling_yolos.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/modeling_yolos.py
new file mode 100644
index 0000000000000000000000000000000000000000..2571cf82733d700cea595bb6fd7710f286358dd8
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/modeling_yolos.py
@@ -0,0 +1,705 @@
+# coding=utf-8
+# Copyright 2022 School of EIC, Huazhong University of Science & Technology and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch YOLOS model."""
+
+import collections.abc
+from dataclasses import dataclass
+from typing import Callable, Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+
+from ...activations import ACT2FN
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring, logging
+from ...utils.generic import can_return_tuple, check_model_inputs
+from .configuration_yolos import YolosConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Output type of [`YolosForObjectDetection`].
+ """
+)
+class YolosObjectDetectionOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` are provided)):
+ Total loss as a linear combination of a negative log-likehood (cross-entropy) for class prediction and a
+ bounding box loss. The latter is defined as a linear combination of the L1 loss and the generalized
+ scale-invariant IoU loss.
+ loss_dict (`Dict`, *optional*):
+ A dictionary containing the individual losses. Useful for logging.
+ logits (`torch.FloatTensor` of shape `(batch_size, num_queries, num_classes + 1)`):
+ Classification logits (including no-object) for all queries.
+ pred_boxes (`torch.FloatTensor` of shape `(batch_size, num_queries, 4)`):
+ Normalized boxes coordinates for all queries, represented as (center_x, center_y, width, height). These
+ values are normalized in [0, 1], relative to the size of each individual image in the batch (disregarding
+ possible padding). You can use [`~YolosImageProcessor.post_process`] to retrieve the unnormalized bounding
+ boxes.
+ auxiliary_outputs (`list[Dict]`, *optional*):
+ Optional, only returned when auxiliary losses are activated (i.e. `config.auxiliary_loss` is set to `True`)
+ and labels are provided. It is a list of dictionaries containing the two above keys (`logits` and
+ `pred_boxes`) for each decoder layer.
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
+ Sequence of hidden-states at the output of the last layer of the decoder of the model.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ loss_dict: Optional[dict] = None
+ logits: Optional[torch.FloatTensor] = None
+ pred_boxes: Optional[torch.FloatTensor] = None
+ auxiliary_outputs: Optional[list[dict]] = None
+ last_hidden_state: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor]] = None
+ attentions: Optional[tuple[torch.FloatTensor]] = None
+
+
+class YolosEmbeddings(nn.Module):
+ """
+ Construct the CLS token, detection tokens, position and patch embeddings.
+
+ """
+
+ def __init__(self, config: YolosConfig) -> None:
+ super().__init__()
+
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
+ self.detection_tokens = nn.Parameter(torch.zeros(1, config.num_detection_tokens, config.hidden_size))
+ self.patch_embeddings = YolosPatchEmbeddings(config)
+ num_patches = self.patch_embeddings.num_patches
+ self.position_embeddings = nn.Parameter(
+ torch.zeros(1, num_patches + config.num_detection_tokens + 1, config.hidden_size)
+ )
+
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.interpolation = InterpolateInitialPositionEmbeddings(config)
+ self.config = config
+
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, height, width = pixel_values.shape
+ embeddings = self.patch_embeddings(pixel_values)
+
+ batch_size, seq_len, _ = embeddings.size()
+
+ # add the [CLS] and detection tokens to the embedded patch tokens
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
+ detection_tokens = self.detection_tokens.expand(batch_size, -1, -1)
+ embeddings = torch.cat((cls_tokens, embeddings, detection_tokens), dim=1)
+
+ # add positional encoding to each token
+ # this might require interpolation of the existing position embeddings
+ position_embeddings = self.interpolation(self.position_embeddings, (height, width))
+
+ embeddings = embeddings + position_embeddings
+ embeddings = self.dropout(embeddings)
+
+ return embeddings
+
+
+class InterpolateInitialPositionEmbeddings(nn.Module):
+ def __init__(self, config) -> None:
+ super().__init__()
+ self.config = config
+
+ def forward(self, pos_embed, img_size=(800, 1344)) -> torch.Tensor:
+ cls_pos_embed = pos_embed[:, 0, :]
+ cls_pos_embed = cls_pos_embed[:, None]
+ det_pos_embed = pos_embed[:, -self.config.num_detection_tokens :, :]
+ patch_pos_embed = pos_embed[:, 1 : -self.config.num_detection_tokens, :]
+ patch_pos_embed = patch_pos_embed.transpose(1, 2)
+ batch_size, hidden_size, seq_len = patch_pos_embed.shape
+
+ patch_height, patch_width = (
+ self.config.image_size[0] // self.config.patch_size,
+ self.config.image_size[1] // self.config.patch_size,
+ )
+ patch_pos_embed = patch_pos_embed.view(batch_size, hidden_size, patch_height, patch_width)
+
+ height, width = img_size
+ new_patch_height, new_patch_width = height // self.config.patch_size, width // self.config.patch_size
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed, size=(new_patch_height, new_patch_width), mode="bicubic", align_corners=False
+ )
+ patch_pos_embed = patch_pos_embed.flatten(2).transpose(1, 2)
+ scale_pos_embed = torch.cat((cls_pos_embed, patch_pos_embed, det_pos_embed), dim=1)
+ return scale_pos_embed
+
+
+class InterpolateMidPositionEmbeddings(nn.Module):
+ def __init__(self, config) -> None:
+ super().__init__()
+ self.config = config
+
+ def forward(self, pos_embed, img_size=(800, 1344)) -> torch.Tensor:
+ cls_pos_embed = pos_embed[:, :, 0, :]
+ cls_pos_embed = cls_pos_embed[:, None]
+ det_pos_embed = pos_embed[:, :, -self.config.num_detection_tokens :, :]
+ patch_pos_embed = pos_embed[:, :, 1 : -self.config.num_detection_tokens, :]
+ patch_pos_embed = patch_pos_embed.transpose(2, 3)
+ depth, batch_size, hidden_size, seq_len = patch_pos_embed.shape
+
+ patch_height, patch_width = (
+ self.config.image_size[0] // self.config.patch_size,
+ self.config.image_size[1] // self.config.patch_size,
+ )
+ patch_pos_embed = patch_pos_embed.view(depth * batch_size, hidden_size, patch_height, patch_width)
+ height, width = img_size
+ new_patch_height, new_patch_width = height // self.config.patch_size, width // self.config.patch_size
+ patch_pos_embed = nn.functional.interpolate(
+ patch_pos_embed, size=(new_patch_height, new_patch_width), mode="bicubic", align_corners=False
+ )
+ patch_pos_embed = (
+ patch_pos_embed.flatten(2)
+ .transpose(1, 2)
+ .contiguous()
+ .view(depth, batch_size, new_patch_height * new_patch_width, hidden_size)
+ )
+ scale_pos_embed = torch.cat((cls_pos_embed, patch_pos_embed, det_pos_embed), dim=2)
+ return scale_pos_embed
+
+
+class YolosPatchEmbeddings(nn.Module):
+ """
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
+ Transformer.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+ image_size, patch_size = config.image_size, config.patch_size
+ num_channels, hidden_size = config.num_channels, config.hidden_size
+
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
+ self.image_size = image_size
+ self.patch_size = patch_size
+ self.num_channels = num_channels
+ self.num_patches = num_patches
+
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
+
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, height, width = pixel_values.shape
+ if num_channels != self.num_channels:
+ raise ValueError(
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
+ )
+
+ embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
+ return embeddings
+
+
+# Copied from transformers.models.vit.modeling_vit.eager_attention_forward
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
+
+ # Normalize the attention scores to probabilities.
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+
+ # Mask heads if we want to
+ if attention_mask is not None:
+ attn_weights = attn_weights * attention_mask
+
+ attn_output = torch.matmul(attn_weights, value)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.vit.modeling_vit.ViTSelfAttention with ViT->Yolos
+class YolosSelfAttention(nn.Module):
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size {config.hidden_size} is not a multiple of the number of attention "
+ f"heads {config.num_attention_heads}."
+ )
+
+ self.config = config
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+ self.dropout_prob = config.attention_probs_dropout_prob
+ self.scaling = self.attention_head_size**-0.5
+ self.is_causal = False
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
+
+ def forward(
+ self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ batch_size = hidden_states.shape[0]
+ new_shape = batch_size, -1, self.num_attention_heads, self.attention_head_size
+
+ key_layer = self.key(hidden_states).view(*new_shape).transpose(1, 2)
+ value_layer = self.value(hidden_states).view(*new_shape).transpose(1, 2)
+ query_layer = self.query(hidden_states).view(*new_shape).transpose(1, 2)
+
+ attention_interface: Callable = eager_attention_forward
+ if self.config._attn_implementation != "eager":
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
+
+ context_layer, attention_probs = attention_interface(
+ self,
+ query_layer,
+ key_layer,
+ value_layer,
+ head_mask,
+ is_causal=self.is_causal,
+ scaling=self.scaling,
+ dropout=0.0 if not self.training else self.dropout_prob,
+ )
+
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.reshape(new_context_layer_shape)
+
+ return context_layer, attention_probs
+
+
+# Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->Yolos
+class YolosSelfOutput(nn.Module):
+ """
+ The residual connection is defined in YolosLayer instead of here (as is the case with other models), due to the
+ layernorm applied before each block.
+ """
+
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.vit.modeling_vit.ViTAttention with ViT->Yolos
+class YolosAttention(nn.Module):
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.attention = YolosSelfAttention(config)
+ self.output = YolosSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads: set[int]):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.attention.query = prune_linear_layer(self.attention.query, index)
+ self.attention.key = prune_linear_layer(self.attention.key, index)
+ self.attention.value = prune_linear_layer(self.attention.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ def forward(self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
+ self_attn_output, _ = self.attention(hidden_states, head_mask)
+ output = self.output(self_attn_output, hidden_states)
+ return output
+
+
+# Copied from transformers.models.vit.modeling_vit.ViTIntermediate with ViT->Yolos
+class YolosIntermediate(nn.Module):
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.vit.modeling_vit.ViTOutput with ViT->Yolos
+class YolosOutput(nn.Module):
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = hidden_states + input_tensor
+ return hidden_states
+
+
+# Copied from transformers.models.vit.modeling_vit.ViTLayer with ViT->Yolos,VIT->YOLOS
+class YolosLayer(GradientCheckpointingLayer):
+ """This corresponds to the Block class in the timm implementation."""
+
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = YolosAttention(config)
+ self.intermediate = YolosIntermediate(config)
+ self.output = YolosOutput(config)
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states: torch.Tensor, head_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
+ hidden_states_norm = self.layernorm_before(hidden_states)
+ attention_output = self.attention(hidden_states_norm, head_mask)
+
+ # first residual connection
+ hidden_states = attention_output + hidden_states
+
+ # in Yolos, layernorm is also applied after self-attention
+ layer_output = self.layernorm_after(hidden_states)
+ layer_output = self.intermediate(layer_output)
+
+ # second residual connection is done here
+ layer_output = self.output(layer_output, hidden_states)
+
+ return layer_output
+
+
+class YolosEncoder(nn.Module):
+ def __init__(self, config: YolosConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([YolosLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ seq_length = (
+ 1 + (config.image_size[0] * config.image_size[1] // config.patch_size**2) + config.num_detection_tokens
+ )
+ self.mid_position_embeddings = (
+ nn.Parameter(
+ torch.zeros(
+ config.num_hidden_layers - 1,
+ 1,
+ seq_length,
+ config.hidden_size,
+ )
+ )
+ if config.use_mid_position_embeddings
+ else None
+ )
+
+ self.interpolation = InterpolateMidPositionEmbeddings(config) if config.use_mid_position_embeddings else None
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ height: int,
+ width: int,
+ head_mask: Optional[torch.Tensor] = None,
+ ) -> BaseModelOutput:
+ if self.config.use_mid_position_embeddings:
+ interpolated_mid_position_embeddings = self.interpolation(self.mid_position_embeddings, (height, width))
+
+ for i, layer_module in enumerate(self.layer):
+ layer_head_mask = head_mask[i] if head_mask is not None else None
+ hidden_states = layer_module(hidden_states, layer_head_mask)
+
+ if self.config.use_mid_position_embeddings:
+ if i < (self.config.num_hidden_layers - 1):
+ hidden_states = hidden_states + interpolated_mid_position_embeddings[i]
+
+ return BaseModelOutput(last_hidden_state=hidden_states)
+
+
+@auto_docstring
+class YolosPreTrainedModel(PreTrainedModel):
+ config: YolosConfig
+ base_model_prefix = "vit"
+ main_input_name = "pixel_values"
+ supports_gradient_checkpointing = True
+ _no_split_modules = []
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": YolosLayer,
+ "attentions": YolosSelfAttention,
+ }
+
+ def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
+ """Initialize the weights"""
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+@auto_docstring
+class YolosModel(YolosPreTrainedModel):
+ def __init__(self, config: YolosConfig, add_pooling_layer: bool = True):
+ r"""
+ add_pooling_layer (bool, *optional*, defaults to `True`):
+ Whether to add a pooling layer
+ """
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = YolosEmbeddings(config)
+ self.encoder = YolosEncoder(config)
+
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.pooler = YolosPooler(config) if add_pooling_layer else None
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> YolosPatchEmbeddings:
+ return self.embeddings.patch_embeddings
+
+ def _prune_heads(self, heads_to_prune: dict[int, list[int]]) -> None:
+ """
+ Prunes heads of the model.
+
+ Args:
+ heads_to_prune (`dict`):
+ See base class `PreTrainedModel`. The input dictionary must have the following format: {layer_num:
+ list of heads to prune in this layer}
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ @check_model_inputs
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPooling:
+ if pixel_values is None:
+ raise ValueError("You have to specify pixel_values")
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ embedding_output = self.embeddings(pixel_values)
+
+ height, width = pixel_values.shape[-2:]
+ encoder_outputs: BaseModelOutput = self.encoder(
+ embedding_output, height=height, width=width, head_mask=head_mask
+ )
+ sequence_output = encoder_outputs.last_hidden_state
+ sequence_output = self.layernorm(sequence_output)
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ return BaseModelOutputWithPooling(last_hidden_state=sequence_output, pooler_output=pooled_output)
+
+
+class YolosPooler(nn.Module):
+ def __init__(self, config: YolosConfig):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.activation = nn.Tanh()
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ # We "pool" the model by simply taking the hidden state corresponding
+ # to the first token.
+ first_token_tensor = hidden_states[:, 0]
+ pooled_output = self.dense(first_token_tensor)
+ pooled_output = self.activation(pooled_output)
+ return pooled_output
+
+
+# Copied from transformers.models.detr.modeling_detr.DetrMLPPredictionHead with Detr->Yolos
+class YolosMLPPredictionHead(nn.Module):
+ """
+ Very simple multi-layer perceptron (MLP, also called FFN), used to predict the normalized center coordinates,
+ height and width of a bounding box w.r.t. an image.
+
+ Copied from https://github.com/facebookresearch/detr/blob/master/models/detr.py
+
+ """
+
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]))
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = nn.functional.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ YOLOS Model (consisting of a ViT encoder) with object detection heads on top, for tasks such as COCO detection.
+ """
+)
+class YolosForObjectDetection(YolosPreTrainedModel):
+ def __init__(self, config: YolosConfig):
+ super().__init__(config)
+
+ # YOLOS (ViT) encoder model
+ self.vit = YolosModel(config, add_pooling_layer=False)
+
+ # Object detection heads
+ # We add one for the "no object" class
+ self.class_labels_classifier = YolosMLPPredictionHead(
+ input_dim=config.hidden_size, hidden_dim=config.hidden_size, output_dim=config.num_labels + 1, num_layers=3
+ )
+ self.bbox_predictor = YolosMLPPredictionHead(
+ input_dim=config.hidden_size, hidden_dim=config.hidden_size, output_dim=4, num_layers=3
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ # taken from https://github.com/facebookresearch/detr/blob/master/models/detr.py
+ @torch.jit.unused
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ # this is a workaround to make torchscript happy, as torchscript
+ # doesn't support dictionary with non-homogeneous values, such
+ # as a dict having both a Tensor and a list.
+ return [{"logits": a, "pred_boxes": b} for a, b in zip(outputs_class[:-1], outputs_coord[:-1])]
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ labels: Optional[list[dict]] = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> YolosObjectDetectionOutput:
+ r"""
+ labels (`list[Dict]` of len `(batch_size,)`, *optional*):
+ Labels for computing the bipartite matching loss. List of dicts, each dictionary containing at least the
+ following 2 keys: `'class_labels'` and `'boxes'` (the class labels and bounding boxes of an image in the
+ batch respectively). The class labels themselves should be a `torch.LongTensor` of len `(number of bounding
+ boxes in the image,)` and the boxes a `torch.FloatTensor` of shape `(number of bounding boxes in the image,
+ 4)`.
+
+ Examples:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, AutoModelForObjectDetection
+ >>> import torch
+ >>> from PIL import Image
+ >>> import requests
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("hustvl/yolos-tiny")
+ >>> model = AutoModelForObjectDetection.from_pretrained("hustvl/yolos-tiny")
+
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> # convert outputs (bounding boxes and class logits) to Pascal VOC format (xmin, ymin, xmax, ymax)
+ >>> target_sizes = torch.tensor([image.size[::-1]])
+ >>> results = image_processor.post_process_object_detection(outputs, threshold=0.9, target_sizes=target_sizes)[
+ ... 0
+ ... ]
+
+ >>> for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
+ ... box = [round(i, 2) for i in box.tolist()]
+ ... print(
+ ... f"Detected {model.config.id2label[label.item()]} with confidence "
+ ... f"{round(score.item(), 3)} at location {box}"
+ ... )
+ Detected remote with confidence 0.991 at location [46.48, 72.78, 178.98, 119.3]
+ Detected remote with confidence 0.908 at location [336.48, 79.27, 368.23, 192.36]
+ Detected cat with confidence 0.934 at location [337.18, 18.06, 638.14, 373.09]
+ Detected cat with confidence 0.979 at location [10.93, 53.74, 313.41, 470.67]
+ Detected remote with confidence 0.974 at location [41.63, 72.23, 178.09, 119.99]
+ ```"""
+
+ # First, sent images through YOLOS base model to obtain hidden states
+ outputs: BaseModelOutputWithPooling = self.vit(pixel_values, **kwargs)
+ sequence_output = outputs.last_hidden_state
+
+ # Take the final hidden states of the detection tokens
+ sequence_output = sequence_output[:, -self.config.num_detection_tokens :, :]
+
+ # Class logits + predicted bounding boxes
+ logits = self.class_labels_classifier(sequence_output)
+ pred_boxes = self.bbox_predictor(sequence_output).sigmoid()
+
+ loss, loss_dict, auxiliary_outputs = None, None, None
+ if labels is not None:
+ outputs_class, outputs_coord = None, None
+ if self.config.auxiliary_loss:
+ intermediate = outputs.hidden_states
+ outputs_class = self.class_labels_classifier(intermediate)
+ outputs_coord = self.bbox_predictor(intermediate).sigmoid()
+ loss, loss_dict, auxiliary_outputs = self.loss_function(
+ logits, labels, self.device, pred_boxes, self.config, outputs_class, outputs_coord
+ )
+
+ return YolosObjectDetectionOutput(
+ loss=loss,
+ loss_dict=loss_dict,
+ logits=logits,
+ pred_boxes=pred_boxes,
+ auxiliary_outputs=auxiliary_outputs,
+ last_hidden_state=outputs.last_hidden_state,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["YolosForObjectDetection", "YolosModel", "YolosPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/modular_yolos.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/modular_yolos.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5fec1ba80ddcf1efeb80739fa960baa91c0ba88
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yolos/modular_yolos.py
@@ -0,0 +1,193 @@
+from typing import Optional, Union
+
+from transformers.models.detr.image_processing_detr_fast import DetrImageProcessorFast
+
+from ...image_transforms import center_to_corners_format
+from ...utils import (
+ TensorType,
+ is_torch_available,
+ logging,
+)
+
+
+if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+
+
+def get_size_with_aspect_ratio(
+ image_size: tuple[int, int], size: int, max_size: Optional[int] = None, mod_size: int = 16
+) -> tuple[int, int]:
+ """
+ Computes the output image size given the input image size and the desired output size with multiple of divisible_size.
+
+ Args:
+ image_size (`tuple[int, int]`):
+ The input image size.
+ size (`int`):
+ The desired output size.
+ max_size (`int`, *optional*):
+ The maximum allowed output size.
+ mod_size (`int`, *optional*):
+ The size to make multiple of mod_size.
+ """
+ height, width = image_size
+ raw_size = None
+ if max_size is not None:
+ min_original_size = float(min((height, width)))
+ max_original_size = float(max((height, width)))
+ if max_original_size / min_original_size * size > max_size:
+ raw_size = max_size * min_original_size / max_original_size
+ size = int(round(raw_size))
+
+ if width < height:
+ ow = size
+ if max_size is not None and raw_size is not None:
+ oh = int(raw_size * height / width)
+ else:
+ oh = int(size * height / width)
+ elif (height <= width and height == size) or (width <= height and width == size):
+ oh, ow = height, width
+ else:
+ oh = size
+ if max_size is not None and raw_size is not None:
+ ow = int(raw_size * width / height)
+ else:
+ ow = int(size * width / height)
+
+ if mod_size is not None:
+ ow_mod = torch.remainder(torch.tensor(ow), mod_size).item()
+ oh_mod = torch.remainder(torch.tensor(oh), mod_size).item()
+ ow = ow - ow_mod
+ oh = oh - oh_mod
+
+ return (oh, ow)
+
+
+class YolosImageProcessorFast(DetrImageProcessorFast):
+ def post_process(self, outputs, target_sizes):
+ """
+ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x,
+ top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`YolosObjectDetectionOutput`]):
+ Raw outputs of the model.
+ target_sizes (`torch.Tensor` of shape `(batch_size, 2)`):
+ Tensor containing the size (height, width) of each image of the batch. For evaluation, this must be the
+ original image size (before any data augmentation). For visualization, this should be the image size
+ after data augment, but before padding.
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ logger.warning_once(
+ "`post_process` is deprecated and will be removed in v5 of Transformers, please use"
+ " `post_process_object_detection` instead, with `threshold=0.` for equivalent results.",
+ )
+
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if len(out_logits) != len(target_sizes):
+ raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the logits")
+ if target_sizes.shape[1] != 2:
+ raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch")
+
+ prob = out_logits.sigmoid()
+ topk_values, topk_indexes = torch.topk(prob.view(out_logits.shape[0], -1), 100, dim=1)
+ scores = topk_values
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
+ labels = topk_indexes % out_logits.shape[2]
+ boxes = center_to_corners_format(out_bbox)
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
+
+ # and from relative [0, 1] to absolute [0, height] coordinates
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = [{"scores": s, "labels": l, "boxes": b} for s, l, b in zip(scores, labels, boxes)]
+
+ return results
+
+ def post_process_object_detection(
+ self, outputs, threshold: float = 0.5, target_sizes: Union[TensorType, list[tuple]] = None, top_k: int = 100
+ ):
+ """
+ Converts the raw output of [`YolosForObjectDetection`] into final bounding boxes in (top_left_x,
+ top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
+
+ Args:
+ outputs ([`YolosObjectDetectionOutput`]):
+ Raw outputs of the model.
+ threshold (`float`, *optional*):
+ Score threshold to keep object detection predictions.
+ target_sizes (`torch.Tensor` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ top_k (`int`, *optional*, defaults to 100):
+ Keep only top k bounding boxes before filtering by thresholding.
+
+ Returns:
+ `list[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
+ in the batch as predicted by the model.
+ """
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
+
+ if target_sizes is not None:
+ if len(out_logits) != len(target_sizes):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
+ )
+
+ prob = out_logits.sigmoid()
+ prob = prob.view(out_logits.shape[0], -1)
+ k_value = min(top_k, prob.size(1))
+ topk_values, topk_indexes = torch.topk(prob, k_value, dim=1)
+ scores = topk_values
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
+ labels = topk_indexes % out_logits.shape[2]
+ boxes = center_to_corners_format(out_bbox)
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
+
+ # and from relative [0, 1] to absolute [0, height] coordinates
+ if target_sizes is not None:
+ if isinstance(target_sizes, list):
+ img_h = torch.Tensor([i[0] for i in target_sizes])
+ img_w = torch.Tensor([i[1] for i in target_sizes])
+ else:
+ img_h, img_w = target_sizes.unbind(1)
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
+ boxes = boxes * scale_fct[:, None, :]
+
+ results = []
+ for s, l, b in zip(scores, labels, boxes):
+ score = s[s > threshold]
+ label = l[s > threshold]
+ box = b[s > threshold]
+ results.append({"scores": score, "labels": label, "boxes": box})
+
+ return results
+
+ def post_process_segmentation():
+ raise NotImplementedError("Segmentation post-processing is not implemented for Deformable DETR yet.")
+
+ def post_process_instance():
+ raise NotImplementedError("Instance post-processing is not implemented for Deformable DETR yet.")
+
+ def post_process_panoptic():
+ raise NotImplementedError("Panoptic post-processing is not implemented for Deformable DETR yet.")
+
+ def post_process_instance_segmentation():
+ raise NotImplementedError("Segmentation post-processing is not implemented for Deformable DETR yet.")
+
+ def post_process_semantic_segmentation():
+ raise NotImplementedError("Semantic segmentation post-processing is not implemented for Deformable DETR yet.")
+
+ def post_process_panoptic_segmentation():
+ raise NotImplementedError("Panoptic segmentation post-processing is not implemented for Deformable DETR yet.")
+
+
+__all__ = ["YolosImageProcessorFast"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yoso/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yoso/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b865cb93ce1134a1a8761bafd1b3498931d7c83
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yoso/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_yoso import *
+ from .modeling_yoso import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yoso/configuration_yoso.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yoso/configuration_yoso.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a7fb1218e402e36f6275f81783e00cc79c36a8d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yoso/configuration_yoso.py
@@ -0,0 +1,144 @@
+# coding=utf-8
+# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""YOSO model configuration"""
+
+from ...configuration_utils import PretrainedConfig
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class YosoConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`YosoModel`]. It is used to instantiate an YOSO
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the YOSO
+ [uw-madison/yoso-4096](https://huggingface.co/uw-madison/yoso-4096) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 50265):
+ Vocabulary size of the YOSO model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`YosoModel`].
+ hidden_size (`int`, *optional*, defaults to 768):
+ Dimension of the encoder layers and the pooler layer.
+ num_hidden_layers (`int`, *optional*, defaults to 12):
+ Number of hidden layers in the Transformer encoder.
+ num_attention_heads (`int`, *optional*, defaults to 12):
+ Number of attention heads for each attention layer in the Transformer encoder.
+ intermediate_size (`int`, *optional*, defaults to 3072):
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
+ The dropout ratio for the attention probabilities.
+ max_position_embeddings (`int`, *optional*, defaults to 512):
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
+ just in case (e.g., 512 or 1024 or 2048).
+ type_vocab_size (`int`, *optional*, defaults to 2):
+ The vocabulary size of the `token_type_ids` passed when calling [`YosoModel`].
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
+ The epsilon used by the layer normalization layers.
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`.
+ use_expectation (`bool`, *optional*, defaults to `True`):
+ Whether or not to use YOSO Expectation. Overrides any effect of num_hash.
+ hash_code_len (`int`, *optional*, defaults to 9):
+ The length of hashes generated by the hash functions.
+ num_hash (`int`, *optional*, defaults to 64):
+ Number of hash functions used in [`YosoSelfAttention`].
+ conv_window (`int`, *optional*):
+ Kernel size of depth-wise convolution.
+ use_fast_hash (`bool`, *optional*, defaults to `False`):
+ Whether or not to use custom cuda kernels which perform fast random projection via hadamard transform.
+ lsh_backward (`bool`, *optional*, defaults to `True`):
+ Whether or not to perform backpropagation using Locality Sensitive Hashing.
+
+ Example:
+
+ ```python
+ >>> from transformers import YosoConfig, YosoModel
+
+ >>> # Initializing a YOSO uw-madison/yoso-4096 style configuration
+ >>> configuration = YosoConfig()
+
+ >>> # Initializing a model (with random weights) from the uw-madison/yoso-4096 style configuration
+ >>> model = YosoModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "yoso"
+
+ def __init__(
+ self,
+ vocab_size=50265,
+ hidden_size=768,
+ num_hidden_layers=12,
+ num_attention_heads=12,
+ intermediate_size=3072,
+ hidden_act="gelu",
+ hidden_dropout_prob=0.1,
+ attention_probs_dropout_prob=0.1,
+ max_position_embeddings=4096,
+ type_vocab_size=1,
+ initializer_range=0.02,
+ layer_norm_eps=1e-12,
+ position_embedding_type="absolute",
+ use_expectation=True,
+ hash_code_len=9,
+ num_hash=64,
+ conv_window=None,
+ use_fast_hash=True,
+ lsh_backward=True,
+ pad_token_id=1,
+ bos_token_id=0,
+ eos_token_id=2,
+ **kwargs,
+ ):
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
+
+ self.vocab_size = vocab_size
+ self.max_position_embeddings = max_position_embeddings
+ self.hidden_size = hidden_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.hidden_dropout_prob = hidden_dropout_prob
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
+ self.initializer_range = initializer_range
+ self.type_vocab_size = type_vocab_size
+ self.layer_norm_eps = layer_norm_eps
+ self.position_embedding_type = position_embedding_type
+ self.use_expectation = use_expectation
+ self.hash_code_len = hash_code_len
+ self.num_hash = num_hash
+ self.conv_window = conv_window
+ self.use_fast_hash = use_fast_hash
+ self.lsh_backward = lsh_backward
+
+
+__all__ = ["YosoConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yoso/modeling_yoso.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yoso/modeling_yoso.py
new file mode 100644
index 0000000000000000000000000000000000000000..221ebaa637feec1e4428085ca11fa204c722c7f6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/yoso/modeling_yoso.py
@@ -0,0 +1,1222 @@
+# coding=utf-8
+# Copyright 2022 University of Wisconsin-Madison and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch YOSO model."""
+
+import math
+from pathlib import Path
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import ACT2FN
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import (
+ BaseModelOutputWithCrossAttentions,
+ MaskedLMOutput,
+ MultipleChoiceModelOutput,
+ QuestionAnsweringModelOutput,
+ SequenceClassifierOutput,
+ TokenClassifierOutput,
+)
+from ...modeling_utils import PreTrainedModel
+from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
+from ...utils import (
+ auto_docstring,
+ is_ninja_available,
+ is_torch_cuda_available,
+ logging,
+)
+from .configuration_yoso import YosoConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+lsh_cumulation = None
+
+
+def load_cuda_kernels():
+ global lsh_cumulation
+ from torch.utils.cpp_extension import load
+
+ def append_root(files):
+ src_folder = Path(__file__).resolve().parent.parent.parent / "kernels" / "yoso"
+ return [src_folder / file for file in files]
+
+ src_files = append_root(["fast_lsh_cumulation_torch.cpp", "fast_lsh_cumulation.cu", "fast_lsh_cumulation_cuda.cu"])
+
+ load("fast_lsh_cumulation", src_files, verbose=True)
+
+ import fast_lsh_cumulation as lsh_cumulation
+
+
+def to_contiguous(input_tensors):
+ if isinstance(input_tensors, list):
+ out = []
+ for tensor in input_tensors:
+ if not tensor.is_contiguous():
+ tensor = tensor.contiguous()
+ out.append(tensor)
+ return out
+ else:
+ if not input_tensors.is_contiguous():
+ input_tensors = input_tensors.contiguous()
+ return input_tensors
+
+
+def normalize(input_tensors):
+ if isinstance(input_tensors, list):
+ out = []
+ for tensor in input_tensors:
+ out.append(nn.functional.normalize(tensor, p=2, dim=-1))
+ return out
+ else:
+ return nn.functional.normalize(input_tensors, p=2, dim=-1)
+
+
+def hashing(query, key, num_hash, hash_len):
+ if len(query.size()) != 3:
+ raise ValueError("Query has incorrect size.")
+ if len(key.size()) != 3:
+ raise ValueError("Key has incorrect size.")
+
+ rmat = torch.randn(query.size(0), query.size(2), num_hash * hash_len, device=query.device)
+ raise_pow = 2 ** torch.arange(hash_len, device=query.device)
+
+ query_projection = torch.matmul(query, rmat).reshape(query.size(0), query.size(1), num_hash, hash_len)
+ key_projection = torch.matmul(key, rmat).reshape(key.size(0), key.size(1), num_hash, hash_len)
+ query_binary = (query_projection > 0).int()
+ key_binary = (key_projection > 0).int()
+ query_hash = torch.sum(query_binary * raise_pow, dim=-1)
+ query_hash = torch.sum(key_binary * raise_pow, dim=-1)
+
+ return query_hash.int(), query_hash.int()
+
+
+class YosoCumulation(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, query_mask, key_mask, query, key, value, config):
+ hash_code_len = config["hash_code_len"]
+
+ expectation = (1 - torch.acos(torch.matmul(query, key.transpose(-1, -2))) / math.pi) ** hash_code_len
+ expectation = expectation * query_mask[:, :, None] * key_mask[:, None, :]
+ cumulation_value = torch.matmul(expectation, value)
+
+ ctx.save_for_backward(query_mask, key_mask, expectation, query, key, value)
+ ctx.config = config
+
+ return cumulation_value
+
+ @staticmethod
+ def backward(ctx, grad):
+ grad = to_contiguous(grad)
+
+ query_mask, key_mask, expectation, query, key, value = ctx.saved_tensors
+ config = ctx.config
+
+ hash_code_len = config["hash_code_len"]
+
+ weighted_exp = torch.matmul(grad, value.transpose(-1, -2)) * expectation
+ grad_query = torch.matmul(weighted_exp, (hash_code_len / 2) * key)
+ grad_key = torch.matmul(weighted_exp.transpose(-1, -2), (hash_code_len / 2) * query)
+ grad_value = torch.matmul(expectation.transpose(-1, -2), grad)
+
+ return None, None, grad_query, grad_key, grad_value, None
+
+
+class YosoLSHCumulation(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, query_mask, key_mask, query, key, value, config):
+ if query_mask.size(0) != key_mask.size(0):
+ raise ValueError("Query mask and Key mask differ in sizes in dimension 0")
+ if query_mask.size(0) != query.size(0):
+ raise ValueError("Query mask and Query differ in sizes in dimension 0")
+ if query_mask.size(0) != key.size(0):
+ raise ValueError("Query mask and Key differ in sizes in dimension 0")
+ if query_mask.size(0) != value.size(0):
+ raise ValueError("Query mask and Value mask differ in sizes in dimension 0")
+ if key.size(1) != value.size(1):
+ raise ValueError("Key and Value differ in sizes in dimension 1")
+ if query.size(2) != key.size(2):
+ raise ValueError("Query and Key differ in sizes in dimension 2")
+
+ query_mask, key_mask, query, key, value = to_contiguous([query_mask, key_mask, query, key, value])
+
+ use_cuda = query_mask.is_cuda
+ num_hash = config["num_hash"]
+ hash_code_len = config["hash_code_len"]
+ hashtable_capacity = int(2**hash_code_len)
+
+ if config["use_fast_hash"]:
+ query_hash_code, key_hash_code = lsh_cumulation.fast_hash(
+ query_mask, query, key_mask, key, num_hash, hash_code_len, use_cuda, 1
+ )
+ else:
+ query_hash_code, key_hash_code = hashing(query, key, num_hash, hash_code_len)
+
+ cumulation_value = lsh_cumulation.lsh_cumulation(
+ query_mask, query_hash_code, key_mask, key_hash_code, value, hashtable_capacity, use_cuda, 1
+ )
+
+ ctx.save_for_backward(query_mask, key_mask, query_hash_code, key_hash_code, query, key, value)
+ ctx.config = config
+
+ return cumulation_value
+
+ @staticmethod
+ def backward(ctx, grad):
+ grad = to_contiguous(grad)
+
+ query_mask, key_mask, query_hash_code, key_hash_code, query, key, value = ctx.saved_tensors
+ config = ctx.config
+
+ use_cuda = grad.is_cuda
+ hash_code_len = config["hash_code_len"]
+ hashtable_capacity = int(2**hash_code_len)
+
+ if config["lsh_backward"]:
+ grad_value = lsh_cumulation.lsh_cumulation(
+ key_mask, key_hash_code, query_mask, query_hash_code, grad, hashtable_capacity, use_cuda, 1
+ )
+ grad_query = lsh_cumulation.lsh_weighted_cumulation(
+ query_mask,
+ query_hash_code,
+ grad,
+ key_mask,
+ key_hash_code,
+ value,
+ (hash_code_len / 2) * key,
+ hashtable_capacity,
+ use_cuda,
+ 4,
+ )
+ grad_key = lsh_cumulation.lsh_weighted_cumulation(
+ key_mask,
+ key_hash_code,
+ value,
+ query_mask,
+ query_hash_code,
+ grad,
+ (hash_code_len / 2) * query,
+ hashtable_capacity,
+ use_cuda,
+ 4,
+ )
+ else:
+ expectation = (1 - torch.acos(torch.matmul(query, key.transpose(-1, -2))) / math.pi) ** hash_code_len
+ expectation = expectation * query_mask[:, :, None] * key_mask[:, None, :]
+ weighted_exp = torch.matmul(grad, value.transpose(-1, -2)) * expectation
+ grad_query = torch.matmul(weighted_exp, (hash_code_len / 2) * key)
+ grad_key = torch.matmul(weighted_exp.transpose(-1, -2), (hash_code_len / 2) * query)
+ grad_value = torch.matmul(expectation.transpose(-1, -2), grad)
+
+ return None, None, grad_query, grad_key, grad_value, None
+
+
+# Copied from transformers.models.nystromformer.modeling_nystromformer.NystromformerEmbeddings
+class YosoEmbeddings(nn.Module):
+ """Construct the embeddings from word, position and token_type embeddings."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
+ self.position_embeddings = nn.Embedding(config.max_position_embeddings + 2, config.hidden_size)
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
+ # any TensorFlow checkpoint file
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
+ self.register_buffer(
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)) + 2, persistent=False
+ )
+ self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
+ self.register_buffer(
+ "token_type_ids",
+ torch.zeros(self.position_ids.size(), dtype=torch.long, device=self.position_ids.device),
+ persistent=False,
+ )
+
+ def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None):
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ seq_length = input_shape[1]
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, :seq_length]
+
+ # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
+ # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
+ # issue #5664
+ if token_type_ids is None:
+ if hasattr(self, "token_type_ids"):
+ buffered_token_type_ids = self.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
+
+ if inputs_embeds is None:
+ inputs_embeds = self.word_embeddings(input_ids)
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
+
+ embeddings = inputs_embeds + token_type_embeddings
+ if self.position_embedding_type == "absolute":
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings += position_embeddings
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+
+class YosoSelfAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None):
+ super().__init__()
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
+ raise ValueError(
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({config.num_attention_heads})"
+ )
+ kernel_loaded = lsh_cumulation is not None
+ if is_torch_cuda_available() and is_ninja_available() and not kernel_loaded:
+ try:
+ load_cuda_kernels()
+ except Exception as e:
+ logger.warning(f"Could not load the custom kernel for multi-scale deformable attention: {e}")
+
+ self.num_attention_heads = config.num_attention_heads
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(config.hidden_size, self.all_head_size)
+ self.key = nn.Linear(config.hidden_size, self.all_head_size)
+ self.value = nn.Linear(config.hidden_size, self.all_head_size)
+
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
+ self.position_embedding_type = (
+ position_embedding_type if position_embedding_type is not None else config.position_embedding_type
+ )
+
+ self.use_expectation = config.use_expectation
+ self.hash_code_len = config.hash_code_len
+ self.use_conv = config.conv_window is not None
+ self.use_fast_hash = config.use_fast_hash
+ self.num_hash = config.num_hash
+ self.lsh_backward = config.lsh_backward
+
+ self.lsh_config = {
+ "hash_code_len": self.hash_code_len,
+ "use_fast_hash": self.use_fast_hash,
+ "num_hash": self.num_hash,
+ "lsh_backward": self.lsh_backward,
+ }
+
+ if config.conv_window is not None:
+ self.conv = nn.Conv2d(
+ in_channels=config.num_attention_heads,
+ out_channels=config.num_attention_heads,
+ kernel_size=(config.conv_window, 1),
+ padding=(config.conv_window // 2, 0),
+ bias=False,
+ groups=config.num_attention_heads,
+ )
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ batch_size, seq_length, _ = hidden_states.shape
+ query_layer = (
+ self.query(hidden_states)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ key_layer = (
+ self.key(hidden_states)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ value_layer = (
+ self.value(hidden_states)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+
+ if self.use_conv:
+ conv_value_layer = self.conv(value_layer * attention_mask[:, None, :, None])
+
+ batch_size, num_heads, seq_len, head_dim = query_layer.size()
+
+ query_layer = query_layer.reshape(batch_size * num_heads, seq_len, head_dim)
+ key_layer = key_layer.reshape(batch_size * num_heads, seq_len, head_dim)
+ value_layer = value_layer.reshape(batch_size * num_heads, seq_len, head_dim)
+
+ attention_mask = 1.0 + attention_mask / 10000.0
+ attention_mask = (
+ attention_mask.unsqueeze(1)
+ .repeat_interleave(num_heads, dim=1)
+ .reshape(batch_size * num_heads, seq_len)
+ .int()
+ )
+
+ # The CUDA kernels are most efficient with inputs whose size is a multiple of a GPU's warp size (32). Inputs
+ # smaller than this are padded with zeros.
+ gpu_warp_size = 32
+
+ if (not self.use_expectation) and head_dim < gpu_warp_size:
+ pad_size = batch_size * num_heads, seq_len, gpu_warp_size - head_dim
+
+ query_layer = torch.cat(
+ [
+ query_layer,
+ torch.zeros(pad_size, device=query_layer.device),
+ ],
+ dim=-1,
+ )
+ key_layer = torch.cat(
+ [
+ key_layer,
+ torch.zeros(pad_size, device=key_layer.device),
+ ],
+ dim=-1,
+ )
+ value_layer = torch.cat(
+ [
+ value_layer,
+ torch.zeros(pad_size, device=value_layer.device),
+ ],
+ dim=-1,
+ )
+
+ if self.use_expectation or self.training:
+ query_layer, key_layer = normalize([query_layer, key_layer])
+
+ if self.use_expectation:
+ context_layer = YosoCumulation.apply(
+ attention_mask, attention_mask, query_layer, key_layer, value_layer, self.lsh_config
+ )
+ else:
+ context_layer = YosoLSHCumulation.apply(
+ attention_mask, attention_mask, query_layer, key_layer, value_layer, self.lsh_config
+ )
+
+ if (not self.use_expectation) and head_dim < gpu_warp_size:
+ context_layer = context_layer[:, :, :head_dim]
+
+ context_layer = normalize(context_layer)
+
+ context_layer = context_layer.reshape(batch_size, num_heads, seq_len, head_dim)
+
+ if self.use_conv:
+ context_layer += conv_value_layer
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(*new_context_layer_shape)
+
+ outputs = (context_layer, context_layer) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSelfOutput
+class YosoSelfOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class YosoAttention(nn.Module):
+ def __init__(self, config, position_embedding_type=None):
+ super().__init__()
+ self.self = YosoSelfAttention(config, position_embedding_type=position_embedding_type)
+ self.output = YosoSelfOutput(config)
+ self.pruned_heads = set()
+
+ def prune_heads(self, heads):
+ if len(heads) == 0:
+ return
+ heads, index = find_pruneable_heads_and_indices(
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
+ )
+
+ # Prune linear layers
+ self.self.query = prune_linear_layer(self.self.query, index)
+ self.self.key = prune_linear_layer(self.self.key, index)
+ self.self.value = prune_linear_layer(self.self.value, index)
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
+
+ # Update hyper params and store pruned heads
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
+ self.pruned_heads = self.pruned_heads.union(heads)
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ self_outputs = self.self(hidden_states, attention_mask, output_attentions)
+ attention_output = self.output(self_outputs[0], hidden_states)
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
+ return outputs
+
+
+# Copied from transformers.models.bert.modeling_bert.BertIntermediate
+class YosoIntermediate(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
+ if isinstance(config.hidden_act, str):
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.intermediate_act_fn = config.hidden_act
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.intermediate_act_fn(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOutput
+class YosoOutput(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states + input_tensor)
+ return hidden_states
+
+
+class YosoLayer(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = YosoAttention(config)
+ self.add_cross_attention = config.add_cross_attention
+ self.intermediate = YosoIntermediate(config)
+ self.output = YosoOutput(config)
+
+ def forward(self, hidden_states, attention_mask=None, output_attentions=False):
+ self_attention_outputs = self.attention(hidden_states, attention_mask, output_attentions=output_attentions)
+ attention_output = self_attention_outputs[0]
+
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
+
+ layer_output = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
+ )
+ outputs = (layer_output,) + outputs
+
+ return outputs
+
+ def feed_forward_chunk(self, attention_output):
+ intermediate_output = self.intermediate(attention_output)
+ layer_output = self.output(intermediate_output, attention_output)
+ return layer_output
+
+
+class YosoEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([YosoLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ attention_mask=None,
+ head_mask=None,
+ output_attentions=False,
+ output_hidden_states=False,
+ return_dict=True,
+ ):
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attentions = () if output_attentions else None
+
+ for i, layer_module in enumerate(self.layer):
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ layer_outputs = layer_module(hidden_states, attention_mask, output_attentions)
+
+ hidden_states = layer_outputs[0]
+ if output_attentions:
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
+
+ if output_hidden_states:
+ all_hidden_states = all_hidden_states + (hidden_states,)
+
+ if not return_dict:
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
+ return BaseModelOutputWithCrossAttentions(
+ last_hidden_state=hidden_states,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform
+class YosoPredictionHeadTransform(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ if isinstance(config.hidden_act, str):
+ self.transform_act_fn = ACT2FN[config.hidden_act]
+ else:
+ self.transform_act_fn = config.hidden_act
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.dense(hidden_states)
+ hidden_states = self.transform_act_fn(hidden_states)
+ hidden_states = self.LayerNorm(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->Yoso
+class YosoLMPredictionHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.transform = YosoPredictionHeadTransform(config)
+
+ # The output weights are the same as the input embeddings, but there is
+ # an output-only bias for each token.
+ self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ self.bias = nn.Parameter(torch.zeros(config.vocab_size))
+
+ # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
+ self.decoder.bias = self.bias
+
+ def _tie_weights(self):
+ self.decoder.bias = self.bias
+
+ def forward(self, hidden_states):
+ hidden_states = self.transform(hidden_states)
+ hidden_states = self.decoder(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->Yoso
+class YosoOnlyMLMHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.predictions = YosoLMPredictionHead(config)
+
+ def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
+ prediction_scores = self.predictions(sequence_output)
+ return prediction_scores
+
+
+@auto_docstring
+class YosoPreTrainedModel(PreTrainedModel):
+ config: YosoConfig
+ base_model_prefix = "yoso"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module: nn.Module):
+ """Initialize the weights"""
+ std = self.config.initializer_range
+ if isinstance(module, nn.Linear):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+ elif isinstance(module, YosoLMPredictionHead):
+ module.bias.data.zero_()
+
+
+@auto_docstring
+class YosoModel(YosoPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.config = config
+
+ self.embeddings = YosoEmbeddings(config)
+ self.encoder = YosoEncoder(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self):
+ return self.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.embeddings.word_embeddings = value
+
+ def _prune_heads(self, heads_to_prune):
+ """
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
+ class PreTrainedModel
+ """
+ for layer, heads in heads_to_prune.items():
+ self.encoder.layer[layer].attention.prune_heads(heads)
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, BaseModelOutputWithCrossAttentions]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
+ input_shape = input_ids.size()
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ batch_size, seq_length = input_shape
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ if attention_mask is None:
+ attention_mask = torch.ones(((batch_size, seq_length)), device=device)
+
+ if token_type_ids is None:
+ if hasattr(self.embeddings, "token_type_ids"):
+ buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
+ buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
+ token_type_ids = buffered_token_type_ids_expanded
+ else:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ )
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=attention_mask,
+ head_mask=head_mask,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+
+ if not return_dict:
+ return (sequence_output,) + encoder_outputs[1:]
+
+ return BaseModelOutputWithCrossAttentions(
+ last_hidden_state=sequence_output,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+@auto_docstring
+class YosoForMaskedLM(YosoPreTrainedModel):
+ _tied_weights_keys = ["cls.predictions.decoder.weight", "cls.predictions.decoder.bias"]
+
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.yoso = YosoModel(config)
+ self.cls = YosoOnlyMLMHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_output_embeddings(self):
+ return self.cls.predictions.decoder
+
+ def set_output_embeddings(self, new_embeddings):
+ self.cls.predictions.decoder = new_embeddings
+ self.cls.predictions.bias = new_embeddings.bias
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, MaskedLMOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
+ config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
+ loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.yoso(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ prediction_scores = self.cls(sequence_output)
+
+ masked_lm_loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss() # -100 index = padding token
+ masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
+
+ if not return_dict:
+ output = (prediction_scores,) + outputs[1:]
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
+
+ return MaskedLMOutput(
+ loss=masked_lm_loss,
+ logits=prediction_scores,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+class YosoClassificationHead(nn.Module):
+ """Head for sentence-level classification tasks."""
+
+ def __init__(self, config):
+ super().__init__()
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
+
+ self.config = config
+
+ def forward(self, features, **kwargs):
+ x = features[:, 0, :] # take token (equiv. to [CLS])
+ x = self.dropout(x)
+ x = self.dense(x)
+ x = ACT2FN[self.config.hidden_act](x)
+ x = self.dropout(x)
+ x = self.out_proj(x)
+ return x
+
+
+@auto_docstring(
+ custom_intro="""
+ YOSO Model transformer with a sequence classification/regression head on top (a linear layer on top of
+ the pooled output) e.g. for GLUE tasks.
+ """
+)
+class YosoForSequenceClassification(YosoPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.yoso = YosoModel(config)
+ self.classifier = YosoClassificationHead(config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, SequenceClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.yoso(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(logits, labels)
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class YosoForMultipleChoice(YosoPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.yoso = YosoModel(config)
+ self.pre_classifier = nn.Linear(config.hidden_size, config.hidden_size)
+ self.classifier = nn.Linear(config.hidden_size, 1)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, MultipleChoiceModelOutput]:
+ r"""
+ input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
+ Indices of input sequence tokens in the vocabulary.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
+ 1]`:
+
+ - 0 corresponds to a *sentence A* token,
+ - 1 corresponds to a *sentence B* token.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
+ config.max_position_embeddings - 1]`.
+
+ [What are position IDs?](../glossary#position-ids)
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
+ model's internal embedding lookup matrix.
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
+ num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
+ `input_ids` above)
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
+
+ input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
+ attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
+ token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
+ position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
+ inputs_embeds = (
+ inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
+ if inputs_embeds is not None
+ else None
+ )
+
+ outputs = self.yoso(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
+ pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
+ pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
+ pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
+ logits = self.classifier(pooled_output)
+
+ reshaped_logits = logits.view(-1, num_choices)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(reshaped_logits, labels)
+
+ if not return_dict:
+ output = (reshaped_logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return MultipleChoiceModelOutput(
+ loss=loss,
+ logits=reshaped_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class YosoForTokenClassification(YosoPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+
+ self.yoso = YosoModel(config)
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ labels: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, TokenClassifierOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.yoso(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ sequence_output = self.dropout(sequence_output)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss_fct = CrossEntropyLoss()
+ # Only keep active parts of the loss
+ if attention_mask is not None:
+ active_loss = attention_mask.view(-1) == 1
+ active_logits = logits.view(-1, self.num_labels)
+ active_labels = torch.where(
+ active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
+ )
+ loss = loss_fct(active_logits, active_labels)
+ else:
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return TokenClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+@auto_docstring
+class YosoForQuestionAnswering(YosoPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ config.num_labels = 2
+ self.num_labels = config.num_labels
+
+ self.yoso = YosoModel(config)
+ self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ token_type_ids: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.Tensor] = None,
+ head_mask: Optional[torch.Tensor] = None,
+ inputs_embeds: Optional[torch.Tensor] = None,
+ start_positions: Optional[torch.Tensor] = None,
+ end_positions: Optional[torch.Tensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, QuestionAnsweringModelOutput]:
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ outputs = self.yoso(
+ input_ids,
+ attention_mask=attention_mask,
+ token_type_ids=token_type_ids,
+ position_ids=position_ids,
+ head_mask=head_mask,
+ inputs_embeds=inputs_embeds,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+
+ sequence_output = outputs[0]
+
+ logits = self.qa_outputs(sequence_output)
+ start_logits, end_logits = logits.split(1, dim=-1)
+ start_logits = start_logits.squeeze(-1)
+ end_logits = end_logits.squeeze(-1)
+
+ total_loss = None
+ if start_positions is not None and end_positions is not None:
+ # If we are on multi-GPU, split add a dimension
+ if len(start_positions.size()) > 1:
+ start_positions = start_positions.squeeze(-1)
+ if len(end_positions.size()) > 1:
+ end_positions = end_positions.squeeze(-1)
+ # sometimes the start/end positions are outside our model inputs, we ignore these terms
+ ignored_index = start_logits.size(1)
+ start_positions = start_positions.clamp(0, ignored_index)
+ end_positions = end_positions.clamp(0, ignored_index)
+
+ loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
+ start_loss = loss_fct(start_logits, start_positions)
+ end_loss = loss_fct(end_logits, end_positions)
+ total_loss = (start_loss + end_loss) / 2
+
+ if not return_dict:
+ output = (start_logits, end_logits) + outputs[1:]
+ return ((total_loss,) + output) if total_loss is not None else output
+
+ return QuestionAnsweringModelOutput(
+ loss=total_loss,
+ start_logits=start_logits,
+ end_logits=end_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "YosoForMaskedLM",
+ "YosoForMultipleChoice",
+ "YosoForQuestionAnswering",
+ "YosoForSequenceClassification",
+ "YosoForTokenClassification",
+ "YosoLayer",
+ "YosoModel",
+ "YosoPreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..48a233755de26862db8489d083ffc7f2809e821d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_zamba import *
+ from .modeling_zamba import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba/configuration_zamba.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba/configuration_zamba.py
new file mode 100644
index 0000000000000000000000000000000000000000..3de9a19d1bd73e52b5f9819bbe67cc816bc10503
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba/configuration_zamba.py
@@ -0,0 +1,227 @@
+# coding=utf-8
+# Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Zamba model configuration"""
+
+import math
+
+from ...configuration_utils import PretrainedConfig
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+
+class ZambaConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`ZambaModel`]. It is used to instantiate a
+ Zamba model according to the specified arguments, defining the model architecture. Instantiating a configuration
+ with the defaults will yield a similar configuration to that of the Zamba-v0.1 model.
+
+ [Zyphra/Zamba-7B-v1](https://huggingface.co/Zyphra/Zamba-7B-v1)
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+
+ Args:
+ vocab_size (`int`, *optional*, defaults to 32000):
+ Vocabulary size of the Zamba model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`ZambaModel`]
+ tie_word_embeddings (`bool`, *optional*, defaults to `True`):
+ Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
+ model has a output word embedding layer.
+ hidden_size (`int`, *optional*, defaults to 3712):
+ Dimension of the hidden representations.
+ attention_hidden_size (`int`, *optional*):
+ Dimension of the hidden representations of the inputs to the Attention layer.
+ intermediate_size (`int`, *optional*, defaults to 14848):
+ Dimension of the MLP representations.
+ num_hidden_layers (`int`, *optional*, defaults to 76):
+ Number of hidden layers in the model.
+ num_attention_heads (`int`, *optional*, defaults to 16):
+ Number of attention heads for each attention layer in the Transformer decoder.
+ attention_head_dim (`int`, *optional*):
+ Dimension of the attention head in the Transformer decoder.
+ num_key_value_heads (`int`, *optional*, defaults to 16):
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
+ `num_key_value_heads=None`, the model will use Multi Head Attention (MHA), if
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
+ by meanpooling all the original heads within that group. For more details, check out [this
+ paper](https://huggingface.co/papers/2305.13245).
+ n_mamba_heads (`int`, *optional*, defaults to 2):
+ Number of mamba heads for each mamba layer.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the decoder.
+ hidden_mamba_act (`str` or `function`, *optional*, defaults to `"silu"`):
+ The non-linear activation function (function or string) in the mamba layer.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
+ The epsilon used by the rms normalization layers.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+ num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
+ integer value, only last `num_logits_to_keep` logits will be calculated. Default is 1 because only the
+ logits of the last prompt token are needed for generation. For long sequences, the logits for the entire
+ sequence may use a lot of memory so, setting `num_logits_to_keep=1` will reduce memory footprint
+ significantly.
+ pad_token_id (`int`, *optional*, defaults to 0):
+ The id of the padding token.
+ bos_token_id (`int`, *optional*, defaults to 1):
+ The id of the "beginning-of-sequence" token.
+ eos_token_id (`int`, *optional*, defaults to 2):
+ The id of the "end-of-sequence" token.
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
+ This value doesn't have any real effect. The maximum sequence length that this model is intended to be
+ used with. It can be used with longer sequences, but performance may degrade.
+ attention_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+ attn_layer_period (`int`, *optional*, defaults to 6):
+ Once in this many layers, we will have a shared attention layer
+ attn_layer_offset (`int`, *optional*, defaults to 4):
+ Offset of the shared attention layer
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
+ Flag indicating whether or not to use the fast mamba kernels. These are available only if `mamba-ssm` and
+ `causal-conv1d` are installed, and the mamba modules are running on a CUDA device. Raises ValueError if
+ `True` and kernels are not available
+ mamba_d_state (`int`, *optional*, defaults to 16):
+ The dimension the mamba state space latents
+ mamba_d_conv (`int`, *optional*, defaults to 4):
+ The size of the mamba convolution kernel
+ mamba_expand (`int`, *optional*, defaults to 2):
+ Expanding factor (relative to hidden_size) used to determine the mamba intermediate size
+ mamba_dt_rank (`Union[int,str]`, *optional*, defaults to `"auto"`):
+ Rank of the mamba discretization projection matrix. `"auto"` means that it will default to `math.ceil(self.hidden_size / 16)`
+ time_step_min (`float`, *optional*, defaults to 0.001):
+ Minimum `time_step` used to bound `dt_proj_bias`.
+ time_step_max (`float`, *optional*, defaults to 0.1):
+ Maximum `time_step` used to bound `dt_proj_bias`.
+ time_step_floor (`float`, *optional*, defaults to 0.0001):
+ Minimum clamping value of the `dt_proj.bias` layer initialization.
+ mamba_conv_bias (`bool`, *optional*, defaults to `True`):
+ Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block.
+ mamba_proj_bias (`bool`, *optional*, defaults to `False`):
+ Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the mamba mixer block
+
+ """
+
+ model_type = "zamba"
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ def __init__(
+ self,
+ vocab_size=32000,
+ tie_word_embeddings=True,
+ hidden_size=3712,
+ attention_hidden_size=None,
+ intermediate_size=14848,
+ num_hidden_layers=76,
+ num_attention_heads=16,
+ attention_head_dim=None,
+ num_key_value_heads=16,
+ n_mamba_heads=2,
+ hidden_act="gelu",
+ hidden_mamba_act="silu",
+ initializer_range=0.02,
+ rms_norm_eps=1e-5,
+ use_cache=True,
+ num_logits_to_keep=1,
+ pad_token_id=0,
+ bos_token_id=1,
+ eos_token_id=2,
+ max_position_embeddings=4096,
+ attention_dropout=0.0,
+ attn_layer_period=6,
+ attn_layer_offset=4,
+ use_mamba_kernels=True,
+ mamba_d_state=16,
+ mamba_d_conv=4,
+ mamba_expand=2,
+ mamba_dt_rank="auto",
+ time_step_min=0.001,
+ time_step_max=0.1,
+ time_step_floor=1e-4,
+ mamba_conv_bias=True,
+ mamba_proj_bias=False,
+ **kwargs,
+ ):
+ self.vocab_size = vocab_size
+ self.tie_word_embeddings = tie_word_embeddings
+ self.hidden_size = hidden_size
+ if attention_hidden_size is None:
+ self.attention_hidden_size = 2 * hidden_size
+ else:
+ self.attention_hidden_size = attention_hidden_size
+ self.intermediate_size = intermediate_size
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ if attention_head_dim is None:
+ self.attention_head_dim = 2 * self.hidden_size // self.num_attention_heads
+ else:
+ self.attention_head_dim = attention_head_dim
+ self.max_position_embeddings = max_position_embeddings
+ self.attention_dropout = attention_dropout
+
+ self.num_key_value_heads = num_key_value_heads
+ self.n_mamba_heads = n_mamba_heads
+ self.hidden_act = hidden_act
+ self.hidden_mamba_act = hidden_mamba_act
+ self.initializer_range = initializer_range
+ self.rms_norm_eps = rms_norm_eps
+
+ self.use_cache = use_cache
+ self.num_logits_to_keep = num_logits_to_keep
+
+ self.attn_layer_period = attn_layer_period
+ self.attn_layer_offset = attn_layer_offset
+
+ self.use_mamba_kernels = use_mamba_kernels
+ self.mamba_d_state = mamba_d_state
+ self.mamba_d_conv = mamba_d_conv
+ self.mamba_expand = mamba_expand
+ self.mamba_dt_rank = math.ceil(self.hidden_size / 16) if mamba_dt_rank == "auto" else mamba_dt_rank
+ self.time_step_min = time_step_min
+ self.time_step_max = time_step_max
+ self.time_step_floor = time_step_floor
+ self.mamba_conv_bias = mamba_conv_bias
+ self.mamba_proj_bias = mamba_proj_bias
+
+ self.layers_block_type = self._layers_block_type(num_hidden_layers, attn_layer_period, attn_layer_offset)
+
+ assert (self.mamba_expand * self.hidden_size) % self.n_mamba_heads == 0, (
+ "`intermediate_size` should be divisible by `n_mamba_heads`."
+ )
+
+ super().__init__(
+ pad_token_id=pad_token_id,
+ bos_token_id=bos_token_id,
+ eos_token_id=eos_token_id,
+ tie_word_embeddings=tie_word_embeddings,
+ **kwargs,
+ )
+
+ def _layers_block_type(self, num_hidden_layers, attn_layer_period, attn_layer_offset):
+ layers = [
+ "mamba",
+ "mamba",
+ "hybrid",
+ ] + ["hybrid" if i % attn_layer_period == attn_layer_offset else "mamba" for i in range(num_hidden_layers - 3)]
+ return layers
+
+
+__all__ = ["ZambaConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba/modeling_zamba.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba/modeling_zamba.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c0f86ea44892de3be584f5cfa6abcbbfcf6898c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba/modeling_zamba.py
@@ -0,0 +1,1311 @@
+# coding=utf-8
+# Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
+#
+# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
+# and OPT implementations in this library. It has been modified from its
+# original forms to accommodate minor architectural differences compared
+# to GPT-NeoX and OPT used by the Meta AI team that trained the model.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch Zamba model."""
+
+import math
+from typing import Any, Callable, Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...generation import GenerationMixin
+from ...modeling_attn_mask_utils import AttentionMaskConverter
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import auto_docstring, logging
+from ...utils.deprecation import deprecate_kwarg
+from ...utils.import_utils import is_causal_conv1d_available, is_mamba_ssm_available
+from .configuration_zamba import ZambaConfig
+
+
+if is_mamba_ssm_available():
+ from mamba_ssm.ops.selective_scan_interface import mamba_inner_fn, selective_scan_fn
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
+else:
+ selective_state_update, selective_scan_fn, mamba_inner_fn = None, None, None
+
+if is_causal_conv1d_available():
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
+else:
+ causal_conv1d_update, causal_conv1d_fn = None, None
+
+is_fast_path_available = all(
+ (selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)
+)
+
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Zamba
+class ZambaRMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps=1e-6):
+ """
+ ZambaRMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+# Copied from transformers.models.llama.modeling_llama.repeat_kv
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+class ZambaHybridDynamicCache:
+ """
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
+ (which has a constant shape regardless of seq_len).
+
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
+ """
+
+ is_compileable = False
+
+ def __init__(self, config, batch_size, dtype=torch.float16, device=None):
+ self.dtype = dtype
+ self.is_compileable = False
+ self.layers_block_type = config.layers_block_type
+ self.has_previous_state = False # only used by mamba
+ self.intermediate_size = config.mamba_expand * config.hidden_size
+ self.ssm_state_size = config.mamba_d_state
+ self.conv_kernel_size = config.mamba_d_conv
+ self.n_mamba_heads = config.n_mamba_heads
+ self.conv_states = []
+ self.ssm_states = []
+ self.transformer_layers = []
+ self._modules = {}
+ self._parameters = {}
+ self._buffers = {}
+ for i in range(config.num_hidden_layers):
+ self.conv_states += [
+ torch.zeros(batch_size, self.intermediate_size, self.conv_kernel_size, device=device, dtype=dtype)
+ ]
+ cache_shape = (
+ batch_size,
+ self.n_mamba_heads,
+ self.intermediate_size // self.n_mamba_heads,
+ self.ssm_state_size,
+ )
+ self.ssm_states += [torch.zeros(cache_shape, device=device, dtype=dtype)]
+ if self.layers_block_type[i] == "hybrid":
+ self.transformer_layers.append(i)
+
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
+
+ def __len__(self):
+ return len(self.key_cache)
+
+ def __getitem__(self, layer_idx: int) -> tuple[torch.Tensor, torch.Tensor]:
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
+
+ # Copied from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache.update
+ def update(
+ self,
+ key_states: torch.Tensor,
+ value_states: torch.Tensor,
+ layer_idx: int,
+ cache_kwargs: Optional[dict[str, Any]] = None,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ # Update the cache
+ if self.key_cache[layer_idx].shape[-1] == 0:
+ self.key_cache[layer_idx] = key_states
+ self.value_cache[layer_idx] = value_states
+ else:
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
+
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
+
+ # Copied from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache.reorder_cache
+ def reorder_cache(self, beam_idx: torch.LongTensor):
+ """Reorders the cache for beam search, given the selected beam indices."""
+ for layer_idx in range(len(self.key_cache)):
+ device = self.key_cache[layer_idx].device
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
+ device = self.value_cache[layer_idx].device
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
+
+ device = self.conv_states[layer_idx].device
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
+ device = self.ssm_states[layer_idx].device
+ self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
+
+ # Copied from transformers.models.jamba.modeling_jamba.HybridMambaAttentionDynamicCache.get_seq_length
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
+ # take any layer that contains cache and not empty tensor
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
+ if len(self.key_cache) <= layer_idx:
+ return 0
+ return self.key_cache[layer_idx].shape[-2]
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
+ attn_weights = attn_weights + causal_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+class ZambaAttention(nn.Module):
+ """
+ Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
+ and "Generating Long Sequences with Sparse Transformers".
+
+ Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
+ The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
+ The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ Additionally, replaced
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2)
+ """
+
+ def __init__(self, config: ZambaConfig, layer_idx: int):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+
+ self.attention_hidden_size = config.attention_hidden_size
+ self.head_dim = config.attention_head_dim
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.max_position_embeddings = config.max_position_embeddings
+ self.scaling = (self.head_dim / 2) ** -0.5
+ self.is_causal = True
+ self.attention_dropout = config.attention_dropout
+
+ self.q_proj = nn.Linear(config.attention_hidden_size, config.num_attention_heads * self.head_dim, bias=False)
+ self.k_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.v_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: Optional[torch.Tensor],
+ past_key_values: Optional[ZambaHybridDynamicCache] = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, layer_idx)
+
+ attention_interface: Callable = eager_attention_forward
+ if self.config._attn_implementation != "eager":
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class ZambaMambaMixer(nn.Module):
+ """
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
+ and is why Mamba is called **selective** state spaces)
+
+ This module differs from `transformers.models.mamba.modeling_mamba.MambaMixer` in two ways:
+ - Added multi-head: the output of `self.in_proj` is split into `self.n_mamba_heads` heads, and each head
+ undergoes an independent forward pass, identical to the original `MambaMixer`, up until the pre-activations of
+ `self.out_proj`. The pre-activations, coming from different mamba heads, are then concatenated and fed into `self.out_proj`.
+ """
+
+ def __init__(self, config: ZambaConfig, layer_idx):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+ self.hidden_size = config.hidden_size
+ self.ssm_state_size = config.mamba_d_state
+ self.conv_kernel_size = config.mamba_d_conv
+ self.intermediate_size = config.mamba_expand * config.hidden_size
+ self.time_step_rank = config.mamba_dt_rank
+ self.n_mamba_heads = config.n_mamba_heads
+ self.mamba_head_dim = self.intermediate_size // self.n_mamba_heads
+ self.use_conv_bias = config.mamba_conv_bias
+ self.use_bias = config.mamba_proj_bias
+ self.conv1d = nn.Conv1d(
+ in_channels=self.intermediate_size,
+ out_channels=self.intermediate_size,
+ bias=self.use_conv_bias,
+ kernel_size=self.conv_kernel_size,
+ groups=self.intermediate_size,
+ padding=self.conv_kernel_size - 1,
+ )
+
+ self.activation = config.hidden_mamba_act
+ self.act = ACT2FN[config.hidden_mamba_act]
+
+ self.use_fast_kernels = config.use_mamba_kernels
+
+ # projection of the input hidden states
+ self.in_proj = nn.Linear(self.hidden_size, self.intermediate_size * 2, bias=self.use_bias)
+ # weight associated to the selective projection used to make dt, B and C input dependent
+ # each mamba head is processed independently
+ self.x_proj_weight = nn.Parameter(
+ torch.zeros(
+ self.n_mamba_heads,
+ self.time_step_rank + self.ssm_state_size * 2,
+ self.mamba_head_dim,
+ )
+ )
+ # time step projection (discretization)
+ self.dt_proj_weight = nn.Parameter(
+ (torch.zeros(self.n_mamba_heads, self.mamba_head_dim, self.time_step_rank) - 0.5)
+ * 2
+ / self.time_step_rank**0.5
+ )
+ self.dt_proj_bias = nn.Parameter(torch.zeros(self.n_mamba_heads, self.mamba_head_dim))
+
+ # S4D real initialization. These are not discretized!
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
+ A = torch.arange(1, self.ssm_state_size + 1, dtype=torch.float32)[None, :]
+ A = A.expand(self.intermediate_size, -1).contiguous()
+ self.A_log = nn.Parameter(torch.log(A).reshape(self.n_mamba_heads, self.mamba_head_dim, -1))
+ self.D = nn.Parameter(torch.ones(self.n_mamba_heads, self.mamba_head_dim))
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.use_bias)
+
+ if not is_fast_path_available:
+ logger.warning_once(
+ "The fast path is not available because on of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)`"
+ " is None. To install follow https://github.com/state-spaces/mamba/#installation and"
+ " https://github.com/Dao-AILab/causal-conv1d. If you want to use the naive implementation, set `use_mamba_kernels=False` in the model config"
+ )
+
+ def cuda_kernels_forward(
+ self, hidden_states: torch.Tensor, cache_params: ZambaHybridDynamicCache = None, attention_mask=None
+ ):
+ batch_size, seq_len, _ = hidden_states.shape
+ use_precomputed_states = cache_params is not None and cache_params.has_previous_state and seq_len == 1
+
+ # 1. Gated linear projection
+ projected_states = self.in_proj(hidden_states).transpose(1, 2)
+
+ hidden_states, gate = projected_states.view(batch_size, -1, 2, seq_len).chunk(2, dim=2)
+ hidden_states = hidden_states.squeeze(2).contiguous()
+ gate = gate.squeeze(2)
+ gate = gate.reshape(batch_size, self.n_mamba_heads, -1, seq_len).transpose(0, 1)
+
+ # 2. Convolution sequence transformation
+ conv_weights = self.conv1d.weight.view(self.conv1d.weight.size(0), self.conv1d.weight.size(2))
+ if use_precomputed_states:
+ hidden_states = causal_conv1d_update(
+ hidden_states.squeeze(-1),
+ cache_params.conv_states[self.layer_idx],
+ conv_weights,
+ self.conv1d.bias,
+ self.activation,
+ )
+ hidden_states = hidden_states.unsqueeze(-1)
+ else:
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
+ if cache_params is not None:
+ conv_states = nn.functional.pad(hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0))
+ cache_params.conv_states[self.layer_idx].copy_(conv_states)
+ hidden_states = causal_conv1d_fn(hidden_states, conv_weights, self.conv1d.bias, activation=self.activation)
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
+
+ # 3. SSM sequence transformation
+ # 3.a. input varying initialization of time_step, B and C
+
+ hidden_states = hidden_states.reshape(-1, self.n_mamba_heads, self.mamba_head_dim, seq_len).transpose(0, 1)
+ ssm_parameters = (self.x_proj_weight[:, None, :, :] @ hidden_states).transpose(-1, -2)
+
+ time_step, B, C = torch.split(
+ ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
+ )
+
+ discrete_time_step = self.dt_proj_weight[:, None] @ time_step.transpose(-1, -2)
+
+ A = -torch.exp(self.A_log.float())
+
+ # 3.c perform the recurrence y ← SSM(A, B, C)(x)
+ time_proj_bias = self.dt_proj_bias.float() if self.dt_proj_bias is not None else None
+ scan_outputs = torch.empty((batch_size, 0, seq_len), device=hidden_states.device, dtype=hidden_states.dtype)
+
+ if use_precomputed_states:
+ for n in range(self.n_mamba_heads):
+ scan_outputs_ = selective_state_update(
+ cache_params.ssm_states[self.layer_idx][:, n],
+ hidden_states[n, ..., 0],
+ discrete_time_step[n, ..., 0],
+ A[n],
+ B[n, :, 0],
+ C[n, :, 0],
+ self.D[n],
+ gate[n, ..., 0],
+ time_proj_bias[n],
+ dt_softplus=True,
+ ).unsqueeze(-1)
+ scan_outputs = torch.cat((scan_outputs, scan_outputs_), dim=1)
+
+ else:
+ ssm_state = torch.empty(
+ (batch_size, 0, self.mamba_head_dim, self.ssm_state_size),
+ device=hidden_states.device,
+ dtype=hidden_states.dtype,
+ )
+ for n in range(self.n_mamba_heads):
+ scan_outputs_, ssm_state_ = selective_scan_fn(
+ hidden_states[n],
+ discrete_time_step[n],
+ A[n],
+ B[n].transpose(1, 2),
+ C[n].transpose(1, 2),
+ self.D[n].float(),
+ gate[n],
+ time_proj_bias[n],
+ delta_softplus=True,
+ return_last_state=True,
+ )
+ scan_outputs = torch.cat((scan_outputs, scan_outputs_), dim=1).contiguous()
+ ssm_state = torch.cat((ssm_state, ssm_state_.unsqueeze(1)), dim=1)
+ if ssm_state is not None and cache_params is not None:
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
+
+ # 4. Final linear projection
+ contextualized_states = self.out_proj(scan_outputs.transpose(1, 2))
+ return contextualized_states
+
+ def slow_forward(self, input_states, cache_params: ZambaHybridDynamicCache = None, attention_mask=None):
+ batch_size, seq_len, _ = input_states.shape
+ dtype = input_states.dtype
+ # 1. Gated linear projection
+ projected_states = self.in_proj(input_states).transpose(1, 2)
+
+ hidden_states, gate = projected_states.view(batch_size, -1, 2, seq_len).chunk(2, dim=2)
+ hidden_states = hidden_states.squeeze(2).contiguous()
+ gate = gate.squeeze(2)
+ gate = gate.reshape(batch_size, self.n_mamba_heads, -1, seq_len).transpose(0, 1)
+
+ use_cache = isinstance(cache_params, ZambaHybridDynamicCache)
+ # 2. Convolution sequence transformation
+ if use_cache and cache_params.ssm_states[self.layer_idx].shape[0] == batch_size:
+ if self.training:
+ # In training mode, we don't want to perform in-place operations on ssm_state so we can compute the backwards pass
+ ssm_state = cache_params.ssm_states[self.layer_idx].clone()
+ else:
+ ssm_state = cache_params.ssm_states[self.layer_idx]
+
+ ssm_state = ssm_state.to(hidden_states.device)
+
+ if (
+ cache_params.has_previous_state
+ and seq_len == 1
+ and cache_params.conv_states[self.layer_idx].shape[0] == batch_size
+ ):
+ conv_state = cache_params.conv_states[self.layer_idx]
+ conv_state = torch.roll(conv_state, shifts=-1, dims=-1)
+ conv_state[:, :, -1] = hidden_states[:, :, 0]
+ cache_params.conv_states[self.layer_idx] = conv_state
+ hidden_states = torch.sum(conv_state * self.conv1d.weight[:, 0, :], dim=-1)
+ if self.use_conv_bias:
+ hidden_states += self.conv1d.bias
+ hidden_states = self.act(hidden_states).to(dtype).unsqueeze(-1)
+ else:
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ hidden_states = hidden_states * attention_mask[:, -hidden_states.shape[-1] :].unsqueeze(1)
+ conv_state = nn.functional.pad(hidden_states, (self.conv_kernel_size - hidden_states.shape[-1], 0))
+ cache_params.conv_states[self.layer_idx] = conv_state
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len])
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ hidden_states = hidden_states * attention_mask[:, -hidden_states.shape[-1] :].unsqueeze(1)
+ else:
+ ssm_state = torch.zeros(
+ (batch_size, self.n_mamba_heads, self.mamba_head_dim, self.ssm_state_size),
+ device=hidden_states.device,
+ dtype=dtype,
+ )
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
+ hidden_states = self.act(self.conv1d(hidden_states)[..., :seq_len])
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ hidden_states = hidden_states * attention_mask.unsqueeze(1)
+
+ # 3. State Space Model sequence transformation
+ # 3.a. Selection: [batch, seq_len, self.time_step_rank + self.ssm_state_size * 2]
+ hidden_states = hidden_states.reshape(-1, self.n_mamba_heads, self.mamba_head_dim, seq_len).transpose(0, 1)
+ ssm_parameters = (self.x_proj_weight[:, None, :, :] @ hidden_states).transpose(-1, -2)
+
+ time_step, B, C = torch.split(
+ ssm_parameters, [self.time_step_rank, self.ssm_state_size, self.ssm_state_size], dim=-1
+ )
+ discrete_time_step = (self.dt_proj_weight[:, None] @ time_step.transpose(-1, -2)) + self.dt_proj_bias[
+ :, None, :, None
+ ]
+
+ discrete_time_step = nn.functional.softplus(discrete_time_step)
+
+ # 3.b. Discretization: B and C to [batch, seq_len, intermediate_size, ssm_state_size] (SRAM)
+ A = -torch.exp(self.A_log.float())
+ discrete_A = torch.exp(A[:, None, :, None, :] * discrete_time_step[:, :, :, :, None])
+ discrete_B = discrete_time_step[:, :, :, :, None] * B[:, :, None, :, :].float()
+ deltaB_u = discrete_B * hidden_states[:, :, :, :, None].float()
+ # 3.c perform the recurrence y ← SSM(A, B, C)(x)
+ scan_outputs = []
+ for i in range(seq_len):
+ ssm_state = discrete_A[:, :, :, i, :].transpose(0, 1) * ssm_state + deltaB_u[:, :, :, i, :].transpose(0, 1)
+ scan_output = torch.matmul(ssm_state.transpose(0, 1).to(dtype), C[:, :, i, :].unsqueeze(-1))
+ scan_outputs.append(scan_output[:, :, :, 0])
+ scan_output = torch.stack(scan_outputs, dim=-1)
+ scan_output = scan_output + (hidden_states * self.D[:, None, :, None])
+ scan_output = scan_output * self.act(gate)
+
+ if use_cache:
+ cache_params.ssm_states[self.layer_idx] = ssm_state
+
+ # 4. Final linear projection
+ contextualized_states = self.out_proj(
+ scan_output.transpose(0, 1).reshape(batch_size, -1, seq_len).transpose(1, 2)
+ )
+ return contextualized_states
+
+ def forward(self, hidden_states, cache_params: ZambaHybridDynamicCache = None, attention_mask=None):
+ if self.use_fast_kernels:
+ if not is_fast_path_available or "cuda" not in self.x_proj_weight.device.type:
+ raise ValueError(
+ "Fast Mamba kernels are not available. Make sure to they are installed and that "
+ "the mamba module is on a CUDA device. lease run 'pip install causal-conv1d>=1.2.0' "
+ "and 'pip install mamba-ssm', or set use_mamba_kernels=False in the model's config."
+ )
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask=attention_mask)
+ return self.slow_forward(hidden_states, cache_params, attention_mask=attention_mask)
+
+
+# Copied from transformers.models.mistral.modeling_mistral.MistralMLP with Mistral->Zamba
+class ZambaMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ def forward(self, x):
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
+ return down_proj
+
+
+class ZambaAttentionDecoderLayer(nn.Module):
+ def __init__(self, config: ZambaConfig, layer_idx: Optional[int] = None):
+ super().__init__()
+ self.self_attn = ZambaAttention(config, layer_idx)
+
+ self.feed_forward = ZambaMLP(config)
+ self.input_layernorm = ZambaRMSNorm(config.attention_hidden_size, eps=config.rms_norm_eps)
+ self.pre_ff_layernorm = ZambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[ZambaHybridDynamicCache] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): output of previous Mamba layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output of shape `(batch, seq_len, embed_dim)`.
+ This is concatenated with `hidden_states` (which is the output of the previous (mamba) layer). The
+ concatenated tensor is then used as input of the pre-attention RMSNorm
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ layer_idx (`int`): layer_idx in the forward pass. Used to distinguish Zamba's tied transformer layers.
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`ZambaHybridDynamicCache`, *optional*): cached past key and value projection states
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
+ Indices depicting the position of the input sequence tokens in the sequence.
+ """
+ hidden_states = torch.concatenate([hidden_states, original_hidden_states], dim=-1)
+ hidden_states = self.input_layernorm(hidden_states)
+ hidden_states, self_attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ **kwargs,
+ )
+ # feed-forward (MLP)
+ hidden_states = self.pre_ff_layernorm(hidden_states)
+ hidden_states = self.feed_forward(hidden_states)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights,)
+
+ return outputs
+
+
+class ZambaMambaDecoderLayer(nn.Module):
+ def __init__(self, config: ZambaConfig, layer_idx: int):
+ super().__init__()
+ self.mamba = ZambaMambaMixer(config=config, layer_idx=layer_idx)
+ self.input_layernorm = ZambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.layer_idx = layer_idx
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: Optional[torch.Tensor] = None,
+ layer_idx: Optional[int] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ causal_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[ZambaHybridDynamicCache] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ cache_position: Optional[torch.LongTensor] = None,
+ transformer_hidden_states: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`ZambaHybridDynamicCache`, *optional*): cached past key and value projection states
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
+ Indices depicting the position of the input sequence tokens in the sequence.
+ """
+
+ residual = hidden_states
+
+ # `transformer_hidden_states` is the output from shared transformer + linear layer (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ # `transformer_hidden_states` is then added to the input to the mamba layer below (as described in eq. (6) of https://huggingface.co/papers/2405.16712).
+ hidden_states = (
+ hidden_states + transformer_hidden_states if transformer_hidden_states is not None else hidden_states
+ )
+ hidden_states = self.input_layernorm(hidden_states)
+
+ hidden_states = self.mamba(
+ hidden_states=hidden_states,
+ cache_params=past_key_values,
+ attention_mask=attention_mask,
+ )
+
+ self_attn_weights = None
+
+ # residual connection after mamba
+ hidden_states = residual + hidden_states
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights,)
+
+ if use_cache:
+ outputs += (past_key_values,)
+
+ return outputs
+
+
+class ZambaHybridLayer(nn.Module):
+ def __init__(self, shared_transf: ZambaAttentionDecoderLayer, linear: nn.Linear, mamba: ZambaMambaDecoderLayer):
+ super().__init__()
+ self.shared_transf = shared_transf
+ self.linear = linear
+ self.mamba_decoder = mamba
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: Optional[torch.Tensor] = None,
+ layer_idx: Optional[int] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ causal_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[ZambaHybridDynamicCache] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ cache_position: Optional[torch.LongTensor] = None,
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output that will be concatenated with
+ hidden activations to form the input of the shared transformer layer.
+ layer_idx (`int`): layer number.
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`ZambaHybridDynamicCache`, *optional*): cached past key and value projection states
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
+ Indices depicting the position of the input sequence tokens in the sequence.
+ """
+
+ layer_outputs = self.shared_transf(
+ hidden_states,
+ original_hidden_states=original_hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=causal_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ cache_position=cache_position,
+ )
+
+ transformer_hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ self_attn_weights = layer_outputs[1]
+
+ transformer_hidden_states = self.linear(transformer_hidden_states)
+
+ layer_outputs = self.mamba_decoder(
+ hidden_states,
+ transformer_hidden_states=transformer_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ cache_position=cache_position,
+ )
+
+ if output_attentions:
+ layer_outputs = (layer_outputs[0], self_attn_weights) + layer_outputs[2:]
+
+ return layer_outputs
+
+
+@auto_docstring
+class ZambaPreTrainedModel(PreTrainedModel):
+ config: ZambaConfig
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["ZambaAttentionDecoderLayer", "ZambaMambaDecoderLayer"]
+ _skip_keys_device_placement = "past_key_values"
+ _supports_flash_attn = False
+ _supports_sdpa = False
+ # Note: only supports ZambaHybridDynamicCache
+ _is_stateful = True
+
+ def _init_weights(self, module):
+ std = self.config.initializer_range
+ if isinstance(module, (nn.Linear, nn.Conv1d)):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.Embedding):
+ module.weight.data.normal_(mean=0.0, std=std)
+ if module.padding_idx is not None:
+ module.weight.data[module.padding_idx].zero_()
+ elif isinstance(module, ZambaRMSNorm):
+ module.weight.data.fill_(1.0)
+ elif isinstance(module, ZambaMambaMixer):
+ module.x_proj_weight.data.normal_(mean=0.0, std=std)
+ dt_init_std = self.config.mamba_dt_rank**-0.5
+ nn.init.uniform_(module.dt_proj_weight, -dt_init_std, dt_init_std)
+
+ mamba_head_dim = self.config.mamba_expand * self.config.hidden_size // self.config.n_mamba_heads
+ dt = torch.exp(
+ torch.rand(self.config.n_mamba_heads, mamba_head_dim)
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
+ + math.log(self.config.time_step_min)
+ ).clamp(min=self.config.time_step_floor)
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
+ module.dt_proj_bias.data.copy_(inv_dt)
+
+ A = torch.arange(1, module.ssm_state_size + 1, dtype=torch.float32)[None, :]
+ A = A.expand(module.intermediate_size, -1).contiguous()
+ module.A_log.data.copy_(torch.log(A).reshape(module.n_mamba_heads, module.mamba_head_dim, -1))
+ module.D.data.fill_(1.0)
+
+
+@auto_docstring
+class ZambaModel(ZambaPreTrainedModel):
+ """
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ZambaDecoderLayer`]
+
+ Args:
+ config: ZambaConfig
+ """
+
+ def __init__(self, config: ZambaConfig):
+ super().__init__(config)
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ block = ZambaAttentionDecoderLayer(config)
+ mamba_layers = []
+ linear_layers = []
+ self.layers_block_type = config.layers_block_type
+ for i in range(config.num_hidden_layers):
+ if config.layers_block_type[i] == "mamba":
+ mamba_layers.append(ZambaMambaDecoderLayer(config, layer_idx=i))
+ elif config.layers_block_type[i] == "hybrid":
+ linear_layers.append(nn.Linear(self.config.hidden_size, self.config.hidden_size, bias=False))
+ mamba_layers.append(ZambaMambaDecoderLayer(config, layer_idx=i))
+ mamba_layers = iter(mamba_layers)
+ linear_layers = iter(linear_layers)
+ layers = []
+ self._tied_weights_keys = []
+ for layer_id, layer_type in enumerate(self.layers_block_type):
+ if layer_type == "hybrid":
+ prefix_name = f"layers.{layer_id}."
+ tied_keys = [
+ "shared_transf.self_attn.q_proj.weight",
+ "shared_transf.self_attn.k_proj.weight",
+ "shared_transf.self_attn.v_proj.weight",
+ "shared_transf.self_attn.o_proj.weight",
+ "shared_transf.feed_forward.gate_proj.weight",
+ "shared_transf.feed_forward.up_proj.weight",
+ "shared_transf.feed_forward.down_proj.weight",
+ "shared_transf.input_layernorm.weight",
+ "shared_transf.pre_ff_layernorm.weight",
+ ]
+ self._tied_weights_keys = [*self._tied_weights_keys, *[prefix_name + key for key in tied_keys]]
+ layers.append(ZambaHybridLayer(block, next(linear_layers), next(mamba_layers)))
+ else:
+ layers.append(next(mamba_layers))
+ self.layers = nn.ModuleList(layers)
+
+ self._attn_implementation = config._attn_implementation
+ self.final_layernorm = ZambaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ self.gradient_checkpointing = False
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[ZambaHybridDynamicCache] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ ) -> Union[tuple, BaseModelOutputWithPast]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError(
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
+ )
+
+ if self.gradient_checkpointing and self.training and use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
+ )
+ use_cache = False
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ hidden_states = inputs_embeds
+
+ original_hidden_states = torch.clone(inputs_embeds)
+ # original_hidden_states: word embedding output that will be concatenated with hidden activations to form the input of the shared transformer layer
+
+ if use_cache and past_key_values is None:
+ logger.warning_once(
+ "Zamba requires an initialized `ZambaHybridDynamicCache` to return a cache. None was "
+ "provided, so no cache will be returned."
+ )
+
+ if cache_position is None:
+ cache_position = torch.arange(hidden_states.shape[1], device=hidden_states.device)
+ if position_ids is None:
+ position_ids = cache_position.unsqueeze(0)
+
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
+
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+
+ for layer_idx, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ if self.gradient_checkpointing and self.training:
+ layer_outputs = self._gradient_checkpointing_func(
+ layer.__call__,
+ hidden_states,
+ original_hidden_states,
+ layer_idx,
+ attention_mask,
+ causal_mask,
+ past_key_values,
+ output_attentions,
+ use_cache,
+ cache_position,
+ )
+ else:
+ layer_outputs = layer(
+ hidden_states,
+ original_hidden_states=original_hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=attention_mask,
+ causal_mask=causal_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ cache_position=cache_position,
+ )
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ if layer_outputs[1] is not None:
+ # append attentions only of attention layers. Mamba layers return `None` as the attention weights
+ all_self_attns += (layer_outputs[1],)
+
+ hidden_states = self.final_layernorm(hidden_states)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ if past_key_values and not past_key_values.has_previous_state:
+ past_key_values.has_previous_state = True
+
+ output = BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ )
+ return output if return_dict else output.to_tuple()
+
+ # Copied from transformers.models.jamba.modeling_jamba.JambaModel._update_causal_mask
+ def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
+ if self.config._attn_implementation == "flash_attention_2":
+ if attention_mask is not None and 0.0 in attention_mask:
+ return attention_mask
+ return None
+
+ dtype, device = input_tensor.dtype, input_tensor.device
+ min_dtype = torch.finfo(dtype).min
+ sequence_length = input_tensor.shape[1]
+ target_length = cache_position[-1] + 1
+
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
+ if sequence_length != 1:
+ causal_mask = torch.triu(causal_mask, diagonal=1)
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
+ if attention_mask is not None:
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
+ if attention_mask.dim() == 2:
+ mask_length = attention_mask.shape[-1]
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
+
+ if (
+ self.config._attn_implementation == "sdpa"
+ and attention_mask is not None
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
+ ):
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
+ # Details: https://github.com/pytorch/pytorch/issues/110213
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
+
+ return causal_mask
+
+
+# Adapted from transformers.models.jamba.modeling_jamba.JambaForCausalLM with Jamba->Zamba, JAMBA->ZAMBA
+class ZambaForCausalLM(ZambaPreTrainedModel, GenerationMixin):
+ def __init__(self, config: ZambaConfig):
+ super().__init__(config)
+ self.model = ZambaModel(config)
+ self._tied_weights_keys = ["lm_head.weight", *self.model._tied_weights_keys]
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[ZambaHybridDynamicCache] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ logits_to_keep: Union[int, torch.Tensor] = 0,
+ **kwargs,
+ ) -> Union[tuple, CausalLMOutputWithPast]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, ZambaForCausalLM
+
+ >>> model = ZambaForCausalLM.from_pretrained("Zyphra/Zamba-7B-v1")
+ >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/Zamba-7B-v1")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ cache_position=cache_position,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return (loss,) + output if loss is not None else output
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ attention_mask=None,
+ inputs_embeds=None,
+ cache_position=None,
+ position_ids=None,
+ use_cache=True,
+ **kwargs,
+ ):
+ # Overwritten -- has a unique cache type, `ZambaHybridDynamicCache`
+
+ empty_past_kv = past_key_values is None
+
+ # Omit tokens covered by past_key_values
+ if not empty_past_kv:
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
+ # (we can't check exception 3 while compiling)
+ if (
+ inputs_embeds is not None # Exception 1
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
+ ):
+ input_ids = input_ids[:, -cache_position.shape[0] :]
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
+ input_ids = input_ids[:, cache_position]
+ else:
+ past_key_values = ZambaHybridDynamicCache(
+ self.config, input_ids.shape[0], dtype=self.dtype, device=self.device
+ )
+
+ if attention_mask is not None and position_ids is None:
+ # create position_ids on the fly for batch generation
+ position_ids = attention_mask.long().cumsum(-1) - 1
+ position_ids.masked_fill_(attention_mask == 0, 1)
+ if not empty_past_kv:
+ position_ids = position_ids[:, -input_ids.shape[1] :]
+
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
+ if inputs_embeds is not None and empty_past_kv:
+ model_inputs = {"inputs_embeds": inputs_embeds}
+ else:
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
+
+ model_inputs.update(
+ {
+ "position_ids": position_ids,
+ "past_key_values": past_key_values,
+ "use_cache": use_cache,
+ "attention_mask": attention_mask,
+ "logits_to_keep": self.config.num_logits_to_keep,
+ "cache_position": cache_position,
+ }
+ )
+ return model_inputs
+
+
+@auto_docstring(
+ custom_intro="""
+ The Zamba Model with a sequence classification head on top (linear layer).
+
+ [`ZambaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
+ (e.g. GPT-2) do.
+
+ Since it does classification on the last token, it requires to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """
+)
+class ZambaForSequenceClassification(ZambaPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.model = ZambaModel(config)
+ self._tied_weights_keys = self.model._tied_weights_keys
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, SequenceClassifierOutputWithPast]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ hidden_states = transformer_outputs[0]
+ logits = self.score(hidden_states)
+
+ if input_ids is not None:
+ batch_size = input_ids.shape[0]
+ else:
+ batch_size = inputs_embeds.shape[0]
+
+ if self.config.pad_token_id is None and batch_size != 1:
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
+ if self.config.pad_token_id is None:
+ last_non_pad_token = -1
+ elif input_ids is not None:
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
+ else:
+ last_non_pad_token = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
+
+ loss = None
+ if labels is not None:
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(pooled_logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(pooled_logits, labels)
+ if not return_dict:
+ output = (pooled_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = ["ZambaForCausalLM", "ZambaForSequenceClassification", "ZambaModel", "ZambaPreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..00db458c72ebd5513d8e8cf1b186f49886745a2a
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/__init__.py
@@ -0,0 +1,27 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_zamba2 import *
+ from .modeling_zamba2 import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/configuration_zamba2.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/configuration_zamba2.py
new file mode 100644
index 0000000000000000000000000000000000000000..2789e508f6fa7e4c79de9abefd0da150ec1aeb2e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/configuration_zamba2.py
@@ -0,0 +1,241 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/zamba2/modular_zamba2.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_zamba2.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# coding=utf-8
+# Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from ...configuration_utils import PretrainedConfig
+
+
+class Zamba2Config(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`Zamba2Model`]. It is used to instantiate a
+ Zamba2 model according to the specified arguments, defining the model architecture. Instantiating a configuration
+ with the defaults will yield a similar configuration to that of the Zamba2 model.
+
+ [Zyphra/Zamba2-2.7B](https://huggingface.co/Zyphra/Zamba2-2.7B)
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+ Args:
+ vocab_size (`int`, *optional*, defaults to 32000):
+ Vocabulary size of the Zamba2 model. Defines the number of different tokens that can be represented by the
+ `inputs_ids` passed when calling [`Zamba2Model`]
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
+ The maximum sequence length that this model might ever be used with.
+ hidden_size (`int`, *optional*, defaults to 2560):
+ Dimension of the hidden representations.
+ num_hidden_layers (`int`, *optional*, defaults to 54):
+ Number of hidden layers in the model.
+ layers_block_type (`list`, *optional*):
+ List of layer types, which can be either "mamba" or "hybrid".
+ mamba_d_state (`int`, *optional*, defaults to 64): shape of the state space latents.
+ mamba_d_conv (`int`, *optional*, defaults to 4): Size of the convolution kernel.
+ mamba_expand (`int`, *optional*, defaults to 2): Expanding factor used to determine the intermediate size.
+ mamba_ngroups (`int`, *optional*, defaults to 1):
+ Number of groups for the evolution matrices of mamba 2.
+ time_step_min (`float`, *optional*, defaults to 0.001):
+ Minimum `time_step` used to bound `dt_proj.bias`.
+ time_step_max (`float`, *optional*, defaults to 0.1):
+ Maximum `time_step` used to bound `dt_proj.bias`.
+ time_step_floor (`float`, *optional*, defaults to 0.0001):
+ Minimum clamping value of the `dt_proj.bias` layer initialization.
+ time_step_limit (`tuple`, *optional*):
+ Accepted range of time step values.
+ n_mamba_heads (`int`, *optional*, defaults to 8):
+ Number of heads for the evolution matrices of mamba 2.
+ use_conv_bias (`bool`, *optional*, defaults to `True`):
+ Whether or not to use bias in the convolution layer of the mixer block.
+ chunk_size (`int`, *optional*, defaults to 256):
+ Size of the chunks that will comprise the sequence.
+ use_mem_eff_path (`bool`, *optional*, defaults to `False`):
+ Whether or not to use the fused conv1d and scan in mamba2 layers.
+ add_bias_linear (`bool`, *optional*, defaults to `False`):
+ Flag indicating whether or not to use bias in various layers
+ intermediate_size (`int`, *optional*, defaults to 4 * hidden_size):
+ Dimension of the MLP representations.
+ hidden_act (`str`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the MLP.
+ num_attention_heads (`int`, *optional*, defaults to 32):
+ Number of attention heads for each attention layer in the Transformer decoder.
+ num_key_value_heads (`int`, *optional*):
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
+ `num_key_value_heads=None`, the model will use Multi Head Attention (MHA), if
+ `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When
+ converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed
+ by meanpooling all the original heads within that group. For more details, check out [this
+ paper](https://huggingface.co/papers/2305.13245).
+ attention_dropout (`float`, *optional*, defaults to 0.0):
+ The dropout ratio for the attention probabilities.
+ num_mem_blocks (`int`, *optional*, defaults to 1):
+ Number of unshared transformer blocks.
+ use_shared_attention_adapter (`bool`, *optional*, defaults to `False`):
+ If True, unshared adapters (formally the same as LoRA but used in the base model) will be added to the q, k, v projectors in the shared attention layers.
+ adapter_rank (`int`, *optional*, defaults to 128):
+ Rank of the adapter in the shared MLP and shared attention layers.
+ use_mem_rope (`bool`, *optional*, defaults to `False`):
+ If True, includes RoPE in the shared attention layers.
+ rope_theta (`float`, *optional*, defaults to `10000.0`):
+ The base period of the RoPE embeddings.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ rms_norm_eps (`float`, *optional*, defaults to 1e-05):
+ The epsilon used by the rms normalization layers.
+ use_cache (`bool`, *optional*, defaults to `True`):
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True`.
+ num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
+ integer value, only last `num_logits_to_keep` logits will be calculated. Default is 1 because only the
+ logits of the last prompt token are needed for generation. For long sequences, the logits for the entire
+ sequence may use a lot of memory so, setting `num_logits_to_keep=1` will reduce memory footprint
+ significantly.
+ pad_token_id (`int`, *optional*, defaults to 0):
+ The id of the padding token.
+ bos_token_id (`int`, *optional*, defaults to 1):
+ The id of the "beginning-of-sequence" token.
+ eos_token_id (`int`, *optional*, defaults to 2):
+ The id of the "end-of-sequence" token.
+ use_long_context (`bool`, *optional*, defaults to `False`):
+ Activates the context-extended version of Zamba by modifying RoPE.
+ ```python
+ >>> from transformers import Zamba2Model, Zamba2Config
+ >>> # Initializing a Zamba2-2.7B style configuration
+ >>> configuration = Zamba2Config()
+ >>> # Initializing a model from the Zamba2-2.7B style configuration
+ >>> model = Zamba2Model(configuration)
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "zamba2"
+ attribute_map = {"head_dim": "attention_head_dim"}
+ keys_to_ignore_at_inference = ["past_key_values"]
+
+ def __init__(
+ self,
+ vocab_size=32000,
+ max_position_embeddings=4096,
+ hidden_size=2560,
+ num_hidden_layers=54,
+ layers_block_type=None,
+ mamba_d_state=64,
+ mamba_d_conv=4,
+ mamba_expand=2,
+ mamba_ngroups=1,
+ time_step_min=0.001,
+ time_step_max=0.1,
+ time_step_floor=1e-4,
+ time_step_limit=None,
+ n_mamba_heads=8,
+ use_conv_bias=True,
+ chunk_size=256,
+ use_mem_eff_path=False,
+ add_bias_linear=False,
+ intermediate_size=None,
+ hidden_act="gelu",
+ num_attention_heads=32,
+ num_key_value_heads=None,
+ attention_dropout=0.0,
+ num_mem_blocks=1,
+ use_shared_attention_adapter=False,
+ adapter_rank=128,
+ use_mem_rope=False,
+ rope_theta=10000,
+ initializer_range=0.02,
+ rms_norm_eps=1e-5,
+ use_cache=True,
+ num_logits_to_keep=1,
+ pad_token_id=0,
+ bos_token_id=1,
+ eos_token_id=2,
+ use_long_context=False,
+ **kwargs,
+ ):
+ super().__init__(
+ pad_token_id=pad_token_id,
+ bos_token_id=bos_token_id,
+ eos_token_id=eos_token_id,
+ **kwargs,
+ )
+ self.vocab_size = vocab_size
+ self.max_position_embeddings = max_position_embeddings
+ self.hidden_size = hidden_size
+ if intermediate_size is None:
+ self.intermediate_size = 4 * hidden_size
+ else:
+ self.intermediate_size = intermediate_size
+ self.hidden_act = hidden_act
+ self.num_hidden_layers = num_hidden_layers
+ self.num_attention_heads = num_attention_heads
+ self.num_mem_blocks = num_mem_blocks
+ self.attention_hidden_size = 2 * hidden_size
+ self.attention_head_dim = 2 * self.hidden_size // self.num_attention_heads
+ self.attention_dropout = attention_dropout
+ self.use_mem_rope = use_mem_rope
+ self.use_long_context = use_long_context
+ if use_mem_rope and use_long_context:
+ a = 8
+ rope_theta = rope_theta * a ** (self.attention_head_dim / (self.attention_head_dim - 2))
+ self.rope_theta = rope_theta
+ self.mamba_d_state = mamba_d_state
+ self.mamba_d_conv = mamba_d_conv
+ self.mamba_expand = mamba_expand
+ self.add_bias_linear = add_bias_linear
+ self.mamba_ngroups = mamba_ngroups
+ self.n_mamba_heads = n_mamba_heads
+ self.mamba_headdim = int(mamba_expand * hidden_size) // n_mamba_heads
+ self.use_conv_bias = use_conv_bias
+ self.chunk_size = chunk_size
+ self.time_step_limit = time_step_limit
+ self.use_shared_attention_adapter = use_shared_attention_adapter
+ self.adapter_rank = adapter_rank
+ self.time_step_min = time_step_min
+ self.time_step_max = time_step_max
+ self.time_step_floor = time_step_floor
+ if use_long_context:
+ self.max_position_embeddings = 16384
+ if num_key_value_heads is None:
+ num_key_value_heads = num_attention_heads
+ self.num_key_value_heads = num_key_value_heads
+ self.num_attention_heads = num_attention_heads
+ self.kv_channels = self.hidden_size // self.num_attention_heads
+ self.num_query_groups = self.num_attention_heads
+ # Below, "mamba" stands for mamba layer, "hybrid" stands for hybrid layer (composed by a shared transformer followed by mamba layer)
+ if layers_block_type is None:
+ self.layers_block_type = (
+ ["mamba"]
+ + (["mamba"] * 5 + ["hybrid"]) * 7
+ + ["mamba"] * 4
+ + ["hybrid"]
+ + ["mamba"] * 3
+ + ["hybrid"]
+ + ["mamba"] * 2
+ )
+ else:
+ self.layers_block_type = layers_block_type
+ self.initializer_range = initializer_range
+ self.rms_norm_eps = rms_norm_eps
+ self.use_cache = use_cache
+ self.num_logits_to_keep = num_logits_to_keep
+ self.hybrid_layer_ids = [index for index, type in enumerate(self.layers_block_type) if type == "hybrid"]
+ self.use_mem_eff_path = use_mem_eff_path
+
+
+__all__ = ["Zamba2Config"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modeling_zamba2.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modeling_zamba2.py
new file mode 100644
index 0000000000000000000000000000000000000000..6881f1278e6e71e6b15dd469486e5131397ba71e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modeling_zamba2.py
@@ -0,0 +1,1734 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/zamba2/modular_zamba2.py.
+# Do NOT edit this file manually as any edits will be overwritten by the generation of
+# the file from the modular. If any change should be done, please apply the change to the
+# modular_zamba2.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# coding=utf-8
+# Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+import re
+from itertools import cycle
+from typing import Any, Callable, Optional, Union
+
+import torch
+from torch import nn
+from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
+
+from ...activations import ACT2FN
+from ...cache_utils import Cache
+from ...generation import GenerationMixin
+from ...modeling_attn_mask_utils import AttentionMaskConverter
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
+from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import auto_docstring, logging
+from ...utils.deprecation import deprecate_kwarg
+from ...utils.import_utils import is_causal_conv1d_available, is_mamba_ssm_available
+from .configuration_zamba2 import Zamba2Config
+
+
+if is_mamba_ssm_available():
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
+else:
+ selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined = None, None, None
+
+if is_causal_conv1d_available():
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
+else:
+ causal_conv1d_update, causal_conv1d_fn = None, None
+
+logger = logging.get_logger(__name__)
+
+
+class Zamba2RMSNormGated(torch.nn.Module):
+ def __init__(self, hidden_size, group_size, eps=1e-6):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+ self.group_size = group_size
+
+ def forward(self, hidden_states, gate=None):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ if gate is not None:
+ hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
+ *prefix_dims, last_dim = hidden_states.shape
+ group_count = last_dim // self.group_size
+ hidden_states_group = hidden_states.view(*prefix_dims, group_count, self.group_size)
+ variance = hidden_states_group.pow(2).mean(-1, keepdim=True)
+ hidden_states_group = hidden_states_group * torch.rsqrt(variance + self.variance_epsilon)
+ hidden_states = hidden_states_group.view(*prefix_dims, group_count * self.group_size)
+ return self.weight * hidden_states.to(input_dtype)
+
+
+class Zamba2RMSNorm(nn.Module):
+ def __init__(self, hidden_size, eps=1e-6):
+ """
+ Zamba2RMSNorm is equivalent to T5LayerNorm
+ """
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+
+ def forward(self, hidden_states):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
+ return self.weight * hidden_states.to(input_dtype)
+
+ def extra_repr(self):
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
+
+
+class Zamba2HybridDynamicCache:
+ """
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
+ (which has a constant shape regardless of seq_len).
+
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
+ """
+
+ is_compileable = False
+
+ def __init__(
+ self, config: Zamba2Config, batch_size: int, dtype: torch.dtype = torch.float16, device: Optional[str] = None
+ ):
+ self.dtype = dtype
+ self.layers_block_type = config.layers_block_type
+ self.has_previous_state = False
+ self.intermediate_size = int(config.mamba_expand * config.hidden_size)
+ self.ssm_state_size = config.mamba_d_state
+ self.conv_kernel_size = config.mamba_d_conv
+ self.n_mamba_heads = config.n_mamba_heads
+ self.transformer_layers = []
+ self._modules = {}
+ self._parameters = {}
+ self._buffers = {}
+ self.conv_states = {}
+ self.ssm_states = {}
+ for i in range(config.num_hidden_layers):
+ self.conv_states[i] = torch.zeros(
+ batch_size,
+ self.intermediate_size + 2 * config.mamba_ngroups * config.mamba_d_state,
+ self.conv_kernel_size,
+ device=device,
+ dtype=dtype,
+ )
+ self.ssm_states[i] = torch.zeros(
+ batch_size, self.n_mamba_heads, config.mamba_headdim, self.ssm_state_size, device=device, dtype=dtype
+ )
+ if self.layers_block_type[i] == "hybrid":
+ self.transformer_layers.append(i)
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
+
+ def __len__(self):
+ return len(self.key_cache)
+
+ def __getitem__(self, layer_idx: int) -> tuple[torch.Tensor, torch.Tensor]:
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
+
+ def update(
+ self,
+ key_states: torch.Tensor,
+ value_states: torch.Tensor,
+ layer_idx: int,
+ cache_kwargs: Optional[dict[str, Any]] = None,
+ ) -> tuple[torch.Tensor, torch.Tensor]:
+ # Update the cache
+ if self.key_cache[layer_idx].shape[-1] == 0:
+ self.key_cache[layer_idx] = key_states
+ self.value_cache[layer_idx] = value_states
+ else:
+ self.key_cache[layer_idx] = torch.cat([self.key_cache[layer_idx], key_states], dim=2)
+ self.value_cache[layer_idx] = torch.cat([self.value_cache[layer_idx], value_states], dim=2)
+
+ return self.key_cache[layer_idx], self.value_cache[layer_idx]
+
+ def reorder_cache(self, beam_idx: torch.LongTensor):
+ """Reorders the cache for beam search, given the selected beam indices."""
+ for layer_idx in range(len(self.key_cache)):
+ device = self.key_cache[layer_idx].device
+ self.key_cache[layer_idx] = self.key_cache[layer_idx].index_select(0, beam_idx.to(device))
+ device = self.value_cache[layer_idx].device
+ self.value_cache[layer_idx] = self.value_cache[layer_idx].index_select(0, beam_idx.to(device))
+
+ device = self.conv_states[layer_idx].device
+ self.conv_states[layer_idx] = self.conv_states[layer_idx].index_select(0, beam_idx.to(device))
+ device = self.ssm_states[layer_idx].device
+ self.ssm_states[layer_idx] = self.ssm_states[layer_idx].index_select(0, beam_idx.to(device))
+
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
+ # take any layer that contains cache and not empty tensor
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
+ if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx].numel() == 0:
+ return 0
+ return self.key_cache[layer_idx].shape[-2]
+
+ def update_conv_state(
+ self, layer_idx: int, new_conv_state: torch.Tensor, cache_position: torch.LongTensor
+ ) -> torch.Tensor:
+ conv_state = self.conv_states[layer_idx]
+ cache_position = cache_position.clamp(0, self.conv_kernel_size - 1)
+
+ conv_state = conv_state.roll(shifts=-1, dims=-1)
+ conv_state[:, :, cache_position] = new_conv_state.to(conv_state.device)
+ self.conv_states[layer_idx].zero_()
+ self.conv_states[layer_idx] += conv_state
+ return self.conv_states[layer_idx]
+
+ def reset(self):
+ self.conv_states.zero_()
+ self.ssm_states.zero_()
+
+
+class Zamba2RotaryEmbedding(nn.Module):
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
+
+ def __init__(self, config: Zamba2Config, device=None):
+ super().__init__()
+ # BC: "rope_type" was originally "type"
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
+ else:
+ self.rope_type = "default"
+ self.max_seq_len_cached = config.max_position_embeddings
+ self.original_max_seq_len = config.max_position_embeddings
+
+ self.config = config
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
+
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
+ self.original_inv_freq = self.inv_freq
+
+ @torch.no_grad()
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
+ def forward(self, x, position_ids):
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
+ position_ids_expanded = position_ids[:, None, :].float()
+
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
+ emb = torch.cat((freqs, freqs), dim=-1)
+ cos = emb.cos() * self.attention_scaling
+ sin = emb.sin() * self.attention_scaling
+
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
+
+
+def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
+ """
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
+ """
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
+ if n_rep == 1:
+ return hidden_states
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: Optional[torch.Tensor],
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ key_states = repeat_kv(key, module.num_key_value_groups)
+ value_states = repeat_kv(value, module.num_key_value_groups)
+
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
+ attn_weights = attn_weights + causal_mask
+
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
+ attn_output = torch.matmul(attn_weights, value_states)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+
+ return attn_output, attn_weights
+
+
+def rotate_half(x):
+ """Rotates half the hidden dims of the input."""
+ x1 = x[..., : x.shape[-1] // 2]
+ x2 = x[..., x.shape[-1] // 2 :]
+ return torch.cat((-x2, x1), dim=-1)
+
+
+def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
+ """Applies Rotary Position Embedding to the query and key tensors.
+
+ Args:
+ q (`torch.Tensor`): The query tensor.
+ k (`torch.Tensor`): The key tensor.
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
+ position_ids (`torch.Tensor`, *optional*):
+ Deprecated and unused.
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
+ Returns:
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
+ """
+ cos = cos.unsqueeze(unsqueeze_dim)
+ sin = sin.unsqueeze(unsqueeze_dim)
+ q_embed = (q * cos) + (rotate_half(q) * sin)
+ k_embed = (k * cos) + (rotate_half(k) * sin)
+ return q_embed, k_embed
+
+
+class Zamba2Attention(nn.Module):
+ """
+ Multi-headed attention from 'Attention Is All You Need' paper.
+
+ Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
+ The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
+ The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ Additionally, replaced
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2)
+ Finally, this attention layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this
+ layer is tied, un-tied adapters (formally the same as LoRA but used in the base model) modules are added to the q, k, v projectors to increase
+ expressivity with a small memory overhead (see Fig. 2 of https://huggingface.co/papers/2411.15242).
+ """
+
+ def __init__(
+ self,
+ config: Zamba2Config,
+ layer_idx: Optional[int] = None,
+ num_fwd_mem_blocks: Optional[int] = None,
+ block_id: Optional[int] = None,
+ ):
+ super().__init__()
+ self.config = config
+ self.layer_idx = layer_idx
+
+ self.attention_hidden_size = config.attention_hidden_size
+ self.head_dim = config.attention_head_dim
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
+ self.max_position_embeddings = config.max_position_embeddings
+ self.scaling = (self.head_dim / 2) ** -0.5
+ self.is_causal = True
+ self.attention_dropout = config.attention_dropout
+
+ self.q_proj = nn.Linear(config.attention_hidden_size, config.num_attention_heads * self.head_dim, bias=False)
+ self.k_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.v_proj = nn.Linear(config.attention_hidden_size, config.num_key_value_heads * self.head_dim, bias=False)
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=False)
+ self.num_fwd_mem_blocks = num_fwd_mem_blocks
+ self.layer_block_map = config.hybrid_layer_ids
+ self.block_id = block_id
+
+ if config.use_shared_attention_adapter:
+ self.linear_q_adapter_list = nn.ModuleList([])
+ self.linear_k_adapter_list = nn.ModuleList([])
+ self.linear_v_adapter_list = nn.ModuleList([])
+
+ for i in range(self.num_fwd_mem_blocks):
+ if i % config.num_mem_blocks == block_id:
+ linear_q_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ linear_k_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ linear_v_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ else:
+ linear_q_adapter = nn.Identity()
+ linear_k_adapter = nn.Identity()
+ linear_v_adapter = nn.Identity()
+ self.linear_q_adapter_list.append(linear_q_adapter)
+ self.linear_k_adapter_list.append(linear_k_adapter)
+ self.linear_v_adapter_list.append(linear_v_adapter)
+
+ self.layer_dic = {value: index for index, value in enumerate(self.layer_block_map)}
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[Zamba2HybridDynamicCache] = None,
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states)
+ key_states = self.k_proj(hidden_states)
+ value_states = self.v_proj(hidden_states)
+ if self.config.use_shared_attention_adapter:
+ adapter_layer_idx = self.layer_dic[layer_idx]
+ query_states = query_states + self.linear_q_adapter_list[adapter_layer_idx](hidden_states)
+ key_states = key_states + self.linear_k_adapter_list[adapter_layer_idx](hidden_states)
+ value_states = value_states + self.linear_v_adapter_list[adapter_layer_idx](hidden_states)
+
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
+
+ if self.config.use_mem_rope:
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, layer_idx)
+
+ attention_interface: Callable = eager_attention_forward
+ if self.config._attn_implementation != "eager":
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+# Helper methods for segment sum computation
+
+
+def pad_tensor_by_size(input_tensor: torch.Tensor, pad_size: int):
+ """
+ Padding x tensor with `pad_size` on the seq_len dim (dim=1)
+
+ Assumes that we only have tensors of either size 4 or 3
+ """
+ pad_shape = (0, 0, 0, 0, 0, pad_size, 0, 0) if len(input_tensor.shape) == 4 else (0, 0, 0, pad_size, 0, 0)
+
+ return torch.nn.functional.pad(input_tensor, pad_shape, mode="constant", value=0)
+
+
+def reshape_into_chunks(input_tensor, pad_size, chunk_size):
+ """
+ Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
+ simultaneously splitting it into chunk sequences.
+
+ Assumes that we only have tensors of either size 4 or 3
+ """
+ # [bsz, seq_len, ...] -> [bsz, seq_len multiple of chunk_size, ...]
+ input_tensor = pad_tensor_by_size(input_tensor, pad_size)
+
+ if len(input_tensor.shape) == 3:
+ # [bsz, seq_len multiple of chunk_size, num_heads] -> [bsz, -1, chunk_size, num_heads]
+ return input_tensor.reshape(input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2])
+ else:
+ # [bsz, seq_len multiple of chunk_size, num_heads, head_dim or state_size] -> [bsz, -1, chunk_size, num_heads, head_dim or state_size]
+ return input_tensor.reshape(
+ input_tensor.shape[0], -1, chunk_size, input_tensor.shape[2], input_tensor.shape[3]
+ )
+
+
+def segment_sum(input_tensor):
+ """
+ More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
+ """
+ chunk_size = input_tensor.size(-1)
+ # 1. expand input tensor to have an additional dimension and repeat along that dimension
+ # [..., chunk_size] -> [..., chunk_size, chunk_size]
+ input_tensor = input_tensor[..., None].expand(*input_tensor.size(), chunk_size)
+ # 2. create a lower triangular mask with the diagonal set to 0 to 0 out elements above diag
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=-1)
+ input_tensor = input_tensor.masked_fill(~mask, 0)
+ # 3. compute actual cumsum
+ tensor_segsum = torch.cumsum(input_tensor, dim=-2)
+
+ # 4. apply mask to keep only the lower triangular part of the cumulative sum result (incl diagonal this time)
+ mask = torch.tril(torch.ones(chunk_size, chunk_size, device=input_tensor.device, dtype=torch.bool), diagonal=0)
+ tensor_segsum = tensor_segsum.masked_fill(~mask, -torch.inf)
+ return tensor_segsum
+
+
+is_fast_path_available = all((selective_state_update, causal_conv1d_fn, causal_conv1d_update))
+
+
+class Zamba2MambaMixer(nn.Module):
+ """
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
+ and is why Mamba is called **selective** state spaces)
+ """
+
+ def __init__(self, config: Zamba2Config, layer_idx: Optional[int] = None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.ssm_state_size = config.mamba_d_state
+ self.conv_kernel_size = config.mamba_d_conv
+ self.intermediate_size = int(config.mamba_expand * self.hidden_size)
+ self.layer_idx = layer_idx
+ self.use_conv_bias = config.use_conv_bias
+ self.activation = "silu"
+ self.act = nn.SiLU()
+ self.use_mem_eff_path = config.use_mem_eff_path
+
+ self.n_groups = config.mamba_ngroups
+ self.head_dim = config.mamba_headdim
+ self.num_heads = self.config.n_mamba_heads
+ self.chunk_size = config.chunk_size
+
+ self.time_step_limit = config.time_step_limit
+ self.time_step_min = config.time_step_min
+ self.time_step_max = config.time_step_max
+
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
+ self.conv1d = nn.Conv1d(
+ in_channels=self.conv_dim,
+ out_channels=self.conv_dim,
+ bias=True,
+ kernel_size=config.mamba_d_conv,
+ groups=self.conv_dim,
+ padding=config.mamba_d_conv - 1,
+ )
+
+ # projection of the input hidden states
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
+ self.in_proj = nn.Linear(
+ self.hidden_size,
+ projection_size,
+ bias=config.add_bias_linear,
+ )
+ # selective projection used to make dt, B and C input dependent
+
+ # time step projection (discretization)
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
+
+ # S4D real initialization. These are not discretized!
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
+ A = torch.arange(1, self.num_heads + 1)
+ self.A_log = nn.Parameter(torch.log(A))
+ self.A_log._no_weight_decay = True
+ self.norm = Zamba2RMSNormGated(
+ self.intermediate_size, group_size=self.intermediate_size // self.n_groups, eps=1e-5
+ )
+ self.D = nn.Parameter(torch.ones(self.num_heads))
+ self.D._no_weight_decay = True
+
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.add_bias_linear)
+
+ if not is_fast_path_available:
+ logger.warning_once(
+ "The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
+ " https://github.com/Dao-AILab/causal-conv1d"
+ )
+
+ def cuda_kernels_forward(
+ self,
+ hidden_states: torch.Tensor,
+ cache_params: Optional[Zamba2HybridDynamicCache] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ):
+ # set up dimensions for reshapes later
+
+ batch_size, seq_len, _ = hidden_states.shape
+ groups_time_state_size = self.n_groups * self.ssm_state_size
+ d_to_remove = 2 * self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.num_heads
+
+ # getting projected states from cache if it exists
+ if cache_params is not None and cache_params.has_previous_state:
+ in_projected_states = self.in_proj(hidden_states.squeeze(1)) # (B 2D)
+ d_mlp = (in_projected_states.shape[-1] - d_to_remove) // 2
+ split_projection_dim = [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads]
+ _, _, gate, hidden_states_B_C, dt = torch.split(in_projected_states, split_projection_dim, dim=-1)
+
+ hidden_states_B_C = causal_conv1d_update(
+ hidden_states_B_C,
+ cache_params.conv_states[self.layer_idx],
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.activation,
+ )
+
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+ A = -torch.exp(self.A_log.float()) # (nheads,)
+
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
+ hidden_states = selective_state_update(
+ cache_params.ssm_states[self.layer_idx],
+ hidden_states_reshaped,
+ dt,
+ A,
+ B,
+ C,
+ D,
+ z=None,
+ dt_bias=dt_bias,
+ dt_softplus=True,
+ )
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
+ hidden_states = self.norm(hidden_states, gate)
+ out = self.out_proj(hidden_states)[:, None, ...]
+ # if no cache is found, calling the kernel
+ else:
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ # 1. Gated MLP's linear projection
+ projected_states = self.in_proj(hidden_states)
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
+ dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
+ if attention_mask is not None:
+ input_not_masked = torch.all(attention_mask == 1)
+ else:
+ input_not_masked = True
+
+ if self.use_mem_eff_path and self.training and cache_params is None and input_not_masked:
+ out, ssm_state = mamba_split_conv1d_scan_combined(
+ projected_states,
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.dt_bias,
+ A,
+ D=self.D,
+ chunk_size=self.chunk_size,
+ seq_idx=None,
+ activation=self.activation,
+ rmsnorm_weight=self.norm.weight,
+ rmsnorm_eps=self.norm.variance_epsilon,
+ outproj_weight=self.out_proj.weight,
+ outproj_bias=self.out_proj.bias,
+ headdim=self.head_dim,
+ ngroups=self.n_groups,
+ norm_before_gate=False,
+ return_final_states=True,
+ **dt_limit_kwargs,
+ )
+
+ else:
+ gate, hidden_states_B_C, time_step = torch.split(
+ projected_states,
+ [self.intermediate_size, self.conv_dim, self.num_heads],
+ dim=-1,
+ )
+
+ # 1D Convolution
+ if cache_params is not None:
+ hidden_states_B_C_t = hidden_states_B_C.transpose(1, 2)
+ conv_state = nn.functional.pad(
+ hidden_states_B_C_t, (self.conv_kernel_size - hidden_states_B_C_t.shape[-1], 0)
+ )
+ cache_params.conv_states[self.layer_idx].copy_(conv_state)
+ if causal_conv1d_fn is None or self.activation not in ["silu", "swish"]:
+ hidden_states_B_C = self.act(
+ self.conv1d(hidden_states_B_C.transpose(1, 2)).transpose(1, 2)[:, :seq_len]
+ ) # (B, L, self.d_inner + 2 * ngroups * d_state)
+ else:
+ hidden_states_B_C = causal_conv1d_fn(
+ x=hidden_states_B_C.transpose(1, 2),
+ weight=self.conv1d.weight.squeeze(1),
+ bias=self.conv1d.bias,
+ activation=self.activation,
+ ).transpose(1, 2)[:, :seq_len]
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ scan_output, ssm_state = mamba_chunk_scan_combined(
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
+ time_step,
+ A,
+ B.view(batch_size, seq_len, self.n_groups, -1),
+ C.view(batch_size, seq_len, self.n_groups, -1),
+ chunk_size=self.chunk_size,
+ D=self.D,
+ z=None,
+ seq_idx=None,
+ return_final_states=True,
+ dt_bias=self.dt_bias,
+ dt_softplus=True,
+ **dt_limit_kwargs,
+ )
+ if ssm_state is not None and cache_params is not None:
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
+ scan_output = scan_output.view(batch_size, seq_len, -1)
+ # Multiply "gate" branch and apply extra normalization layer
+ scan_output = self.norm(scan_output, gate)
+ out = self.out_proj(scan_output)
+ return out
+
+ # fmt: off
+ def torch_forward(self, input_states, cache_params: Optional[Zamba2HybridDynamicCache]=None, attention_mask: Optional[torch.Tensor]=None):
+ batch_size, seq_len, _ = input_states.shape
+ dtype = input_states.dtype
+ # Gated MLP's linear projection
+ if cache_params is not None and cache_params.has_previous_state:
+ projected_states = self.in_proj(input_states.squeeze(1))
+ else:
+ if attention_mask is not None and not torch.all(attention_mask==1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ input_states = (input_states * attention_mask[:, :, None]).to(dtype)
+ projected_states = self.in_proj(input_states)
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size- self.num_heads) // 2
+ _, _, gate, hidden_states, dt = projected_states.split(
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
+ )
+
+ # Convolution sequence transformation
+ if cache_params is not None:
+ ssm_state = cache_params.ssm_states[self.layer_idx].clone()
+ ssm_state = ssm_state.to(hidden_states.device)
+ if cache_params.has_previous_state:
+ gate = gate.unsqueeze(1)
+ conv_state = cache_params.conv_states[self.layer_idx] # [batch, intermediate_size, conv_kernel_size]
+ conv_state = torch.roll(conv_state, shifts=-1, dims=-1)
+ # handle batched generation - states are copied through
+ conv_state[:, :, -1] = hidden_states[:, 0, :] if hidden_states.ndim == 3 else hidden_states
+ cache_params.conv_states[self.layer_idx].copy_(conv_state)
+ hidden_states = torch.sum(conv_state.to(projected_states.device) * self.conv1d.weight[:, 0, :], dim=-1)
+ if self.use_conv_bias:
+ hidden_states += self.conv1d.bias
+ hidden_states = self.act(hidden_states).to(dtype)[:, None, ...] # [batch, 1, intermediate_size] : decoding
+ else:
+ hidden_states = hidden_states.transpose(1,2)
+ conv_state = nn.functional.pad(
+ hidden_states,
+ (self.conv_kernel_size - hidden_states.shape[-1], 0)
+ )
+ cache_params.conv_states[self.layer_idx].copy_(conv_state)
+ hidden_states = self.act(self.conv1d(hidden_states).transpose(1,2))[:, :seq_len, :] # [batch, intermediate_size, seq_len]
+ if attention_mask is not None and not torch.all(attention_mask==1):
+ dtype = hidden_states.dtype
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ else:
+ ssm_state = torch.zeros(
+ (batch_size, self.num_heads, self.head_dim, self.ssm_state_size),
+ device=hidden_states.device, dtype=dtype
+ )
+ hidden_states = self.act(self.conv1d(hidden_states.transpose(1, 2))[..., :seq_len].transpose(1, 2))
+ hidden_states, B, C = torch.split(hidden_states, [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size], dim=-1)
+ A = -torch.exp(self.A_log.float()) # [num_heads]
+ if cache_params is not None and cache_params.has_previous_state:
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
+ # for batched generation
+ dt = dt[:, None, ...] if dt.ndim == 2 else dt[:, 0, :][:, None, ...]
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
+ # [num_heads] -> [num_heads, head_dim]
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
+
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
+ dt = torch.clamp(dt, self.time_step_min) #, self.time_step_max)
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ # [bsz, num_heads, head_dim, state_size]
+ dA = torch.exp(dt[..., None] * A)
+
+ # Discretize B
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
+ B = B.reshape(batch_size, -1, B.shape[-1])
+ # [bsz, num_heads, head_dim, state_size]
+ dB = dt[..., None] * B[..., None, :]
+
+ # Discretize x into dB
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
+ dBx = dB * hidden_states[..., None]
+
+ # State calculation
+ cache_params.ssm_states[self.layer_idx].copy_(
+ cache_params.ssm_states[self.layer_idx] * dA + dBx
+ )
+
+ # Subsequent output
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
+ C = C.reshape(batch_size, -1, C.shape[-1])
+ # [bsz, num_heads, head_dim]
+
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(C.dtype) # Shape: [b, h, d, n]
+ # Reshape ssm_states to merge the first two dimensions
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
+ y = y.view(batch_size, self.num_heads, self.head_dim)
+
+ # D skip connection
+ # [num_heads] -> [num_heads, head_dim]
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
+ y = (y + hidden_states * D).to(y.dtype)
+
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
+ y = y.reshape(batch_size, -1)[:, None, ...]
+ else:
+ # begin ssd naive implementation without einsums
+ dt = nn.functional.softplus(dt + self.dt_bias)
+ dt = torch.clamp(dt, self.time_step_min)
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
+
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
+
+ # Discretize x and A
+ hidden_states = hidden_states * dt[..., None]
+ A = A.to(hidden_states.dtype) * dt
+
+ # Rearrange into blocks/chunks
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
+
+
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
+ A = A.permute(0, 3, 1, 2)
+ A_cumsum = torch.cumsum(A, dim=-1)
+
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
+ # This is the analog of a causal mask
+ L = torch.exp(segment_sum(A))
+
+ # First, contraction of C and B to get G (attention-weights like)
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, : ,:] # shape: (b, c, l, s, h, n)
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
+
+
+ # Step 2: Compute M, equivalent to applying attention mask to weights
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
+ M = M_intermediate.sum(dim=-1)
+
+ # Step 3: Compute Y_diag (apply to values)
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(3)
+
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
+
+ decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
+ B_decay_contraction = B * decay_states.permute(0, 2, 3, 1)[..., None]
+ # permute back B * decay states
+ states = (B_decay_contraction.permute(0, 1, 3, 2, 4)[..., None] * hidden_states.permute(0, 1, 3, 2, 4)[..., None, :]).sum(dim=3).permute(0, 1, 2, 4, 3)
+ if cache_params is not None and cache_params.has_previous_state:
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...]
+ else:
+ previous_states = torch.zeros_like(states[:, :1])
+ states = torch.cat([previous_states, states], dim=1)
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
+
+ states_permuted = states.permute(0, 2, 1, 3, 4)
+ result = (decay_chunk[..., None, None] * states_permuted[:, :, None, ...]).sum(dim=2)
+ new_states = result.permute(0, 2, 1, 3, 4)
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
+
+ # Compute state -> output conversion per chunk
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
+ state_decay_out = torch.exp(A_cumsum)
+ # compute Yoff
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
+
+ y = Y_diag + Y_off
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
+
+ y = y + D_residual
+ # Cutting off padded chunks
+ if pad_size > 0:
+ y = y[:, :seq_len, :, :]
+ y = y.reshape(batch_size, seq_len, -1)
+ if ssm_state is not None and cache_params is not None:
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
+
+ scan_output = self.norm(y, gate)
+
+ # end ssd naive
+
+ # 4. Final linear projection
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
+ return contextualized_states
+ # fmt: on
+
+ def forward(
+ self,
+ hidden_states,
+ cache_params: Optional[Zamba2HybridDynamicCache] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ):
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
+
+ return self.torch_forward(hidden_states, cache_params, attention_mask)
+
+
+class Zamba2MLP(nn.Module):
+ def __init__(self, config: Zamba2Config, num_fwd_mem_blocks=None, block_id: Optional[int] = None):
+ """
+ This MLP layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this layer
+ is tied, un-tied adapter modules (formally same as LoRA, but used in the base model) are added to the up and gate projectors to increase expressivity with a small memory overhead.
+ """
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.num_fwd_mem_blocks = num_fwd_mem_blocks
+ self.block_id = block_id
+
+ self.gate_up_proj = nn.Linear(self.hidden_size, 2 * self.intermediate_size, bias=config.add_bias_linear)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.add_bias_linear)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ self.gate_up_proj_adapter_list = nn.ModuleList([])
+ for i in range(self.num_fwd_mem_blocks):
+ if i % config.num_mem_blocks == block_id:
+ gate_up_proj_adapter = nn.Sequential(
+ nn.Linear(self.config.hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, 2 * self.intermediate_size, bias=False),
+ )
+ else:
+ gate_up_proj_adapter = nn.Identity()
+ self.gate_up_proj_adapter_list.append(gate_up_proj_adapter)
+
+ layer_block_map = config.hybrid_layer_ids
+ self.layer_dic = {value: index for index, value in enumerate(layer_block_map)}
+
+ def forward(self, hidden_state, layer_idx=None):
+ gate_up_state = self.gate_up_proj(hidden_state)
+ layer_idx = self.layer_dic[layer_idx]
+ gate_up_state = gate_up_state + self.gate_up_proj_adapter_list[layer_idx](hidden_state)
+
+ gate_up_state = torch.chunk(gate_up_state, 2, dim=-1)
+ hidden_state = self.act_fn(gate_up_state[0]) * gate_up_state[1]
+ output = self.down_proj(hidden_state)
+ return output
+
+
+class Zamba2AttentionDecoderLayer(nn.Module):
+ def __init__(self, config: Zamba2Config, block_id: Optional[int] = None, layer_idx: Optional[int] = None):
+ super().__init__()
+ self.block_id = block_id
+ num_gs = len(config.hybrid_layer_ids)
+ self.self_attn = Zamba2Attention(config, layer_idx=-1, num_fwd_mem_blocks=num_gs, block_id=block_id)
+ self.feed_forward = Zamba2MLP(config, num_fwd_mem_blocks=num_gs, block_id=block_id)
+ self.input_layernorm = Zamba2RMSNorm(config.attention_hidden_size, eps=config.rms_norm_eps)
+ self.pre_ff_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[Zamba2HybridDynamicCache] = None,
+ output_attentions: Optional[bool] = False,
+ position_embeddings: Optional[torch.LongTensor] = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): output of previous Mamba layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output of shape `(batch, seq_len, embed_dim)`.
+ This is concatenated with `hidden_states` (which is the output of the previous (mamba) layer). The
+ concatenated tensor is then used as input of the pre-attention RMSNorm
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Zamba2HybridDynamicCache`, *optional*): cached past key and value projection states
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
+ with `head_dim` being the embedding dimension of each attention head.
+ """
+ hidden_states = torch.concatenate([hidden_states, original_hidden_states], dim=-1)
+ hidden_states = self.input_layernorm(hidden_states)
+ hidden_states, self_attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.pre_ff_layernorm(hidden_states)
+ hidden_states = self.feed_forward(hidden_states, layer_idx)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights,)
+
+ return outputs
+
+
+class Zamba2MambaDecoderLayer(nn.Module):
+ def __init__(self, config: Zamba2Config, layer_idx: int):
+ super().__init__()
+ self.mamba = Zamba2MambaMixer(config=config, layer_idx=layer_idx)
+ self.input_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ self.layer_idx = layer_idx
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: Optional[torch.Tensor] = None,
+ layer_idx: Optional[int] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ causal_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[Zamba2HybridDynamicCache] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ cache_position: Optional[torch.LongTensor] = None,
+ transformer_hidden_states: Optional[torch.Tensor] = None,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Zamba2HybridDynamicCache`, *optional*): cached past key and value projection states
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
+ Indices depicting the position of the input sequence tokens in the sequence.
+ """
+
+ residual = hidden_states
+
+ # `transformer_hidden_states` is the output from shared transformer + linear layer (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ # `transformer_hidden_states` is then added to the input to the mamba layer below (as described in eq. (6) of https://huggingface.co/papers/2405.16712).
+ hidden_states = (
+ hidden_states + transformer_hidden_states if transformer_hidden_states is not None else hidden_states
+ )
+ hidden_states = self.input_layernorm(hidden_states)
+
+ hidden_states = self.mamba(
+ hidden_states=hidden_states,
+ cache_params=past_key_values,
+ attention_mask=attention_mask,
+ )
+
+ self_attn_weights = None
+
+ # residual connection after mamba
+ hidden_states = residual + hidden_states
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights,)
+
+ if use_cache:
+ outputs += (past_key_values,)
+
+ return outputs
+
+
+class Zamba2HybridLayer(nn.Module):
+ def __init__(
+ self, shared_transformer: Zamba2AttentionDecoderLayer, linear: nn.Linear, mamba: Zamba2MambaDecoderLayer
+ ):
+ super().__init__()
+ self.linear = linear
+ self.mamba_decoder = mamba
+ self.shared_transformer = shared_transformer
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: Optional[torch.Tensor] = None,
+ layer_idx: Optional[int] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ causal_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[Zamba2HybridDynamicCache] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ position_embeddings: Optional[torch.LongTensor] = None,
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output that will be concatenated with
+ hidden activations to form the input of the shared transformer layer.
+ layer_idx (`int`): layer number.
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Zamba2HybridDynamicCache`, *optional*): cached past key and value projection states
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
+ with `head_dim` being the embedding dimension of each attention head.
+ """
+
+ layer_outputs = self.shared_transformer(
+ hidden_states,
+ original_hidden_states=original_hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=causal_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ position_embeddings=position_embeddings,
+ )
+
+ transformer_hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ self_attn_weights = layer_outputs[1]
+
+ transformer_hidden_states = self.linear(transformer_hidden_states)
+
+ layer_outputs = self.mamba_decoder(
+ hidden_states,
+ transformer_hidden_states=transformer_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ )
+
+ if output_attentions:
+ layer_outputs = (layer_outputs[0], self_attn_weights) + layer_outputs[2:]
+
+ return layer_outputs
+
+
+class Zamba2PreTrainedModel(PreTrainedModel):
+ config: Zamba2Config
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Zamba2AttentionDecoderLayer", "Zamba2MambaDecoderLayer"]
+ _skip_keys_device_placement = "past_key_values"
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_sdpa = True
+ # Note: only supports Zamba2HybridDynamicCache
+ _is_stateful = True
+
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, Zamba2MambaMixer):
+ dt = torch.exp(
+ torch.rand(self.config.n_mamba_heads)
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
+ + math.log(self.config.time_step_min)
+ ).clamp(min=self.config.time_step_floor)
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
+ module.dt_bias.data.copy_(inv_dt)
+
+ A = torch.arange(1, module.num_heads + 1)
+ module.A_log.data.copy_(torch.log(A))
+ module.D.data.fill_(1.0)
+
+
+@auto_docstring
+class Zamba2Model(Zamba2PreTrainedModel):
+ """
+ Model consisting of *config.num_hidden_layers* layers.
+
+ Args:
+ config: Zamba2Config
+ """
+
+ def __init__(self, config: Zamba2Config):
+ super().__init__(config)
+ self.config = config
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ blocks = [Zamba2AttentionDecoderLayer(config, block_id=k) for k in range(config.num_mem_blocks)]
+ mamba_layers = []
+ linear_layers = []
+ self.layers_block_type = config.layers_block_type
+ for i in range(config.num_hidden_layers):
+ if config.layers_block_type[i] == "mamba":
+ mamba_layers.append(Zamba2MambaDecoderLayer(config, layer_idx=i))
+ elif config.layers_block_type[i] == "hybrid":
+ linear_layers.append(nn.Linear(self.config.hidden_size, self.config.hidden_size, bias=False))
+ mamba_layers.append(Zamba2MambaDecoderLayer(config, layer_idx=i))
+ mamba_layers = iter(mamba_layers)
+ linear_layers = iter(linear_layers)
+ blocks = cycle(blocks)
+ layers = self.get_layers(blocks, linear_layers, mamba_layers)
+ self.layers = nn.ModuleList(layers)
+
+ self._attn_implementation = config._attn_implementation
+ self.final_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ if config.use_mem_rope:
+ if config.use_long_context:
+ logger.warning_once(
+ "`use_long_context` set to `True`: using rescaled `rope_theta` and extended `max_position_embeddings`."
+ )
+ self.rotary_emb = Zamba2RotaryEmbedding(config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Zamba2HybridDynamicCache] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ ) -> Union[tuple, BaseModelOutputWithPast]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError(
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
+ )
+
+ if self.gradient_checkpointing and self.training and use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
+ )
+ use_cache = False
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ hidden_states = inputs_embeds
+
+ original_hidden_states = torch.clone(inputs_embeds)
+ # original_hidden_states: word embedding output that will be concatenated with hidden activations to form the input of the shared transformer layer
+
+ if use_cache and past_key_values is None:
+ batch_size = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
+ past_key_values = Zamba2HybridDynamicCache(self.config, batch_size, dtype=self.dtype, device=self.device)
+
+ if cache_position is None:
+ past_seen_tokens = (
+ past_key_values.get_seq_length(layer_idx=self.first_transformer_layer_id)
+ if past_key_values is not None
+ else 0
+ )
+ cache_position = torch.arange(
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
+ )
+ if position_ids is None:
+ position_ids = cache_position.unsqueeze(0)
+
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
+
+ # create position embeddings to be shared across the decoder layers
+ if self.config.use_mem_rope:
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+ else:
+ position_embeddings = None
+
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+
+ for layer_idx, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ if self.gradient_checkpointing and self.training:
+ layer_outputs = self._gradient_checkpointing_func(
+ layer.__call__,
+ hidden_states,
+ original_hidden_states,
+ layer_idx,
+ attention_mask,
+ causal_mask,
+ past_key_values,
+ output_attentions,
+ use_cache,
+ position_embeddings,
+ )
+ else:
+ layer_outputs = layer(
+ hidden_states,
+ original_hidden_states=original_hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=attention_mask,
+ causal_mask=causal_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ )
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ if layer_outputs[1] is not None:
+ # append attentions only of attention layers. Mamba layers return `None` as the attention weights
+ all_self_attns += (layer_outputs[1],)
+
+ hidden_states = self.final_layernorm(hidden_states)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ if past_key_values is not None and not past_key_values.has_previous_state:
+ past_key_values.has_previous_state = True
+
+ output = BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ )
+ return output if return_dict else output.to_tuple()
+
+ def _update_causal_mask(self, attention_mask, input_tensor, cache_position):
+ if self.config._attn_implementation == "flash_attention_2":
+ if attention_mask is not None and 0.0 in attention_mask:
+ return attention_mask
+ return None
+
+ dtype, device = input_tensor.dtype, input_tensor.device
+ min_dtype = torch.finfo(dtype).min
+ sequence_length = input_tensor.shape[1]
+ target_length = cache_position[-1] + 1
+
+ causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
+ if sequence_length != 1:
+ causal_mask = torch.triu(causal_mask, diagonal=1)
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
+ causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1)
+ if attention_mask is not None:
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
+ if attention_mask.dim() == 2:
+ mask_length = attention_mask.shape[-1]
+ padding_mask = causal_mask[..., :mask_length].eq(0.0) * attention_mask[:, None, None, :].eq(0.0)
+ causal_mask[..., :mask_length] = causal_mask[..., :mask_length].masked_fill(padding_mask, min_dtype)
+
+ if (
+ self.config._attn_implementation == "sdpa"
+ and attention_mask is not None
+ and attention_mask.device.type in ["cuda", "xpu", "npu"]
+ ):
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
+ # Details: https://github.com/pytorch/pytorch/issues/110213
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
+
+ return causal_mask
+
+ def get_layers(self, blocks, linear_layers, mamba_layers):
+ layers = []
+ self._tied_weights_keys = []
+ self.first_transformer_layer_id = 0
+ for layer_id, layer_type in enumerate(self.layers_block_type):
+ if layer_type == "hybrid":
+ if self.first_transformer_layer_id == 0:
+ self.first_transformer_layer_id = layer_id
+ block = next(blocks)
+ if self.config.num_mem_blocks * len(self.config.hybrid_layer_ids) > 1:
+ prefix_pattern = rf"^layers\.{layer_id}\.shared_transformer\."
+ main_keys_pattern = re.compile(
+ prefix_pattern
+ + r"(?:"
+ + r"self_attn\.(?:q_proj|k_proj|v_proj|o_proj)\.weight|"
+ + r"feed_forward\.(?:gate_up_proj|down_proj)\.weight|"
+ + r"(?:input_layernorm|pre_ff_layernorm)\.weight"
+ + r")$"
+ )
+ self._tied_weights_keys.append(main_keys_pattern)
+
+ adapter_id = 0
+ for _layer_type in self.layers_block_type:
+ if _layer_type == "hybrid" and adapter_id % self.config.num_mem_blocks == block.block_id:
+ adapter_pattern = re.compile(
+ r"^shared_transformer\.feed_forward\.gate_up_proj_adapter_list\."
+ + str(adapter_id)
+ + r"\.(?:0|1)\.weight$"
+ )
+ self._tied_weights_keys.append(adapter_pattern)
+ adapter_id += 1
+ if self.config.use_shared_attention_adapter:
+ adapter_id = 0
+ for _layer_type in self.layers_block_type:
+ if _layer_type == "hybrid" and adapter_id % self.config.num_mem_blocks == block.block_id:
+ attn_adapter_pattern = re.compile(
+ r"^shared_transformer\.self_attn\."
+ + r"(?:linear_q_adapter_list|linear_k_adapter_list|linear_v_adapter_list)\."
+ + str(adapter_id)
+ + r"\.(?:0|1)\.weight$"
+ )
+ self._tied_weights_keys.append(attn_adapter_pattern)
+ adapter_id += 1
+ layers.append(Zamba2HybridLayer(block, next(linear_layers), next(mamba_layers)))
+ else:
+ layers.append(next(mamba_layers))
+ return layers
+
+
+# Adapted from transformers.models.jamba.modeling_jamba.JambaForCausalLM with Jamba->Zamba2, JAMBA->ZAMBA2
+class Zamba2ForCausalLM(Zamba2PreTrainedModel, GenerationMixin):
+ def __init__(self, config: Zamba2Config):
+ super().__init__(config)
+ self.model = Zamba2Model(config)
+ self._tied_weights_keys = ["lm_head.weight", *self.model._tied_weights_keys]
+ self.vocab_size = config.vocab_size
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Zamba2HybridDynamicCache] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ logits_to_keep: Union[int, torch.Tensor] = 0,
+ **kwargs,
+ ) -> Union[tuple, CausalLMOutputWithPast]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
+
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, Zamba2ForCausalLM
+
+ >>> model = Zamba2ForCausalLM.from_pretrained("Zyphra/Zamba2-7B-v1")
+ >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/Zamba2-7B-v1")
+
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
+
+ >>> # Generate
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
+ ```"""
+
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
+ outputs = self.model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ cache_position=cache_position,
+ return_dict=return_dict,
+ )
+
+ hidden_states = outputs[0]
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
+
+ if not return_dict:
+ output = (logits,) + outputs[1:]
+ return (loss,) + output if loss is not None else output
+
+ return CausalLMOutputWithPast(
+ loss=loss,
+ logits=logits,
+ past_key_values=outputs.past_key_values,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+ def prepare_inputs_for_generation(
+ self,
+ input_ids,
+ past_key_values=None,
+ attention_mask=None,
+ inputs_embeds=None,
+ cache_position=None,
+ position_ids=None,
+ use_cache=True,
+ **kwargs,
+ ):
+ # Overwritten -- has a unique cache type, `Zamba2HybridDynamicCache`
+
+ empty_past_kv = past_key_values is None
+
+ # Omit tokens covered by past_key_values
+ if not empty_past_kv:
+ # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
+ # Exception 1: when passing input_embeds, input_ids may be missing entries
+ # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
+ # Exception 3: with synced GPUs cache_position may go out of bounds, but we only want dummy token in that case.
+ # (we can't check exception 3 while compiling)
+ if (
+ inputs_embeds is not None # Exception 1
+ or cache_position[-1] >= input_ids.shape[1] # Exception 3
+ ):
+ input_ids = input_ids[:, -cache_position.shape[0] :]
+ elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
+ input_ids = input_ids[:, cache_position]
+ else:
+ past_key_values = Zamba2HybridDynamicCache(
+ self.config, input_ids.shape[0], dtype=self.dtype, device=self.device
+ )
+
+ if attention_mask is not None and position_ids is None:
+ # create position_ids on the fly for batch generation
+ position_ids = attention_mask.long().cumsum(-1) - 1
+ position_ids.masked_fill_(attention_mask == 0, 1)
+ if not empty_past_kv:
+ position_ids = position_ids[:, -input_ids.shape[1] :]
+
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
+ if inputs_embeds is not None and empty_past_kv:
+ model_inputs = {"inputs_embeds": inputs_embeds}
+ else:
+ model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
+
+ model_inputs.update(
+ {
+ "position_ids": position_ids,
+ "past_key_values": past_key_values,
+ "use_cache": use_cache,
+ "attention_mask": attention_mask,
+ "logits_to_keep": self.config.num_logits_to_keep,
+ "cache_position": cache_position,
+ }
+ )
+ return model_inputs
+
+
+@auto_docstring(
+ custom_intro="""
+ The Zamba2 Model with a sequence classification head on top (linear layer).
+
+ [`Zamba2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
+ (e.g. GPT-2) do.
+
+ Since it does classification on the last token, it requires to know the position of the last token. If a
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
+ each row of the batch).
+ """
+)
+class Zamba2ForSequenceClassification(Zamba2PreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+ self.num_labels = config.num_labels
+ self.model = Zamba2Model(config)
+ self._tied_weights_keys = self.model._tied_weights_keys
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Union[Cache, list[torch.FloatTensor]]] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ labels: Optional[torch.LongTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple, SequenceClassifierOutputWithPast]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
+ """
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ transformer_outputs = self.model(
+ input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ past_key_values=past_key_values,
+ inputs_embeds=inputs_embeds,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ hidden_states = transformer_outputs[0]
+ logits = self.score(hidden_states)
+
+ if input_ids is not None:
+ batch_size = input_ids.shape[0]
+ else:
+ batch_size = inputs_embeds.shape[0]
+
+ if self.config.pad_token_id is None and batch_size != 1:
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
+ if self.config.pad_token_id is None:
+ last_non_pad_token = -1
+ elif input_ids is not None:
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device, dtype=torch.int32)
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
+ else:
+ last_non_pad_token = -1
+ logger.warning_once(
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
+ )
+
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
+
+ loss = None
+ if labels is not None:
+ labels = labels.to(logits.device)
+ if self.config.problem_type is None:
+ if self.num_labels == 1:
+ self.config.problem_type = "regression"
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
+ self.config.problem_type = "single_label_classification"
+ else:
+ self.config.problem_type = "multi_label_classification"
+
+ if self.config.problem_type == "regression":
+ loss_fct = MSELoss()
+ if self.num_labels == 1:
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
+ else:
+ loss = loss_fct(pooled_logits, labels)
+ elif self.config.problem_type == "single_label_classification":
+ loss_fct = CrossEntropyLoss()
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
+ elif self.config.problem_type == "multi_label_classification":
+ loss_fct = BCEWithLogitsLoss()
+ loss = loss_fct(pooled_logits, labels)
+ if not return_dict:
+ output = (pooled_logits,) + transformer_outputs[1:]
+ return ((loss,) + output) if loss is not None else output
+
+ return SequenceClassifierOutputWithPast(
+ loss=loss,
+ logits=pooled_logits,
+ past_key_values=transformer_outputs.past_key_values,
+ hidden_states=transformer_outputs.hidden_states,
+ attentions=transformer_outputs.attentions,
+ )
+
+
+__all__ = ["Zamba2ForCausalLM", "Zamba2ForSequenceClassification", "Zamba2Model", "Zamba2PreTrainedModel"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modular_zamba2.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modular_zamba2.py
new file mode 100644
index 0000000000000000000000000000000000000000..acf552a2abb10e4672d2ff5958edcc3998168a8e
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zamba2/modular_zamba2.py
@@ -0,0 +1,1155 @@
+# coding=utf-8
+# Copyright 2024 Zyphra Technologies and the HuggingFace Inc. team. All rights reserved.
+#
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+import re
+from itertools import cycle
+from typing import Callable, Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+
+from ...activations import ACT2FN
+from ...modeling_flash_attention_utils import FlashAttentionKwargs
+from ...modeling_outputs import BaseModelOutputWithPast
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import (
+ logging,
+)
+from ...utils.deprecation import deprecate_kwarg
+from ...utils.import_utils import (
+ is_causal_conv1d_available,
+ is_mamba_ssm_available,
+)
+from ..llama.modeling_llama import LlamaRotaryEmbedding, apply_rotary_pos_emb
+from ..mamba2.modeling_mamba2 import pad_tensor_by_size, reshape_into_chunks, segment_sum
+from ..zamba.modeling_zamba import (
+ ZambaAttention,
+ ZambaAttentionDecoderLayer,
+ ZambaForCausalLM,
+ ZambaForSequenceClassification,
+ ZambaHybridDynamicCache,
+ ZambaHybridLayer,
+ ZambaMambaDecoderLayer,
+ ZambaModel,
+ ZambaRMSNorm,
+ eager_attention_forward,
+)
+from .configuration_zamba2 import Zamba2Config
+
+
+if is_mamba_ssm_available():
+ from mamba_ssm.ops.triton.selective_state_update import selective_state_update
+ from mamba_ssm.ops.triton.ssd_combined import mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined
+else:
+ selective_state_update, mamba_chunk_scan_combined, mamba_split_conv1d_scan_combined = None, None, None
+
+if is_causal_conv1d_available():
+ from causal_conv1d import causal_conv1d_fn, causal_conv1d_update
+else:
+ causal_conv1d_update, causal_conv1d_fn = None, None
+
+is_fast_path_available = all((selective_state_update, causal_conv1d_fn, causal_conv1d_update))
+
+
+_CONFIG_FOR_DOC = "Zyphra/Zamba2-2.7B"
+
+logger = logging.get_logger(__name__)
+
+
+class Zamba2RMSNormGated(torch.nn.Module):
+ def __init__(self, hidden_size, group_size, eps=1e-6):
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(hidden_size))
+ self.variance_epsilon = eps
+ self.group_size = group_size
+
+ def forward(self, hidden_states, gate=None):
+ input_dtype = hidden_states.dtype
+ hidden_states = hidden_states.to(torch.float32)
+ if gate is not None:
+ hidden_states = hidden_states * nn.functional.silu(gate.to(torch.float32))
+ *prefix_dims, last_dim = hidden_states.shape
+ group_count = last_dim // self.group_size
+ hidden_states_group = hidden_states.view(*prefix_dims, group_count, self.group_size)
+ variance = hidden_states_group.pow(2).mean(-1, keepdim=True)
+ hidden_states_group = hidden_states_group * torch.rsqrt(variance + self.variance_epsilon)
+ hidden_states = hidden_states_group.view(*prefix_dims, group_count * self.group_size)
+ return self.weight * hidden_states.to(input_dtype)
+
+
+class Zamba2RMSNorm(ZambaRMSNorm):
+ pass
+
+
+class Zamba2HybridDynamicCache(ZambaHybridDynamicCache):
+ """
+ A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
+ (which has a constant shape regardless of seq_len).
+
+ This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
+ and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
+ For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
+ while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
+ For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
+ while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
+ and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
+ """
+
+ def __init__(
+ self, config: Zamba2Config, batch_size: int, dtype: torch.dtype = torch.float16, device: Optional[str] = None
+ ):
+ self.dtype = dtype
+ self.layers_block_type = config.layers_block_type
+ self.has_previous_state = False
+ self.intermediate_size = int(config.mamba_expand * config.hidden_size)
+ self.ssm_state_size = config.mamba_d_state
+ self.conv_kernel_size = config.mamba_d_conv
+ self.n_mamba_heads = config.n_mamba_heads
+ self.transformer_layers = []
+ self._modules = {}
+ self._parameters = {}
+ self._buffers = {}
+ self.conv_states = {}
+ self.ssm_states = {}
+ for i in range(config.num_hidden_layers):
+ self.conv_states[i] = torch.zeros(
+ batch_size,
+ self.intermediate_size + 2 * config.mamba_ngroups * config.mamba_d_state,
+ self.conv_kernel_size,
+ device=device,
+ dtype=dtype,
+ )
+ self.ssm_states[i] = torch.zeros(
+ batch_size, self.n_mamba_heads, config.mamba_headdim, self.ssm_state_size, device=device, dtype=dtype
+ )
+ if self.layers_block_type[i] == "hybrid":
+ self.transformer_layers.append(i)
+ self.key_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
+ self.value_cache = [torch.tensor([[]] * batch_size, device=device) for _ in range(config.num_hidden_layers)]
+
+ def update_conv_state(
+ self, layer_idx: int, new_conv_state: torch.Tensor, cache_position: torch.LongTensor
+ ) -> torch.Tensor:
+ conv_state = self.conv_states[layer_idx]
+ cache_position = cache_position.clamp(0, self.conv_kernel_size - 1)
+
+ conv_state = conv_state.roll(shifts=-1, dims=-1)
+ conv_state[:, :, cache_position] = new_conv_state.to(conv_state.device)
+ self.conv_states[layer_idx].zero_()
+ self.conv_states[layer_idx] += conv_state
+ return self.conv_states[layer_idx]
+
+ def reset(self):
+ self.conv_states.zero_()
+ self.ssm_states.zero_()
+
+ def get_seq_length(self, layer_idx: Optional[int] = 0) -> int:
+ """Returns the sequence length of the cached states. A layer index can be optionally passed."""
+ # take any layer that contains cache and not empty tensor
+ layer_idx = self.transformer_layers[0] if layer_idx not in self.transformer_layers else layer_idx
+ if len(self.key_cache) <= layer_idx or self.key_cache[layer_idx].numel() == 0:
+ return 0
+ return self.key_cache[layer_idx].shape[-2]
+
+
+class Zamba2RotaryEmbedding(LlamaRotaryEmbedding):
+ pass
+
+
+class Zamba2Attention(ZambaAttention):
+ """
+ Multi-headed attention from 'Attention Is All You Need' paper.
+
+ Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
+ The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
+ The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ Additionally, replaced
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2)
+ Finally, this attention layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this
+ layer is tied, un-tied adapters (formally the same as LoRA but used in the base model) modules are added to the q, k, v projectors to increase
+ expressivity with a small memory overhead (see Fig. 2 of https://huggingface.co/papers/2411.15242).
+ """
+
+ def __init__(
+ self,
+ config: Zamba2Config,
+ layer_idx: Optional[int] = None,
+ num_fwd_mem_blocks: Optional[int] = None,
+ block_id: Optional[int] = None,
+ ):
+ super().__init__(config, layer_idx)
+ self.num_fwd_mem_blocks = num_fwd_mem_blocks
+ self.layer_block_map = config.hybrid_layer_ids
+ self.block_id = block_id
+
+ if config.use_shared_attention_adapter:
+ self.linear_q_adapter_list = nn.ModuleList([])
+ self.linear_k_adapter_list = nn.ModuleList([])
+ self.linear_v_adapter_list = nn.ModuleList([])
+
+ for i in range(self.num_fwd_mem_blocks):
+ if i % config.num_mem_blocks == block_id:
+ linear_q_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ linear_k_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ linear_v_adapter = nn.Sequential(
+ nn.Linear(self.attention_hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, self.attention_hidden_size, bias=False),
+ )
+ else:
+ linear_q_adapter = nn.Identity()
+ linear_k_adapter = nn.Identity()
+ linear_v_adapter = nn.Identity()
+ self.linear_q_adapter_list.append(linear_q_adapter)
+ self.linear_k_adapter_list.append(linear_k_adapter)
+ self.linear_v_adapter_list.append(linear_v_adapter)
+
+ self.layer_dic = {value: index for index, value in enumerate(self.layer_block_map)}
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[Zamba2HybridDynamicCache] = None,
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.head_dim)
+
+ query_states = self.q_proj(hidden_states)
+ key_states = self.k_proj(hidden_states)
+ value_states = self.v_proj(hidden_states)
+ if self.config.use_shared_attention_adapter:
+ adapter_layer_idx = self.layer_dic[layer_idx]
+ query_states = query_states + self.linear_q_adapter_list[adapter_layer_idx](hidden_states)
+ key_states = key_states + self.linear_k_adapter_list[adapter_layer_idx](hidden_states)
+ value_states = value_states + self.linear_v_adapter_list[adapter_layer_idx](hidden_states)
+
+ query_states = query_states.view(hidden_shape).transpose(1, 2)
+ key_states = key_states.view(hidden_shape).transpose(1, 2)
+ value_states = value_states.view(hidden_shape).transpose(1, 2)
+
+ if self.config.use_mem_rope:
+ cos, sin = position_embeddings
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
+
+ if past_key_values is not None:
+ key_states, value_states = past_key_values.update(key_states, value_states, layer_idx)
+
+ attention_interface: Callable = eager_attention_forward
+ if self.config._attn_implementation != "eager":
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ query_states,
+ key_states,
+ value_states,
+ attention_mask,
+ dropout=0.0 if not self.training else self.attention_dropout,
+ scaling=self.scaling,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.o_proj(attn_output)
+ return attn_output, attn_weights
+
+
+class Zamba2MambaMixer(nn.Module):
+ """
+ Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
+ A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
+ ∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
+ and is why Mamba is called **selective** state spaces)
+ """
+
+ def __init__(self, config: Zamba2Config, layer_idx: Optional[int] = None):
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.ssm_state_size = config.mamba_d_state
+ self.conv_kernel_size = config.mamba_d_conv
+ self.intermediate_size = int(config.mamba_expand * self.hidden_size)
+ self.layer_idx = layer_idx
+ self.use_conv_bias = config.use_conv_bias
+ self.activation = "silu"
+ self.act = nn.SiLU()
+ self.use_mem_eff_path = config.use_mem_eff_path
+
+ self.n_groups = config.mamba_ngroups
+ self.head_dim = config.mamba_headdim
+ self.num_heads = self.config.n_mamba_heads
+ self.chunk_size = config.chunk_size
+
+ self.time_step_limit = config.time_step_limit
+ self.time_step_min = config.time_step_min
+ self.time_step_max = config.time_step_max
+
+ self.conv_dim = self.intermediate_size + 2 * self.n_groups * self.ssm_state_size
+ self.conv1d = nn.Conv1d(
+ in_channels=self.conv_dim,
+ out_channels=self.conv_dim,
+ bias=True,
+ kernel_size=config.mamba_d_conv,
+ groups=self.conv_dim,
+ padding=config.mamba_d_conv - 1,
+ )
+
+ # projection of the input hidden states
+ projection_size = self.intermediate_size + self.conv_dim + self.num_heads
+ self.in_proj = nn.Linear(
+ self.hidden_size,
+ projection_size,
+ bias=config.add_bias_linear,
+ )
+ # selective projection used to make dt, B and C input dependent
+
+ # time step projection (discretization)
+ # instantiate once and copy inv_dt in init_weights of PretrainedModel
+ self.dt_bias = nn.Parameter(torch.ones(self.num_heads))
+
+ # S4D real initialization. These are not discretized!
+ # The core is to load them, compute the discrete states, then write the updated state. Keeps the memory bounded
+ A = torch.arange(1, self.num_heads + 1)
+ self.A_log = nn.Parameter(torch.log(A))
+ self.A_log._no_weight_decay = True
+ self.norm = Zamba2RMSNormGated(
+ self.intermediate_size, group_size=self.intermediate_size // self.n_groups, eps=1e-5
+ )
+ self.D = nn.Parameter(torch.ones(self.num_heads))
+ self.D._no_weight_decay = True
+
+ self.out_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.add_bias_linear)
+
+ if not is_fast_path_available:
+ logger.warning_once(
+ "The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)`"
+ " is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and"
+ " https://github.com/Dao-AILab/causal-conv1d"
+ )
+
+ def cuda_kernels_forward(
+ self,
+ hidden_states: torch.Tensor,
+ cache_params: Optional[Zamba2HybridDynamicCache] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ):
+ # set up dimensions for reshapes later
+
+ batch_size, seq_len, _ = hidden_states.shape
+ groups_time_state_size = self.n_groups * self.ssm_state_size
+ d_to_remove = 2 * self.intermediate_size + 2 * self.n_groups * self.ssm_state_size + self.num_heads
+
+ # getting projected states from cache if it exists
+ if cache_params is not None and cache_params.has_previous_state:
+ in_projected_states = self.in_proj(hidden_states.squeeze(1)) # (B 2D)
+ d_mlp = (in_projected_states.shape[-1] - d_to_remove) // 2
+ split_projection_dim = [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads]
+ _, _, gate, hidden_states_B_C, dt = torch.split(in_projected_states, split_projection_dim, dim=-1)
+
+ hidden_states_B_C = causal_conv1d_update(
+ hidden_states_B_C,
+ cache_params.conv_states[self.layer_idx],
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.activation,
+ )
+
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+ A = -torch.exp(self.A_log.float()) # (nheads,)
+
+ A = A[:, None, ...][:, :, None].expand(-1, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ dt = dt[:, :, None].expand(-1, -1, self.head_dim)
+ dt_bias = self.dt_bias[:, None, ...].expand(-1, self.head_dim)
+ D = self.D[:, None, ...].expand(-1, self.head_dim)
+ B = B.view(batch_size, self.n_groups, B.shape[1] // self.n_groups)
+ C = C.view(batch_size, self.n_groups, C.shape[1] // self.n_groups)
+ hidden_states_reshaped = hidden_states.view(batch_size, self.num_heads, self.head_dim)
+ hidden_states = selective_state_update(
+ cache_params.ssm_states[self.layer_idx],
+ hidden_states_reshaped,
+ dt,
+ A,
+ B,
+ C,
+ D,
+ z=None,
+ dt_bias=dt_bias,
+ dt_softplus=True,
+ )
+ hidden_states = hidden_states.view(batch_size, self.num_heads * self.head_dim)
+ hidden_states = self.norm(hidden_states, gate)
+ out = self.out_proj(hidden_states)[:, None, ...]
+ # if no cache is found, calling the kernel
+ else:
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ # 1. Gated MLP's linear projection
+ projected_states = self.in_proj(hidden_states)
+ A = -torch.exp(self.A_log.float()) # (num_heads) or (intermediate_size, state_size)
+ dt_limit_kwargs = {} if self.time_step_limit is None else {"dt_limit": self.time_step_limit}
+ if attention_mask is not None:
+ input_not_masked = torch.all(attention_mask == 1)
+ else:
+ input_not_masked = True
+
+ if self.use_mem_eff_path and self.training and cache_params is None and input_not_masked:
+ out, ssm_state = mamba_split_conv1d_scan_combined(
+ projected_states,
+ self.conv1d.weight.squeeze(1),
+ self.conv1d.bias,
+ self.dt_bias,
+ A,
+ D=self.D,
+ chunk_size=self.chunk_size,
+ seq_idx=None,
+ activation=self.activation,
+ rmsnorm_weight=self.norm.weight,
+ rmsnorm_eps=self.norm.variance_epsilon,
+ outproj_weight=self.out_proj.weight,
+ outproj_bias=self.out_proj.bias,
+ headdim=self.head_dim,
+ ngroups=self.n_groups,
+ norm_before_gate=False,
+ return_final_states=True,
+ **dt_limit_kwargs,
+ )
+
+ else:
+ gate, hidden_states_B_C, time_step = torch.split(
+ projected_states,
+ [self.intermediate_size, self.conv_dim, self.num_heads],
+ dim=-1,
+ )
+
+ # 1D Convolution
+ if cache_params is not None:
+ hidden_states_B_C_t = hidden_states_B_C.transpose(1, 2)
+ conv_state = nn.functional.pad(
+ hidden_states_B_C_t, (self.conv_kernel_size - hidden_states_B_C_t.shape[-1], 0)
+ )
+ cache_params.conv_states[self.layer_idx].copy_(conv_state)
+ if causal_conv1d_fn is None or self.activation not in ["silu", "swish"]:
+ hidden_states_B_C = self.act(
+ self.conv1d(hidden_states_B_C.transpose(1, 2)).transpose(1, 2)[:, :seq_len]
+ ) # (B, L, self.d_inner + 2 * ngroups * d_state)
+ else:
+ hidden_states_B_C = causal_conv1d_fn(
+ x=hidden_states_B_C.transpose(1, 2),
+ weight=self.conv1d.weight.squeeze(1),
+ bias=self.conv1d.bias,
+ activation=self.activation,
+ ).transpose(1, 2)[:, :seq_len]
+ hidden_states, B, C = torch.split(
+ hidden_states_B_C,
+ [self.intermediate_size, groups_time_state_size, groups_time_state_size],
+ dim=-1,
+ )
+ if attention_mask is not None and not torch.all(attention_mask == 1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ dtype = hidden_states.dtype
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ scan_output, ssm_state = mamba_chunk_scan_combined(
+ hidden_states.view(batch_size, seq_len, -1, self.head_dim),
+ time_step,
+ A,
+ B.view(batch_size, seq_len, self.n_groups, -1),
+ C.view(batch_size, seq_len, self.n_groups, -1),
+ chunk_size=self.chunk_size,
+ D=self.D,
+ z=None,
+ seq_idx=None,
+ return_final_states=True,
+ dt_bias=self.dt_bias,
+ dt_softplus=True,
+ **dt_limit_kwargs,
+ )
+ if ssm_state is not None and cache_params is not None:
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
+ scan_output = scan_output.view(batch_size, seq_len, -1)
+ # Multiply "gate" branch and apply extra normalization layer
+ scan_output = self.norm(scan_output, gate)
+ out = self.out_proj(scan_output)
+ return out
+
+ # fmt: off
+ def torch_forward(self, input_states, cache_params: Optional[Zamba2HybridDynamicCache]=None, attention_mask: Optional[torch.Tensor]=None):
+ batch_size, seq_len, _ = input_states.shape
+ dtype = input_states.dtype
+ # Gated MLP's linear projection
+ if cache_params is not None and cache_params.has_previous_state:
+ projected_states = self.in_proj(input_states.squeeze(1))
+ else:
+ if attention_mask is not None and not torch.all(attention_mask==1):
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ input_states = (input_states * attention_mask[:, :, None]).to(dtype)
+ projected_states = self.in_proj(input_states)
+ d_mlp = (projected_states.shape[-1] - 2 * self.intermediate_size - 2 * self.n_groups * self.ssm_state_size- self.num_heads) // 2
+ _, _, gate, hidden_states, dt = projected_states.split(
+ [d_mlp, d_mlp, self.intermediate_size, self.conv_dim, self.num_heads], dim=-1
+ )
+
+ # Convolution sequence transformation
+ if cache_params is not None:
+ ssm_state = cache_params.ssm_states[self.layer_idx].clone()
+ ssm_state = ssm_state.to(hidden_states.device)
+ if cache_params.has_previous_state:
+ gate = gate.unsqueeze(1)
+ conv_state = cache_params.conv_states[self.layer_idx] # [batch, intermediate_size, conv_kernel_size]
+ conv_state = torch.roll(conv_state, shifts=-1, dims=-1)
+ # handle batched generation - states are copied through
+ conv_state[:, :, -1] = hidden_states[:, 0, :] if hidden_states.ndim == 3 else hidden_states
+ cache_params.conv_states[self.layer_idx].copy_(conv_state)
+ hidden_states = torch.sum(conv_state.to(projected_states.device) * self.conv1d.weight[:, 0, :], dim=-1)
+ if self.use_conv_bias:
+ hidden_states += self.conv1d.bias
+ hidden_states = self.act(hidden_states).to(dtype)[:, None, ...] # [batch, 1, intermediate_size] : decoding
+ else:
+ hidden_states = hidden_states.transpose(1,2)
+ conv_state = nn.functional.pad(
+ hidden_states,
+ (self.conv_kernel_size - hidden_states.shape[-1], 0)
+ )
+ cache_params.conv_states[self.layer_idx].copy_(conv_state)
+ hidden_states = self.act(self.conv1d(hidden_states).transpose(1,2))[:, :seq_len, :] # [batch, intermediate_size, seq_len]
+ if attention_mask is not None and not torch.all(attention_mask==1):
+ dtype = hidden_states.dtype
+ # tune out hidden states for pad tokens, see https://github.com/state-spaces/mamba/issues/66
+ hidden_states = (hidden_states * attention_mask[:, :, None]).to(dtype)
+ else:
+ ssm_state = torch.zeros(
+ (batch_size, self.num_heads, self.head_dim, self.ssm_state_size),
+ device=hidden_states.device, dtype=dtype
+ )
+ hidden_states = self.act(self.conv1d(hidden_states.transpose(1, 2))[..., :seq_len].transpose(1, 2))
+ hidden_states, B, C = torch.split(hidden_states, [self.intermediate_size, self.n_groups * self.ssm_state_size, self.n_groups * self.ssm_state_size], dim=-1)
+ A = -torch.exp(self.A_log.float()) # [num_heads]
+ if cache_params is not None and cache_params.has_previous_state:
+ # Note: there is no need to pad parameter matrices here, as there is just one new token
+ # for batched generation
+ dt = dt[:, None, ...] if dt.ndim == 2 else dt[:, 0, :][:, None, ...]
+ dt = dt.transpose(1, 2).expand(batch_size, dt.shape[-1], self.head_dim)
+ # [num_heads] -> [num_heads, head_dim]
+ dt_bias = self.dt_bias[..., None].expand(self.dt_bias.shape[0], self.head_dim)
+
+ dt = torch.nn.functional.softplus(dt + dt_bias.to(dt.dtype))
+ dt = torch.clamp(dt, self.time_step_min) #, self.time_step_max)
+ A = A[..., None, None].expand(self.num_heads, self.head_dim, self.ssm_state_size).to(dtype=torch.float32)
+ # [bsz, num_heads, head_dim, state_size]
+ dA = torch.exp(dt[..., None] * A)
+
+ # Discretize B
+ # [bsz, n_groups * state_size] -> [bsz, n_groups, 1, state_size] ->
+ # -> [bsz, n_groups, group to head repetition factor, state_size] -> [bsz, num_heads, state_size]
+ B = B.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ B = B.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, B.shape[-1]).contiguous()
+ B = B.reshape(batch_size, -1, B.shape[-1])
+ # [bsz, num_heads, head_dim, state_size]
+ dB = dt[..., None] * B[..., None, :]
+
+ # Discretize x into dB
+ # [bsz, intermediate_size] -> [bsz, num_heads, head_dim]
+ hidden_states = hidden_states.reshape(batch_size, -1, self.head_dim)
+ dBx = dB * hidden_states[..., None]
+
+ # State calculation
+ cache_params.ssm_states[self.layer_idx].copy_(
+ cache_params.ssm_states[self.layer_idx] * dA + dBx
+ )
+
+ # Subsequent output
+ # [bsz, n_groups * state_size] -> [bsz, num_heads, state_size]
+ C = C.reshape(batch_size, self.n_groups, -1)[..., None, :]
+ C = C.expand(batch_size, self.n_groups, self.num_heads // self.n_groups, C.shape[-1]).contiguous()
+ C = C.reshape(batch_size, -1, C.shape[-1])
+ # [bsz, num_heads, head_dim]
+
+ ssm_states = cache_params.ssm_states[self.layer_idx].to(C.dtype) # Shape: [b, h, d, n]
+ # Reshape ssm_states to merge the first two dimensions
+ ssm_states_reshaped = ssm_states.view(batch_size * self.num_heads, self.head_dim, self.ssm_state_size) # Shape: [b*h, d, n]
+ C_reshaped = C.view(batch_size * self.num_heads, self.ssm_state_size, 1) # Shape: [b*h, n, 1]
+ y = torch.bmm(ssm_states_reshaped, C_reshaped)
+ y = y.view(batch_size, self.num_heads, self.head_dim)
+
+ # D skip connection
+ # [num_heads] -> [num_heads, head_dim]
+ D = self.D[..., None].expand(self.D.shape[0], self.head_dim)
+ y = (y + hidden_states * D).to(y.dtype)
+
+ # [bsz, num_heads, head_dim] -> [bsz, 1, intermediate_size]
+ y = y.reshape(batch_size, -1)[:, None, ...]
+ else:
+ # begin ssd naive implementation without einsums
+ dt = nn.functional.softplus(dt + self.dt_bias)
+ dt = torch.clamp(dt, self.time_step_min)
+ hidden_states = hidden_states.reshape(batch_size, seq_len, -1, self.head_dim).float()
+ B = B.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ C = C.reshape(batch_size, seq_len, -1, self.ssm_state_size).float()
+ B = B.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ C = C.repeat_interleave(self.num_heads // self.n_groups, dim=2, output_size=self.num_heads)
+ pad_size = (self.chunk_size - seq_len % self.chunk_size) % self.chunk_size
+
+ D_residual = self.D[..., None] * pad_tensor_by_size(hidden_states, pad_size)
+
+ # Discretize x and A
+ hidden_states = hidden_states * dt[..., None]
+ A = A.to(hidden_states.dtype) * dt
+
+ # Rearrange into blocks/chunks
+ hidden_states, A, B, C = [reshape_into_chunks(t, pad_size, self.chunk_size) for t in (hidden_states, A, B, C)]
+
+
+ # [bsz, -1, chunk_size, num_heads] -> [bsz, num_heads, -1, chunk_size]
+ A = A.permute(0, 3, 1, 2)
+ A_cumsum = torch.cumsum(A, dim=-1)
+
+ # 1. Compute the output for each intra-chunk (diagonal blocks)
+ # This is the analog of a causal mask
+ L = torch.exp(segment_sum(A))
+
+ # First, contraction of C and B to get G (attention-weights like)
+ G_intermediate = C[:, :, :, None, :, :] * B[:, :, None, :, : ,:] # shape: (b, c, l, s, h, n)
+ G = G_intermediate.sum(dim=-1) # shape: (b, c, l, s, h)
+
+
+ # Step 2: Compute M, equivalent to applying attention mask to weights
+ M_intermediate = G[..., None] * L.permute(0, 2, 3, 4, 1)[..., None]
+ M = M_intermediate.sum(dim=-1)
+
+ # Step 3: Compute Y_diag (apply to values)
+ Y_diag = (M[..., None] * hidden_states[:, :, None]).sum(3)
+
+ # (right term of low-rank factorization of off-diagonal blocks; B terms)
+
+ decay_states = torch.exp(A_cumsum[:, :, :, -1:] - A_cumsum)
+ B_decay_contraction = B * decay_states.permute(0, 2, 3, 1)[..., None]
+ # permute back B * decay states
+ states = (B_decay_contraction.permute(0, 1, 3, 2, 4)[..., None] * hidden_states.permute(0, 1, 3, 2, 4)[..., None, :]).sum(dim=3).permute(0, 1, 2, 4, 3)
+ if cache_params is not None and cache_params.has_previous_state:
+ previous_states = cache_params.ssm_states[self.layer_idx][:, None, ...]
+ else:
+ previous_states = torch.zeros_like(states[:, :1])
+ states = torch.cat([previous_states, states], dim=1)
+ decay_chunk = torch.exp(segment_sum(nn.functional.pad(A_cumsum[:, :, :, -1], (1, 0))))
+
+ states_permuted = states.permute(0, 2, 1, 3, 4)
+ result = (decay_chunk[..., None, None] * states_permuted[:, :, None, ...]).sum(dim=2)
+ new_states = result.permute(0, 2, 1, 3, 4)
+ states, ssm_state = new_states[:, :-1], new_states[:, -1]
+
+ # Compute state -> output conversion per chunk
+ # (left term of low-rank factorization of off-diagonal blocks; C terms)
+ state_decay_out = torch.exp(A_cumsum)
+ # compute Yoff
+ C_times_states = (C[..., None, :] * states[:, :, None, ...])
+ state_decay_out_permuted = state_decay_out.permute(0, 2, 3, 1)
+ Y_off = (C_times_states.sum(-1) * state_decay_out_permuted[..., None])
+ # Add output of intra-chunk and inter-chunk terms (diagonal and off-diagonal blocks)
+
+ y = Y_diag + Y_off
+ # [bsz, -1, self.chunk_size, num_heads, head_dim] -> [bsz, (padded) seq_len, num_heads, head_dim]
+ y = y.reshape(batch_size, -1, self.num_heads, self.head_dim)
+
+ y = y + D_residual
+ # Cutting off padded chunks
+ if pad_size > 0:
+ y = y[:, :seq_len, :, :]
+ y = y.reshape(batch_size, seq_len, -1)
+ if ssm_state is not None and cache_params is not None:
+ cache_params.ssm_states[self.layer_idx].copy_(ssm_state)
+
+ scan_output = self.norm(y, gate)
+
+ # end ssd naive
+
+ # 4. Final linear projection
+ contextualized_states = self.out_proj(scan_output.to(dtype)) # [batch, seq_len, hidden_size]
+ return contextualized_states
+ # fmt: on
+
+ def forward(
+ self,
+ hidden_states,
+ cache_params: Optional[Zamba2HybridDynamicCache] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ):
+ if is_fast_path_available and "cuda" in self.in_proj.weight.device.type:
+ return self.cuda_kernels_forward(hidden_states, cache_params, attention_mask)
+
+ return self.torch_forward(hidden_states, cache_params, attention_mask)
+
+
+class Zamba2MLP(nn.Module):
+ def __init__(self, config: Zamba2Config, num_fwd_mem_blocks=None, block_id: Optional[int] = None):
+ """
+ This MLP layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this layer
+ is tied, un-tied adapter modules (formally same as LoRA, but used in the base model) are added to the up and gate projectors to increase expressivity with a small memory overhead.
+ """
+ super().__init__()
+ self.config = config
+ self.hidden_size = config.hidden_size
+ self.intermediate_size = config.intermediate_size
+ self.num_fwd_mem_blocks = num_fwd_mem_blocks
+ self.block_id = block_id
+
+ self.gate_up_proj = nn.Linear(self.hidden_size, 2 * self.intermediate_size, bias=config.add_bias_linear)
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.add_bias_linear)
+ self.act_fn = ACT2FN[config.hidden_act]
+
+ self.gate_up_proj_adapter_list = nn.ModuleList([])
+ for i in range(self.num_fwd_mem_blocks):
+ if i % config.num_mem_blocks == block_id:
+ gate_up_proj_adapter = nn.Sequential(
+ nn.Linear(self.config.hidden_size, self.config.adapter_rank, bias=False),
+ nn.Linear(self.config.adapter_rank, 2 * self.intermediate_size, bias=False),
+ )
+ else:
+ gate_up_proj_adapter = nn.Identity()
+ self.gate_up_proj_adapter_list.append(gate_up_proj_adapter)
+
+ layer_block_map = config.hybrid_layer_ids
+ self.layer_dic = {value: index for index, value in enumerate(layer_block_map)}
+
+ def forward(self, hidden_state, layer_idx=None):
+ gate_up_state = self.gate_up_proj(hidden_state)
+ layer_idx = self.layer_dic[layer_idx]
+ gate_up_state = gate_up_state + self.gate_up_proj_adapter_list[layer_idx](hidden_state)
+
+ gate_up_state = torch.chunk(gate_up_state, 2, dim=-1)
+ hidden_state = self.act_fn(gate_up_state[0]) * gate_up_state[1]
+ output = self.down_proj(hidden_state)
+ return output
+
+
+class Zamba2AttentionDecoderLayer(ZambaAttentionDecoderLayer):
+ def __init__(self, config: Zamba2Config, block_id: Optional[int] = None, layer_idx: Optional[int] = None):
+ self.block_id = block_id
+ num_gs = len(config.hybrid_layer_ids)
+ super().__init__(config, layer_idx)
+ self.self_attn = Zamba2Attention(config, layer_idx=-1, num_fwd_mem_blocks=num_gs, block_id=block_id)
+ self.feed_forward = Zamba2MLP(config, num_fwd_mem_blocks=num_gs, block_id=block_id)
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: torch.Tensor,
+ layer_idx: int,
+ attention_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[Zamba2HybridDynamicCache] = None,
+ output_attentions: Optional[bool] = False,
+ position_embeddings: Optional[torch.LongTensor] = None,
+ **kwargs: Unpack[FlashAttentionKwargs],
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): output of previous Mamba layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output of shape `(batch, seq_len, embed_dim)`.
+ This is concatenated with `hidden_states` (which is the output of the previous (mamba) layer). The
+ concatenated tensor is then used as input of the pre-attention RMSNorm
+ (see fig. 2 in https://huggingface.co/papers/2405.16712).
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Zamba2HybridDynamicCache`, *optional*): cached past key and value projection states
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
+ with `head_dim` being the embedding dimension of each attention head.
+ """
+ hidden_states = torch.concatenate([hidden_states, original_hidden_states], dim=-1)
+ hidden_states = self.input_layernorm(hidden_states)
+ hidden_states, self_attn_weights = self.self_attn(
+ hidden_states=hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ position_embeddings=position_embeddings,
+ **kwargs,
+ )
+
+ hidden_states = self.pre_ff_layernorm(hidden_states)
+ hidden_states = self.feed_forward(hidden_states, layer_idx)
+
+ outputs = (hidden_states,)
+
+ if output_attentions:
+ outputs += (self_attn_weights,)
+
+ return outputs
+
+
+class Zamba2MambaDecoderLayer(ZambaMambaDecoderLayer):
+ def __init__(self, config: Zamba2Config, layer_idx: int):
+ super().__init__(config, layer_idx)
+ self.mamba = Zamba2MambaMixer(config=config, layer_idx=layer_idx)
+ self.input_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+
+
+class Zamba2HybridLayer(ZambaHybridLayer):
+ def __init__(
+ self, shared_transformer: Zamba2AttentionDecoderLayer, linear: nn.Linear, mamba: Zamba2MambaDecoderLayer
+ ):
+ super().__init__(shared_transformer, linear, mamba)
+ del self.shared_transf
+ self.shared_transformer = shared_transformer
+
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ original_hidden_states: Optional[torch.Tensor] = None,
+ layer_idx: Optional[int] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ causal_mask: Optional[torch.Tensor] = None,
+ past_key_values: Optional[Zamba2HybridDynamicCache] = None,
+ output_attentions: Optional[bool] = False,
+ use_cache: Optional[bool] = False,
+ position_embeddings: Optional[torch.LongTensor] = None,
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
+ """
+ Args:
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
+ original_hidden_states (`torch.FloatTensor`): word embedding output that will be concatenated with
+ hidden activations to form the input of the shared transformer layer.
+ layer_idx (`int`): layer number.
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
+ `(batch, sequence_length)` where padding elements are indicated by 0.
+ past_key_values (`Zamba2HybridDynamicCache`, *optional*): cached past key and value projection states
+ output_attentions (`bool`, *optional*):
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
+ returned tensors for more detail.
+ use_cache (`bool`, *optional*):
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
+ (see `past_key_values`).
+ position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
+ with `head_dim` being the embedding dimension of each attention head.
+ """
+
+ layer_outputs = self.shared_transformer(
+ hidden_states,
+ original_hidden_states=original_hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=causal_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ position_embeddings=position_embeddings,
+ )
+
+ transformer_hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ self_attn_weights = layer_outputs[1]
+
+ transformer_hidden_states = self.linear(transformer_hidden_states)
+
+ layer_outputs = self.mamba_decoder(
+ hidden_states,
+ transformer_hidden_states=transformer_hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ )
+
+ if output_attentions:
+ layer_outputs = (layer_outputs[0], self_attn_weights) + layer_outputs[2:]
+
+ return layer_outputs
+
+
+class Zamba2PreTrainedModel(PreTrainedModel):
+ config: Zamba2Config
+ base_model_prefix = "model"
+ supports_gradient_checkpointing = True
+ _no_split_modules = ["Zamba2AttentionDecoderLayer", "Zamba2MambaDecoderLayer"]
+ _skip_keys_device_placement = "past_key_values"
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_sdpa = True
+ # Note: only supports Zamba2HybridDynamicCache
+ _is_stateful = True
+
+ def _init_weights(self, module):
+ super()._init_weights(module)
+ if isinstance(module, Zamba2MambaMixer):
+ dt = torch.exp(
+ torch.rand(self.config.n_mamba_heads)
+ * (math.log(self.config.time_step_max) - math.log(self.config.time_step_min))
+ + math.log(self.config.time_step_min)
+ ).clamp(min=self.config.time_step_floor)
+ # # Inverse of softplus: https://github.com/pytorch/pytorch/issues/72759
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
+ module.dt_bias.data.copy_(inv_dt)
+
+ A = torch.arange(1, module.num_heads + 1)
+ module.A_log.data.copy_(torch.log(A))
+ module.D.data.fill_(1.0)
+
+
+class Zamba2Model(ZambaModel, Zamba2PreTrainedModel):
+ """
+ Model consisting of *config.num_hidden_layers* layers.
+
+ Args:
+ config: Zamba2Config
+ """
+
+ def __init__(self, config: Zamba2Config):
+ Zamba2PreTrainedModel.__init__(self, config)
+ self.config = config
+ self.padding_idx = config.pad_token_id
+ self.vocab_size = config.vocab_size
+
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
+ blocks = [Zamba2AttentionDecoderLayer(config, block_id=k) for k in range(config.num_mem_blocks)]
+ mamba_layers = []
+ linear_layers = []
+ self.layers_block_type = config.layers_block_type
+ for i in range(config.num_hidden_layers):
+ if config.layers_block_type[i] == "mamba":
+ mamba_layers.append(Zamba2MambaDecoderLayer(config, layer_idx=i))
+ elif config.layers_block_type[i] == "hybrid":
+ linear_layers.append(nn.Linear(self.config.hidden_size, self.config.hidden_size, bias=False))
+ mamba_layers.append(Zamba2MambaDecoderLayer(config, layer_idx=i))
+ mamba_layers = iter(mamba_layers)
+ linear_layers = iter(linear_layers)
+ blocks = cycle(blocks)
+ layers = self.get_layers(blocks, linear_layers, mamba_layers)
+ self.layers = nn.ModuleList(layers)
+
+ self._attn_implementation = config._attn_implementation
+ self.final_layernorm = Zamba2RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
+ if config.use_mem_rope:
+ if config.use_long_context:
+ logger.warning_once(
+ "`use_long_context` set to `True`: using rescaled `rope_theta` and extended `max_position_embeddings`."
+ )
+ self.rotary_emb = Zamba2RotaryEmbedding(config)
+ self.gradient_checkpointing = False
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_layers(self, blocks, linear_layers, mamba_layers):
+ layers = []
+ self._tied_weights_keys = []
+ self.first_transformer_layer_id = 0
+ for layer_id, layer_type in enumerate(self.layers_block_type):
+ if layer_type == "hybrid":
+ if self.first_transformer_layer_id == 0:
+ self.first_transformer_layer_id = layer_id
+ block = next(blocks)
+ if self.config.num_mem_blocks * len(self.config.hybrid_layer_ids) > 1:
+ prefix_pattern = rf"^layers\.{layer_id}\.shared_transformer\."
+ main_keys_pattern = re.compile(
+ prefix_pattern
+ + r"(?:"
+ + r"self_attn\.(?:q_proj|k_proj|v_proj|o_proj)\.weight|"
+ + r"feed_forward\.(?:gate_up_proj|down_proj)\.weight|"
+ + r"(?:input_layernorm|pre_ff_layernorm)\.weight"
+ + r")$"
+ )
+ self._tied_weights_keys.append(main_keys_pattern)
+
+ adapter_id = 0
+ for _layer_type in self.layers_block_type:
+ if _layer_type == "hybrid" and adapter_id % self.config.num_mem_blocks == block.block_id:
+ adapter_pattern = re.compile(
+ r"^shared_transformer\.feed_forward\.gate_up_proj_adapter_list\."
+ + str(adapter_id)
+ + r"\.(?:0|1)\.weight$"
+ )
+ self._tied_weights_keys.append(adapter_pattern)
+ adapter_id += 1
+ if self.config.use_shared_attention_adapter:
+ adapter_id = 0
+ for _layer_type in self.layers_block_type:
+ if _layer_type == "hybrid" and adapter_id % self.config.num_mem_blocks == block.block_id:
+ attn_adapter_pattern = re.compile(
+ r"^shared_transformer\.self_attn\."
+ + r"(?:linear_q_adapter_list|linear_k_adapter_list|linear_v_adapter_list)\."
+ + str(adapter_id)
+ + r"\.(?:0|1)\.weight$"
+ )
+ self._tied_weights_keys.append(attn_adapter_pattern)
+ adapter_id += 1
+ layers.append(Zamba2HybridLayer(block, next(linear_layers), next(mamba_layers)))
+ else:
+ layers.append(next(mamba_layers))
+ return layers
+
+ def forward(
+ self,
+ input_ids: Optional[torch.LongTensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ position_ids: Optional[torch.LongTensor] = None,
+ past_key_values: Optional[Zamba2HybridDynamicCache] = None,
+ inputs_embeds: Optional[torch.FloatTensor] = None,
+ use_cache: Optional[bool] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ cache_position: Optional[torch.LongTensor] = None,
+ ) -> Union[tuple, BaseModelOutputWithPast]:
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if (input_ids is None) ^ (inputs_embeds is not None):
+ raise ValueError(
+ "You cannot specify both input_ids and inputs_embeds at the same time, and must specify either one"
+ )
+
+ if self.gradient_checkpointing and self.training and use_cache:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
+ )
+ use_cache = False
+
+ if inputs_embeds is None:
+ inputs_embeds = self.embed_tokens(input_ids)
+
+ hidden_states = inputs_embeds
+
+ original_hidden_states = torch.clone(inputs_embeds)
+ # original_hidden_states: word embedding output that will be concatenated with hidden activations to form the input of the shared transformer layer
+
+ if use_cache and past_key_values is None:
+ batch_size = input_ids.shape[0] if input_ids is not None else inputs_embeds.shape[0]
+ past_key_values = Zamba2HybridDynamicCache(self.config, batch_size, dtype=self.dtype, device=self.device)
+
+ if cache_position is None:
+ past_seen_tokens = (
+ past_key_values.get_seq_length(layer_idx=self.first_transformer_layer_id)
+ if past_key_values is not None
+ else 0
+ )
+ cache_position = torch.arange(
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
+ )
+ if position_ids is None:
+ position_ids = cache_position.unsqueeze(0)
+
+ causal_mask = self._update_causal_mask(attention_mask, inputs_embeds, cache_position)
+
+ # create position embeddings to be shared across the decoder layers
+ if self.config.use_mem_rope:
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
+ else:
+ position_embeddings = None
+
+ all_hidden_states = () if output_hidden_states else None
+ all_self_attns = () if output_attentions else None
+
+ for layer_idx, layer in enumerate(self.layers):
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ if self.gradient_checkpointing and self.training:
+ layer_outputs = self._gradient_checkpointing_func(
+ layer.__call__,
+ hidden_states,
+ original_hidden_states,
+ layer_idx,
+ attention_mask,
+ causal_mask,
+ past_key_values,
+ output_attentions,
+ use_cache,
+ position_embeddings,
+ )
+ else:
+ layer_outputs = layer(
+ hidden_states,
+ original_hidden_states=original_hidden_states,
+ layer_idx=layer_idx,
+ attention_mask=attention_mask,
+ causal_mask=causal_mask,
+ past_key_values=past_key_values,
+ output_attentions=output_attentions,
+ use_cache=use_cache,
+ position_embeddings=position_embeddings,
+ )
+ hidden_states = layer_outputs[0]
+
+ if output_attentions:
+ if layer_outputs[1] is not None:
+ # append attentions only of attention layers. Mamba layers return `None` as the attention weights
+ all_self_attns += (layer_outputs[1],)
+
+ hidden_states = self.final_layernorm(hidden_states)
+
+ # add hidden states from the last decoder layer
+ if output_hidden_states:
+ all_hidden_states += (hidden_states,)
+
+ if past_key_values is not None and not past_key_values.has_previous_state:
+ past_key_values.has_previous_state = True
+
+ output = BaseModelOutputWithPast(
+ last_hidden_state=hidden_states,
+ past_key_values=past_key_values if use_cache else None,
+ hidden_states=all_hidden_states,
+ attentions=all_self_attns,
+ )
+ return output if return_dict else output.to_tuple()
+
+
+class Zamba2ForCausalLM(ZambaForCausalLM):
+ pass
+
+
+class Zamba2ForSequenceClassification(ZambaForSequenceClassification):
+ pass
+
+
+__all__ = [
+ "Zamba2ForCausalLM",
+ "Zamba2ForSequenceClassification",
+ "Zamba2Model",
+ "Zamba2PreTrainedModel",
+]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..abc436fa801f8d7f8cf0e6f44504b33f528131ec
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/__init__.py
@@ -0,0 +1,29 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import TYPE_CHECKING
+
+from ...utils import _LazyModule
+from ...utils.import_utils import define_import_structure
+
+
+if TYPE_CHECKING:
+ from .configuration_zoedepth import *
+ from .image_processing_zoedepth import *
+ from .image_processing_zoedepth_fast import *
+ from .modeling_zoedepth import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/configuration_zoedepth.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/configuration_zoedepth.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac89f815f82cca720838257c190bfd0bb034d60d
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/configuration_zoedepth.py
@@ -0,0 +1,245 @@
+# coding=utf-8
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""ZoeDepth model configuration"""
+
+from ...configuration_utils import PretrainedConfig
+from ...utils import logging
+from ..auto.configuration_auto import CONFIG_MAPPING
+
+
+logger = logging.get_logger(__name__)
+
+ZOEDEPTH_PRETRAINED_CONFIG_ARCHIVE_MAP = {
+ "Intel/zoedepth-nyu": "https://huggingface.co/Intel/zoedepth-nyu/resolve/main/config.json",
+}
+
+
+class ZoeDepthConfig(PretrainedConfig):
+ r"""
+ This is the configuration class to store the configuration of a [`ZoeDepthForDepthEstimation`]. It is used to instantiate an ZoeDepth
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
+ defaults will yield a similar configuration to that of the ZoeDepth
+ [Intel/zoedepth-nyu](https://huggingface.co/Intel/zoedepth-nyu) architecture.
+
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PretrainedConfig`] for more information.
+
+ Args:
+ backbone_config (`Union[dict[str, Any], PretrainedConfig]`, *optional*, defaults to `BeitConfig()`):
+ The configuration of the backbone model.
+ backbone (`str`, *optional*):
+ Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
+ will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
+ is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
+ use_pretrained_backbone (`bool`, *optional*, defaults to `False`):
+ Whether to use pretrained weights for the backbone.
+ backbone_kwargs (`dict`, *optional*):
+ Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
+ e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
+ initializer_range (`float`, *optional*, defaults to 0.02):
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ batch_norm_eps (`float`, *optional*, defaults to 1e-05):
+ The epsilon used by the batch normalization layers.
+ readout_type (`str`, *optional*, defaults to `"project"`):
+ The readout type to use when processing the readout token (CLS token) of the intermediate hidden states of
+ the ViT backbone. Can be one of [`"ignore"`, `"add"`, `"project"`].
+
+ - "ignore" simply ignores the CLS token.
+ - "add" passes the information from the CLS token to all other tokens by adding the representations.
+ - "project" passes information to the other tokens by concatenating the readout to all other tokens before
+ projecting the
+ representation to the original feature dimension D using a linear layer followed by a GELU non-linearity.
+ reassemble_factors (`list[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`):
+ The up/downsampling factors of the reassemble layers.
+ neck_hidden_sizes (`list[str]`, *optional*, defaults to `[96, 192, 384, 768]`):
+ The hidden sizes to project to for the feature maps of the backbone.
+ fusion_hidden_size (`int`, *optional*, defaults to 256):
+ The number of channels before fusion.
+ head_in_index (`int`, *optional*, defaults to -1):
+ The index of the features to use in the heads.
+ use_batch_norm_in_fusion_residual (`bool`, *optional*, defaults to `False`):
+ Whether to use batch normalization in the pre-activate residual units of the fusion blocks.
+ use_bias_in_fusion_residual (`bool`, *optional*, defaults to `True`):
+ Whether to use bias in the pre-activate residual units of the fusion blocks.
+ num_relative_features (`int`, *optional*, defaults to 32):
+ The number of features to use in the relative depth estimation head.
+ add_projection (`bool`, *optional*, defaults to `False`):
+ Whether to add a projection layer before the depth estimation head.
+ bottleneck_features (`int`, *optional*, defaults to 256):
+ The number of features in the bottleneck layer.
+ num_attractors (`list[int], *optional*, defaults to `[16, 8, 4, 1]`):
+ The number of attractors to use in each stage.
+ bin_embedding_dim (`int`, *optional*, defaults to 128):
+ The dimension of the bin embeddings.
+ attractor_alpha (`int`, *optional*, defaults to 1000):
+ The alpha value to use in the attractor.
+ attractor_gamma (`int`, *optional*, defaults to 2):
+ The gamma value to use in the attractor.
+ attractor_kind (`str`, *optional*, defaults to `"mean"`):
+ The kind of attractor to use. Can be one of [`"mean"`, `"sum"`].
+ min_temp (`float`, *optional*, defaults to 0.0212):
+ The minimum temperature value to consider.
+ max_temp (`float`, *optional*, defaults to 50.0):
+ The maximum temperature value to consider.
+ bin_centers_type (`str`, *optional*, defaults to `"softplus"`):
+ Activation type used for bin centers. Can be "normed" or "softplus". For "normed" bin centers, linear normalization trick
+ is applied. This results in bounded bin centers. For "softplus", softplus activation is used and thus are unbounded.
+ bin_configurations (`list[dict]`, *optional*, defaults to `[{'n_bins': 64, 'min_depth': 0.001, 'max_depth': 10.0}]`):
+ Configuration for each of the bin heads.
+ Each configuration should consist of the following keys:
+ - name (`str`): The name of the bin head - only required in case of multiple bin configurations.
+ - `n_bins` (`int`): The number of bins to use.
+ - `min_depth` (`float`): The minimum depth value to consider.
+ - `max_depth` (`float`): The maximum depth value to consider.
+ In case only a single configuration is passed, the model will use a single head with the specified configuration.
+ In case multiple configurations are passed, the model will use multiple heads with the specified configurations.
+ num_patch_transformer_layers (`int`, *optional*):
+ The number of transformer layers to use in the patch transformer. Only used in case of multiple bin configurations.
+ patch_transformer_hidden_size (`int`, *optional*):
+ The hidden size to use in the patch transformer. Only used in case of multiple bin configurations.
+ patch_transformer_intermediate_size (`int`, *optional*):
+ The intermediate size to use in the patch transformer. Only used in case of multiple bin configurations.
+ patch_transformer_num_attention_heads (`int`, *optional*):
+ The number of attention heads to use in the patch transformer. Only used in case of multiple bin configurations.
+
+ Example:
+
+ ```python
+ >>> from transformers import ZoeDepthConfig, ZoeDepthForDepthEstimation
+
+ >>> # Initializing a ZoeDepth zoedepth-large style configuration
+ >>> configuration = ZoeDepthConfig()
+
+ >>> # Initializing a model from the zoedepth-large style configuration
+ >>> model = ZoeDepthForDepthEstimation(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "zoedepth"
+
+ def __init__(
+ self,
+ backbone_config=None,
+ backbone=None,
+ use_pretrained_backbone=False,
+ backbone_kwargs=None,
+ hidden_act="gelu",
+ initializer_range=0.02,
+ batch_norm_eps=1e-05,
+ readout_type="project",
+ reassemble_factors=[4, 2, 1, 0.5],
+ neck_hidden_sizes=[96, 192, 384, 768],
+ fusion_hidden_size=256,
+ head_in_index=-1,
+ use_batch_norm_in_fusion_residual=False,
+ use_bias_in_fusion_residual=None,
+ num_relative_features=32,
+ add_projection=False,
+ bottleneck_features=256,
+ num_attractors=[16, 8, 4, 1],
+ bin_embedding_dim=128,
+ attractor_alpha=1000,
+ attractor_gamma=2,
+ attractor_kind="mean",
+ min_temp=0.0212,
+ max_temp=50.0,
+ bin_centers_type="softplus",
+ bin_configurations=[{"n_bins": 64, "min_depth": 0.001, "max_depth": 10.0}],
+ num_patch_transformer_layers=None,
+ patch_transformer_hidden_size=None,
+ patch_transformer_intermediate_size=None,
+ patch_transformer_num_attention_heads=None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+
+ if readout_type not in ["ignore", "add", "project"]:
+ raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']")
+
+ if attractor_kind not in ["mean", "sum"]:
+ raise ValueError("Attractor_kind must be one of ['mean', 'sum']")
+
+ if use_pretrained_backbone:
+ raise ValueError("Pretrained backbones are not supported yet.")
+
+ if backbone_config is not None and backbone is not None:
+ raise ValueError("You can't specify both `backbone` and `backbone_config`.")
+
+ if backbone_config is None and backbone is None:
+ logger.info("`backbone_config` is `None`. Initializing the config with the default `BEiT` backbone.")
+ backbone_config = CONFIG_MAPPING["beit"](
+ image_size=384,
+ num_hidden_layers=24,
+ hidden_size=1024,
+ intermediate_size=4096,
+ num_attention_heads=16,
+ use_relative_position_bias=True,
+ reshape_hidden_states=False,
+ out_features=["stage6", "stage12", "stage18", "stage24"],
+ )
+ elif isinstance(backbone_config, dict):
+ backbone_model_type = backbone_config.get("model_type")
+ config_class = CONFIG_MAPPING[backbone_model_type]
+ backbone_config = config_class.from_dict(backbone_config)
+
+ if backbone_kwargs is not None and backbone_kwargs and backbone_config is not None:
+ raise ValueError("You can't specify both `backbone_kwargs` and `backbone_config`.")
+
+ self.backbone_config = backbone_config
+ self.backbone = backbone
+ self.hidden_act = hidden_act
+ self.use_pretrained_backbone = use_pretrained_backbone
+ self.initializer_range = initializer_range
+ self.batch_norm_eps = batch_norm_eps
+ self.readout_type = readout_type
+ self.reassemble_factors = reassemble_factors
+ self.neck_hidden_sizes = neck_hidden_sizes
+ self.fusion_hidden_size = fusion_hidden_size
+ self.head_in_index = head_in_index
+ self.use_batch_norm_in_fusion_residual = use_batch_norm_in_fusion_residual
+ self.use_bias_in_fusion_residual = use_bias_in_fusion_residual
+ self.num_relative_features = num_relative_features
+ self.add_projection = add_projection
+
+ self.bottleneck_features = bottleneck_features
+ self.num_attractors = num_attractors
+ self.bin_embedding_dim = bin_embedding_dim
+ self.attractor_alpha = attractor_alpha
+ self.attractor_gamma = attractor_gamma
+ self.attractor_kind = attractor_kind
+ self.min_temp = min_temp
+ self.max_temp = max_temp
+ self.bin_centers_type = bin_centers_type
+ self.bin_configurations = bin_configurations
+ self.num_patch_transformer_layers = num_patch_transformer_layers
+ self.patch_transformer_hidden_size = patch_transformer_hidden_size
+ self.patch_transformer_intermediate_size = patch_transformer_intermediate_size
+ self.patch_transformer_num_attention_heads = patch_transformer_num_attention_heads
+
+ @property
+ def sub_configs(self):
+ return (
+ {"backbone_config": type(self.backbone_config)}
+ if getattr(self, "backbone_config", None) is not None
+ else {}
+ )
+
+
+__all__ = ["ZOEDEPTH_PRETRAINED_CONFIG_ARCHIVE_MAP", "ZoeDepthConfig"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_zoedepth.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_zoedepth.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fb125e2b79381e7bcd548e547e5d34ec7c814e6
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_zoedepth.py
@@ -0,0 +1,562 @@
+# coding=utf-8
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Image processor class for ZoeDepth."""
+
+import math
+from collections.abc import Iterable
+from typing import TYPE_CHECKING, Optional, Union
+
+import numpy as np
+
+
+if TYPE_CHECKING:
+ from .modeling_zoedepth import ZoeDepthDepthEstimatorOutput
+
+from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
+from ...image_transforms import PaddingMode, pad, to_channel_dimension_format
+from ...image_utils import (
+ IMAGENET_STANDARD_MEAN,
+ IMAGENET_STANDARD_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ get_image_size,
+ infer_channel_dimension_format,
+ is_scaled_image,
+ make_list_of_images,
+ to_numpy_array,
+ valid_images,
+ validate_preprocess_arguments,
+)
+from ...utils import (
+ TensorType,
+ filter_out_non_signature_kwargs,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+
+
+if is_vision_available():
+ import PIL
+
+if is_torch_available():
+ import torch
+ from torch import nn
+
+
+logger = logging.get_logger(__name__)
+
+
+def get_resize_output_image_size(
+ input_image: np.ndarray,
+ output_size: Union[int, Iterable[int]],
+ keep_aspect_ratio: bool,
+ multiple: int,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+) -> tuple[int, int]:
+ def constrain_to_multiple_of(val, multiple, min_val=0):
+ x = (np.round(val / multiple) * multiple).astype(int)
+
+ if x < min_val:
+ x = math.ceil(val / multiple) * multiple
+
+ return x
+
+ output_size = (output_size, output_size) if isinstance(output_size, int) else output_size
+
+ input_height, input_width = get_image_size(input_image, input_data_format)
+ output_height, output_width = output_size
+
+ # determine new height and width
+ scale_height = output_height / input_height
+ scale_width = output_width / input_width
+
+ if keep_aspect_ratio:
+ # scale as little as possible
+ if abs(1 - scale_width) < abs(1 - scale_height):
+ # fit width
+ scale_height = scale_width
+ else:
+ # fit height
+ scale_width = scale_height
+
+ new_height = constrain_to_multiple_of(scale_height * input_height, multiple=multiple)
+ new_width = constrain_to_multiple_of(scale_width * input_width, multiple=multiple)
+
+ return (new_height, new_width)
+
+
+class ZoeDepthImageProcessor(BaseImageProcessor):
+ r"""
+ Constructs a ZoeDepth image processor.
+
+ Args:
+ do_pad (`bool`, *optional*, defaults to `True`):
+ Whether to apply pad the input.
+ do_rescale (`bool`, *optional*, defaults to `True`):
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by `do_rescale` in
+ `preprocess`.
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
+ Scale factor to use if rescaling the image. Can be overridden by `rescale_factor` in `preprocess`.
+ do_normalize (`bool`, *optional*, defaults to `True`):
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
+ method.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
+ image_std (`float` or `list[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
+ do_resize (`bool`, *optional*, defaults to `True`):
+ Whether to resize the image's (height, width) dimensions. Can be overridden by `do_resize` in `preprocess`.
+ size (`dict[str, int]` *optional*, defaults to `{"height": 384, "width": 512}`):
+ Size of the image after resizing. Size of the image after resizing. If `keep_aspect_ratio` is `True`,
+ the image is resized by choosing the smaller of the height and width scaling factors and using it for both dimensions.
+ If `ensure_multiple_of` is also set, the image is further resized to a size that is a multiple of this value.
+ Can be overridden by `size` in `preprocess`.
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
+ Defines the resampling filter to use if resizing the image. Can be overridden by `resample` in `preprocess`.
+ keep_aspect_ratio (`bool`, *optional*, defaults to `True`):
+ If `True`, the image is resized by choosing the smaller of the height and width scaling factors and using it
+ for both dimensions. This ensures that the image is scaled down as little as possible while still fitting
+ within the desired output size. In case `ensure_multiple_of` is also set, the image is further resized to a
+ size that is a multiple of this value by flooring the height and width to the nearest multiple of this value.
+ Can be overridden by `keep_aspect_ratio` in `preprocess`.
+ ensure_multiple_of (`int`, *optional*, defaults to 32):
+ If `do_resize` is `True`, the image is resized to a size that is a multiple of this value. Works by flooring
+ the height and width to the nearest multiple of this value.
+
+ Works both with and without `keep_aspect_ratio` being set to `True`. Can be overridden by `ensure_multiple_of`
+ in `preprocess`.
+ """
+
+ model_input_names = ["pixel_values"]
+
+ def __init__(
+ self,
+ do_pad: bool = True,
+ do_rescale: bool = True,
+ rescale_factor: Union[int, float] = 1 / 255,
+ do_normalize: bool = True,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ do_resize: bool = True,
+ size: Optional[dict[str, int]] = None,
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
+ keep_aspect_ratio: bool = True,
+ ensure_multiple_of: int = 32,
+ **kwargs,
+ ) -> None:
+ super().__init__(**kwargs)
+ self.do_rescale = do_rescale
+ self.rescale_factor = rescale_factor
+ self.do_pad = do_pad
+ self.do_normalize = do_normalize
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
+ size = size if size is not None else {"height": 384, "width": 512}
+ size = get_size_dict(size)
+ self.do_resize = do_resize
+ self.size = size
+ self.keep_aspect_ratio = keep_aspect_ratio
+ self.ensure_multiple_of = ensure_multiple_of
+ self.resample = resample
+
+ def resize(
+ self,
+ image: np.ndarray,
+ size: dict[str, int],
+ keep_aspect_ratio: bool = False,
+ ensure_multiple_of: int = 1,
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ ) -> np.ndarray:
+ """
+ Resize an image to target size `(size["height"], size["width"])`. If `keep_aspect_ratio` is `True`, the image
+ is resized to the largest possible size such that the aspect ratio is preserved. If `ensure_multiple_of` is
+ set, the image is resized to a size that is a multiple of this value.
+
+ Args:
+ image (`np.ndarray`):
+ Image to resize.
+ size (`dict[str, int]`):
+ Target size of the output image.
+ keep_aspect_ratio (`bool`, *optional*, defaults to `False`):
+ If `True`, the image is resized to the largest possible size such that the aspect ratio is preserved.
+ ensure_multiple_of (`int`, *optional*, defaults to 1):
+ The image is resized to a size that is a multiple of this value.
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
+ Defines the resampling filter to use if resizing the image. Otherwise, the image is resized to size
+ specified in `size`.
+ data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
+ input_data_format (`str` or `ChannelDimension`, *optional*):
+ The channel dimension format of the input image. If not provided, it will be inferred.
+ """
+ if input_data_format is None:
+ input_data_format = infer_channel_dimension_format(image)
+
+ data_format = data_format if data_format is not None else input_data_format
+
+ size = get_size_dict(size)
+ if "height" not in size or "width" not in size:
+ raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}")
+
+ output_size = get_resize_output_image_size(
+ image,
+ output_size=(size["height"], size["width"]),
+ keep_aspect_ratio=keep_aspect_ratio,
+ multiple=ensure_multiple_of,
+ input_data_format=input_data_format,
+ )
+
+ height, width = output_size
+
+ torch_image = torch.from_numpy(image).unsqueeze(0)
+ torch_image = torch_image.permute(0, 3, 1, 2) if input_data_format == "channels_last" else torch_image
+
+ # TODO support align_corners=True in image_transforms.resize
+ requires_backends(self, "torch")
+ resample_to_mode = {PILImageResampling.BILINEAR: "bilinear", PILImageResampling.BICUBIC: "bicubic"}
+ mode = resample_to_mode[resample]
+ resized_image = nn.functional.interpolate(
+ torch_image, (int(height), int(width)), mode=mode, align_corners=True
+ )
+ resized_image = resized_image.squeeze().numpy()
+
+ resized_image = to_channel_dimension_format(
+ resized_image, data_format, input_channel_dim=ChannelDimension.FIRST
+ )
+
+ return resized_image
+
+ def pad_image(
+ self,
+ image: np.array,
+ mode: PaddingMode = PaddingMode.REFLECT,
+ data_format: Optional[Union[str, ChannelDimension]] = None,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ ):
+ """
+ Pad an image as done in the original ZoeDepth implementation.
+
+ Padding fixes the boundary artifacts in the output depth map.
+ Boundary artifacts are sometimes caused by the fact that the model is trained on NYU raw dataset
+ which has a black or white border around the image. This function pads the input image and crops
+ the prediction back to the original size / view.
+
+ Args:
+ image (`np.ndarray`):
+ Image to pad.
+ mode (`PaddingMode`):
+ The padding mode to use. Can be one of:
+ - `"constant"`: pads with a constant value.
+ - `"reflect"`: pads with the reflection of the vector mirrored on the first and last values of the
+ vector along each axis.
+ - `"replicate"`: pads with the replication of the last value on the edge of the array along each axis.
+ - `"symmetric"`: pads with the reflection of the vector mirrored along the edge of the array.
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
+ The channel dimension format for the output image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - Unset: Use the channel dimension format of the input image.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+ """
+ height, width = get_image_size(image, input_data_format)
+
+ pad_height = int(np.sqrt(height / 2) * 3)
+ pad_width = int(np.sqrt(width / 2) * 3)
+
+ return pad(
+ image,
+ padding=((pad_height, pad_height), (pad_width, pad_width)),
+ mode=mode,
+ data_format=data_format,
+ input_data_format=input_data_format,
+ )
+
+ @filter_out_non_signature_kwargs()
+ def preprocess(
+ self,
+ images: ImageInput,
+ do_pad: Optional[bool] = None,
+ do_rescale: Optional[bool] = None,
+ rescale_factor: Optional[float] = None,
+ do_normalize: Optional[bool] = None,
+ image_mean: Optional[Union[float, list[float]]] = None,
+ image_std: Optional[Union[float, list[float]]] = None,
+ do_resize: Optional[bool] = None,
+ size: Optional[int] = None,
+ keep_aspect_ratio: Optional[bool] = None,
+ ensure_multiple_of: Optional[int] = None,
+ resample: PILImageResampling = None,
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ data_format: ChannelDimension = ChannelDimension.FIRST,
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
+ ) -> PIL.Image.Image:
+ """
+ Preprocess an image or batch of images.
+
+ Args:
+ images (`ImageInput`):
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
+ do_pad (`bool`, *optional*, defaults to `self.do_pad`):
+ Whether to pad the input image.
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
+ Whether to rescale the image values between [0 - 1].
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
+ Whether to normalize the image.
+ image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
+ Image mean.
+ image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
+ Image standard deviation.
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
+ Whether to resize the image.
+ size (`dict[str, int]`, *optional*, defaults to `self.size`):
+ Size of the image after resizing. If `keep_aspect_ratio` is `True`, he image is resized by choosing the
+ smaller of the height and width scaling factors and using it for both dimensions. If `ensure_multiple_of`
+ is also set, the image is further resized to a size that is a multiple of this value.
+ keep_aspect_ratio (`bool`, *optional*, defaults to `self.keep_aspect_ratio`):
+ If `True` and `do_resize=True`, the image is resized by choosing the smaller of the height and width
+ scaling factors and using it for both dimensions. This ensures that the image is scaled down as little
+ as possible while still fitting within the desired output size. In case `ensure_multiple_of` is also
+ set, the image is further resized to a size that is a multiple of this value by flooring the height and
+ width to the nearest multiple of this value.
+ ensure_multiple_of (`int`, *optional*, defaults to `self.ensure_multiple_of`):
+ If `do_resize` is `True`, the image is resized to a size that is a multiple of this value. Works by
+ flooring the height and width to the nearest multiple of this value.
+
+ Works both with and without `keep_aspect_ratio` being set to `True`. Can be overridden by
+ `ensure_multiple_of` in `preprocess`.
+ resample (`int`, *optional*, defaults to `self.resample`):
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
+ has an effect if `do_resize` is set to `True`.
+ return_tensors (`str` or `TensorType`, *optional*):
+ The type of tensors to return. Can be one of:
+ - Unset: Return a list of `np.ndarray`.
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
+ The channel dimension format for the output image. Can be one of:
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ input_data_format (`ChannelDimension` or `str`, *optional*):
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
+ from the input image. Can be one of:
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
+ """
+ do_resize = do_resize if do_resize is not None else self.do_resize
+ size = size if size is not None else self.size
+ size = get_size_dict(size)
+ keep_aspect_ratio = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
+ ensure_multiple_of = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
+ resample = resample if resample is not None else self.resample
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
+ image_mean = image_mean if image_mean is not None else self.image_mean
+ image_std = image_std if image_std is not None else self.image_std
+ do_pad = do_pad if do_pad is not None else self.do_pad
+
+ images = make_list_of_images(images)
+
+ if not valid_images(images):
+ raise ValueError(
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
+ "torch.Tensor, tf.Tensor or jax.ndarray."
+ )
+ validate_preprocess_arguments(
+ do_rescale=do_rescale,
+ rescale_factor=rescale_factor,
+ do_normalize=do_normalize,
+ image_mean=image_mean,
+ image_std=image_std,
+ do_resize=do_resize,
+ size=size,
+ resample=resample,
+ )
+ # All transformations expect numpy arrays.
+ images = [to_numpy_array(image) for image in images]
+
+ if do_rescale and is_scaled_image(images[0]):
+ logger.warning_once(
+ "It looks like you are trying to rescale already rescaled images. If the input"
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
+ )
+
+ if input_data_format is None:
+ # We assume that all images have the same channel dimension format.
+ input_data_format = infer_channel_dimension_format(images[0])
+
+ if do_rescale:
+ images = [
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
+ for image in images
+ ]
+
+ if do_pad:
+ images = [self.pad_image(image=image, input_data_format=input_data_format) for image in images]
+
+ if do_resize:
+ images = [
+ self.resize(
+ image=image,
+ size=size,
+ resample=resample,
+ keep_aspect_ratio=keep_aspect_ratio,
+ ensure_multiple_of=ensure_multiple_of,
+ input_data_format=input_data_format,
+ )
+ for image in images
+ ]
+
+ if do_normalize:
+ images = [
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
+ for image in images
+ ]
+
+ images = [
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
+ ]
+
+ data = {"pixel_values": images}
+ return BatchFeature(data=data, tensor_type=return_tensors)
+
+ def post_process_depth_estimation(
+ self,
+ outputs: "ZoeDepthDepthEstimatorOutput",
+ source_sizes: Optional[Union[TensorType, list[tuple[int, int]], None]] = None,
+ target_sizes: Optional[Union[TensorType, list[tuple[int, int]], None]] = None,
+ outputs_flipped: Optional[Union["ZoeDepthDepthEstimatorOutput", None]] = None,
+ do_remove_padding: Optional[Union[bool, None]] = None,
+ ) -> list[dict[str, TensorType]]:
+ """
+ Converts the raw output of [`ZoeDepthDepthEstimatorOutput`] into final depth predictions and depth PIL images.
+ Only supports PyTorch.
+
+ Args:
+ outputs ([`ZoeDepthDepthEstimatorOutput`]):
+ Raw outputs of the model.
+ source_sizes (`TensorType` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the source size
+ (height, width) of each image in the batch before preprocessing. This argument should be dealt as
+ "required" unless the user passes `do_remove_padding=False` as input to this function.
+ target_sizes (`TensorType` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ outputs_flipped ([`ZoeDepthDepthEstimatorOutput`], *optional*):
+ Raw outputs of the model from flipped input (averaged out in the end).
+ do_remove_padding (`bool`, *optional*):
+ By default ZoeDepth adds padding equal to `int(√(height / 2) * 3)` (and similarly for width) to fix the
+ boundary artifacts in the output depth map, so we need remove this padding during post_processing. The
+ parameter exists here in case the user changed the image preprocessing to not include padding.
+
+ Returns:
+ `list[dict[str, TensorType]]`: A list of dictionaries of tensors representing the processed depth
+ predictions.
+ """
+ requires_backends(self, "torch")
+
+ predicted_depth = outputs.predicted_depth
+
+ if (outputs_flipped is not None) and (predicted_depth.shape != outputs_flipped.predicted_depth.shape):
+ raise ValueError("Make sure that `outputs` and `outputs_flipped` have the same shape")
+
+ if (target_sizes is not None) and (len(predicted_depth) != len(target_sizes)):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the predicted depth"
+ )
+
+ if do_remove_padding is None:
+ do_remove_padding = self.do_pad
+
+ if source_sizes is None and do_remove_padding:
+ raise ValueError(
+ "Either `source_sizes` should be passed in, or `do_remove_padding` should be set to False"
+ )
+
+ if (source_sizes is not None) and (len(predicted_depth) != len(source_sizes)):
+ raise ValueError(
+ "Make sure that you pass in as many source image sizes as the batch dimension of the logits"
+ )
+
+ if outputs_flipped is not None:
+ predicted_depth = (predicted_depth + torch.flip(outputs_flipped.predicted_depth, dims=[-1])) / 2
+
+ predicted_depth = predicted_depth.unsqueeze(1)
+
+ # Zoe Depth model adds padding around the images to fix the boundary artifacts in the output depth map
+ # The padding length is `int(np.sqrt(img_h/2) * fh)` for the height and similar for the width
+ # fh (and fw respectively) are equal to '3' by default
+ # Check [here](https://github.com/isl-org/ZoeDepth/blob/edb6daf45458569e24f50250ef1ed08c015f17a7/zoedepth/models/depth_model.py#L57)
+ # for the original implementation.
+ # In this section, we remove this padding to get the final depth image and depth prediction
+ padding_factor_h = padding_factor_w = 3
+
+ results = []
+ target_sizes = [None] * len(predicted_depth) if target_sizes is None else target_sizes
+ source_sizes = [None] * len(predicted_depth) if source_sizes is None else source_sizes
+ for depth, target_size, source_size in zip(predicted_depth, target_sizes, source_sizes):
+ # depth.shape = [1, H, W]
+ if source_size is not None:
+ pad_h = pad_w = 0
+
+ if do_remove_padding:
+ pad_h = int(np.sqrt(source_size[0] / 2) * padding_factor_h)
+ pad_w = int(np.sqrt(source_size[1] / 2) * padding_factor_w)
+
+ depth = nn.functional.interpolate(
+ depth.unsqueeze(1),
+ size=[source_size[0] + 2 * pad_h, source_size[1] + 2 * pad_w],
+ mode="bicubic",
+ align_corners=False,
+ )
+
+ if pad_h > 0:
+ depth = depth[:, :, pad_h:-pad_h, :]
+ if pad_w > 0:
+ depth = depth[:, :, :, pad_w:-pad_w]
+
+ depth = depth.squeeze(1)
+ # depth.shape = [1, H, W]
+ if target_size is not None:
+ target_size = [target_size[0], target_size[1]]
+ depth = nn.functional.interpolate(
+ depth.unsqueeze(1), size=target_size, mode="bicubic", align_corners=False
+ )
+ depth = depth.squeeze()
+ # depth.shape = [H, W]
+ results.append({"predicted_depth": depth})
+
+ return results
+
+
+__all__ = ["ZoeDepthImageProcessor"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_zoedepth_fast.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_zoedepth_fast.py
new file mode 100644
index 0000000000000000000000000000000000000000..793c386fdc75daa8cad9a54baa68428f08bf91d2
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/image_processing_zoedepth_fast.py
@@ -0,0 +1,326 @@
+# coding=utf-8
+# Copyright 2025 The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""Fast Image processor class for ZoeDepth."""
+
+from typing import (
+ Optional,
+ Union,
+)
+
+import numpy as np
+
+from ...image_processing_utils import (
+ BatchFeature,
+)
+from ...image_processing_utils_fast import (
+ BaseImageProcessorFast,
+ DefaultFastImageProcessorKwargs,
+ group_images_by_shape,
+ reorder_images,
+)
+from ...image_utils import (
+ IMAGENET_STANDARD_MEAN,
+ IMAGENET_STANDARD_STD,
+ ChannelDimension,
+ ImageInput,
+ PILImageResampling,
+ SizeDict,
+ get_image_size,
+)
+from ...processing_utils import Unpack
+from ...utils import (
+ TensorType,
+ auto_docstring,
+ is_torch_available,
+ is_torchvision_available,
+ is_torchvision_v2_available,
+ logging,
+ requires_backends,
+)
+from .image_processing_zoedepth import get_resize_output_image_size
+from .modeling_zoedepth import ZoeDepthDepthEstimatorOutput
+
+
+if is_torch_available():
+ import torch
+
+if is_torchvision_available():
+ if is_torchvision_v2_available():
+ from torchvision.transforms.v2 import functional as F
+ else:
+ from torchvision.transforms import functional as F
+
+ from torchvision.transforms import InterpolationMode
+
+
+logger = logging.get_logger(__name__)
+
+
+class ZoeDepthFastImageProcessorKwargs(DefaultFastImageProcessorKwargs):
+ """
+ do_pad (`bool`, *optional*, defaults to `True`):
+ Whether to apply pad the input.
+ keep_aspect_ratio (`bool`, *optional*, defaults to `True`):
+ If `True`, the image is resized by choosing the smaller of the height and width scaling factors and using it
+ for both dimensions. This ensures that the image is scaled down as little as possible while still fitting
+ within the desired output size. In case `ensure_multiple_of` is also set, the image is further resized to a
+ size that is a multiple of this value by flooring the height and width to the nearest multiple of this value.
+ Can be overridden by `keep_aspect_ratio` in `preprocess`.
+ ensure_multiple_of (`int`, *optional*, defaults to 32):
+ If `do_resize` is `True`, the image is resized to a size that is a multiple of this value. Works by flooring
+ the height and width to the nearest multiple of this value.
+ Works both with and without `keep_aspect_ratio` being set to `True`.
+ Can be overridden by `ensure_multiple_of` in `preprocess`.
+ """
+
+ do_pad: Optional[bool]
+ keep_aspect_ratio: Optional[bool]
+ ensure_multiple_of: Optional[int]
+
+
+@auto_docstring
+class ZoeDepthImageProcessorFast(BaseImageProcessorFast):
+ do_pad = True
+ do_rescale = True
+ do_normalize = True
+ image_mean = IMAGENET_STANDARD_MEAN
+ image_std = IMAGENET_STANDARD_STD
+ do_resize = True
+ size = {"height": 384, "width": 512}
+ resample = PILImageResampling.BILINEAR
+ keep_aspect_ratio = True
+ ensure_multiple_of = 1 / 32
+ valid_kwargs = ZoeDepthFastImageProcessorKwargs
+
+ def __init__(self, **kwargs: Unpack[ZoeDepthFastImageProcessorKwargs]) -> None:
+ super().__init__(**kwargs)
+
+ @auto_docstring
+ def preprocess(
+ self,
+ images: ImageInput,
+ **kwargs: Unpack[ZoeDepthFastImageProcessorKwargs],
+ ) -> BatchFeature:
+ return super().preprocess(images, **kwargs)
+
+ def resize(
+ self,
+ images: "torch.Tensor",
+ size: SizeDict,
+ keep_aspect_ratio: bool = False,
+ ensure_multiple_of: int = 1,
+ interpolation: Optional["F.InterpolationMode"] = None,
+ ) -> "torch.Tensor":
+ """
+ Resize an image or batchd images to target size `(size["height"], size["width"])`. If `keep_aspect_ratio` is `True`, the image
+ is resized to the largest possible size such that the aspect ratio is preserved. If `ensure_multiple_of` is
+ set, the image is resized to a size that is a multiple of this value.
+
+ Args:
+ images (`torch.Tensor`):
+ Images to resize.
+ size (`dict[str, int]`):
+ Target size of the output image.
+ keep_aspect_ratio (`bool`, *optional*, defaults to `False`):
+ If `True`, the image is resized to the largest possible size such that the aspect ratio is preserved.
+ ensure_multiple_of (`int`, *optional*, defaults to 1):
+ The image is resized to a size that is a multiple of this value.
+ interpolation (`F.InterpolationMode`, *optional*, defaults to `InterpolationMode.BILINEAR`):
+ Defines the resampling filter to use if resizing the image. Otherwise, the image is resized to size
+ specified in `size`.
+ """
+ if not size.height or not size.width:
+ raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size}")
+ output_size = get_resize_output_image_size(
+ images,
+ output_size=(size.height, size.width),
+ keep_aspect_ratio=keep_aspect_ratio,
+ multiple=ensure_multiple_of,
+ input_data_format=ChannelDimension.FIRST,
+ )
+ height, width = output_size
+
+ resized_images = torch.nn.functional.interpolate(
+ images, (int(height), int(width)), mode=interpolation.value, align_corners=True
+ )
+
+ return resized_images
+
+ def _pad_images(
+ self,
+ images: "torch.Tensor",
+ ):
+ """
+ Args:
+ image (`torch.Tensor`):
+ Image to pad.
+ """
+ height, width = get_image_size(images, channel_dim=ChannelDimension.FIRST)
+
+ pad_height = int(np.sqrt(height / 2) * 3)
+ pad_width = int(np.sqrt(width / 2) * 3)
+
+ return F.pad(images, padding=(pad_width, pad_height), padding_mode="reflect")
+
+ def _preprocess(
+ self,
+ images: list["torch.Tensor"],
+ do_resize: bool,
+ size: SizeDict,
+ keep_aspect_ratio: Optional[bool],
+ ensure_multiple_of: Optional[int],
+ interpolation: Optional["F.InterpolationMode"],
+ do_pad: bool,
+ do_rescale: bool,
+ rescale_factor: Optional[float],
+ do_normalize: bool,
+ image_mean: Optional[Union[float, list[float]]],
+ image_std: Optional[Union[float, list[float]]],
+ disable_grouping: Optional[bool],
+ return_tensors: Optional[Union[str, TensorType]] = None,
+ **kwargs,
+ ) -> BatchFeature:
+ # Group images by size for batched resizing
+ grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping)
+ resized_images_grouped = {}
+ for shape, stacked_images in grouped_images.items():
+ if do_rescale:
+ stacked_images = self.rescale(stacked_images, rescale_factor)
+ if do_pad:
+ stacked_images = self._pad_images(images=stacked_images)
+ if do_resize:
+ stacked_images = self.resize(
+ stacked_images, size, keep_aspect_ratio, ensure_multiple_of, interpolation
+ )
+ if do_normalize:
+ stacked_images = self.normalize(stacked_images, image_mean, image_std)
+ resized_images_grouped[shape] = stacked_images
+ resized_images = reorder_images(resized_images_grouped, grouped_images_index)
+
+ processed_images = torch.stack(resized_images, dim=0) if return_tensors else resized_images
+
+ return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors)
+
+ def post_process_depth_estimation(
+ self,
+ outputs: "ZoeDepthDepthEstimatorOutput",
+ source_sizes: Optional[Union[TensorType, list[tuple[int, int]], None]] = None,
+ target_sizes: Optional[Union[TensorType, list[tuple[int, int]], None]] = None,
+ outputs_flipped: Optional[Union["ZoeDepthDepthEstimatorOutput", None]] = None,
+ do_remove_padding: Optional[Union[bool, None]] = None,
+ ) -> list[dict[str, TensorType]]:
+ """
+ Converts the raw output of [`ZoeDepthDepthEstimatorOutput`] into final depth predictions and depth PIL images.
+ Only supports PyTorch.
+
+ Args:
+ outputs ([`ZoeDepthDepthEstimatorOutput`]):
+ Raw outputs of the model.
+ source_sizes (`TensorType` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the source size
+ (height, width) of each image in the batch before preprocessing. This argument should be dealt as
+ "required" unless the user passes `do_remove_padding=False` as input to this function.
+ target_sizes (`TensorType` or `list[tuple[int, int]]`, *optional*):
+ Tensor of shape `(batch_size, 2)` or list of tuples (`tuple[int, int]`) containing the target size
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
+ outputs_flipped ([`ZoeDepthDepthEstimatorOutput`], *optional*):
+ Raw outputs of the model from flipped input (averaged out in the end).
+ do_remove_padding (`bool`, *optional*):
+ By default ZoeDepth adds padding equal to `int(√(height / 2) * 3)` (and similarly for width) to fix the
+ boundary artifacts in the output depth map, so we need remove this padding during post_processing. The
+ parameter exists here in case the user changed the image preprocessing to not include padding.
+
+ Returns:
+ `list[dict[str, TensorType]]`: A list of dictionaries of tensors representing the processed depth
+ predictions.
+ """
+ requires_backends(self, "torch")
+
+ predicted_depth = outputs.predicted_depth
+
+ if (outputs_flipped is not None) and (predicted_depth.shape != outputs_flipped.predicted_depth.shape):
+ raise ValueError("Make sure that `outputs` and `outputs_flipped` have the same shape")
+
+ if (target_sizes is not None) and (len(predicted_depth) != len(target_sizes)):
+ raise ValueError(
+ "Make sure that you pass in as many target sizes as the batch dimension of the predicted depth"
+ )
+
+ if do_remove_padding is None:
+ do_remove_padding = self.do_pad
+
+ if source_sizes is None and do_remove_padding:
+ raise ValueError(
+ "Either `source_sizes` should be passed in, or `do_remove_padding` should be set to False"
+ )
+
+ if (source_sizes is not None) and (len(predicted_depth) != len(source_sizes)):
+ raise ValueError(
+ "Make sure that you pass in as many source image sizes as the batch dimension of the logits"
+ )
+
+ if outputs_flipped is not None:
+ predicted_depth = (predicted_depth + torch.flip(outputs_flipped.predicted_depth, dims=[-1])) / 2
+
+ predicted_depth = predicted_depth.unsqueeze(1)
+
+ # Zoe Depth model adds padding around the images to fix the boundary artifacts in the output depth map
+ # The padding length is `int(np.sqrt(img_h/2) * fh)` for the height and similar for the width
+ # fh (and fw respectively) are equal to '3' by default
+ # Check [here](https://github.com/isl-org/ZoeDepth/blob/edb6daf45458569e24f50250ef1ed08c015f17a7/zoedepth/models/depth_model.py#L57)
+ # for the original implementation.
+ # In this section, we remove this padding to get the final depth image and depth prediction
+ padding_factor_h = padding_factor_w = 3
+
+ results = []
+ target_sizes = [None] * len(predicted_depth) if target_sizes is None else target_sizes
+ source_sizes = [None] * len(predicted_depth) if source_sizes is None else source_sizes
+ for depth, target_size, source_size in zip(predicted_depth, target_sizes, source_sizes):
+ # depth.shape = [1, H, W]
+ if source_size is not None:
+ pad_h = pad_w = 0
+
+ if do_remove_padding:
+ pad_h = int(np.sqrt(source_size[0] / 2) * padding_factor_h)
+ pad_w = int(np.sqrt(source_size[1] / 2) * padding_factor_w)
+
+ depth = F.resize(
+ depth,
+ size=[source_size[0] + 2 * pad_h, source_size[1] + 2 * pad_w],
+ interpolation=InterpolationMode.BICUBIC,
+ antialias=False,
+ )
+
+ if pad_h > 0:
+ depth = depth[:, pad_h:-pad_h, :]
+ if pad_w > 0:
+ depth = depth[:, :, pad_w:-pad_w]
+
+ if target_size is not None:
+ target_size = [target_size[0], target_size[1]]
+ depth = F.resize(
+ depth,
+ size=target_size,
+ interpolation=InterpolationMode.BICUBIC,
+ antialias=False,
+ )
+ depth = depth.squeeze(0)
+ # depth.shape = [H, W]
+ results.append({"predicted_depth": depth})
+
+ return results
+
+
+__all__ = ["ZoeDepthImageProcessorFast"]
diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/modeling_zoedepth.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/modeling_zoedepth.py
new file mode 100644
index 0000000000000000000000000000000000000000..d79bb27d56c03c0cd04a32c5e0b28116a3b5854c
--- /dev/null
+++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/models/zoedepth/modeling_zoedepth.py
@@ -0,0 +1,1353 @@
+# coding=utf-8
+# Copyright 2024 Intel Labs and The HuggingFace Inc. team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+"""PyTorch ZoeDepth model."""
+
+import math
+from dataclasses import dataclass
+from typing import Optional, Union
+
+import torch
+import torch.utils.checkpoint
+from torch import nn
+
+from ...activations import ACT2FN
+from ...modeling_outputs import DepthEstimatorOutput
+from ...modeling_utils import PreTrainedModel
+from ...utils import ModelOutput, auto_docstring, logging
+from ...utils.backbone_utils import load_backbone
+from .configuration_zoedepth import ZoeDepthConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+@dataclass
+@auto_docstring(
+ custom_intro="""
+ Extension of `DepthEstimatorOutput` to include domain logits (ZoeDepth specific).
+ """
+)
+class ZoeDepthDepthEstimatorOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Classification (or regression if config.num_labels==1) loss.
+ domain_logits (`torch.FloatTensor` of shape `(batch_size, num_domains)`):
+ Logits for each domain (e.g. NYU and KITTI) in case multiple metric heads are used.
+ """
+
+ loss: Optional[torch.FloatTensor] = None
+ predicted_depth: Optional[torch.FloatTensor] = None
+ domain_logits: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+
+
+class ZoeDepthReassembleStage(nn.Module):
+ """
+ This class reassembles the hidden states of the backbone into image-like feature representations at various
+ resolutions.
+
+ This happens in 3 stages:
+ 1. Map the N + 1 tokens to a set of N tokens, by taking into account the readout ([CLS]) token according to
+ `config.readout_type`.
+ 2. Project the channel dimension of the hidden states according to `config.neck_hidden_sizes`.
+ 3. Resizing the spatial dimensions (height, width).
+
+ Args:
+ config (`[ZoeDepthConfig]`):
+ Model configuration class defining the model architecture.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.readout_type = config.readout_type
+ self.layers = nn.ModuleList()
+
+ for neck_hidden_size, factor in zip(config.neck_hidden_sizes, config.reassemble_factors):
+ self.layers.append(ZoeDepthReassembleLayer(config, channels=neck_hidden_size, factor=factor))
+
+ if config.readout_type == "project":
+ self.readout_projects = nn.ModuleList()
+ hidden_size = config.backbone_hidden_size
+ for _ in config.neck_hidden_sizes:
+ self.readout_projects.append(
+ nn.Sequential(nn.Linear(2 * hidden_size, hidden_size), ACT2FN[config.hidden_act])
+ )
+
+ def forward(self, hidden_states: list[torch.Tensor], patch_height, patch_width) -> list[torch.Tensor]:
+ """
+ Args:
+ hidden_states (`list[torch.FloatTensor]`, each of shape `(batch_size, sequence_length + 1, hidden_size)`):
+ List of hidden states from the backbone.
+ """
+ batch_size = hidden_states[0].shape[0]
+
+ # stack along batch dimension
+ # shape (batch_size*num_stages, sequence_length + 1, hidden_size)
+ hidden_states = torch.cat(hidden_states, dim=0)
+
+ cls_token, hidden_states = hidden_states[:, 0], hidden_states[:, 1:]
+ # reshape hidden_states to (batch_size*num_stages, num_channels, height, width)
+ total_batch_size, sequence_length, num_channels = hidden_states.shape
+ hidden_states = hidden_states.reshape(total_batch_size, patch_height, patch_width, num_channels)
+ hidden_states = hidden_states.permute(0, 3, 1, 2).contiguous()
+
+ if self.readout_type == "project":
+ # reshape to (batch_size*num_stages, height*width, num_channels)
+ hidden_states = hidden_states.flatten(2).permute((0, 2, 1))
+ readout = cls_token.unsqueeze(dim=1).expand_as(hidden_states)
+ # concatenate the readout token to the hidden states
+ # to get (batch_size*num_stages, height*width, 2*num_channels)
+ hidden_states = torch.cat((hidden_states, readout), -1)
+ elif self.readout_type == "add":
+ hidden_states = hidden_states + cls_token.unsqueeze(-1)
+
+ out = []
+ for stage_idx, hidden_state in enumerate(hidden_states.split(batch_size, dim=0)):
+ if self.readout_type == "project":
+ hidden_state = self.readout_projects[stage_idx](hidden_state)
+
+ # reshape back to (batch_size, num_channels, height, width)
+ hidden_state = hidden_state.permute(0, 2, 1).reshape(batch_size, -1, patch_height, patch_width)
+ hidden_state = self.layers[stage_idx](hidden_state)
+ out.append(hidden_state)
+
+ return out
+
+
+class ZoeDepthReassembleLayer(nn.Module):
+ def __init__(self, config, channels, factor):
+ super().__init__()
+ # projection
+ hidden_size = config.backbone_hidden_size
+ self.projection = nn.Conv2d(in_channels=hidden_size, out_channels=channels, kernel_size=1)
+
+ # up/down sampling depending on factor
+ if factor > 1:
+ self.resize = nn.ConvTranspose2d(channels, channels, kernel_size=factor, stride=factor, padding=0)
+ elif factor == 1:
+ self.resize = nn.Identity()
+ elif factor < 1:
+ # so should downsample
+ self.resize = nn.Conv2d(channels, channels, kernel_size=3, stride=int(1 / factor), padding=1)
+
+ # Copied from transformers.models.dpt.modeling_dpt.DPTReassembleLayer.forward with DPT->ZoeDepth
+ def forward(self, hidden_state):
+ hidden_state = self.projection(hidden_state)
+ hidden_state = self.resize(hidden_state)
+ return hidden_state
+
+
+# Copied from transformers.models.dpt.modeling_dpt.DPTFeatureFusionStage with DPT->ZoeDepth
+class ZoeDepthFeatureFusionStage(nn.Module):
+ def __init__(self, config: ZoeDepthConfig):
+ super().__init__()
+ self.layers = nn.ModuleList()
+ for _ in range(len(config.neck_hidden_sizes)):
+ self.layers.append(ZoeDepthFeatureFusionLayer(config))
+
+ def forward(self, hidden_states):
+ # reversing the hidden_states, we start from the last
+ hidden_states = hidden_states[::-1]
+
+ fused_hidden_states = []
+ fused_hidden_state = None
+ for hidden_state, layer in zip(hidden_states, self.layers):
+ if fused_hidden_state is None:
+ # first layer only uses the last hidden_state
+ fused_hidden_state = layer(hidden_state)
+ else:
+ fused_hidden_state = layer(fused_hidden_state, hidden_state)
+ fused_hidden_states.append(fused_hidden_state)
+
+ return fused_hidden_states
+
+
+# Copied from transformers.models.dpt.modeling_dpt.DPTPreActResidualLayer with DPT->ZoeDepth
+class ZoeDepthPreActResidualLayer(nn.Module):
+ """
+ ResidualConvUnit, pre-activate residual unit.
+
+ Args:
+ config (`[ZoeDepthConfig]`):
+ Model configuration class defining the model architecture.
+ """
+
+ # Ignore copy
+ def __init__(self, config):
+ super().__init__()
+
+ self.use_batch_norm = config.use_batch_norm_in_fusion_residual
+ use_bias_in_fusion_residual = (
+ config.use_bias_in_fusion_residual
+ if config.use_bias_in_fusion_residual is not None
+ else not self.use_batch_norm
+ )
+
+ self.activation1 = nn.ReLU()
+ self.convolution1 = nn.Conv2d(
+ config.fusion_hidden_size,
+ config.fusion_hidden_size,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=use_bias_in_fusion_residual,
+ )
+
+ self.activation2 = nn.ReLU()
+ self.convolution2 = nn.Conv2d(
+ config.fusion_hidden_size,
+ config.fusion_hidden_size,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=use_bias_in_fusion_residual,
+ )
+
+ if self.use_batch_norm:
+ self.batch_norm1 = nn.BatchNorm2d(config.fusion_hidden_size, eps=config.batch_norm_eps)
+ self.batch_norm2 = nn.BatchNorm2d(config.fusion_hidden_size, eps=config.batch_norm_eps)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ residual = hidden_state
+ hidden_state = self.activation1(hidden_state)
+
+ hidden_state = self.convolution1(hidden_state)
+
+ if self.use_batch_norm:
+ hidden_state = self.batch_norm1(hidden_state)
+
+ hidden_state = self.activation2(hidden_state)
+ hidden_state = self.convolution2(hidden_state)
+
+ if self.use_batch_norm:
+ hidden_state = self.batch_norm2(hidden_state)
+
+ return hidden_state + residual
+
+
+# Copied from transformers.models.dpt.modeling_dpt.DPTFeatureFusionLayer with DPT->ZoeDepth
+class ZoeDepthFeatureFusionLayer(nn.Module):
+ """Feature fusion layer, merges feature maps from different stages.
+
+ Args:
+ config (`[ZoeDepthConfig]`):
+ Model configuration class defining the model architecture.
+ align_corners (`bool`, *optional*, defaults to `True`):
+ The align_corner setting for bilinear upsample.
+ """
+
+ def __init__(self, config: ZoeDepthConfig, align_corners: bool = True):
+ super().__init__()
+
+ self.align_corners = align_corners
+
+ self.projection = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=1, bias=True)
+
+ self.residual_layer1 = ZoeDepthPreActResidualLayer(config)
+ self.residual_layer2 = ZoeDepthPreActResidualLayer(config)
+
+ def forward(self, hidden_state: torch.Tensor, residual: Optional[torch.Tensor] = None) -> torch.Tensor:
+ if residual is not None:
+ if hidden_state.shape != residual.shape:
+ residual = nn.functional.interpolate(
+ residual, size=(hidden_state.shape[2], hidden_state.shape[3]), mode="bilinear", align_corners=False
+ )
+ hidden_state = hidden_state + self.residual_layer1(residual)
+
+ hidden_state = self.residual_layer2(hidden_state)
+ hidden_state = nn.functional.interpolate(
+ hidden_state, scale_factor=2, mode="bilinear", align_corners=self.align_corners
+ )
+ hidden_state = self.projection(hidden_state)
+
+ return hidden_state
+
+
+class ZoeDepthNeck(nn.Module):
+ """
+ ZoeDepthNeck. A neck is a module that is normally used between the backbone and the head. It takes a list of tensors as
+ input and produces another list of tensors as output. For ZoeDepth, it includes 2 stages:
+
+ * ZoeDepthReassembleStage
+ * ZoeDepthFeatureFusionStage.
+
+ Args:
+ config (dict): config dict.
+ """
+
+ # Copied from transformers.models.dpt.modeling_dpt.DPTNeck.__init__ with DPT->ZoeDepth
+ def __init__(self, config: ZoeDepthConfig):
+ super().__init__()
+ self.config = config
+
+ # postprocessing: only required in case of a non-hierarchical backbone (e.g. ViT, BEiT)
+ if config.backbone_config is not None and config.backbone_config.model_type in ["swinv2"]:
+ self.reassemble_stage = None
+ else:
+ self.reassemble_stage = ZoeDepthReassembleStage(config)
+
+ self.convs = nn.ModuleList()
+ for channel in config.neck_hidden_sizes:
+ self.convs.append(nn.Conv2d(channel, config.fusion_hidden_size, kernel_size=3, padding=1, bias=False))
+
+ # fusion
+ self.fusion_stage = ZoeDepthFeatureFusionStage(config)
+
+ def forward(self, hidden_states: list[torch.Tensor], patch_height, patch_width) -> list[torch.Tensor]:
+ """
+ Args:
+ hidden_states (`list[torch.FloatTensor]`, each of shape `(batch_size, sequence_length, hidden_size)` or `(batch_size, hidden_size, height, width)`):
+ List of hidden states from the backbone.
+ """
+ if not isinstance(hidden_states, (tuple, list)):
+ raise TypeError("hidden_states should be a tuple or list of tensors")
+
+ if len(hidden_states) != len(self.config.neck_hidden_sizes):
+ raise ValueError("The number of hidden states should be equal to the number of neck hidden sizes.")
+
+ # postprocess hidden states
+ if self.reassemble_stage is not None:
+ hidden_states = self.reassemble_stage(hidden_states, patch_height, patch_width)
+
+ features = [self.convs[i](feature) for i, feature in enumerate(hidden_states)]
+
+ # fusion blocks
+ output = self.fusion_stage(features)
+
+ return output, features[-1]
+
+
+class ZoeDepthRelativeDepthEstimationHead(nn.Module):
+ """
+ Relative depth estimation head consisting of 3 convolutional layers. It progressively halves the feature dimension and upsamples
+ the predictions to the input resolution after the first convolutional layer (details can be found in DPT's paper's
+ supplementary material).
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ self.head_in_index = config.head_in_index
+
+ self.projection = None
+ if config.add_projection:
+ self.projection = nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
+
+ features = config.fusion_hidden_size
+ self.conv1 = nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1)
+ self.upsample = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)
+ self.conv2 = nn.Conv2d(features // 2, config.num_relative_features, kernel_size=3, stride=1, padding=1)
+ self.conv3 = nn.Conv2d(config.num_relative_features, 1, kernel_size=1, stride=1, padding=0)
+
+ def forward(self, hidden_states: list[torch.Tensor]) -> torch.Tensor:
+ # use last features
+ hidden_states = hidden_states[self.head_in_index]
+
+ if self.projection is not None:
+ hidden_states = self.projection(hidden_states)
+ hidden_states = nn.ReLU()(hidden_states)
+
+ hidden_states = self.conv1(hidden_states)
+ hidden_states = self.upsample(hidden_states)
+ hidden_states = self.conv2(hidden_states)
+ hidden_states = nn.ReLU()(hidden_states)
+ # we need the features here (after second conv + ReLu)
+ features = hidden_states
+ hidden_states = self.conv3(hidden_states)
+ hidden_states = nn.ReLU()(hidden_states)
+
+ predicted_depth = hidden_states.squeeze(dim=1)
+
+ return predicted_depth, features
+
+
+def log_binom(n, k, eps=1e-7):
+ """log(nCk) using stirling approximation"""
+ n = n + eps
+ k = k + eps
+ return n * torch.log(n) - k * torch.log(k) - (n - k) * torch.log(n - k + eps)
+
+
+class LogBinomialSoftmax(nn.Module):
+ def __init__(self, n_classes=256, act=torch.softmax):
+ """Compute log binomial distribution for n_classes
+
+ Args:
+ n_classes (`int`, *optional*, defaults to 256):
+ Number of output classes.
+ act (`torch.nn.Module`, *optional*, defaults to `torch.softmax`):
+ Activation function to apply to the output.
+ """
+ super().__init__()
+ self.k = n_classes
+ self.act = act
+ self.register_buffer("k_idx", torch.arange(0, n_classes).view(1, -1, 1, 1), persistent=False)
+ self.register_buffer("k_minus_1", torch.tensor([self.k - 1]).view(1, -1, 1, 1), persistent=False)
+
+ def forward(self, probabilities, temperature=1.0, eps=1e-4):
+ """Compute the log binomial distribution for probabilities.
+
+ Args:
+ probabilities (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
+ Tensor containing probabilities of each class.
+ temperature (`float` or `torch.Tensor` of shape `(batch_size, num_channels, height, width)`, *optional*, defaults to 1):
+ Temperature of distribution.
+ eps (`float`, *optional*, defaults to 1e-4):
+ Small number for numerical stability.
+
+ Returns:
+ `torch.Tensor` of shape `(batch_size, num_channels, height, width)`:
+ Log binomial distribution logbinomial(p;t).
+ """
+ if probabilities.ndim == 3:
+ probabilities = probabilities.unsqueeze(1) # make it (batch_size, num_channels, height, width)
+
+ one_minus_probabilities = torch.clamp(1 - probabilities, eps, 1)
+ probabilities = torch.clamp(probabilities, eps, 1)
+ y = (
+ log_binom(self.k_minus_1, self.k_idx)
+ + self.k_idx * torch.log(probabilities)
+ + (self.k_minus_1 - self.k_idx) * torch.log(one_minus_probabilities)
+ )
+ return self.act(y / temperature, dim=1)
+
+
+class ZoeDepthConditionalLogBinomialSoftmax(nn.Module):
+ def __init__(
+ self,
+ config,
+ in_features,
+ condition_dim,
+ n_classes=256,
+ bottleneck_factor=2,
+ ):
+ """Per-pixel MLP followed by a Conditional Log Binomial softmax.
+
+ Args:
+ in_features (`int`):
+ Number of input channels in the main feature.
+ condition_dim (`int`):
+ Number of input channels in the condition feature.
+ n_classes (`int`, *optional*, defaults to 256):
+ Number of classes.
+ bottleneck_factor (`int`, *optional*, defaults to 2):
+ Hidden dim factor.
+
+ """
+ super().__init__()
+
+ bottleneck = (in_features + condition_dim) // bottleneck_factor
+ self.mlp = nn.Sequential(
+ nn.Conv2d(in_features + condition_dim, bottleneck, kernel_size=1, stride=1, padding=0),
+ nn.GELU(),
+ # 2 for probabilities linear norm, 2 for temperature linear norm
+ nn.Conv2d(bottleneck, 2 + 2, kernel_size=1, stride=1, padding=0),
+ nn.Softplus(),
+ )
+
+ self.p_eps = 1e-4
+ self.max_temp = config.max_temp
+ self.min_temp = config.min_temp
+ self.log_binomial_transform = LogBinomialSoftmax(n_classes, act=torch.softmax)
+
+ def forward(self, main_feature, condition_feature):
+ """
+ Args:
+ main_feature (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
+ Main feature.
+ condition_feature (torch.Tensor of shape `(batch_size, num_channels, height, width)`):
+ Condition feature.
+
+ Returns:
+ `torch.Tensor`:
+ Output log binomial distribution
+ """
+ probabilities_and_temperature = self.mlp(torch.concat((main_feature, condition_feature), dim=1))
+ probabilities, temperature = (
+ probabilities_and_temperature[:, :2, ...],
+ probabilities_and_temperature[:, 2:, ...],
+ )
+
+ probabilities = probabilities + self.p_eps
+ probabilities = probabilities[:, 0, ...] / (probabilities[:, 0, ...] + probabilities[:, 1, ...])
+
+ temperature = temperature + self.p_eps
+ temperature = temperature[:, 0, ...] / (temperature[:, 0, ...] + temperature[:, 1, ...])
+ temperature = temperature.unsqueeze(1)
+ temperature = (self.max_temp - self.min_temp) * temperature + self.min_temp
+
+ return self.log_binomial_transform(probabilities, temperature)
+
+
+class ZoeDepthSeedBinRegressor(nn.Module):
+ def __init__(self, config, n_bins=16, mlp_dim=256, min_depth=1e-3, max_depth=10):
+ """Bin center regressor network.
+
+ Can be "normed" or "unnormed". If "normed", bin centers are bounded on the (min_depth, max_depth) interval.
+
+ Args:
+ config (`int`):
+ Model configuration.
+ n_bins (`int`, *optional*, defaults to 16):
+ Number of bin centers.
+ mlp_dim (`int`, *optional*, defaults to 256):
+ Hidden dimension.
+ min_depth (`float`, *optional*, defaults to 1e-3):
+ Min depth value.
+ max_depth (`float`, *optional*, defaults to 10):
+ Max depth value.
+ """
+ super().__init__()
+
+ self.in_features = config.bottleneck_features
+ self.bin_centers_type = config.bin_centers_type
+ self.min_depth = min_depth
+ self.max_depth = max_depth
+
+ self.conv1 = nn.Conv2d(self.in_features, mlp_dim, 1, 1, 0)
+ self.act1 = nn.ReLU(inplace=True)
+ self.conv2 = nn.Conv2d(mlp_dim, n_bins, 1, 1, 0)
+ self.act2 = nn.ReLU(inplace=True) if self.bin_centers_type == "normed" else nn.Softplus()
+
+ def forward(self, x):
+ """
+ Returns tensor of bin_width vectors (centers). One vector b for every pixel
+ """
+ x = self.conv1(x)
+ x = self.act1(x)
+ x = self.conv2(x)
+ bin_centers = self.act2(x)
+
+ if self.bin_centers_type == "normed":
+ bin_centers = bin_centers + 1e-3
+ bin_widths_normed = bin_centers / bin_centers.sum(dim=1, keepdim=True)
+ # shape (batch_size, num_channels, height, width)
+ bin_widths = (self.max_depth - self.min_depth) * bin_widths_normed
+ # pad has the form (left, right, top, bottom, front, back)
+ bin_widths = nn.functional.pad(bin_widths, (0, 0, 0, 0, 1, 0), mode="constant", value=self.min_depth)
+ # shape (batch_size, num_channels, height, width)
+ bin_edges = torch.cumsum(bin_widths, dim=1)
+
+ bin_centers = 0.5 * (bin_edges[:, :-1, ...] + bin_edges[:, 1:, ...])
+ return bin_widths_normed, bin_centers
+
+ else:
+ return bin_centers, bin_centers
+
+
+@torch.jit.script
+def inv_attractor(dx, alpha: float = 300, gamma: int = 2):
+ """Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a - c, a = attractor point, c = bin center, dc = shift in bin center
+ This is the default one according to the accompanying paper.
+
+ Args:
+ dx (`torch.Tensor`):
+ The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center.
+ alpha (`float`, *optional*, defaults to 300):
+ Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction.
+ gamma (`int`, *optional*, defaults to 2):
+ Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected.
+ Lower gamma = farther reach.
+
+ Returns:
+ torch.Tensor: Delta shifts - dc; New bin centers = Old bin centers + dc
+ """
+ return dx.div(1 + alpha * dx.pow(gamma))
+
+
+class ZoeDepthAttractorLayer(nn.Module):
+ def __init__(
+ self,
+ config,
+ n_bins,
+ n_attractors=16,
+ min_depth=1e-3,
+ max_depth=10,
+ memory_efficient=False,
+ ):
+ """
+ Attractor layer for bin centers. Bin centers are bounded on the interval (min_depth, max_depth)
+ """
+ super().__init__()
+
+ self.alpha = config.attractor_alpha
+ self.gemma = config.attractor_gamma
+ self.kind = config.attractor_kind
+
+ self.n_attractors = n_attractors
+ self.n_bins = n_bins
+ self.min_depth = min_depth
+ self.max_depth = max_depth
+ self.memory_efficient = memory_efficient
+
+ # MLP to predict attractor points
+ in_features = mlp_dim = config.bin_embedding_dim
+ self.conv1 = nn.Conv2d(in_features, mlp_dim, 1, 1, 0)
+ self.act1 = nn.ReLU(inplace=True)
+ self.conv2 = nn.Conv2d(mlp_dim, n_attractors * 2, 1, 1, 0) # x2 for linear norm
+ self.act2 = nn.ReLU(inplace=True)
+
+ def forward(self, x, prev_bin, prev_bin_embedding=None, interpolate=True):
+ """
+ The forward pass of the attractor layer. This layer predicts the new bin centers based on the previous bin centers
+ and the attractor points (the latter are predicted by the MLP).
+
+ Args:
+ x (`torch.Tensor` of shape `(batch_size, num_channels, height, width)`):
+ Feature block.
+ prev_bin (`torch.Tensor` of shape `(batch_size, prev_number_of_bins, height, width)`):
+ Previous bin centers normed.
+ prev_bin_embedding (`torch.Tensor`, *optional*):
+ Optional previous bin embeddings.
+ interpolate (`bool`, *optional*, defaults to `True`):
+ Whether to interpolate the previous bin embeddings to the size of the input features.
+
+ Returns:
+ `tuple[`torch.Tensor`, `torch.Tensor`]:
+ New bin centers normed and scaled.
+ """
+ if prev_bin_embedding is not None:
+ if interpolate:
+ prev_bin_embedding = nn.functional.interpolate(
+ prev_bin_embedding, x.shape[-2:], mode="bilinear", align_corners=True
+ )
+ x = x + prev_bin_embedding
+
+ x = self.conv1(x)
+ x = self.act1(x)
+ x = self.conv2(x)
+ attractors = self.act2(x)
+
+ attractors = attractors + 1e-3
+ batch_size, _, height, width = attractors.shape
+ attractors = attractors.view(batch_size, self.n_attractors, 2, height, width)
+ # batch_size, num_attractors, 2, height, width
+ # note: original repo had a bug here: https://github.com/isl-org/ZoeDepth/blame/edb6daf45458569e24f50250ef1ed08c015f17a7/zoedepth/models/layers/attractor.py#L105C9-L106C50
+ # we include the bug to maintain compatibility with the weights
+ attractors_normed = attractors[:, :, 0, ...] # batch_size, batch_size*num_attractors, height, width
+
+ bin_centers = nn.functional.interpolate(prev_bin, (height, width), mode="bilinear", align_corners=True)
+
+ # note: only attractor_type = "exp" is supported here, since no checkpoints were released with other attractor types
+
+ if not self.memory_efficient:
+ func = {"mean": torch.mean, "sum": torch.sum}[self.kind]
+ # shape (batch_size, num_bins, height, width)
+ delta_c = func(inv_attractor(attractors_normed.unsqueeze(2) - bin_centers.unsqueeze(1)), dim=1)
+ else:
+ delta_c = torch.zeros_like(bin_centers, device=bin_centers.device)
+ for i in range(self.n_attractors):
+ # shape (batch_size, num_bins, height, width)
+ delta_c += inv_attractor(attractors_normed[:, i, ...].unsqueeze(1) - bin_centers)
+
+ if self.kind == "mean":
+ delta_c = delta_c / self.n_attractors
+
+ bin_new_centers = bin_centers + delta_c
+ bin_centers = (self.max_depth - self.min_depth) * bin_new_centers + self.min_depth
+ bin_centers, _ = torch.sort(bin_centers, dim=1)
+ bin_centers = torch.clip(bin_centers, self.min_depth, self.max_depth)
+ return bin_new_centers, bin_centers
+
+
+class ZoeDepthAttractorLayerUnnormed(nn.Module):
+ def __init__(
+ self,
+ config,
+ n_bins,
+ n_attractors=16,
+ min_depth=1e-3,
+ max_depth=10,
+ memory_efficient=True,
+ ):
+ """
+ Attractor layer for bin centers. Bin centers are unbounded
+ """
+ super().__init__()
+
+ self.n_attractors = n_attractors
+ self.n_bins = n_bins
+ self.min_depth = min_depth
+ self.max_depth = max_depth
+ self.alpha = config.attractor_alpha
+ self.gamma = config.attractor_alpha
+ self.kind = config.attractor_kind
+ self.memory_efficient = memory_efficient
+
+ in_features = mlp_dim = config.bin_embedding_dim
+ self.conv1 = nn.Conv2d(in_features, mlp_dim, 1, 1, 0)
+ self.act1 = nn.ReLU(inplace=True)
+ self.conv2 = nn.Conv2d(mlp_dim, n_attractors, 1, 1, 0)
+ self.act2 = nn.Softplus()
+
+ def forward(self, x, prev_bin, prev_bin_embedding=None, interpolate=True):
+ """
+ The forward pass of the attractor layer. This layer predicts the new bin centers based on the previous bin centers
+ and the attractor points (the latter are predicted by the MLP).
+
+ Args:
+ x (`torch.Tensor` of shape (batch_size, num_channels, height, width)`):
+ Feature block.
+ prev_bin (`torch.Tensor` of shape (batch_size, prev_num_bins, height, width)`):
+ Previous bin centers normed.
+ prev_bin_embedding (`torch.Tensor`, *optional*):
+ Optional previous bin embeddings.
+ interpolate (`bool`, *optional*, defaults to `True`):
+ Whether to interpolate the previous bin embeddings to the size of the input features.
+
+ Returns:
+ `tuple[`torch.Tensor`, `torch.Tensor`]:
+ New bin centers unbounded. Two outputs just to keep the API consistent with the normed version.
+ """
+ if prev_bin_embedding is not None:
+ if interpolate:
+ prev_bin_embedding = nn.functional.interpolate(
+ prev_bin_embedding, x.shape[-2:], mode="bilinear", align_corners=True
+ )
+ x = x + prev_bin_embedding
+
+ x = self.conv1(x)
+ x = self.act1(x)
+ x = self.conv2(x)
+ attractors = self.act2(x)
+
+ height, width = attractors.shape[-2:]
+
+ bin_centers = nn.functional.interpolate(prev_bin, (height, width), mode="bilinear", align_corners=True)
+
+ if not self.memory_efficient:
+ func = {"mean": torch.mean, "sum": torch.sum}[self.kind]
+ # shape batch_size, num_bins, height, width
+ delta_c = func(inv_attractor(attractors.unsqueeze(2) - bin_centers.unsqueeze(1)), dim=1)
+ else:
+ delta_c = torch.zeros_like(bin_centers, device=bin_centers.device)
+ for i in range(self.n_attractors):
+ # shape batch_size, num_bins, height, width
+ delta_c += inv_attractor(attractors[:, i, ...].unsqueeze(1) - bin_centers)
+
+ if self.kind == "mean":
+ delta_c = delta_c / self.n_attractors
+
+ bin_new_centers = bin_centers + delta_c
+ bin_centers = bin_new_centers
+
+ return bin_new_centers, bin_centers
+
+
+class ZoeDepthProjector(nn.Module):
+ def __init__(self, in_features, out_features, mlp_dim=128):
+ """Projector MLP.
+
+ Args:
+ in_features (`int`):
+ Number of input channels.
+ out_features (`int`):
+ Number of output channels.
+ mlp_dim (`int`, *optional*, defaults to 128):
+ Hidden dimension.
+ """
+ super().__init__()
+
+ self.conv1 = nn.Conv2d(in_features, mlp_dim, 1, 1, 0)
+ self.act = nn.ReLU(inplace=True)
+ self.conv2 = nn.Conv2d(mlp_dim, out_features, 1, 1, 0)
+
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
+ hidden_state = self.conv1(hidden_state)
+ hidden_state = self.act(hidden_state)
+ hidden_state = self.conv2(hidden_state)
+
+ return hidden_state
+
+
+# Copied from transformers.models.grounding_dino.modeling_grounding_dino.GroundingDinoMultiheadAttention with GroundingDino->ZoeDepth
+class ZoeDepthMultiheadAttention(nn.Module):
+ """Equivalent implementation of nn.MultiheadAttention with `batch_first=True`."""
+
+ # Ignore copy
+ def __init__(self, hidden_size, num_attention_heads, dropout):
+ super().__init__()
+ if hidden_size % num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({hidden_size}) is not a multiple of the number of attention "
+ f"heads ({num_attention_heads})"
+ )
+
+ self.num_attention_heads = num_attention_heads
+ self.attention_head_size = int(hidden_size / num_attention_heads)
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
+
+ self.query = nn.Linear(hidden_size, self.all_head_size)
+ self.key = nn.Linear(hidden_size, self.all_head_size)
+ self.value = nn.Linear(hidden_size, self.all_head_size)
+
+ self.out_proj = nn.Linear(hidden_size, hidden_size)
+
+ self.dropout = nn.Dropout(dropout)
+
+ def forward(
+ self,
+ queries: torch.Tensor,
+ keys: torch.Tensor,
+ values: torch.Tensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ output_attentions: Optional[bool] = False,
+ ) -> tuple[torch.Tensor]:
+ batch_size, seq_length, _ = queries.shape
+ query_layer = (
+ self.query(queries)
+ .view(batch_size, -1, self.num_attention_heads, self.attention_head_size)
+ .transpose(1, 2)
+ )
+ key_layer = (
+ self.key(keys).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
+ )
+ value_layer = (
+ self.value(values).view(batch_size, -1, self.num_attention_heads, self.attention_head_size).transpose(1, 2)
+ )
+
+ # Take the dot product between "query" and "key" to get the raw attention scores.
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
+
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
+ if attention_mask is not None:
+ # Apply the attention mask is (precomputed for all layers in ZoeDepthModel forward() function)
+ attention_scores = attention_scores + attention_mask
+
+ # Normalize the attention scores to probabilities.
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
+
+ # This is actually dropping out entire tokens to attend to, which might
+ # seem a bit unusual, but is taken from the original Transformer paper.
+ attention_probs = self.dropout(attention_probs)
+
+ context_layer = torch.matmul(attention_probs, value_layer)
+
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
+ context_layer = context_layer.view(new_context_layer_shape)
+
+ context_layer = self.out_proj(context_layer)
+
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
+
+ return outputs
+
+
+class ZoeDepthTransformerEncoderLayer(nn.Module):
+ def __init__(self, config, dropout=0.1, activation="relu"):
+ super().__init__()
+
+ hidden_size = config.patch_transformer_hidden_size
+ intermediate_size = config.patch_transformer_intermediate_size
+ num_attention_heads = config.patch_transformer_num_attention_heads
+
+ self.self_attn = ZoeDepthMultiheadAttention(hidden_size, num_attention_heads, dropout=dropout)
+
+ self.linear1 = nn.Linear(hidden_size, intermediate_size)
+ self.dropout = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(intermediate_size, hidden_size)
+
+ self.norm1 = nn.LayerNorm(hidden_size)
+ self.norm2 = nn.LayerNorm(hidden_size)
+ self.dropout1 = nn.Dropout(dropout)
+ self.dropout2 = nn.Dropout(dropout)
+
+ self.activation = ACT2FN[activation]
+
+ def forward(
+ self,
+ src,
+ src_mask: Optional[torch.Tensor] = None,
+ ):
+ queries = keys = src
+ src2 = self.self_attn(queries=queries, keys=keys, values=src, attention_mask=src_mask)[0]
+ src = src + self.dropout1(src2)
+ src = self.norm1(src)
+ src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
+ src = src + self.dropout2(src2)
+ src = self.norm2(src)
+ return src
+
+
+class ZoeDepthPatchTransformerEncoder(nn.Module):
+ def __init__(self, config):
+ """ViT-like transformer block
+
+ Args:
+ config (`ZoeDepthConfig`):
+ Model configuration class defining the model architecture.
+ """
+ super().__init__()
+
+ in_channels = config.bottleneck_features
+
+ self.transformer_encoder = nn.ModuleList(
+ [ZoeDepthTransformerEncoderLayer(config) for _ in range(config.num_patch_transformer_layers)]
+ )
+
+ self.embedding_convPxP = nn.Conv2d(
+ in_channels, config.patch_transformer_hidden_size, kernel_size=1, stride=1, padding=0
+ )
+
+ def positional_encoding_1d(self, batch_size, sequence_length, embedding_dim, device="cpu", dtype=torch.float32):
+ """Generate positional encodings
+
+ Args:
+ sequence_length (int): Sequence length
+ embedding_dim (int): Embedding dimension
+
+ Returns:
+ torch.Tensor: Positional encodings.
+ """
+ position = torch.arange(0, sequence_length, dtype=dtype, device=device).unsqueeze(1)
+ index = torch.arange(0, embedding_dim, 2, dtype=dtype, device=device).unsqueeze(0)
+ div_term = torch.exp(index * (-torch.log(torch.tensor(10000.0, device=device)) / embedding_dim))
+ pos_encoding = position * div_term
+ pos_encoding = torch.cat([torch.sin(pos_encoding), torch.cos(pos_encoding)], dim=1)
+ pos_encoding = pos_encoding.unsqueeze(dim=0).repeat(batch_size, 1, 1)
+ return pos_encoding
+
+ def forward(self, x):
+ """Forward pass
+
+ Args:
+ x (torch.Tensor - NCHW): Input feature tensor
+
+ Returns:
+ torch.Tensor - Transformer output embeddings of shape (batch_size, sequence_length, embedding_dim)
+ """
+ embeddings = self.embedding_convPxP(x).flatten(2) # shape (batch_size, num_channels, sequence_length)
+ # add an extra special CLS token at the start for global accumulation
+ embeddings = nn.functional.pad(embeddings, (1, 0))
+
+ embeddings = embeddings.permute(0, 2, 1)
+ batch_size, sequence_length, embedding_dim = embeddings.shape
+ embeddings = embeddings + self.positional_encoding_1d(
+ batch_size, sequence_length, embedding_dim, device=embeddings.device, dtype=embeddings.dtype
+ )
+
+ for i in range(4):
+ embeddings = self.transformer_encoder[i](embeddings)
+
+ return embeddings
+
+
+class ZoeDepthMLPClassifier(nn.Module):
+ def __init__(self, in_features, out_features) -> None:
+ super().__init__()
+
+ hidden_features = in_features
+ self.linear1 = nn.Linear(in_features, hidden_features)
+ self.activation = nn.ReLU()
+ self.linear2 = nn.Linear(hidden_features, out_features)
+
+ def forward(self, hidden_state):
+ hidden_state = self.linear1(hidden_state)
+ hidden_state = self.activation(hidden_state)
+ domain_logits = self.linear2(hidden_state)
+
+ return domain_logits
+
+
+class ZoeDepthMultipleMetricDepthEstimationHeads(nn.Module):
+ """
+ Multiple metric depth estimation heads. A MLP classifier is used to route between 2 different heads.
+ """
+
+ def __init__(self, config):
+ super().__init__()
+
+ bin_embedding_dim = config.bin_embedding_dim
+ n_attractors = config.num_attractors
+ self.bin_configurations = config.bin_configurations
+ self.bin_centers_type = config.bin_centers_type
+
+ # Bottleneck convolution
+ bottleneck_features = config.bottleneck_features
+ self.conv2 = nn.Conv2d(bottleneck_features, bottleneck_features, kernel_size=1, stride=1, padding=0)
+
+ # Transformer classifier on the bottleneck
+ self.patch_transformer = ZoeDepthPatchTransformerEncoder(config)
+ # MLP classifier
+ self.mlp_classifier = ZoeDepthMLPClassifier(in_features=128, out_features=2)
+
+ # Regressor and attractor
+ if self.bin_centers_type == "normed":
+ Attractor = ZoeDepthAttractorLayer
+ elif self.bin_centers_type == "softplus":
+ Attractor = ZoeDepthAttractorLayerUnnormed
+ # We have bins for each bin configuration
+ # Create a map (ModuleDict) of 'name' -> seed_bin_regressor
+ self.seed_bin_regressors = nn.ModuleDict(
+ {
+ conf["name"]: ZoeDepthSeedBinRegressor(
+ config,
+ n_bins=conf["n_bins"],
+ mlp_dim=bin_embedding_dim // 2,
+ min_depth=conf["min_depth"],
+ max_depth=conf["max_depth"],
+ )
+ for conf in config.bin_configurations
+ }
+ )
+
+ self.seed_projector = ZoeDepthProjector(
+ in_features=bottleneck_features, out_features=bin_embedding_dim, mlp_dim=bin_embedding_dim // 2
+ )
+ self.projectors = nn.ModuleList(
+ [
+ ZoeDepthProjector(
+ in_features=config.fusion_hidden_size,
+ out_features=bin_embedding_dim,
+ mlp_dim=bin_embedding_dim // 2,
+ )
+ for _ in range(4)
+ ]
+ )
+
+ # Create a map (ModuleDict) of 'name' -> attractors (ModuleList)
+ self.attractors = nn.ModuleDict(
+ {
+ configuration["name"]: nn.ModuleList(
+ [
+ Attractor(
+ config,
+ n_bins=n_attractors[i],
+ min_depth=configuration["min_depth"],
+ max_depth=configuration["max_depth"],
+ )
+ for i in range(len(n_attractors))
+ ]
+ )
+ for configuration in config.bin_configurations
+ }
+ )
+
+ last_in = config.num_relative_features
+ # conditional log binomial for each bin configuration
+ self.conditional_log_binomial = nn.ModuleDict(
+ {
+ configuration["name"]: ZoeDepthConditionalLogBinomialSoftmax(
+ config,
+ last_in,
+ bin_embedding_dim,
+ configuration["n_bins"],
+ bottleneck_factor=4,
+ )
+ for configuration in config.bin_configurations
+ }
+ )
+
+ def forward(self, outconv_activation, bottleneck, feature_blocks, relative_depth):
+ x = self.conv2(bottleneck)
+
+ # Predict which path to take
+ # Embedding is of shape (batch_size, hidden_size)
+ embedding = self.patch_transformer(x)[:, 0, :]
+
+ # MLP classifier to get logits of shape (batch_size, 2)
+ domain_logits = self.mlp_classifier(embedding)
+ domain_vote = torch.softmax(domain_logits.sum(dim=0, keepdim=True), dim=-1)
+
+ # Get the path
+ names = [configuration["name"] for configuration in self.bin_configurations]
+ bin_configurations_name = names[torch.argmax(domain_vote, dim=-1).squeeze().item()]
+
+ try:
+ conf = [config for config in self.bin_configurations if config["name"] == bin_configurations_name][0]
+ except IndexError:
+ raise ValueError(f"bin_configurations_name {bin_configurations_name} not found in bin_configurationss")
+
+ min_depth = conf["min_depth"]
+ max_depth = conf["max_depth"]
+
+ seed_bin_regressor = self.seed_bin_regressors[bin_configurations_name]
+ _, seed_bin_centers = seed_bin_regressor(x)
+ if self.bin_centers_type in ["normed", "hybrid2"]:
+ prev_bin = (seed_bin_centers - min_depth) / (max_depth - min_depth)
+ else:
+ prev_bin = seed_bin_centers
+ prev_bin_embedding = self.seed_projector(x)
+
+ attractors = self.attractors[bin_configurations_name]
+ for projector, attractor, feature in zip(self.projectors, attractors, feature_blocks):
+ bin_embedding = projector(feature)
+ bin, bin_centers = attractor(bin_embedding, prev_bin, prev_bin_embedding, interpolate=True)
+ prev_bin = bin
+ prev_bin_embedding = bin_embedding
+
+ last = outconv_activation
+
+ bin_centers = nn.functional.interpolate(bin_centers, last.shape[-2:], mode="bilinear", align_corners=True)
+ bin_embedding = nn.functional.interpolate(bin_embedding, last.shape[-2:], mode="bilinear", align_corners=True)
+
+ conditional_log_binomial = self.conditional_log_binomial[bin_configurations_name]
+ x = conditional_log_binomial(last, bin_embedding)
+
+ # Now depth value is Sum px * cx , where cx are bin_centers from the last bin tensor
+ out = torch.sum(x * bin_centers, dim=1, keepdim=True)
+
+ return out, domain_logits
+
+
+class ZoeDepthMetricDepthEstimationHead(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+
+ bin_configuration = config.bin_configurations[0]
+ n_bins = bin_configuration["n_bins"]
+ min_depth = bin_configuration["min_depth"]
+ max_depth = bin_configuration["max_depth"]
+ bin_embedding_dim = config.bin_embedding_dim
+ n_attractors = config.num_attractors
+ bin_centers_type = config.bin_centers_type
+
+ self.min_depth = min_depth
+ self.max_depth = max_depth
+ self.bin_centers_type = bin_centers_type
+
+ # Bottleneck convolution
+ bottleneck_features = config.bottleneck_features
+ self.conv2 = nn.Conv2d(bottleneck_features, bottleneck_features, kernel_size=1, stride=1, padding=0)
+
+ # Regressor and attractor
+ if self.bin_centers_type == "normed":
+ Attractor = ZoeDepthAttractorLayer
+ elif self.bin_centers_type == "softplus":
+ Attractor = ZoeDepthAttractorLayerUnnormed
+
+ self.seed_bin_regressor = ZoeDepthSeedBinRegressor(
+ config, n_bins=n_bins, min_depth=min_depth, max_depth=max_depth
+ )
+ self.seed_projector = ZoeDepthProjector(in_features=bottleneck_features, out_features=bin_embedding_dim)
+
+ self.projectors = nn.ModuleList(
+ [
+ ZoeDepthProjector(in_features=config.fusion_hidden_size, out_features=bin_embedding_dim)
+ for _ in range(4)
+ ]
+ )
+ self.attractors = nn.ModuleList(
+ [
+ Attractor(
+ config,
+ n_bins=n_bins,
+ n_attractors=n_attractors[i],
+ min_depth=min_depth,
+ max_depth=max_depth,
+ )
+ for i in range(4)
+ ]
+ )
+
+ last_in = config.num_relative_features + 1 # +1 for relative depth
+
+ # use log binomial instead of softmax
+ self.conditional_log_binomial = ZoeDepthConditionalLogBinomialSoftmax(
+ config,
+ last_in,
+ bin_embedding_dim,
+ n_classes=n_bins,
+ )
+
+ def forward(self, outconv_activation, bottleneck, feature_blocks, relative_depth):
+ x = self.conv2(bottleneck)
+ _, seed_bin_centers = self.seed_bin_regressor(x)
+
+ if self.bin_centers_type in ["normed", "hybrid2"]:
+ prev_bin = (seed_bin_centers - self.min_depth) / (self.max_depth - self.min_depth)
+ else:
+ prev_bin = seed_bin_centers
+
+ prev_bin_embedding = self.seed_projector(x)
+
+ # unroll this loop for better performance
+ for projector, attractor, feature in zip(self.projectors, self.attractors, feature_blocks):
+ bin_embedding = projector(feature)
+ bin, bin_centers = attractor(bin_embedding, prev_bin, prev_bin_embedding, interpolate=True)
+ prev_bin = bin.clone()
+ prev_bin_embedding = bin_embedding.clone()
+
+ last = outconv_activation
+
+ # concatenative relative depth with last. First interpolate relative depth to last size
+ relative_conditioning = relative_depth.unsqueeze(1)
+ relative_conditioning = nn.functional.interpolate(
+ relative_conditioning, size=last.shape[2:], mode="bilinear", align_corners=True
+ )
+ last = torch.cat([last, relative_conditioning], dim=1)
+
+ bin_embedding = nn.functional.interpolate(bin_embedding, last.shape[-2:], mode="bilinear", align_corners=True)
+ x = self.conditional_log_binomial(last, bin_embedding)
+
+ # Now depth value is Sum px * cx , where cx are bin_centers from the last bin tensor
+ bin_centers = nn.functional.interpolate(bin_centers, x.shape[-2:], mode="bilinear", align_corners=True)
+ out = torch.sum(x * bin_centers, dim=1, keepdim=True)
+
+ return out, None
+
+
+# Modified from transformers.models.dpt.modeling_dpt.DPTPreTrainedModel with DPT->ZoeDepth,dpt->zoedepth
+# avoiding sdpa and flash_attn_2 support, it's done int the backend
+@auto_docstring
+class ZoeDepthPreTrainedModel(PreTrainedModel):
+ config: ZoeDepthConfig
+ base_model_prefix = "zoedepth"
+ main_input_name = "pixel_values"
+ supports_gradient_checkpointing = True
+
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.ConvTranspose2d)):
+ # Slightly different from the TF version which uses truncated_normal for initialization
+ # cf https://github.com/pytorch/pytorch/pull/5617
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
+ if module.bias is not None:
+ module.bias.data.zero_()
+ elif isinstance(module, nn.LayerNorm):
+ module.bias.data.zero_()
+ module.weight.data.fill_(1.0)
+
+
+@auto_docstring(
+ custom_intro="""
+ ZoeDepth model with one or multiple metric depth estimation head(s) on top.
+ """
+)
+class ZoeDepthForDepthEstimation(ZoeDepthPreTrainedModel):
+ def __init__(self, config):
+ super().__init__(config)
+
+ self.backbone = load_backbone(config)
+
+ if hasattr(self.backbone.config, "hidden_size") and hasattr(self.backbone.config, "patch_size"):
+ config.backbone_hidden_size = self.backbone.config.hidden_size
+ self.patch_size = self.backbone.config.patch_size
+ else:
+ raise ValueError(
+ "ZoeDepth assumes the backbone's config to have `hidden_size` and `patch_size` attributes"
+ )
+
+ self.neck = ZoeDepthNeck(config)
+ self.relative_head = ZoeDepthRelativeDepthEstimationHead(config)
+
+ self.metric_head = (
+ ZoeDepthMultipleMetricDepthEstimationHeads(config)
+ if len(config.bin_configurations) > 1
+ else ZoeDepthMetricDepthEstimationHead(config)
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor,
+ labels: Optional[torch.LongTensor] = None,
+ output_attentions: Optional[bool] = None,
+ output_hidden_states: Optional[bool] = None,
+ return_dict: Optional[bool] = None,
+ ) -> Union[tuple[torch.Tensor], DepthEstimatorOutput]:
+ r"""
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
+ Ground truth depth estimation maps for computing the loss.
+
+ Examples:
+ ```python
+ >>> from transformers import AutoImageProcessor, ZoeDepthForDepthEstimation
+ >>> import torch
+ >>> import numpy as np
+ >>> from PIL import Image
+ >>> import requests
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = Image.open(requests.get(url, stream=True).raw)
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("Intel/zoedepth-nyu-kitti")
+ >>> model = ZoeDepthForDepthEstimation.from_pretrained("Intel/zoedepth-nyu-kitti")
+
+ >>> # prepare image for the model
+ >>> inputs = image_processor(images=image, return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> # interpolate to original size
+ >>> post_processed_output = image_processor.post_process_depth_estimation(
+ ... outputs,
+ ... source_sizes=[(image.height, image.width)],
+ ... )
+
+ >>> # visualize the prediction
+ >>> predicted_depth = post_processed_output[0]["predicted_depth"]
+ >>> depth = predicted_depth * 255 / predicted_depth.max()
+ >>> depth = depth.detach().cpu().numpy()
+ >>> depth = Image.fromarray(depth.astype("uint8"))
+ ```"""
+ loss = None
+ if labels is not None:
+ raise NotImplementedError("Training is not implemented yet")
+
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+ output_hidden_states = (
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
+ )
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
+
+ outputs = self.backbone.forward_with_filtered_kwargs(
+ pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
+ )
+ hidden_states = outputs.feature_maps
+
+ _, _, height, width = pixel_values.shape
+ patch_size = self.patch_size
+ patch_height = height // patch_size
+ patch_width = width // patch_size
+
+ hidden_states, features = self.neck(hidden_states, patch_height, patch_width)
+
+ out = [features] + hidden_states
+
+ relative_depth, features = self.relative_head(hidden_states)
+
+ out = [features] + out
+
+ metric_depth, domain_logits = self.metric_head(
+ outconv_activation=out[0], bottleneck=out[1], feature_blocks=out[2:], relative_depth=relative_depth
+ )
+ metric_depth = metric_depth.squeeze(dim=1)
+
+ if not return_dict:
+ if domain_logits is not None:
+ output = (metric_depth, domain_logits) + outputs[1:]
+ else:
+ output = (metric_depth,) + outputs[1:]
+
+ return ((loss,) + output) if loss is not None else output
+
+ return ZoeDepthDepthEstimatorOutput(
+ loss=loss,
+ predicted_depth=metric_depth,
+ domain_logits=domain_logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = ["ZoeDepthForDepthEstimation", "ZoeDepthPreTrainedModel"]