diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/isympy.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/isympy.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1a336af1b4073abea092211ecd55affd56b9c524
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/isympy.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpatch.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpatch.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ae43425ab2cb9a9f9b493014b1e5b48484249c5a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpatch.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpointer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpointer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8cad5d36457533f9e6e72b00f3f09fa1904422a7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/jsonpointer.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/mypy_extensions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/mypy_extensions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ed6ec19919f9b06ee3af1155b343649fc21a9b7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/mypy_extensions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/six.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/six.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8d325b70ba5ab83a3aa550dbb062273e4327d821
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/six.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/threadpoolctl.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/threadpoolctl.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1e0b777dddb21d9d5cd3a50be72666e1d568df88
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/threadpoolctl.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/typing_inspect.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/typing_inspect.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c7c75f3f64208e6940f509a80f853b7b64e56d2d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/__pycache__/typing_inspect.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..94f71b99ecefd27e6cf3fd06fc3c0eef5fd73910
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__init__.py
@@ -0,0 +1,239 @@
+# don't import any costly modules
+import os
+import sys
+
+report_url = (
+ "https://github.com/pypa/setuptools/issues/new?template=distutils-deprecation.yml"
+)
+
+
+def warn_distutils_present():
+ if 'distutils' not in sys.modules:
+ return
+ import warnings
+
+ warnings.warn(
+ "Distutils was imported before Setuptools, but importing Setuptools "
+ "also replaces the `distutils` module in `sys.modules`. This may lead "
+ "to undesirable behaviors or errors. To avoid these issues, avoid "
+ "using distutils directly, ensure that setuptools is installed in the "
+ "traditional way (e.g. not an editable install), and/or make sure "
+ "that setuptools is always imported before distutils."
+ )
+
+
+def clear_distutils():
+ if 'distutils' not in sys.modules:
+ return
+ import warnings
+
+ warnings.warn(
+ "Setuptools is replacing distutils. Support for replacing "
+ "an already imported distutils is deprecated. In the future, "
+ "this condition will fail. "
+ f"Register concerns at {report_url}"
+ )
+ mods = [
+ name
+ for name in sys.modules
+ if name == "distutils" or name.startswith("distutils.")
+ ]
+ for name in mods:
+ del sys.modules[name]
+
+
+def enabled():
+ """
+ Allow selection of distutils by environment variable.
+ """
+ which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
+ if which == 'stdlib':
+ import warnings
+
+ warnings.warn(
+ "Reliance on distutils from stdlib is deprecated. Users "
+ "must rely on setuptools to provide the distutils module. "
+ "Avoid importing distutils or import setuptools first, "
+ "and avoid setting SETUPTOOLS_USE_DISTUTILS=stdlib. "
+ f"Register concerns at {report_url}"
+ )
+ return which == 'local'
+
+
+def ensure_local_distutils():
+ import importlib
+
+ clear_distutils()
+
+ # With the DistutilsMetaFinder in place,
+ # perform an import to cause distutils to be
+ # loaded from setuptools._distutils. Ref #2906.
+ with shim():
+ importlib.import_module('distutils')
+
+ # check that submodules load as expected
+ core = importlib.import_module('distutils.core')
+ assert '_distutils' in core.__file__, core.__file__
+ assert 'setuptools._distutils.log' not in sys.modules
+
+
+def do_override():
+ """
+ Ensure that the local copy of distutils is preferred over stdlib.
+
+ See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
+ for more motivation.
+ """
+ if enabled():
+ warn_distutils_present()
+ ensure_local_distutils()
+
+
+class _TrivialRe:
+ def __init__(self, *patterns) -> None:
+ self._patterns = patterns
+
+ def match(self, string):
+ return all(pat in string for pat in self._patterns)
+
+
+class DistutilsMetaFinder:
+ def find_spec(self, fullname, path, target=None):
+ # optimization: only consider top level modules and those
+ # found in the CPython test suite.
+ if path is not None and not fullname.startswith('test.'):
+ return None
+
+ method_name = 'spec_for_{fullname}'.format(**locals())
+ method = getattr(self, method_name, lambda: None)
+ return method()
+
+ def spec_for_distutils(self):
+ if self.is_cpython():
+ return None
+
+ import importlib
+ import importlib.abc
+ import importlib.util
+
+ try:
+ mod = importlib.import_module('setuptools._distutils')
+ except Exception:
+ # There are a couple of cases where setuptools._distutils
+ # may not be present:
+ # - An older Setuptools without a local distutils is
+ # taking precedence. Ref #2957.
+ # - Path manipulation during sitecustomize removes
+ # setuptools from the path but only after the hook
+ # has been loaded. Ref #2980.
+ # In either case, fall back to stdlib behavior.
+ return None
+
+ class DistutilsLoader(importlib.abc.Loader):
+ def create_module(self, spec):
+ mod.__name__ = 'distutils'
+ return mod
+
+ def exec_module(self, module):
+ pass
+
+ return importlib.util.spec_from_loader(
+ 'distutils', DistutilsLoader(), origin=mod.__file__
+ )
+
+ @staticmethod
+ def is_cpython():
+ """
+ Suppress supplying distutils for CPython (build and tests).
+ Ref #2965 and #3007.
+ """
+ return os.path.isfile('pybuilddir.txt')
+
+ def spec_for_pip(self):
+ """
+ Ensure stdlib distutils when running under pip.
+ See pypa/pip#8761 for rationale.
+ """
+ if sys.version_info >= (3, 12) or self.pip_imported_during_build():
+ return
+ clear_distutils()
+ self.spec_for_distutils = lambda: None
+
+ @classmethod
+ def pip_imported_during_build(cls):
+ """
+ Detect if pip is being imported in a build script. Ref #2355.
+ """
+ import traceback
+
+ return any(
+ cls.frame_file_is_setup(frame) for frame, line in traceback.walk_stack(None)
+ )
+
+ @staticmethod
+ def frame_file_is_setup(frame):
+ """
+ Return True if the indicated frame suggests a setup.py file.
+ """
+ # some frames may not have __file__ (#2940)
+ return frame.f_globals.get('__file__', '').endswith('setup.py')
+
+ def spec_for_sensitive_tests(self):
+ """
+ Ensure stdlib distutils when running select tests under CPython.
+
+ python/cpython#91169
+ """
+ clear_distutils()
+ self.spec_for_distutils = lambda: None
+
+ sensitive_tests = (
+ [
+ 'test.test_distutils',
+ 'test.test_peg_generator',
+ 'test.test_importlib',
+ ]
+ if sys.version_info < (3, 10)
+ else [
+ 'test.test_distutils',
+ ]
+ )
+
+
+for name in DistutilsMetaFinder.sensitive_tests:
+ setattr(
+ DistutilsMetaFinder,
+ f'spec_for_{name}',
+ DistutilsMetaFinder.spec_for_sensitive_tests,
+ )
+
+
+DISTUTILS_FINDER = DistutilsMetaFinder()
+
+
+def add_shim():
+ DISTUTILS_FINDER in sys.meta_path or insert_shim()
+
+
+class shim:
+ def __enter__(self) -> None:
+ insert_shim()
+
+ def __exit__(self, exc: object, value: object, tb: object) -> None:
+ _remove_shim()
+
+
+def insert_shim():
+ sys.meta_path.insert(0, DISTUTILS_FINDER)
+
+
+def _remove_shim():
+ try:
+ sys.meta_path.remove(DISTUTILS_FINDER)
+ except ValueError:
+ pass
+
+
+if sys.version_info < (3, 12):
+ # DistutilsMetaFinder can only be disabled in Python < 3.12 (PEP 632)
+ remove_shim = _remove_shim
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ed5816e55e2654ba65e47d201f6b0c0f47db6342
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/override.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/override.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..309a9993808f5bc80521029097d0b64cf4dfcd6f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/__pycache__/override.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/override.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/override.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cc433a4a55e3b41fa31089918fb62096092f89f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/_distutils_hack/override.py
@@ -0,0 +1 @@
+__import__('_distutils_hack').do_override()
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7baa8c4b68127d5cdf0be9a799429e61347c2694
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__init__.py
@@ -0,0 +1,33 @@
+# This is a stub package designed to roughly emulate the _yaml
+# extension module, which previously existed as a standalone module
+# and has been moved into the `yaml` package namespace.
+# It does not perfectly mimic its old counterpart, but should get
+# close enough for anyone who's relying on it even when they shouldn't.
+import yaml
+
+# in some circumstances, the yaml module we imoprted may be from a different version, so we need
+# to tread carefully when poking at it here (it may not have the attributes we expect)
+if not getattr(yaml, '__with_libyaml__', False):
+ from sys import version_info
+
+ exc = ModuleNotFoundError if version_info >= (3, 6) else ImportError
+ raise exc("No module named '_yaml'")
+else:
+ from yaml._yaml import *
+ import warnings
+ warnings.warn(
+ 'The _yaml extension module is now located at yaml._yaml'
+ ' and its location is subject to change. To use the'
+ ' LibYAML-based parser and emitter, import from `yaml`:'
+ ' `from yaml import CLoader as Loader, CDumper as Dumper`.',
+ DeprecationWarning
+ )
+ del warnings
+ # Don't `del yaml` here because yaml is actually an existing
+ # namespace member of _yaml.
+
+__name__ = '_yaml'
+# If the module is top-level (i.e. not a part of any specific package)
+# then the attribute should be set to ''.
+# https://docs.python.org/3.8/library/types.html
+__package__ = ''
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..92215c13c356b15f4b0a3a1423ead9a643b7e4dd
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/_yaml/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers-5.8.1.dist-info/licenses/LICENSE b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers-5.8.1.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..68b7d66c97d66c58de883ed0c451af2b3183e6f3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers-5.8.1.dist-info/licenses/LICENSE
@@ -0,0 +1,203 @@
+Copyright 2018- The Hugging Face team. All rights reserved.
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ 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.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..237f765be195f552e8f4d3fb43fdb8b3343c0ce3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/_typing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/_typing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59a8717dca4b8608f6f268c179f57c2bb0303be2
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/_typing.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/activations.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/activations.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..108c412aaaf0855a292f8bb3f15a152d36bd1f90
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/activations.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/audio_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/audio_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a2e5294bd53cc76c4f656a8481ca458bf6e3400
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/audio_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/backbone_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/backbone_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cbea02baa1c7437d8bf4a3eae9906f0a1bad0c0
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/backbone_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/cache_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/cache_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..520dcf37addf3aaa7117f8a6ab662e63297b278a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/cache_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/configuration_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/configuration_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c85c609457e80e1ab6b4748dab520d7a52fcf58d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/configuration_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/conversion_mapping.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/conversion_mapping.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dab75668052130e691a7db9af3c5c8b349ab2063
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/conversion_mapping.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/convert_slow_tokenizers_checkpoints_to_fast.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/convert_slow_tokenizers_checkpoints_to_fast.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3d18f779b790efe30c86d393fd645f5e5048d9f9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/convert_slow_tokenizers_checkpoints_to_fast.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/core_model_loading.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/core_model_loading.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a31487ec66a781226a53ffb74d33b9f688f4fb15
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/core_model_loading.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/debug_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/debug_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..338aa0b06d0f607687cb7376d54b40c67b7c5a24
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/debug_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_check.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_check.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..78adc3528c39a606e7e4757781194f6cc8370310
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_check.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_table.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_table.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0da8a1e685e91e3cd96cd5fcaa75780c0e67f69
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dependency_versions_table.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dynamic_module_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dynamic_module_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a62e94fefb40fb2e4a4d09548b0d3c5040544f05
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/dynamic_module_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_sequence_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_sequence_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9a07aa7bae3362e1635b9321076418c759fb1a4b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_sequence_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5fe8c115045e9d8ac4db092a2f23f1d867560dfd
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/feature_extraction_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/file_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/file_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f75fe1749774605f640c364e922ec9e34ca5bf4d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/file_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/fusion_mapping.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/fusion_mapping.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8f582f6973acb08b83aeb2e7d424e91229c1eec8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/fusion_mapping.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hf_argparser.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hf_argparser.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9b6a542079a9b81edb543a03602e3840f99ba1e3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hf_argparser.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hyperparameter_search.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hyperparameter_search.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e9d82accddbbad82cbff833b2666c4605d0519d1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/hyperparameter_search.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_backends.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_backends.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8b525810a50bbd367c29446da98ad5d57e3585c4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_backends.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..316f74c83cd7795406bb8af0965e0b98fd9aa189
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..adfb45be789dbcdcb337b1b13e6c8b2aeecce04a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_processing_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_transforms.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_transforms.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e500210d2bc5ae85af7073fd63da21331fa7fd13
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_transforms.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..43dde778d53708f1ef8095b29afa95f8ed253a2e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/image_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/initialization.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/initialization.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d0f55a85f59577c9fb3ce9d6f3dbe0302b8d8525
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/initialization.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/masking_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/masking_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..71b014e7a39d5ea2f1b6d868c5458f5db67af829
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/masking_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/model_debugging_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/model_debugging_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bcf793687309fedaa145832945b008bb8987c30d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/model_debugging_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modelcard.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modelcard.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f427731c5f36ee9711538fa8bc3576ec7ff6a989
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modelcard.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_attn_mask_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_attn_mask_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8ae4ce54a4c41e9b62584634fb4b5adde590039
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_attn_mask_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_flash_attention_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_flash_attention_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b8c7c7d60043c9b12b206069fa1dcba2b33079b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_flash_attention_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_gguf_pytorch_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_gguf_pytorch_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..02a8f2d22dd8cc862ed6100b391e1f9ec5713eed
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_gguf_pytorch_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_layers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_layers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..df528a2e2d9e251f38b483e9f49533a43cef51b3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_layers.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_rope_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_rope_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e71a55278efa511df10564b95a0d6d208f432f1a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/modeling_rope_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/monkey_patching.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/monkey_patching.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d8caab9a6cec0d3ca1ef492bc61127faba14043f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/monkey_patching.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/optimization.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/optimization.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2d9a3b694d0d1b648f21b74453880b9c92322942
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/optimization.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/pytorch_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/pytorch_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..88527e62423f9d64d9800be3e078d98669f9393e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/pytorch_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/safetensors_conversion.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/safetensors_conversion.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..688b43d6fee832459a9e81911b5f41e1eb3bb137
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/safetensors_conversion.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/time_series_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/time_series_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..16736b3ce9a01c3bd76ee41d35e0b405bc464619
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/time_series_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_mistral_common.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_mistral_common.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6041311d7f1a34643a08651678c08887226e29f3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_mistral_common.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_python.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_python.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..965ad5be45659de8a89d79ce598b94a60e9201fb
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_python.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_sentencepiece.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_sentencepiece.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b9e23be10e9b58643cad48bace0ab7e5def0b77a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_sentencepiece.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_tokenizers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_tokenizers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb9c79f0e3d073291c4d4a7d947242b7c02ed757
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/tokenization_utils_tokenizers.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_callback.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_callback.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..77d818f41469af1347432cf936c2ef75991da913
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_callback.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_jit_checkpoint.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_jit_checkpoint.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e362573a7babfb1588426f309055dcfedd38ba2d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_jit_checkpoint.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_optimizer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_optimizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..92021c97488e33f9a5d5ff2cfa41b5090d755120
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_optimizer.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_pt_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_pt_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bacc0cbd80ab55cb1efc0a7e6594384d0d47c732
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_pt_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_seq2seq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_seq2seq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cdfac859ae34b85da4b188bcecd80eef241b112
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_seq2seq.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ba4474fff631d01fa54abb8da821d28fdb2d69c1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/trainer_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/training_args_seq2seq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/training_args_seq2seq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..59cb1a2980cd3218bcea5b0397b61c44d53c6c1b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/training_args_seq2seq.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_processing_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_processing_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4ad34794da2a3433a3aaa887623ec45c095ccecc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_processing_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..792c30c3694366b2785d4abc6ce824655dac73bc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/__pycache__/video_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8568c82be1c638c0ccd34d460fd8b0f73dcbec4e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/__init__.py
@@ -0,0 +1,13 @@
+# Copyright 2025 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.
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/add_new_model_like.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/add_new_model_like.py
new file mode 100644
index 0000000000000000000000000000000000000000..3293f6a4ba8cea00e98fb3bedae4bc996830a615
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/cli/add_new_model_like.py
@@ -0,0 +1,790 @@
+# 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.
+import difflib
+import os
+import re
+import subprocess
+import textwrap
+from collections.abc import Callable
+from datetime import date
+from pathlib import Path
+from typing import Annotated, Any, cast
+
+import typer
+
+from ..utils import is_libcst_available
+
+
+# We protect this import to avoid requiring it for all `transformers` CLI commands - however it is actually
+# strictly required for this one (we need it both for modular and for the following Visitor)
+if is_libcst_available():
+ import libcst as cst
+ from libcst import CSTVisitor
+ from libcst import matchers as m
+
+ class ClassFinder(CSTVisitor):
+ """
+ A visitor to find all classes in a python module.
+ """
+
+ def __init__(self):
+ self.classes: list = []
+ self.public_classes: list = []
+ self.is_in_class = False
+
+ def visit_ClassDef(self, node: cst.ClassDef) -> None:
+ """Record class names. We assume classes always only appear at top-level (i.e. no class definition in function or similar)"""
+ self.classes.append(node.name.value)
+ self.is_in_class = True
+
+ def leave_ClassDef(self, node: cst.ClassDef):
+ self.is_in_class = False
+
+ def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine):
+ """Record all public classes inside the `__all__` assignment."""
+ simple_top_level_assign_structure = m.SimpleStatementLine(
+ body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])]
+ )
+ if not self.is_in_class and m.matches(node, simple_top_level_assign_structure):
+ stmt = cast(cst.Assign, node.body[0])
+ assigned_variable = cast(cst.Name, stmt.targets[0].target).value
+ if assigned_variable == "__all__":
+ elements = cast(cst.Tuple, stmt.value).elements
+ self.public_classes = [cast(cst.SimpleString, element.value).value for element in elements]
+
+
+CURRENT_YEAR = date.today().year
+REPO_PATH = Path(__file__).parents[3]
+
+COPYRIGHT = f"""
+# coding=utf-8
+# Copyright {CURRENT_YEAR} 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.
+""".lstrip()
+
+### Entrypoint
+
+
+def add_new_model_like(
+ repo_path: Annotated[
+ str | None, typer.Argument(help="When not using an editable install, the path to the Transformers repo.")
+ ] = None,
+):
+ """
+ Add a new model to the library, based on an existing one.
+ """
+ (
+ old_model_infos,
+ new_lowercase_name,
+ new_model_paper_name,
+ filenames_to_add,
+ ) = get_user_input()
+
+ _add_new_model_like_internal(
+ repo_path=Path(repo_path) if repo_path is not None else REPO_PATH,
+ old_model_infos=old_model_infos,
+ new_lowercase_name=new_lowercase_name,
+ new_model_paper_name=new_model_paper_name,
+ filenames_to_add=filenames_to_add,
+ )
+
+
+### Core logic
+
+
+class ModelInfos:
+ """
+ Retrieve the basic information about an existing model classes.
+ """
+
+ def __init__(self, lowercase_name: str):
+ from ..models.auto.configuration_auto import CONFIG_MAPPING_NAMES
+ from ..models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING_NAMES
+ from ..models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING_NAMES
+ from ..models.auto.processing_auto import PROCESSOR_MAPPING_NAMES
+ from ..models.auto.tokenization_auto import TOKENIZER_MAPPING_NAMES
+ from ..models.auto.video_processing_auto import VIDEO_PROCESSOR_MAPPING_NAMES
+
+ # Just to make sure it's indeed lowercase
+ self.lowercase_name = lowercase_name.lower().replace(" ", "_").replace("-", "_")
+ if self.lowercase_name not in CONFIG_MAPPING_NAMES:
+ self.lowercase_name.replace("_", "-")
+ if self.lowercase_name not in CONFIG_MAPPING_NAMES:
+ raise ValueError(f"{lowercase_name} is not a valid model name")
+
+ self.config_class = CONFIG_MAPPING_NAMES[self.lowercase_name]
+ self.camelcase_name = self.config_class.replace("Config", "")
+
+ # Get tokenizer class
+ if self.lowercase_name in TOKENIZER_MAPPING_NAMES:
+ self.tokenizer_class = None
+ self.fast_tokenizer_class = TOKENIZER_MAPPING_NAMES[self.lowercase_name]
+ self.fast_tokenizer_class = (
+ None if self.fast_tokenizer_class == "PreTrainedTokenizerFast" else self.fast_tokenizer_class
+ )
+ else:
+ self.tokenizer_class, self.fast_tokenizer_class = None, None
+
+ self.image_processor_classes = IMAGE_PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None)
+ self.video_processor_class = VIDEO_PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None)
+ self.feature_extractor_class = FEATURE_EXTRACTOR_MAPPING_NAMES.get(self.lowercase_name, None)
+ self.processor_class = PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None)
+
+
+def add_content_to_file(file_name: str | os.PathLike, new_content: str, add_after: str):
+ """
+ A utility to add some content inside a given file.
+
+ Args:
+ file_name (`str` or `os.PathLike`):
+ The name of the file in which we want to insert some content.
+ new_content (`str`):
+ The content to add.
+ add_after (`str`):
+ The new content is added just after the first instance matching it.
+ """
+ with open(file_name, "r", encoding="utf-8") as f:
+ old_content = f.read()
+
+ before, after = old_content.split(add_after, 1)
+ new_content = before + add_after + new_content + after
+
+ with open(file_name, "w", encoding="utf-8") as f:
+ f.write(new_content)
+
+
+def add_model_to_auto_mappings(
+ repo_path: Path,
+ old_model_infos: ModelInfos,
+ new_lowercase_name: str,
+ new_model_paper_name: str,
+ filenames_to_add: list[tuple[str, bool]],
+):
+ """
+ Add a model to all the relevant mappings in the auto module.
+
+ Args:
+ old_model_infos (`ModelInfos`):
+ The structure containing the class information of the old model.
+ new_lowercase_name (`str`):
+ The new lowercase model name.
+ new_model_paper_name (`str`):
+ The fully cased name (as in the official paper name) of the new model.
+ filenames_to_add (`list[tuple[str, bool]]`):
+ A list of tuples of all potential filenames to add for a new model, along a boolean flag describing if we
+ should add this file or not. For example, [(`modeling_xxx.px`, True), (`configuration_xxx.py`, True), (`tokenization_xxx.py`, False),...]
+ """
+ new_cased_name = "".join(x.title() for x in new_lowercase_name.replace("-", "_").split("_"))
+ old_lowercase_name = old_model_infos.lowercase_name
+ old_cased_name = old_model_infos.camelcase_name
+ filenames_to_add = [
+ (filename.replace(old_lowercase_name, "auto"), to_add) for filename, to_add in filenames_to_add[1:]
+ ]
+ # fast tokenizer has the same auto mappings as normal ones
+ corrected_filenames_to_add = []
+ has_image_processor = has_video_processor = False
+ for file, to_add in filenames_to_add:
+ if "image_processing" in file:
+ has_image_processor = True
+ elif "video_processing" in file:
+ has_video_processor = True
+ elif re.search(r"(?:tokenization)|(?:image_processing)_auto_fast.py", file):
+ previous_file, previous_to_add = corrected_filenames_to_add[-1]
+ corrected_filenames_to_add[-1] = (previous_file, previous_to_add or to_add)
+ else:
+ corrected_filenames_to_add.append((file, to_add))
+
+ # Add the config and image/video processor mappings directly as the handling is a bit different
+ add_content_to_file(
+ repo_path / "src" / "transformers" / "models" / "auto" / "auto_mappings.py",
+ new_content=f'("{new_lowercase_name}", "{new_cased_name}Config"),\n ',
+ add_after="CONFIG_MAPPING_NAMES = OrderedDict(\n [\n ",
+ )
+ autofile = (repo_path / "src" / "transformers" / "models" / "auto" / "auto_mappings.py").read_text()
+ if has_image_processor:
+ matching_lines = re.findall(rf'^\s+\("{old_lowercase_name}",\s+{{[^}}]+}}\),?$', autofile, re.MULTILINE)
+ if matching_lines:
+ match = matching_lines[0]
+ add_content_to_file(
+ repo_path / "src" / "transformers" / "models" / "auto" / "auto_mappings.py",
+ new_content=match.replace(old_lowercase_name, new_lowercase_name).replace(
+ old_cased_name, new_cased_name
+ )
+ + "\n",
+ add_after="IMAGE_PROCESSOR_MAPPING_NAMES = OrderedDict(\n [\n",
+ )
+ if has_video_processor:
+ # Extract the VIDEO_PROCESSOR_MAPPING_NAMES block first
+ block_match = re.search(
+ r"VIDEO_PROCESSOR_MAPPING_NAMES\s*=\s*OrderedDict\(\s*\[(.*?)\]\s*\)", autofile, re.DOTALL
+ )
+ block = block_match.group(1) # type: ignore
+ matching_lines = re.findall(rf'^\s+\("{old_lowercase_name}",\s+"[^"]+"\),?$', block, re.MULTILINE)
+ if matching_lines:
+ match = matching_lines[0]
+ add_content_to_file(
+ repo_path / "src" / "transformers" / "models" / "auto" / "auto_mappings.py",
+ new_content=match.replace(old_lowercase_name, new_lowercase_name).replace(
+ old_cased_name, new_cased_name
+ )
+ + "\n",
+ add_after="VIDEO_PROCESSOR_MAPPING_NAMES = OrderedDict(\n [\n",
+ )
+
+ for filename, to_add in corrected_filenames_to_add:
+ if to_add:
+ # The auto mapping
+ filename = filename.replace("_fast.py", ".py")
+ file = (repo_path / "src" / "transformers" / "models" / "auto" / filename).read_text()
+ # The regex has to be a bit complex like this as the tokenizer mapping has new lines everywhere
+ matching_lines = re.findall(
+ rf'( {{8,12}}\(\s*"{old_lowercase_name}",.*?\),\n)(?: {{4,12}}\(|\])', file, re.DOTALL
+ )
+ for match in matching_lines:
+ add_content_to_file(
+ repo_path / "src" / "transformers" / "models" / "auto" / filename,
+ new_content=match.replace(old_lowercase_name, new_lowercase_name).replace(
+ old_cased_name, new_cased_name
+ ),
+ add_after=match,
+ )
+
+
+def create_doc_file(new_paper_name: str, public_classes: list[str]):
+ """
+ Create a new doc file to fill for the new model.
+
+ Args:
+ new_paper_name (`str`):
+ The fully cased name (as in the official paper name) of the new model.
+ public_classes (`list[str]`):
+ A list of all the public classes that the model will have in the library.
+ """
+ added_note = (
+ "\n\n⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that "
+ "may not be rendered properly in your Markdown viewer.\n\n-->\n\n"
+ )
+ copyright_for_markdown = re.sub(r"# ?", "", COPYRIGHT).replace("coding=utf-8\n", " batch_size, channels, spec_height * freq_ratio, spec_width // freq_ratio
+ normalized_input_features = normalized_input_features.reshape(
+ batch, channels * self.freq_ratio, time // self.freq_ratio, freq
+ )
+ normalized_input_features = normalized_input_features.permute(0, 1, 3, 2).contiguous()
+ normalized_input_features = normalized_input_features.reshape(
+ batch, channels, freq * self.freq_ratio, time // self.freq_ratio
+ )
+
+ return normalized_input_features
+
+ @can_return_tuple
+ def forward(
+ self,
+ input_features,
+ is_longer: torch.FloatTensor | None = None,
+ output_attentions: bool | None = False,
+ output_hidden_states: bool | None = False,
+ output_hidden_states_before_downsampling: bool | None = False,
+ always_partition: bool | None = False,
+ return_dict: bool | None = True,
+ ) -> tuple | ClapAudioModelOutput:
+ # Unique logic so no refactor here yet
+ output_hidden_states = output_hidden_states or self.config.output_hidden_states
+ output_attentions = output_attentions or self.config.output_attentions
+
+ input_features = input_features.transpose(1, 3)
+ normalized_input_features = self.batch_norm(input_features)
+ normalized_input_features = normalized_input_features.transpose(1, 3)
+
+ is_longer_list_idx = None
+ if self.enable_fusion:
+ is_longer_list = is_longer.to(input_features.device)
+ is_longer_list_idx = torch.where(is_longer_list == 1)[0]
+
+ hidden_states = self.reshape_mel2img(normalized_input_features)
+
+ frames_num = hidden_states.shape[2]
+
+ hidden_states = self.patch_embed(hidden_states, is_longer_list_idx)
+
+ 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
+
+ input_dimensions = self.input_resolutions[0]
+
+ if output_hidden_states:
+ batch_size, _, hidden_size = hidden_states.shape
+ # rearrange batch_size (height width) channels -> batch_size channel height width
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
+ all_hidden_states += (hidden_states,)
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
+
+ for i, layer_module in enumerate(self.layers):
+ input_dimensions = self.input_resolutions[i]
+
+ layer_outputs = layer_module(hidden_states, input_dimensions, output_attentions, always_partition)
+
+ hidden_states = layer_outputs[0]
+
+ hidden_states_before_downsampling = layer_outputs[1]
+ output_dimensions = layer_outputs[2]
+
+ input_dimensions = (output_dimensions[-2], output_dimensions[-1])
+
+ if output_hidden_states and output_hidden_states_before_downsampling:
+ batch_size, _, hidden_size = hidden_states_before_downsampling.shape
+ # rearrange batch_size (height width) channels -> batch_size channel height width
+ # here we use the original (not downsampled) height and width
+ reshaped_hidden_state = hidden_states_before_downsampling.view(
+ batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
+ )
+ reshaped_hidden_state = reshaped_hidden_state.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:
+ batch_size, _, hidden_size = hidden_states.shape
+ # rearrange batch_size (height width) channels -> batch_size channel height width
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
+ reshaped_hidden_state = reshaped_hidden_state.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[3:]
+
+ last_hidden_state = self.norm(hidden_states)
+
+ batch_size, _, n_channels = last_hidden_state.shape
+
+ freq_shape = frames_num // (2 ** (len(self.depths) - 1)) // self.patch_stride[0]
+ temporal_shape = frames_num // (2 ** (len(self.depths) - 1)) // self.patch_stride[1]
+
+ last_hidden_state = (
+ last_hidden_state.permute(0, 2, 1).contiguous().reshape(batch_size, n_channels, freq_shape, temporal_shape)
+ )
+
+ batch_size, n_channels, n_frequencies, n_temp = last_hidden_state.shape
+ # group 2D CNN
+ c_freq_bin = n_frequencies // self.freq_ratio
+ last_hidden_state = last_hidden_state.reshape(
+ batch_size, n_channels, n_frequencies // c_freq_bin, c_freq_bin, n_temp
+ )
+ last_hidden_state = (
+ last_hidden_state.permute(0, 1, 3, 2, 4).contiguous().reshape(batch_size, n_channels, c_freq_bin, -1)
+ )
+ latent_output = self.avgpool(torch.flatten(last_hidden_state, 2))
+ latent_output = torch.flatten(latent_output, 1)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=latent_output,
+ hidden_states=all_reshaped_hidden_states,
+ attentions=all_self_attentions,
+ )
+
+
+class ClapProjectionLayer(nn.Module):
+ def __init__(self, config: ClapAudioConfig | ClapTextConfig):
+ super().__init__()
+ self.config = config
+ hidden_size = config.hidden_size
+ projection_dim = config.projection_dim
+
+ self.linear1 = nn.Linear(hidden_size, projection_dim)
+ self.activation = ACT2FN[config.projection_hidden_act]
+ self.linear2 = nn.Linear(projection_dim, projection_dim)
+
+ def forward(self, hidden_states):
+ hidden_states = self.linear1(hidden_states)
+ hidden_states = self.activation(hidden_states)
+ hidden_states = self.linear2(hidden_states)
+ return hidden_states
+
+
+# Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->ClapText, persistent=False->persistent=True
+class ClapTextEmbeddings(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.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
+
+ 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)), persistent=True
+ )
+ self.register_buffer(
+ "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=True
+ )
+
+ 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: torch.LongTensor | None = None,
+ token_type_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ past_key_values_length: int = 0,
+ ) -> torch.Tensor:
+ 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, self.padding_idx, past_key_values_length
+ )
+ else:
+ position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds, self.padding_idx)
+
+ if input_ids is not None:
+ input_shape = input_ids.size()
+ else:
+ input_shape = inputs_embeds.size()[:-1]
+
+ batch_size, seq_length = input_shape
+
+ # 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"):
+ # NOTE: We assume either pos ids to have bsz == 1 (broadcastable) or bsz == effective bsz (input_shape[0])
+ buffered_token_type_ids = self.token_type_ids.expand(position_ids.shape[0], -1)
+ buffered_token_type_ids = torch.gather(buffered_token_type_ids, dim=1, index=position_ids)
+ token_type_ids = buffered_token_type_ids.expand(batch_size, seq_length)
+ 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
+
+ position_embeddings = self.position_embeddings(position_ids)
+ embeddings = embeddings + position_embeddings
+
+ embeddings = self.LayerNorm(embeddings)
+ embeddings = self.dropout(embeddings)
+ return embeddings
+
+ @staticmethod
+ def create_position_ids_from_inputs_embeds(inputs_embeds, padding_idx):
+ """
+ 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(
+ padding_idx + 1, sequence_length + padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
+ )
+ return position_ids.unsqueeze(0).expand(input_shape)
+
+ @staticmethod
+ 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
+
+
+# Copied from transformers.models.align.modeling_align.eager_attention_forward
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs,
+):
+ attn_weights = torch.matmul(query, key.transpose(2, 3)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_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)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.align.modeling_align.AlignTextSelfAttention with Align->Clap
+class ClapTextSelfAttention(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.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.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.attention_dropout = config.attention_probs_dropout_prob
+ self.scaling = self.attention_head_size**-0.5
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ input_shape = hidden_states.shape[:-1]
+ hidden_shape = (*input_shape, -1, self.attention_head_size)
+
+ query_states = self.query(hidden_states).view(hidden_shape).transpose(1, 2)
+ key_states = self.key(hidden_states).view(hidden_shape).transpose(1, 2)
+ value_states = self.value(hidden_states).view(hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ 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()
+ return attn_output, attn_weights
+
+
+# Copied from transformers.models.bert.modeling_bert.BertSelfOutput
+class ClapTextSelfOutput(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
+
+
+# Copied from transformers.models.align.modeling_align.AlignTextAttention with Align->Clap
+class ClapTextAttention(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.self = ClapTextSelfAttention(config)
+ self.output = ClapTextSelfOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states, _ = self.self(
+ hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = self.output(hidden_states, residual)
+ return hidden_states
+
+
+# Copied from transformers.models.bert.modeling_bert.BertIntermediate
+class ClapTextIntermediate(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 ClapTextOutput(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.align.modeling_align.AlignTextLayer with Align->Clap
+class ClapTextLayer(GradientCheckpointingLayer):
+ def __init__(self, config):
+ super().__init__()
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
+ self.seq_len_dim = 1
+ self.attention = ClapTextAttention(config)
+ self.intermediate = ClapTextIntermediate(config)
+ self.output = ClapTextOutput(config)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.Tensor:
+ hidden_states = self.attention(
+ hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+
+ hidden_states = apply_chunking_to_forward(
+ self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, hidden_states
+ )
+
+ return hidden_states
+
+ 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.align.modeling_align.AlignTextEncoder with Align->Clap
+class ClapTextEncoder(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.layer = nn.ModuleList([ClapTextLayer(config) for i in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.FloatTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ for layer_module in self.layer:
+ hidden_states = layer_module(
+ hidden_states,
+ attention_mask,
+ **kwargs,
+ )
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ )
+
+
+# Copied from transformers.models.bert.modeling_bert.BertPooler
+class ClapTextPooler(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 ClapPreTrainedModel(PreTrainedModel):
+ config: ClapConfig
+ base_model_prefix = "clap"
+ input_modalities = ("audio", "text")
+ supports_gradient_checkpointing = False
+
+ @torch.no_grad()
+ def _init_weights(self, module: nn.Module):
+ """Initialize the weights"""
+ factor = self.config.initializer_factor
+
+ if isinstance(module, ClapTextEmbeddings):
+ init.normal_(module.position_embeddings.weight, mean=0.0, std=factor * 0.02)
+ init.normal_(module.token_type_embeddings.weight, mean=0.0, std=factor * 0.02)
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ init.zeros_(module.token_type_ids)
+ elif isinstance(module, ClapModel):
+ init.constant_(module.logit_scale_a, math.log(self.config.logit_scale_init_value))
+ init.constant_(module.logit_scale_t, math.log(self.config.logit_scale_init_value))
+ elif isinstance(module, nn.Embedding):
+ init.normal_(module.weight, mean=0.0, std=factor * 0.02)
+ elif isinstance(module, (nn.LayerNorm, nn.BatchNorm2d)):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ if getattr(module, "running_mean", None) is not None:
+ init.zeros_(module.running_mean)
+ init.ones_(module.running_var)
+ init.zeros_(module.num_batches_tracked)
+ elif isinstance(module, (nn.Conv2d, nn.Linear)):
+ in_proj_std = (self.config.hidden_size**-0.5) * ((2 * self.config.num_hidden_layers) ** -0.5) * factor
+ init.normal_(module.weight, std=in_proj_std)
+ if module.bias is not None:
+ init.zeros_(module.bias)
+ elif isinstance(module, ClapAudioSelfAttention):
+ init.zeros_(module.relative_position_bias_table)
+ init.copy_(module.relative_position_index, module.create_relative_position_index())
+
+
+class ClapAudioModel(ClapPreTrainedModel):
+ config: ClapAudioConfig
+ main_input_name = "input_features"
+ input_modalities = "audio"
+
+ def __init__(self, config: ClapAudioConfig):
+ super().__init__(config)
+ self.audio_encoder = ClapAudioEncoder(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.audio_encoder.patch_embed.proj
+
+ @auto_docstring
+ def forward(
+ self,
+ input_features: torch.FloatTensor | None = None,
+ is_longer: torch.BoolTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*):
+ Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance
+ the features.
+
+ Examples:
+
+ ```python
+ >>> from datasets import load_dataset
+ >>> from transformers import AutoProcessor, ClapAudioModel
+
+ >>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example")
+ >>> audio_sample = dataset["train"]["audio"][0]["array"]
+
+ >>> model = ClapAudioModel.from_pretrained("laion/clap-htsat-fused")
+ >>> processor = AutoProcessor.from_pretrained("laion/clap-htsat-fused")
+
+ >>> inputs = processor(audio=audio_sample, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ ```"""
+ return self.audio_encoder(
+ input_features=input_features,
+ is_longer=is_longer,
+ **kwargs,
+ )
+
+
+@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 ClapTextModel(ClapPreTrainedModel):
+ config: ClapTextConfig
+ input_modalities = ("text",)
+ _can_record_outputs = {
+ "hidden_states": ClapTextLayer,
+ "attentions": ClapTextSelfAttention,
+ }
+
+ 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 = ClapTextEmbeddings(config)
+ self.encoder = ClapTextEncoder(config)
+
+ self.pooler = ClapTextPooler(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
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ token_type_ids: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ inputs_embeds: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPooling:
+ 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)
+
+ # 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)
+
+ 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=extended_attention_mask,
+ **kwargs,
+ )
+ sequence_output = encoder_outputs[0]
+ 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,
+ )
+
+
+@auto_docstring
+class ClapModel(ClapPreTrainedModel):
+ config: ClapConfig
+
+ def __init__(self, config: ClapConfig):
+ super().__init__(config)
+
+ if not isinstance(config.text_config, ClapTextConfig):
+ raise TypeError(
+ "config.text_config is expected to be of type ClapTextConfig but is of type"
+ f" {type(config.text_config)}."
+ )
+
+ if not isinstance(config.audio_config, ClapAudioConfig):
+ raise TypeError(
+ "config.audio_config is expected to be of type ClapAudioConfig but is of type"
+ f" {type(config.audio_config)}."
+ )
+
+ text_config = config.text_config
+ audio_config = config.audio_config
+
+ self.logit_scale_a = nn.Parameter(torch.tensor(math.log(config.logit_scale_init_value)))
+ self.logit_scale_t = nn.Parameter(torch.tensor(math.log(config.logit_scale_init_value)))
+
+ self.projection_dim = config.projection_dim
+
+ self.text_model = ClapTextModel(text_config)
+ self.text_projection = ClapProjectionLayer(text_config)
+
+ self.audio_model = ClapAudioModel(audio_config)
+ self.audio_projection = ClapProjectionLayer(audio_config)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def get_text_features(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, ClapModel
+
+ >>> model = ClapModel.from_pretrained("laion/clap-htsat-unfused")
+ >>> tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused")
+
+ >>> inputs = tokenizer(["the sound of a cat", "the sound of a dog"], padding=True, return_tensors="pt")
+ >>> with torch.inference_mode():
+ ... text_features = model.get_text_features(**inputs)
+ ```"""
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ text_features = self.text_projection(text_outputs.pooler_output)
+ text_outputs.pooler_output = F.normalize(text_features, dim=-1)
+
+ return text_outputs
+
+ @can_return_tuple
+ @auto_docstring
+ def get_audio_features(
+ self,
+ input_features: torch.Tensor,
+ is_longer: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*):
+ Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance
+ the features.
+
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoFeatureExtractor, ClapModel
+
+ >>> model = ClapModel.from_pretrained("laion/clap-htsat-unfused")
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("laion/clap-htsat-unfused")
+ >>> random_audio = torch.rand((16_000))
+
+ >>> inputs = feature_extractor(random_audio, return_tensors="pt")
+ >>> with torch.inference_mode():
+ ... audio_features = model.get_audio_features(**inputs)
+ ```"""
+ audio_outputs: BaseModelOutputWithPooling = self.audio_model(
+ input_features=input_features, is_longer=is_longer, **kwargs
+ )
+ audio_features = self.audio_projection(audio_outputs.pooler_output)
+ audio_outputs.pooler_output = F.normalize(audio_features, dim=-1)
+
+ return audio_outputs
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ input_features: torch.FloatTensor | None = None,
+ is_longer: torch.BoolTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ return_loss: bool | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | ClapOutput:
+ r"""
+ is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*):
+ Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance
+ the features.
+ return_loss (`bool`, *optional*):
+ Whether or not to return the contrastive loss.
+
+ Examples:
+
+ ```python
+ >>> from datasets import load_dataset
+ >>> from transformers import AutoProcessor, ClapModel
+
+ >>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example")
+ >>> audio_sample = dataset["train"]["audio"][0]["array"]
+
+ >>> model = ClapModel.from_pretrained("laion/clap-htsat-unfused")
+ >>> processor = AutoProcessor.from_pretrained("laion/clap-htsat-unfused")
+
+ >>> input_text = ["Sound of a dog", "Sound of vacuum cleaner"]
+
+ >>> inputs = processor(text=input_text, audio=audio_sample, return_tensors="pt", padding=True)
+
+ >>> outputs = model(**inputs)
+ >>> logits_per_audio = outputs.logits_per_audio # this is the audio-text similarity score
+ >>> probs = logits_per_audio.softmax(dim=-1) # we can take the softmax to get the label probabilities
+ ```"""
+ audio_outputs = self.audio_model(
+ input_features=input_features,
+ is_longer=is_longer,
+ **kwargs,
+ )
+
+ text_outputs = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ audio_embeds = audio_outputs.pooler_output
+ audio_embeds = self.audio_projection(audio_embeds)
+
+ text_embeds = text_outputs.pooler_output
+ text_embeds = self.text_projection(text_embeds)
+
+ # normalized features
+ audio_embeds = audio_embeds / audio_embeds.norm(p=2, dim=-1, keepdim=True)
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
+
+ # cosine similarity as logits
+ logit_scale_text = self.logit_scale_t.exp()
+ logit_scale_audio = self.logit_scale_a.exp()
+ logits_per_text = torch.matmul(text_embeds, audio_embeds.t()) * logit_scale_text
+ logits_per_audio = torch.matmul(audio_embeds, text_embeds.t()) * logit_scale_audio
+
+ loss = None
+ if return_loss:
+ caption_loss = contrastive_loss(logits_per_text)
+ audio_loss = contrastive_loss(logits_per_audio.t())
+ loss = (caption_loss + audio_loss) / 2.0
+
+ return ClapOutput(
+ loss=loss,
+ logits_per_audio=logits_per_audio,
+ logits_per_text=logits_per_text,
+ text_embeds=text_embeds,
+ audio_embeds=audio_embeds,
+ text_model_output=text_outputs,
+ audio_model_output=audio_outputs,
+ )
+
+
+@auto_docstring
+class ClapTextModelWithProjection(ClapPreTrainedModel):
+ config: ClapTextConfig
+ input_modalities = ("text",)
+ _can_record_outputs = {
+ "hidden_states": ClapTextLayer,
+ "attentions": ClapTextSelfAttention,
+ }
+
+ def __init__(self, config: ClapTextConfig):
+ super().__init__(config)
+ self.text_model = ClapTextModel(config)
+ self.text_projection = ClapProjectionLayer(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.text_model.embeddings.word_embeddings
+
+ def set_input_embeddings(self, value):
+ self.text_model.embeddings.word_embeddings = value
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | ClapTextModelOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, ClapTextModelWithProjection
+
+ >>> model = ClapTextModelWithProjection.from_pretrained("laion/clap-htsat-unfused")
+ >>> tokenizer = AutoTokenizer.from_pretrained("laion/clap-htsat-unfused")
+
+ >>> inputs = tokenizer(["a sound of a cat", "a sound of a dog"], padding=True, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> text_embeds = outputs.text_embeds
+ ```"""
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ pooled_output = text_outputs.pooler_output
+ text_embeds = self.text_projection(pooled_output)
+
+ return ClapTextModelOutput(
+ text_embeds=text_embeds,
+ last_hidden_state=text_outputs.last_hidden_state,
+ hidden_states=text_outputs.hidden_states,
+ attentions=text_outputs.attentions,
+ )
+
+
+@auto_docstring
+class ClapAudioModelWithProjection(ClapPreTrainedModel):
+ config: ClapAudioConfig
+ main_input_name = "input_features"
+ input_modalities = "audio"
+
+ def __init__(self, config: ClapAudioConfig):
+ super().__init__(config)
+ self.audio_model = ClapAudioModel(config)
+ self.audio_projection = ClapProjectionLayer(config)
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.audio_model.audio_encoder.patch_embed.proj
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_features: torch.FloatTensor | None = None,
+ is_longer: torch.BoolTensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | ClapAudioModelOutput:
+ r"""
+ is_longer (`torch.FloatTensor`, of shape `(batch_size, 1)`, *optional*):
+ Whether the audio clip is longer than `max_length`. If `True`, a feature fusion will be enabled to enhance
+ the features.
+
+ Examples:
+
+ ```python
+ >>> from datasets import load_dataset
+ >>> from transformers import ClapAudioModelWithProjection, ClapProcessor
+
+ >>> model = ClapAudioModelWithProjection.from_pretrained("laion/clap-htsat-fused")
+ >>> processor = ClapProcessor.from_pretrained("laion/clap-htsat-fused")
+
+ >>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example")
+ >>> audio_sample = dataset["train"]["audio"][0]["array"]
+
+ >>> inputs = processor(audio=audio_sample, return_tensors="pt")
+ >>> outputs = model(**inputs)
+ >>> audio_embeds = outputs.audio_embeds
+ ```"""
+ audio_outputs: BaseModelOutputWithPooling = self.audio_model(
+ input_features=input_features,
+ is_longer=is_longer,
+ **kwargs,
+ )
+
+ audio_embeds = self.audio_projection(audio_outputs.pooler_output)
+
+ return ClapAudioModelOutput(
+ audio_embeds=audio_embeds,
+ last_hidden_state=audio_outputs.last_hidden_state,
+ attentions=audio_outputs.attentions,
+ hidden_states=audio_outputs.hidden_states,
+ )
+
+
+__all__ = [
+ "ClapModel",
+ "ClapPreTrainedModel",
+ "ClapTextModel",
+ "ClapTextModelWithProjection",
+ "ClapAudioModel",
+ "ClapAudioModelWithProjection",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clap/processing_clap.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clap/processing_clap.py
new file mode 100644
index 0000000000000000000000000000000000000000..567aa19ce60775e9f14ed220f4edecb910cf1c21
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clap/processing_clap.py
@@ -0,0 +1,31 @@
+# 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.
+"""
+Audio/Text processor class for CLAP
+"""
+
+from ...processing_utils import ProcessorMixin
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring
+class ClapProcessor(ProcessorMixin):
+ def __init__(self, feature_extractor, tokenizer):
+ super().__init__(feature_extractor, tokenizer)
+
+
+__all__ = ["ClapProcessor"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b3554d4ac39ae7b8316c59457058222f1b38dd42
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/__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_clip import *
+ from .image_processing_clip import *
+ from .image_processing_pil_clip import *
+ from .modeling_clip import *
+ from .processing_clip import *
+ from .tokenization_clip import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/configuration_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/configuration_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..dec74a2b75c66f177ad7001bcf4ae22b4bfe42c1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/configuration_clip.py
@@ -0,0 +1,248 @@
+# 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.
+"""CLIP model configuration"""
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="openai/clip-vit-base-patch32")
+@strict
+class CLIPTextConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import CLIPTextConfig, CLIPTextModel
+
+ >>> # Initializing a CLIPTextConfig with openai/clip-vit-base-patch32 style configuration
+ >>> configuration = CLIPTextConfig()
+
+ >>> # Initializing a CLIPTextModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
+ >>> model = CLIPTextModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "clip_text_model"
+ base_config_key = "text_config"
+
+ vocab_size: int = 49408
+ hidden_size: int = 512
+ intermediate_size: int = 2048
+ projection_dim: int | None = 512
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 8
+ max_position_embeddings: int = 77
+ hidden_act: str = "quick_gelu"
+ layer_norm_eps: float | None = 1e-5
+ attention_dropout: int | float | None = 0.0
+ initializer_range: float = 0.02
+ initializer_factor: float | None = 1.0
+
+ # This differs from `CLIPTokenizer`'s default and from openai/clip
+ # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 49406
+ eos_token_id: int | list[int] | None = 49407
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.hidden_size % self.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({self.num_attention_heads})."
+ )
+
+
+@auto_docstring(checkpoint="openai/clip-vit-base-patch32")
+@strict
+class CLIPVisionConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import CLIPVisionConfig, CLIPVisionModel
+
+ >>> # Initializing a CLIPVisionConfig with openai/clip-vit-base-patch32 style configuration
+ >>> configuration = CLIPVisionConfig()
+
+ >>> # Initializing a CLIPVisionModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
+ >>> model = CLIPVisionModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "clip_vision_model"
+ base_config_key = "vision_config"
+
+ hidden_size: int = 768
+ intermediate_size: int = 3072
+ projection_dim: int = 512
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ num_channels: int = 3
+ image_size: int | list[int] | tuple[int, int] | None = 224
+ patch_size: int | list[int] | tuple[int, int] | None = 32
+ hidden_act: str = "quick_gelu"
+ layer_norm_eps: float = 1e-5
+ attention_dropout: int | float | None = 0.0
+ initializer_range: float = 0.02
+ initializer_factor: float = 1.0
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.hidden_size % self.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({self.num_attention_heads})."
+ )
+
+
+@auto_docstring(checkpoint="openai/clip-vit-base-patch32")
+@strict
+class CLIPConfig(PreTrainedConfig):
+ r"""
+ text_config (`dict`, *optional*):
+ Dictionary of configuration options used to initialize [`CLIPTextConfig`].
+ vision_config (`dict`, *optional*):
+ Dictionary of configuration options used to initialize [`CLIPVisionConfig`].
+ logit_scale_init_value (`float | int`, *optional*, defaults to 2.6592):
+ The initial value of the *logit_scale* parameter. Default is used as per the original CLIP implementation.
+
+ Example:
+
+ ```python
+ >>> from transformers import CLIPConfig, CLIPModel
+
+ >>> # Initializing a CLIPConfig with openai/clip-vit-base-patch32 style configuration
+ >>> configuration = CLIPConfig()
+
+ >>> # Initializing a CLIPModel (with random weights) from the openai/clip-vit-base-patch32 style configuration
+ >>> model = CLIPModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+
+ >>> # We can also initialize a CLIPConfig from a CLIPTextConfig and a CLIPVisionConfig
+ >>> from transformers import CLIPTextConfig, CLIPVisionConfig
+
+ >>> # Initializing a CLIPText and CLIPVision configuration
+ >>> config_text = CLIPTextConfig()
+ >>> config_vision = CLIPVisionConfig()
+
+ >>> config = CLIPConfig(text_config=config_text, vision_config=config_vision)
+ ```"""
+
+ model_type = "clip"
+ sub_configs = {"text_config": CLIPTextConfig, "vision_config": CLIPVisionConfig}
+
+ text_config: dict | CLIPTextConfig | None = None
+ vision_config: dict | CLIPVisionConfig | None = None
+ projection_dim: int | None = 512
+ logit_scale_init_value: float | int | None = 2.6592
+ initializer_factor: float | None = 1.0
+
+ def __post_init__(self, **kwargs):
+ if self.text_config is None:
+ text_config = {}
+ logger.info("`text_config` is `None`. Initializing the `CLIPTextConfig` with default values.")
+ elif isinstance(self.text_config, CLIPTextConfig):
+ text_config = self.text_config.to_dict()
+ else:
+ text_config = self.text_config
+
+ if self.vision_config is None:
+ vision_config = {}
+ logger.info("`vision_config` is `None`. initializing the `CLIPVisionConfig` with default values.")
+ elif isinstance(self.vision_config, CLIPVisionConfig):
+ vision_config = self.vision_config.to_dict()
+ else:
+ vision_config = self.vision_config
+
+ # For backward compatibility check keyword args
+ # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
+ # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
+ # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
+ text_config_dict = kwargs.pop("text_config_dict", None)
+ vision_config_dict = kwargs.pop("vision_config_dict", None)
+
+ if text_config_dict is not None:
+ # This is the complete result when using `text_config_dict`.
+ _text_config_dict = CLIPTextConfig(**text_config_dict).to_dict()
+
+ # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
+ for key, value in _text_config_dict.items():
+ if key in text_config and value != text_config[key] and key != "transformers_version":
+ # If specified in `text_config_dict`
+ if key in text_config_dict:
+ message = (
+ f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
+ f'The value `text_config_dict["{key}"]` will be used instead.'
+ )
+ # If inferred from default argument values (just to be super careful)
+ else:
+ message = (
+ f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The "
+ f'value `text_config["{key}"]` will be overridden.'
+ )
+ logger.info(message)
+
+ # Update all values in `text_config` with the ones in `_text_config_dict`.
+ text_config.update(_text_config_dict)
+
+ if vision_config_dict is not None:
+ # This is the complete result when using `vision_config_dict`.
+ _vision_config_dict = CLIPVisionConfig(**vision_config_dict).to_dict()
+ # convert keys to string instead of integer
+ if "id2label" in _vision_config_dict:
+ _vision_config_dict["id2label"] = {
+ str(key): value for key, value in _vision_config_dict["id2label"].items()
+ }
+
+ # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
+ for key, value in _vision_config_dict.items():
+ if key in vision_config and value != vision_config[key] and key != "transformers_version":
+ # If specified in `vision_config_dict`
+ if key in vision_config_dict:
+ message = (
+ f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
+ f'values. The value `vision_config_dict["{key}"]` will be used instead.'
+ )
+ # If inferred from default argument values (just to be super careful)
+ else:
+ message = (
+ f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. "
+ f'The value `vision_config["{key}"]` will be overridden.'
+ )
+ logger.info(message)
+
+ # Update all values in `vision_config` with the ones in `_vision_config_dict`.
+ vision_config.update(_vision_config_dict)
+
+ # Finally we can convert back our unified text/vision configs to `PretrainedConfig`
+ self.text_config = CLIPTextConfig(**text_config)
+ self.vision_config = CLIPVisionConfig(**vision_config)
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["CLIPConfig", "CLIPTextConfig", "CLIPVisionConfig"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..d79b1a716b02e38e94f84e3ae7f89a47062e858d
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_clip.py
@@ -0,0 +1,45 @@
+# 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.
+"""Image processor class for CLIP."""
+
+from ...image_processing_backends import TorchvisionBackend
+from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import auto_docstring
+
+
+@auto_docstring
+class CLIPImageProcessor(TorchvisionBackend):
+ resample = PILImageResampling.BICUBIC
+ image_mean = OPENAI_CLIP_MEAN
+ image_std = OPENAI_CLIP_STD
+ size = {"shortest_edge": 224}
+ default_to_square = False
+ crop_size = {"height": 224, "width": 224}
+ do_resize = True
+ do_center_crop = True
+ do_rescale = True
+ do_normalize = True
+ do_convert_rgb = True
+
+ def __init__(self, **kwargs: Unpack[ImagesKwargs]):
+ # for backwards compatibility of KOSMOS-2
+ if "use_square_size" in kwargs and kwargs["use_square_size"]:
+ kwargs["size"] = {"height": self.size["shortest_edge"], "width": self.size["shortest_edge"]}
+ kwargs.pop("use_square_size")
+
+ super().__init__(**kwargs)
+
+
+__all__ = ["CLIPImageProcessor"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_pil_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_pil_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..228309ec0557196877d9585ed872bf036dbcc1d1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/image_processing_pil_clip.py
@@ -0,0 +1,45 @@
+# 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.
+"""Image processor class for CLIP."""
+
+from ...image_processing_backends import PilBackend
+from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling
+from ...processing_utils import ImagesKwargs, Unpack
+from ...utils import auto_docstring
+
+
+@auto_docstring
+class CLIPImageProcessorPil(PilBackend):
+ resample = PILImageResampling.BICUBIC
+ image_mean = OPENAI_CLIP_MEAN
+ image_std = OPENAI_CLIP_STD
+ size = {"shortest_edge": 224}
+ default_to_square = False
+ crop_size = {"height": 224, "width": 224}
+ do_resize = True
+ do_center_crop = True
+ do_rescale = True
+ do_normalize = True
+ do_convert_rgb = True
+
+ def __init__(self, **kwargs: Unpack[ImagesKwargs]):
+ # for backwards compatibility of KOSMOS-2
+ if "use_square_size" in kwargs and kwargs["use_square_size"]:
+ kwargs["size"] = {"height": self.size["shortest_edge"], "width": self.size["shortest_edge"]}
+ kwargs.pop("use_square_size")
+
+ super().__init__(**kwargs)
+
+
+__all__ = ["CLIPImageProcessorPil"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/modeling_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/modeling_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b2e983c78ba7416a24f2783cfc7cededb6a3533
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/modeling_clip.py
@@ -0,0 +1,1035 @@
+# Copyright 2021 The OpenAI Team Authors 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.
+"""PyTorch CLIP model."""
+
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...masking_utils import create_causal_mask
+from ...modeling_layers import GradientCheckpointingLayer
+from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
+from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
+from ...processing_utils import Unpack
+from ...utils import (
+ ModelOutput,
+ TransformersKwargs,
+ auto_docstring,
+ logging,
+ torch_int,
+)
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_clip import CLIPConfig, CLIPTextConfig, CLIPVisionConfig
+
+
+logger = logging.get_logger(__name__)
+
+
+# contrastive loss function, adapted from
+# https://sachinruk.github.io/blog/2021-03-07-clip.html
+def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
+ return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
+
+
+def image_text_contrastive_loss(similarity: torch.Tensor) -> torch.Tensor:
+ caption_loss = contrastive_loss(similarity)
+ image_loss = contrastive_loss(similarity.T)
+ return (caption_loss + image_loss) / 2.0
+
+
+def _get_vector_norm(tensor: torch.Tensor) -> torch.Tensor:
+ """
+ This method is equivalent to tensor.norm(p=2, dim=-1, keepdim=True) and used to make
+ model `executorch` exportable. See issue https://github.com/pytorch/executorch/issues/3566
+ """
+ square_tensor = torch.pow(tensor, 2)
+ sum_tensor = torch.sum(square_tensor, dim=-1, keepdim=True)
+ normed_tensor = torch.pow(sum_tensor, 0.5)
+ return normed_tensor
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.
+ """
+)
+@dataclass
+class CLIPVisionModelOutput(ModelOutput):
+ r"""
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
+ The image embeddings obtained by applying the projection layer to the pooler_output.
+ """
+
+ image_embeds: torch.FloatTensor | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@auto_docstring(
+ custom_intro="""
+ Base class for text model's outputs that also contains a pooling of the last hidden states.
+ """
+)
+@dataclass
+class CLIPTextModelOutput(ModelOutput):
+ r"""
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
+ The text embeddings obtained by applying the projection layer to the pooler_output.
+ """
+
+ text_embeds: torch.FloatTensor | None = None
+ last_hidden_state: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@dataclass
+@auto_docstring
+class CLIPOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
+ Contrastive loss for image-text similarity.
+ logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
+ similarity scores.
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
+ similarity scores.
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The text embeddings obtained by applying the projection layer to the pooled output of [`CLIPTextModel`].
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPVisionModel`].
+ text_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`CLIPTextModel`].
+ vision_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`CLIPVisionModel`].
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits_per_image: torch.FloatTensor | None = None
+ logits_per_text: torch.FloatTensor | None = None
+ text_embeds: torch.FloatTensor | None = None
+ image_embeds: torch.FloatTensor | None = None
+ text_model_output: BaseModelOutputWithPooling = None
+ vision_model_output: BaseModelOutputWithPooling = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(v.to_tuple() if isinstance(v, ModelOutput) else v for v in self.values())
+
+
+class CLIPVisionEmbeddings(nn.Module):
+ def __init__(self, config: CLIPVisionConfig):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.image_size = config.image_size
+ self.patch_size = config.patch_size
+
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
+
+ self.patch_embedding = nn.Conv2d(
+ in_channels=config.num_channels,
+ out_channels=self.embed_dim,
+ kernel_size=self.patch_size,
+ stride=self.patch_size,
+ bias=False,
+ )
+
+ self.num_patches = (self.image_size // self.patch_size) ** 2
+ self.num_positions = self.num_patches + 1
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
+
+ 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
+ position_embedding = self.position_embedding.weight.unsqueeze(0)
+ num_positions = position_embedding.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_embedding(self.position_ids)
+
+ class_pos_embed = position_embedding[:, :1]
+ patch_pos_embed = position_embedding[:, 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.FloatTensor, interpolate_pos_encoding=False) -> torch.Tensor:
+ batch_size, _, height, width = pixel_values.shape
+ if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
+ raise ValueError(
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size}*{self.image_size})."
+ )
+ target_dtype = self.patch_embedding.weight.dtype
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
+
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
+ if interpolate_pos_encoding:
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
+ else:
+ embeddings = embeddings + self.position_embedding(self.position_ids)
+ return embeddings
+
+
+class CLIPTextEmbeddings(nn.Module):
+ def __init__(self, config: CLIPTextConfig):
+ super().__init__()
+ embed_dim = config.hidden_size
+
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
+
+ # 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
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ ) -> torch.Tensor:
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
+ max_position_embedding = self.position_embedding.weight.shape[0]
+
+ if seq_length > max_position_embedding:
+ raise ValueError(
+ f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
+ f"{seq_length} and max_position_embeddings: {max_position_embedding}"
+ )
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, :seq_length]
+
+ if inputs_embeds is None:
+ inputs_embeds = self.token_embedding(input_ids)
+
+ position_embeddings = self.position_embedding(position_ids)
+ embeddings = inputs_embeds + position_embeddings
+
+ return embeddings
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_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)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+ return attn_output, attn_weights
+
+
+class CLIPAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: CLIPVisionConfig | CLIPTextConfig):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.embed_dim // self.num_heads
+ self.scale = self.head_dim**-0.5
+ self.dropout = config.attention_dropout
+ self.is_causal = False
+
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.head_dim)
+ queries = self.q_proj(hidden_states)
+ keys = self.k_proj(hidden_states)
+ values = self.v_proj(hidden_states)
+
+ queries = queries.view(hidden_shape).transpose(1, 2)
+ keys = keys.view(hidden_shape).transpose(1, 2)
+ values = values.view(hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ queries,
+ keys,
+ values,
+ attention_mask,
+ scaling=self.scale,
+ dropout=0.0 if not self.training else self.dropout,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class CLIPMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[config.hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class CLIPEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: CLIPVisionConfig | CLIPTextConfig):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+ self.self_attn = CLIPAttention(config)
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.mlp = CLIPMLP(config)
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+@auto_docstring
+class CLIPPreTrainedModel(PreTrainedModel):
+ config: CLIPConfig
+ base_model_prefix = "clip"
+ input_modalities = ("image", "text")
+ _no_split_modules = ["CLIPTextEmbeddings", "CLIPEncoderLayer", "CLIPVisionEmbeddings"]
+
+ supports_gradient_checkpointing = True
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": CLIPEncoderLayer,
+ "attentions": CLIPAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ factor = self.config.initializer_factor
+ if isinstance(module, CLIPTextEmbeddings):
+ init.normal_(module.token_embedding.weight, mean=0.0, std=factor * 0.02)
+ init.normal_(module.position_embedding.weight, mean=0.0, std=factor * 0.02)
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ elif isinstance(module, CLIPVisionEmbeddings):
+ init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
+ init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
+ init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
+ init.copy_(module.position_ids, torch.arange(module.num_positions).expand((1, -1)))
+ elif isinstance(module, CLIPAttention):
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ out_proj_std = (module.embed_dim**-0.5) * factor
+ init.normal_(module.q_proj.weight, std=in_proj_std)
+ init.normal_(module.k_proj.weight, std=in_proj_std)
+ init.normal_(module.v_proj.weight, std=in_proj_std)
+ init.normal_(module.out_proj.weight, std=out_proj_std)
+ elif isinstance(module, CLIPMLP):
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
+ init.normal_(module.fc1.weight, std=fc_std)
+ init.normal_(module.fc2.weight, std=in_proj_std)
+ elif isinstance(module, CLIPModel):
+ init.normal_(
+ module.text_projection.weight,
+ std=module.text_embed_dim**-0.5 * factor,
+ )
+ init.normal_(
+ module.visual_projection.weight,
+ std=module.vision_embed_dim**-0.5 * factor,
+ )
+ elif isinstance(module, CLIPVisionModelWithProjection):
+ init.normal_(
+ module.visual_projection.weight,
+ std=self.config.hidden_size**-0.5 * factor,
+ )
+ elif isinstance(module, CLIPTextModelWithProjection):
+ init.normal_(
+ module.text_projection.weight,
+ std=self.config.hidden_size**-0.5 * factor,
+ )
+ elif isinstance(module, CLIPForImageClassification):
+ init.normal_(
+ module.classifier.weight,
+ std=self.config.vision_config.hidden_size**-0.5 * factor,
+ )
+
+ if isinstance(module, nn.LayerNorm):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ if isinstance(module, nn.Linear) and module.bias is not None:
+ init.zeros_(module.bias)
+
+
+class CLIPEncoder(nn.Module):
+ """
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
+ [`CLIPEncoderLayer`].
+
+ Args:
+ config: CLIPConfig
+ """
+
+ def __init__(self, config: CLIPConfig):
+ super().__init__()
+ self.config = config
+ self.layers = nn.ModuleList([CLIPEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ inputs_embeds,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ hidden_states = inputs_embeds
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(
+ hidden_states,
+ attention_mask,
+ **kwargs,
+ )
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The text model from CLIP without any head or projection on top.
+ """
+)
+class CLIPTextModel(CLIPPreTrainedModel):
+ config: CLIPTextConfig
+ input_modalities = ("text",)
+ _input_embed_layer = "token_embedding"
+
+ def __init__(self, config: CLIPTextConfig):
+ super().__init__(config)
+ embed_dim = config.hidden_size
+ self.embeddings = CLIPTextEmbeddings(config)
+ self.encoder = CLIPEncoder(config)
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+
+ # For `pooled_output` computation
+ self.eos_token_id = config.eos_token_id
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, CLIPTextModel
+
+ >>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
+ ```"""
+ if input_ids is None:
+ raise ValueError("You have to specify input_ids")
+
+ input_shape = input_ids.size()
+ input_ids = input_ids.view(-1, input_shape[-1])
+
+ hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
+
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ )
+
+ kwargs.pop("is_causal", None)
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ is_causal=True,
+ **kwargs,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
+
+ if self.eos_token_id == 2:
+ # The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here.
+ # A CLIP model with such `eos_token_id` in the config can't work correctly with extra new tokens added
+ # ------------------------------------------------------------
+ # text_embeds.shape = [batch_size, sequence_length, transformer.width]
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
+ # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
+ pooled_output = last_hidden_state[
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
+ input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
+ ]
+ else:
+ # The config gets updated `eos_token_id` from PR #24773 (so the use of extra new tokens is possible)
+ pooled_output = last_hidden_state[
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
+ # We need to get the first position of `eos_token_id` value (`pad_token_ids` might equal to `eos_token_id`)
+ # Note: we assume each sequence (along batch dim.) contains an `eos_token_id` (e.g. prepared by the tokenizer)
+ (input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.eos_token_id)
+ .int()
+ .argmax(dim=-1),
+ ]
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The vision model from CLIP without any head or projection on top.
+ """
+)
+class CLIPVisionModel(CLIPPreTrainedModel):
+ config: CLIPVisionConfig
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _input_embed_layer = "patch_embedding"
+
+ def __init__(self, config: CLIPVisionConfig):
+ super().__init__(config)
+ embed_dim = config.hidden_size
+
+ self.embeddings = CLIPVisionEmbeddings(config)
+ self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.encoder = CLIPEncoder(config)
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ interpolate_pos_encoding: bool | None = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutputWithPooling:
+ r"""
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from transformers import AutoProcessor, CLIPVisionModel
+
+ >>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ >>> pooled_output = outputs.pooler_output # pooled CLS states
+ ```"""
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
+ hidden_states = self.pre_layrnorm(hidden_states)
+
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ **kwargs,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ pooled_output = last_hidden_state[:, 0, :]
+ pooled_output = self.post_layernorm(pooled_output)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+
+@auto_docstring
+class CLIPModel(CLIPPreTrainedModel):
+ def __init__(self, config: CLIPConfig):
+ super().__init__(config)
+
+ text_config = config.text_config
+ vision_config = config.vision_config
+
+ self.projection_dim = config.projection_dim
+ self.text_embed_dim = text_config.hidden_size
+ self.vision_embed_dim = vision_config.hidden_size
+
+ self.text_model = CLIPTextModel._from_config(text_config)
+ self.vision_model = CLIPVisionModel._from_config(vision_config)
+
+ self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
+ self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def get_text_features(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, CLIPModel
+
+ >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+
+ >>> with torch.inference_mode():
+ ... text_features = model.get_text_features(**inputs)
+ ```"""
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = text_outputs.pooler_output
+ text_outputs.pooler_output = self.text_projection(pooled_output)
+
+ return text_outputs
+
+ @can_return_tuple
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, CLIPModel
+ >>> from transformers.image_utils import load_image
+
+ >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+
+ >>> with torch.inference_mode():
+ ... image_features = model.get_image_features(**inputs)
+ ```"""
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = vision_outputs.pooler_output
+ vision_outputs.pooler_output = self.visual_projection(pooled_output)
+
+ return vision_outputs
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ return_loss: bool | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CLIPOutput:
+ r"""
+ return_loss (`bool`, *optional*):
+ Whether or not to return the contrastive loss.
+
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, CLIPModel
+ >>> from transformers.image_utils import load_image
+
+ >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> inputs = processor(
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
+ ... )
+
+ >>> with torch.inference_mode():
+ ... outputs = model(**inputs)
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
+ ```"""
+ vision_outputs: BaseModelOutputWithPooling = self.get_image_features(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+
+ text_outputs: BaseModelOutputWithPooling = self.get_text_features(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ image_embeds = vision_outputs.pooler_output
+ text_embeds = text_outputs.pooler_output
+
+ # normalized features
+ image_embeds = image_embeds / _get_vector_norm(image_embeds)
+ text_embeds = text_embeds / _get_vector_norm(text_embeds)
+
+ # cosine similarity as logits
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device))
+ logits_per_text = logits_per_text * self.logit_scale.exp().to(text_embeds.device)
+
+ logits_per_image = logits_per_text.t()
+
+ loss = None
+ if return_loss:
+ loss = image_text_contrastive_loss(logits_per_text)
+
+ return CLIPOutput(
+ loss=loss,
+ logits_per_image=logits_per_image,
+ logits_per_text=logits_per_text,
+ text_embeds=text_embeds,
+ image_embeds=image_embeds,
+ text_model_output=text_outputs,
+ vision_model_output=vision_outputs,
+ )
+
+
+@auto_docstring
+class CLIPTextModelWithProjection(CLIPPreTrainedModel):
+ config: CLIPTextConfig
+ input_modalities = ("text",)
+
+ def __init__(self, config: CLIPTextConfig):
+ super().__init__(config)
+
+ self.text_model = CLIPTextModel._from_config(config)
+ self.text_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.text_model.embeddings.token_embedding
+
+ def set_input_embeddings(self, value):
+ self.text_model.embeddings.token_embedding = value
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CLIPTextModelOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, CLIPTextModelWithProjection
+
+ >>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
+ >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+
+ >>> with torch.inference_mode():
+ ... outputs = model(**inputs)
+ >>> text_embeds = outputs.text_embeds
+ ```"""
+
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ **kwargs,
+ )
+ pooled_output = text_outputs.pooler_output
+ text_embeds = self.text_projection(pooled_output)
+
+ return CLIPTextModelOutput(
+ text_embeds=text_embeds,
+ last_hidden_state=text_outputs.last_hidden_state,
+ hidden_states=text_outputs.hidden_states,
+ attentions=text_outputs.attentions,
+ )
+
+
+@auto_docstring
+class CLIPVisionModelWithProjection(CLIPPreTrainedModel):
+ config: CLIPVisionConfig
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+
+ def __init__(self, config: CLIPVisionConfig):
+ super().__init__(config)
+
+ self.vision_model = CLIPVisionModel._from_config(config)
+ self.visual_projection = nn.Linear(config.hidden_size, config.projection_dim, bias=False)
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ def get_input_embeddings(self) -> nn.Module:
+ return self.vision_model.embeddings.patch_embedding
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None = None,
+ interpolate_pos_encoding: bool = False,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CLIPVisionModelOutput:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, CLIPVisionModelWithProjection
+ >>> from transformers.image_utils import load_image
+
+ >>> model = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
+ >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+
+ >>> with torch.inference_mode():
+ ... outputs = model(**inputs)
+ >>> image_embeds = outputs.image_embeds
+ ```"""
+
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+ pooled_output = vision_outputs.pooler_output
+ image_embeds = self.visual_projection(pooled_output)
+
+ return CLIPVisionModelOutput(
+ image_embeds=image_embeds,
+ last_hidden_state=vision_outputs.last_hidden_state,
+ hidden_states=vision_outputs.hidden_states,
+ attentions=vision_outputs.attentions,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ CLIP vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of
+ the patch tokens) e.g. for ImageNet.
+ """
+)
+class CLIPForImageClassification(CLIPPreTrainedModel):
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+
+ def __init__(self, config: CLIPConfig) -> None:
+ super().__init__(config)
+
+ self.num_labels = config.num_labels
+ self.vision_model = CLIPVisionModel._from_config(config.vision_config)
+
+ # Classifier head
+ self.classifier = (
+ nn.Linear(config.vision_config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
+ )
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.Tensor | None = None,
+ labels: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> 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).
+ """
+ outputs: BaseModelOutputWithPooling = self.vision_model(
+ pixel_values,
+ **kwargs,
+ )
+
+ sequence_output = outputs.last_hidden_state
+
+ sequence_output = torch.mean(sequence_output[:, 1:, :], dim=1)
+ logits = self.classifier(sequence_output)
+
+ loss = None
+ if labels is not None:
+ loss = self.loss_function(labels, logits, self.config)
+
+ return ImageClassifierOutput(
+ loss=loss,
+ logits=logits,
+ hidden_states=outputs.hidden_states,
+ attentions=outputs.attentions,
+ )
+
+
+__all__ = [
+ "CLIPModel",
+ "CLIPPreTrainedModel",
+ "CLIPTextModel",
+ "CLIPTextModelWithProjection",
+ "CLIPVisionModel",
+ "CLIPVisionModelWithProjection",
+ "CLIPForImageClassification",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/processing_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/processing_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..f69b275c48b248f1e35419ba4f174f5a75d04f21
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/processing_clip.py
@@ -0,0 +1,28 @@
+# 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.
+"""
+Image/Text processor class for CLIP
+"""
+
+from ...processing_utils import ProcessorMixin
+from ...utils import auto_docstring
+
+
+@auto_docstring
+class CLIPProcessor(ProcessorMixin):
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
+ super().__init__(image_processor, tokenizer)
+
+
+__all__ = ["CLIPProcessor"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/tokenization_clip.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/tokenization_clip.py
new file mode 100644
index 0000000000000000000000000000000000000000..018c630afbce1cc439477a94779044a2e724a7c5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clip/tokenization_clip.py
@@ -0,0 +1,142 @@
+# Copyright 2021 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 CLIP."""
+
+from tokenizers import Regex, Tokenizer, decoders, normalizers, pre_tokenizers, processors
+from tokenizers.models import BPE
+
+from ...tokenization_utils_tokenizers import TokenizersBackend
+from ...utils import logging
+
+
+logger = logging.get_logger(__name__)
+
+VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
+
+
+class CLIPTokenizer(TokenizersBackend):
+ """
+ Construct a CLIP tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
+ Byte-Pair-Encoding.
+
+ This tokenizer inherits from [`TokenizersBackend`] which contains most of the main methods. Users should
+ refer to this superclass for more information regarding those methods.
+
+ Args:
+ vocab (`str`, `dict` or `list`, *optional*):
+ Vocabulary dict to use for the tokenizer.
+ merges (`str` or `list`, *optional*):
+ Merges list to use for the BPE tokenizer.
+ 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.
+ bos_token (`str`, *optional*, defaults to `"<|startoftext|>"`):
+ The beginning of sequence token.
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
+ The end of sequence token.
+ pad_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
+ The token used for padding, for example when batching sequences of different lengths.
+ """
+
+ vocab_files_names = VOCAB_FILES_NAMES
+ model_input_names = ["input_ids", "attention_mask"]
+ model = BPE
+
+ def __init__(
+ self,
+ vocab: str | dict[str, int] | None = None,
+ merges: str | list[str] | None = None,
+ unk_token: str = "<|endoftext|>",
+ bos_token: str = "<|startoftext|>",
+ eos_token: str = "<|endoftext|>",
+ pad_token: str = "<|endoftext|>",
+ **kwargs,
+ ):
+ _vocab = (
+ vocab
+ if vocab is not None
+ else {
+ str(bos_token): 0,
+ str(eos_token): 1,
+ str(pad_token): 2,
+ }
+ )
+
+ self._merges = merges or []
+
+ self._tokenizer = Tokenizer(
+ BPE(
+ vocab=_vocab,
+ merges=self._merges,
+ dropout=None,
+ continuing_subword_prefix="",
+ end_of_word_suffix="",
+ fuse_unk=False,
+ unk_token=str(unk_token),
+ )
+ )
+
+ self._tokenizer.normalizer = normalizers.Sequence(
+ [normalizers.NFC(), normalizers.Replace(Regex(r"\s+"), " "), normalizers.Lowercase()]
+ )
+
+ self._tokenizer.pre_tokenizer = pre_tokenizers.Sequence(
+ [
+ pre_tokenizers.Split(
+ Regex(
+ r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+"""
+ ),
+ behavior="removed",
+ invert=True,
+ ),
+ pre_tokenizers.ByteLevel(add_prefix_space=False),
+ ]
+ )
+
+ self._tokenizer.decoder = decoders.ByteLevel()
+
+ super().__init__(
+ unk_token=unk_token,
+ bos_token=bos_token,
+ eos_token=eos_token,
+ pad_token=pad_token,
+ **kwargs,
+ )
+
+ self._tokenizer.post_processor = processors.RobertaProcessing(
+ sep=(str(eos_token), self.eos_token_id),
+ cls=(str(bos_token), self.bos_token_id),
+ add_prefix_space=False,
+ trim_offsets=False,
+ )
+
+ # Very ugly hack to enable padding to have a correct decoding see https://github.com/huggingface/tokenizers/issues/872
+ self._wrap_decode_method_backend_tokenizer()
+
+ def _wrap_decode_method_backend_tokenizer(self):
+ orig_decode_method = self.backend_tokenizer.decode
+
+ ## define this as a local variable to avoid circular reference
+ ## See: https://github.com/huggingface/transformers/issues/30930
+ end_of_word_suffix = self.backend_tokenizer.model.end_of_word_suffix
+
+ def new_decode_method(*args, **kwargs):
+ text = orig_decode_method(*args, **kwargs)
+ text = text.replace(end_of_word_suffix, " ").strip()
+ return text
+
+ self.backend_tokenizer.decode = new_decode_method
+
+
+__all__ = ["CLIPTokenizer"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..55b38987fd0a3e443b8ae94ffbdd6f73c79ba619
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/__init__.py
@@ -0,0 +1,28 @@
+# 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_clipseg import *
+ from .modeling_clipseg import *
+ from .processing_clipseg import *
+else:
+ import sys
+
+ _file = globals()["__file__"]
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/configuration_clipseg.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/configuration_clipseg.py
new file mode 100644
index 0000000000000000000000000000000000000000..8964ab511d1091f6a18118fba31485c2ab2a403f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/configuration_clipseg.py
@@ -0,0 +1,262 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/clipseg/modular_clipseg.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_clipseg.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2022 The OpenAI Team Authors 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 huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="CIDAS/clipseg-rd64")
+@strict
+class CLIPSegTextConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import CLIPSegTextConfig, CLIPSegTextModel
+
+ >>> # Initializing a CLIPSegTextConfig with CIDAS/clipseg-rd64 style configuration
+ >>> configuration = CLIPSegTextConfig()
+
+ >>> # Initializing a CLIPSegTextModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
+ >>> model = CLIPSegTextModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "clipseg_text_model"
+ base_config_key = "text_config"
+
+ vocab_size: int = 49408
+ hidden_size: int = 512
+ intermediate_size: int = 2048
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 8
+ max_position_embeddings: int = 77
+ hidden_act: str = "quick_gelu"
+ layer_norm_eps: float | None = 1e-5
+ attention_dropout: int | float | None = 0.0
+ initializer_range: float = 0.02
+ initializer_factor: float | None = 1.0
+
+ # This differs from `CLIPSegTokenizer`'s default and from openai/clipseg
+ # See https://github.com/huggingface/transformers/pull/24773#issuecomment-1632287538
+ pad_token_id: int | None = 1
+ bos_token_id: int | None = 49406
+ eos_token_id: int | list[int] | None = 49407
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.hidden_size % self.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({self.num_attention_heads})."
+ )
+
+
+@auto_docstring(checkpoint="CIDAS/clipseg-rd64")
+@strict
+class CLIPSegVisionConfig(PreTrainedConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import CLIPSegVisionConfig, CLIPSegVisionModel
+
+ >>> # Initializing a CLIPSegVisionConfig with CIDAS/clipseg-rd64 style configuration
+ >>> configuration = CLIPSegVisionConfig()
+
+ >>> # Initializing a CLIPSegVisionModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
+ >>> model = CLIPSegVisionModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "clipseg_vision_model"
+ base_config_key = "vision_config"
+
+ hidden_size: int = 768
+ intermediate_size: int = 3072
+ num_hidden_layers: int = 12
+ num_attention_heads: int = 12
+ num_channels: int = 3
+ image_size: int | list[int] | tuple[int, int] | None = 224
+ patch_size: int | list[int] | tuple[int, int] | None = 32
+ hidden_act: str = "quick_gelu"
+ layer_norm_eps: float = 1e-5
+ attention_dropout: int | float | None = 0.0
+ initializer_range: float = 0.02
+ initializer_factor: float = 1.0
+
+ def validate_architecture(self):
+ """Part of `@strict`-powered validation. Validates the architecture of the config."""
+ if self.hidden_size % self.num_attention_heads != 0:
+ raise ValueError(
+ f"The hidden size ({self.hidden_size}) is not a multiple of the number of attention "
+ f"heads ({self.num_attention_heads})."
+ )
+
+
+@auto_docstring(checkpoint="CIDAS/clipseg-rd64")
+@strict
+class CLIPSegConfig(PreTrainedConfig):
+ r"""
+ extract_layers (`list[int]`, *optional*, defaults to `[3, 6, 9]`):
+ Layers to extract when forwarding the query image through the frozen visual backbone of CLIP.
+ reduce_dim (`int`, *optional*, defaults to 64):
+ Dimensionality to reduce the CLIP vision embedding.
+ conditional_layer (`int`, *optional*, defaults to 0):
+ The layer to use of the Transformer encoder whose activations will be combined with the condition
+ embeddings using FiLM (Feature-wise Linear Modulation). If 0, the last layer is used.
+ use_complex_transposed_convolution (`bool`, *optional*, defaults to `False`):
+ Whether to use a more complex transposed convolution in the decoder, enabling more fine-grained
+ segmentation..
+
+ Example:
+
+ ```python
+ >>> from transformers import CLIPSegConfig, CLIPSegModel
+
+ >>> # Initializing a CLIPSegConfig with CIDAS/clipseg-rd64 style configuration
+ >>> configuration = CLIPSegConfig()
+
+ >>> # Initializing a CLIPSegModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
+ >>> model = CLIPSegModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+
+ >>> # We can also initialize a CLIPSegConfig from a CLIPSegTextConfig and a CLIPSegVisionConfig
+
+ >>> # Initializing a CLIPSegText and CLIPSegVision configuration
+ >>> config_text = CLIPSegTextConfig()
+ >>> config_vision = CLIPSegVisionConfig()
+
+ >>> config = CLIPSegConfig(text_config=config_text, vision_config=config_vision)
+ ```"""
+
+ model_type = "clipseg"
+ sub_configs = {"text_config": CLIPSegTextConfig, "vision_config": CLIPSegVisionConfig}
+
+ text_config: dict | CLIPSegTextConfig | None = None
+ vision_config: dict | CLIPSegVisionConfig | None = None
+ projection_dim: int | None = 512
+ logit_scale_init_value: float | int | None = 2.6592
+ initializer_factor: float | None = 1.0
+
+ extract_layers: list[int] | tuple[int, ...] = (3, 6, 9)
+ reduce_dim: int = 64
+ decoder_num_attention_heads: int = 4
+ decoder_attention_dropout: float | int = 0.0
+ decoder_hidden_act: str = "quick_gelu"
+ decoder_intermediate_size: int = 2048
+ conditional_layer: int = 0
+ use_complex_transposed_convolution: bool = False
+
+ def __post_init__(self, **kwargs):
+ if self.text_config is None:
+ text_config = {}
+ logger.info("`text_config` is `None`. Initializing the `CLIPSegTextConfig` with default values.")
+ elif isinstance(self.text_config, CLIPSegTextConfig):
+ text_config = self.text_config.to_dict()
+ else:
+ text_config = self.text_config
+
+ if self.vision_config is None:
+ vision_config = {}
+ logger.info("`vision_config` is `None`. initializing the `CLIPSegVisionConfig` with default values.")
+ elif isinstance(self.vision_config, CLIPSegVisionConfig):
+ vision_config = self.vision_config.to_dict()
+ else:
+ vision_config = self.vision_config
+
+ # For backward compatibility check keyword args
+ # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
+ # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
+ # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
+ text_config_dict = kwargs.pop("text_config_dict", None)
+ vision_config_dict = kwargs.pop("vision_config_dict", None)
+
+ if text_config_dict is not None:
+ # This is the complete result when using `text_config_dict`.
+ _text_config_dict = CLIPSegTextConfig(**text_config_dict).to_dict()
+
+ # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
+ for key, value in _text_config_dict.items():
+ if key in text_config and value != text_config[key] and key != "transformers_version":
+ # If specified in `text_config_dict`
+ if key in text_config_dict:
+ message = (
+ f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
+ f'The value `text_config_dict["{key}"]` will be used instead.'
+ )
+ # If inferred from default argument values (just to be super careful)
+ else:
+ message = (
+ f"`text_config_dict` is provided which will be used to initialize `CLIPTextConfig`. The "
+ f'value `text_config["{key}"]` will be overridden.'
+ )
+ logger.info(message)
+
+ # Update all values in `text_config` with the ones in `_text_config_dict`.
+ text_config.update(_text_config_dict)
+
+ if vision_config_dict is not None:
+ # This is the complete result when using `vision_config_dict`.
+ _vision_config_dict = CLIPSegVisionConfig(**vision_config_dict).to_dict()
+ # convert keys to string instead of integer
+ if "id2label" in _vision_config_dict:
+ _vision_config_dict["id2label"] = {
+ str(key): value for key, value in _vision_config_dict["id2label"].items()
+ }
+
+ # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
+ for key, value in _vision_config_dict.items():
+ if key in vision_config and value != vision_config[key] and key != "transformers_version":
+ # If specified in `vision_config_dict`
+ if key in vision_config_dict:
+ message = (
+ f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
+ f'values. The value `vision_config_dict["{key}"]` will be used instead.'
+ )
+ # If inferred from default argument values (just to be super careful)
+ else:
+ message = (
+ f"`vision_config_dict` is provided which will be used to initialize `CLIPVisionConfig`. "
+ f'The value `vision_config["{key}"]` will be overridden.'
+ )
+ logger.info(message)
+
+ # Update all values in `vision_config` with the ones in `_vision_config_dict`.
+ vision_config.update(_vision_config_dict)
+
+ # Finally we can convert back our unified text/vision configs to `PretrainedConfig`
+ self.text_config = CLIPSegTextConfig(**text_config)
+ self.vision_config = CLIPSegVisionConfig(**vision_config)
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["CLIPSegConfig", "CLIPSegTextConfig", "CLIPSegVisionConfig"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modeling_clipseg.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modeling_clipseg.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf17b44b00c20cd687a5dac2462930fa8d312104
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modeling_clipseg.py
@@ -0,0 +1,1128 @@
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# This file was automatically generated from src/transformers/models/clipseg/modular_clipseg.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_clipseg.py file directly. One of our CI enforces this.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# Copyright 2022 The OpenAI Team Authors 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.
+
+import copy
+import math
+from collections.abc import Callable
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+from torch import nn
+
+from ... import initialization as init
+from ...activations import ACT2FN
+from ...masking_utils import create_causal_mask
+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 ...utils import ModelOutput, TransformersKwargs, auto_docstring, torch_int
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from .configuration_clipseg import CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig
+
+
+@dataclass
+@auto_docstring
+class CLIPSegOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
+ Contrastive loss for image-text similarity.
+ logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
+ similarity scores.
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
+ similarity scores.
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The text embeddings obtained by applying the projection layer to the pooled output of [`CLIPSegTextModel`].
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
+ The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPSegVisionModel`].
+ text_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`CLIPSegTextModel`].
+ vision_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`CLIPSegVisionModel`].
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits_per_image: torch.FloatTensor | None = None
+ logits_per_text: torch.FloatTensor | None = None
+ text_embeds: torch.FloatTensor | None = None
+ image_embeds: torch.FloatTensor | None = None
+ text_model_output: BaseModelOutputWithPooling = None
+ vision_model_output: BaseModelOutputWithPooling = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(v.to_tuple() if isinstance(v, ModelOutput) else v for v in self.values())
+
+
+@dataclass
+@auto_docstring
+class CLIPSegDecoderOutput(ModelOutput):
+ r"""
+ logits (`torch.FloatTensor` of shape `(batch_size, height, width)`):
+ Classification scores for each pixel.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*,):
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
+ Rreturned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`
+ attentions (`tuple(torch.FloatTensor)`, *optional*):
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads. Returned when `output_attentions=True` is passed or when `config.output_attentions=True`
+ """
+
+ logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@dataclass
+@auto_docstring
+class CLIPSegImageSegmentationOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Binary cross entropy loss for segmentation.
+ logits (`torch.FloatTensor` of shape `(batch_size, height, width)`):
+ Classification scores for each pixel.
+ conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, projection_dim)`):
+ Conditional embeddings used for segmentation.
+ pooled_output (`torch.FloatTensor` of shape `(batch_size, embed_dim)`):
+ Pooled output of the [`CLIPSegVisionModel`].
+ vision_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`CLIPSegVisionModel`].
+ decoder_output (`CLIPSegDecoderOutput`):
+ The output of the [`CLIPSegDecoder`].
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ conditional_embeddings: torch.FloatTensor | None = None
+ pooled_output: torch.FloatTensor | None = None
+ vision_model_output: BaseModelOutputWithPooling = None
+ decoder_output: CLIPSegDecoderOutput = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(v.to_tuple() if isinstance(v, ModelOutput) else v for v in self.values())
+
+
+class CLIPSegVisionEmbeddings(nn.Module):
+ def __init__(self, config: CLIPSegVisionConfig):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.image_size = config.image_size
+ self.patch_size = config.patch_size
+
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
+
+ self.patch_embedding = nn.Conv2d(
+ in_channels=config.num_channels,
+ out_channels=self.embed_dim,
+ kernel_size=self.patch_size,
+ stride=self.patch_size,
+ bias=False,
+ )
+
+ self.num_patches = (self.image_size // self.patch_size) ** 2
+ self.num_positions = self.num_patches + 1
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
+
+ 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
+ position_embedding = self.position_embedding.weight.unsqueeze(0)
+ num_positions = position_embedding.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_embedding(self.position_ids)
+
+ class_pos_embed = position_embedding[:, :1]
+ patch_pos_embed = position_embedding[:, 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.FloatTensor, interpolate_pos_encoding=True) -> torch.Tensor:
+ batch_size, _, height, width = pixel_values.shape
+ if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
+ raise ValueError(
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size}*{self.image_size})."
+ )
+ target_dtype = self.patch_embedding.weight.dtype
+ patch_embeds = self.patch_embedding(pixel_values.to(dtype=target_dtype)) # shape = [*, width, grid, grid]
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
+
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
+ if interpolate_pos_encoding:
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
+ else:
+ embeddings = embeddings + self.position_embedding(self.position_ids)
+ return embeddings
+
+
+class CLIPSegTextEmbeddings(nn.Module):
+ def __init__(self, config: CLIPSegTextConfig):
+ super().__init__()
+ embed_dim = config.hidden_size
+
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
+
+ # 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
+ )
+
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ inputs_embeds: torch.FloatTensor | None = None,
+ ) -> torch.Tensor:
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
+ max_position_embedding = self.position_embedding.weight.shape[0]
+
+ if seq_length > max_position_embedding:
+ raise ValueError(
+ f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
+ f"{seq_length} and max_position_embeddings: {max_position_embedding}"
+ )
+
+ if position_ids is None:
+ position_ids = self.position_ids[:, :seq_length]
+
+ if inputs_embeds is None:
+ inputs_embeds = self.token_embedding(input_ids)
+
+ position_embeddings = self.position_embedding(position_ids)
+ embeddings = inputs_embeds + position_embeddings
+
+ return embeddings
+
+
+def eager_attention_forward(
+ module: nn.Module,
+ query: torch.Tensor,
+ key: torch.Tensor,
+ value: torch.Tensor,
+ attention_mask: torch.Tensor | None,
+ scaling: float,
+ dropout: float = 0.0,
+ **kwargs: Unpack[TransformersKwargs],
+):
+ attn_weights = torch.matmul(query, key.transpose(-1, -2)) * scaling
+ if attention_mask is not None:
+ attn_weights = attn_weights + attention_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)
+ attn_output = attn_output.transpose(1, 2).contiguous()
+ return attn_output, attn_weights
+
+
+class CLIPSegAttention(nn.Module):
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
+
+ def __init__(self, config: CLIPSegVisionConfig | CLIPSegTextConfig):
+ super().__init__()
+ self.config = config
+ self.embed_dim = config.hidden_size
+ self.num_heads = config.num_attention_heads
+ self.head_dim = self.embed_dim // self.num_heads
+ self.scale = self.head_dim**-0.5
+ self.dropout = config.attention_dropout
+ self.is_causal = False
+
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple[torch.Tensor, torch.Tensor | None]:
+ """Input shape: Batch x Time x Channel"""
+
+ input_shape = hidden_states.shape[:-1]
+
+ hidden_shape = (*input_shape, -1, self.head_dim)
+ queries = self.q_proj(hidden_states)
+ keys = self.k_proj(hidden_states)
+ values = self.v_proj(hidden_states)
+
+ queries = queries.view(hidden_shape).transpose(1, 2)
+ keys = keys.view(hidden_shape).transpose(1, 2)
+ values = values.view(hidden_shape).transpose(1, 2)
+
+ attention_interface: Callable = ALL_ATTENTION_FUNCTIONS.get_interface(
+ self.config._attn_implementation, eager_attention_forward
+ )
+
+ attn_output, attn_weights = attention_interface(
+ self,
+ queries,
+ keys,
+ values,
+ attention_mask,
+ scaling=self.scale,
+ dropout=0.0 if not self.training else self.dropout,
+ **kwargs,
+ )
+
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
+ attn_output = self.out_proj(attn_output)
+
+ return attn_output, attn_weights
+
+
+class CLIPSegMLP(nn.Module):
+ def __init__(self, config):
+ super().__init__()
+ self.config = config
+ self.activation_fn = ACT2FN[config.hidden_act]
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.fc1(hidden_states)
+ hidden_states = self.activation_fn(hidden_states)
+ hidden_states = self.fc2(hidden_states)
+ return hidden_states
+
+
+class CLIPSegEncoderLayer(GradientCheckpointingLayer):
+ def __init__(self, config: CLIPSegVisionConfig | CLIPSegTextConfig):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+ self.self_attn = CLIPSegAttention(config)
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.mlp = CLIPSegMLP(config)
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ hidden_states = self.layer_norm1(hidden_states)
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+ hidden_states = residual + hidden_states
+
+ residual = hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+
+ return hidden_states
+
+
+class CLIPSegDecoderLayer(GradientCheckpointingLayer):
+ """
+ CLIPSeg decoder layer, which is identical to `CLIPSegEncoderLayer`, except that normalization is applied after
+ self-attention/MLP, rather than before.
+ """
+
+ def __init__(self, config: CLIPSegVisionConfig | CLIPSegTextConfig):
+ super().__init__()
+ self.embed_dim = config.hidden_size
+ self.self_attn = CLIPSegAttention(config)
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+ self.mlp = CLIPSegMLP(config)
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor]:
+ residual = hidden_states
+
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+
+ hidden_states = residual + hidden_states
+ hidden_states = self.layer_norm1(hidden_states)
+
+ residual = hidden_states
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+
+ return hidden_states
+
+
+@auto_docstring
+class CLIPSegPreTrainedModel(PreTrainedModel):
+ config: CLIPSegConfig
+ base_model_prefix = "clipseg"
+ input_modalities = ("image", "text")
+ _no_split_modules = ["CLIPSegTextEmbeddings", "CLIPSegEncoderLayer", "CLIPSegVisionEmbeddings"]
+
+ supports_gradient_checkpointing = True
+ _supports_sdpa = True
+ _supports_flash_attn = True
+ _supports_flex_attn = True
+ _supports_attention_backend = True
+ _can_record_outputs = {
+ "hidden_states": [CLIPSegEncoderLayer, CLIPSegDecoderLayer],
+ "attentions": CLIPSegAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ factor = self.config.initializer_factor
+ if isinstance(module, CLIPSegTextEmbeddings):
+ init.normal_(module.token_embedding.weight, mean=0.0, std=factor * 0.02)
+ init.normal_(module.position_embedding.weight, mean=0.0, std=factor * 0.02)
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ elif isinstance(module, CLIPSegVisionEmbeddings):
+ init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
+ init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
+ init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
+ init.copy_(module.position_ids, torch.arange(module.num_positions).expand((1, -1)))
+ elif isinstance(module, CLIPSegAttention):
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ out_proj_std = (module.embed_dim**-0.5) * factor
+ init.normal_(module.q_proj.weight, std=in_proj_std)
+ init.normal_(module.k_proj.weight, std=in_proj_std)
+ init.normal_(module.v_proj.weight, std=in_proj_std)
+ init.normal_(module.out_proj.weight, std=out_proj_std)
+ elif isinstance(module, CLIPSegMLP):
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
+ init.normal_(module.fc1.weight, std=fc_std)
+ init.normal_(module.fc2.weight, std=in_proj_std)
+ elif isinstance(module, CLIPSegModel):
+ init.normal_(
+ module.text_projection.weight,
+ std=module.text_embed_dim**-0.5 * factor,
+ )
+ init.normal_(
+ module.visual_projection.weight,
+ std=module.vision_embed_dim**-0.5 * factor,
+ )
+
+ if isinstance(module, nn.LayerNorm):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ if isinstance(module, nn.Linear) and module.bias is not None:
+ init.zeros_(module.bias)
+
+
+class CLIPSegEncoder(nn.Module):
+ """
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
+ [`CLIPSegEncoderLayer`].
+
+ Args:
+ config: CLIPSegConfig
+ """
+
+ def __init__(self, config: CLIPSegConfig):
+ super().__init__()
+ self.config = config
+ self.layers = nn.ModuleList([CLIPSegEncoderLayer(config) for _ in range(config.num_hidden_layers)])
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ inputs_embeds,
+ attention_mask: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> BaseModelOutput:
+ hidden_states = inputs_embeds
+ for encoder_layer in self.layers:
+ hidden_states = encoder_layer(
+ hidden_states,
+ attention_mask,
+ **kwargs,
+ )
+
+ return BaseModelOutput(
+ last_hidden_state=hidden_states,
+ )
+
+
+class CLIPSegDecoder(CLIPSegPreTrainedModel):
+ def __init__(self, config: CLIPSegConfig):
+ super().__init__(config)
+
+ self.conditional_layer = config.conditional_layer
+
+ self.film_mul = nn.Linear(config.projection_dim, config.reduce_dim)
+ self.film_add = nn.Linear(config.projection_dim, config.reduce_dim)
+
+ if config.use_complex_transposed_convolution:
+ transposed_kernels = (config.vision_config.patch_size // 4, config.vision_config.patch_size // 4)
+
+ self.transposed_convolution = nn.Sequential(
+ nn.Conv2d(config.reduce_dim, config.reduce_dim, kernel_size=3, padding=1),
+ nn.ReLU(),
+ nn.ConvTranspose2d(
+ config.reduce_dim,
+ config.reduce_dim // 2,
+ kernel_size=transposed_kernels[0],
+ stride=transposed_kernels[0],
+ ),
+ nn.ReLU(),
+ nn.ConvTranspose2d(
+ config.reduce_dim // 2, 1, kernel_size=transposed_kernels[1], stride=transposed_kernels[1]
+ ),
+ )
+ else:
+ self.transposed_convolution = nn.ConvTranspose2d(
+ config.reduce_dim, 1, config.vision_config.patch_size, stride=config.vision_config.patch_size
+ )
+
+ depth = len(config.extract_layers)
+ self.reduces = nn.ModuleList(
+ [nn.Linear(config.vision_config.hidden_size, config.reduce_dim) for _ in range(depth)]
+ )
+
+ decoder_config = copy.deepcopy(config.vision_config)
+ decoder_config.hidden_size = config.reduce_dim
+ decoder_config.num_attention_heads = config.decoder_num_attention_heads
+ decoder_config.intermediate_size = config.decoder_intermediate_size
+ decoder_config.hidden_act = "relu"
+ self.layers = nn.ModuleList([CLIPSegDecoderLayer(decoder_config) for _ in range(len(config.extract_layers))])
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ hidden_states: tuple[torch.Tensor],
+ conditional_embeddings: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CLIPSegDecoderOutput:
+ r"""
+ conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, config.projection_dim)`, *optional*):
+ The conditional embeddings for the query images. If provided, the model will use this instead of computing
+ the embeddings from the conditional_pixel_values.
+ """
+ activations = hidden_states[::-1]
+
+ output = None
+ for i, (activation, layer, reduce) in enumerate(zip(activations, self.layers, self.reduces)):
+ if output is not None:
+ output = reduce(activation) + output
+ else:
+ output = reduce(activation)
+
+ if i == self.conditional_layer:
+ output = self.film_mul(conditional_embeddings) * output.permute(1, 0, 2) + self.film_add(
+ conditional_embeddings
+ )
+ output = output.permute(1, 0, 2)
+
+ output = layer(output, attention_mask=None, **kwargs)
+
+ output = output[:, 1:, :].transpose(1, 2) # remove cls token and reshape to [batch_size, reduce_dim, seq_len]
+
+ size = int(math.sqrt(output.shape[2]))
+
+ batch_size = conditional_embeddings.shape[0]
+ output = output.view(batch_size, output.shape[1], size, size)
+
+ logits = self.transposed_convolution(output).squeeze(1)
+
+ return CLIPSegDecoderOutput(logits=logits)
+
+
+@auto_docstring(
+ custom_intro="""
+ The text model from CLIPSEG without any head or projection on top.
+ """
+)
+class CLIPSegTextModel(CLIPSegPreTrainedModel):
+ config: CLIPSegTextConfig
+ input_modalities = ("text",)
+ _input_embed_layer = "token_embedding"
+
+ def __init__(self, config: CLIPSegTextConfig):
+ super().__init__(config)
+ embed_dim = config.hidden_size
+ self.embeddings = CLIPSegTextEmbeddings(config)
+ self.encoder = CLIPSegEncoder(config)
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+
+ # For `pooled_output` computation
+ self.eos_token_id = config.eos_token_id
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, CLIPSegTextModel
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegTextModel.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
+ ```"""
+ if input_ids is None:
+ raise ValueError("You have to specify input_ids")
+
+ input_shape = input_ids.size()
+ input_ids = input_ids.view(-1, input_shape[-1])
+
+ hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
+
+ attention_mask = create_causal_mask(
+ config=self.config,
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ )
+
+ kwargs.pop("is_causal", None)
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ attention_mask=attention_mask,
+ is_causal=True,
+ **kwargs,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
+
+ if self.eos_token_id == 2:
+ # The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here.
+ # A CLIPSEG model with such `eos_token_id` in the config can't work correctly with extra new tokens added
+ # ------------------------------------------------------------
+ # text_embeds.shape = [batch_size, sequence_length, transformer.width]
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
+ # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
+ pooled_output = last_hidden_state[
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
+ input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
+ ]
+ else:
+ # The config gets updated `eos_token_id` from PR #24773 (so the use of extra new tokens is possible)
+ pooled_output = last_hidden_state[
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
+ # We need to get the first position of `eos_token_id` value (`pad_token_ids` might equal to `eos_token_id`)
+ # Note: we assume each sequence (along batch dim.) contains an `eos_token_id` (e.g. prepared by the tokenizer)
+ (input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.eos_token_id)
+ .int()
+ .argmax(dim=-1),
+ ]
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ The vision model from CLIPSEG without any head or projection on top.
+ """
+)
+class CLIPSegVisionModel(CLIPSegPreTrainedModel):
+ config: CLIPSegVisionConfig
+ main_input_name = "pixel_values"
+ input_modalities = ("image",)
+ _input_embed_layer = "patch_embedding"
+
+ def __init__(self, config: CLIPSegVisionConfig):
+ super().__init__(config)
+ embed_dim = config.hidden_size
+
+ self.embeddings = CLIPSegVisionEmbeddings(config)
+ self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.encoder = CLIPSegEncoder(config)
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs(tie_last_hidden_states=False)
+ @auto_docstring
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None,
+ interpolate_pos_encoding: bool | None = True,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from PIL import Image
+ >>> from transformers import AutoProcessor, CLIPSegVisionModel
+
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegVisionModel.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ >>> pooled_output = outputs.pooler_output # pooled CLS states
+ ```"""
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
+ hidden_states = self.pre_layrnorm(hidden_states)
+
+ encoder_outputs: BaseModelOutput = self.encoder(
+ inputs_embeds=hidden_states,
+ **kwargs,
+ )
+
+ last_hidden_state = encoder_outputs.last_hidden_state
+ pooled_output = last_hidden_state[:, 0, :]
+ pooled_output = self.post_layernorm(pooled_output)
+
+ return BaseModelOutputWithPooling(
+ last_hidden_state=last_hidden_state,
+ pooler_output=pooled_output,
+ )
+
+
+# contrastive loss function, adapted from
+# https://sachinruk.github.io/blog/2021-03-07-clipseg.html
+def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
+ return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
+
+
+def image_text_contrastive_loss(similarity: torch.Tensor) -> torch.Tensor:
+ caption_loss = contrastive_loss(similarity)
+ image_loss = contrastive_loss(similarity.T)
+ return (caption_loss + image_loss) / 2.0
+
+
+def _get_vector_norm(tensor: torch.Tensor) -> torch.Tensor:
+ """
+ This method is equivalent to tensor.norm(p=2, dim=-1, keepdim=True) and used to make
+ model `executorch` exportable. See issue https://github.com/pytorch/executorch/issues/3566
+ """
+ square_tensor = torch.pow(tensor, 2)
+ sum_tensor = torch.sum(square_tensor, dim=-1, keepdim=True)
+ normed_tensor = torch.pow(sum_tensor, 0.5)
+ return normed_tensor
+
+
+@auto_docstring
+class CLIPSegModel(CLIPSegPreTrainedModel):
+ def __init__(self, config: CLIPSegConfig):
+ super().__init__(config)
+
+ text_config = config.text_config
+ vision_config = config.vision_config
+
+ self.projection_dim = config.projection_dim
+ self.text_embed_dim = text_config.hidden_size
+ self.vision_embed_dim = vision_config.hidden_size
+
+ self.text_model = CLIPSegTextModel._from_config(text_config)
+ self.vision_model = CLIPSegVisionModel._from_config(vision_config)
+
+ self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
+ self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
+
+ # Initialize weights and apply final processing
+ self.post_init()
+
+ @can_return_tuple
+ @auto_docstring
+ def get_text_features(
+ self,
+ input_ids: torch.Tensor,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, CLIPSegModel
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+ >>> with torch.inference_mode():
+ ... text_features = model.get_text_features(**inputs)
+ ```"""
+ text_outputs: BaseModelOutputWithPooling = self.text_model(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = text_outputs.pooler_output
+ text_outputs.pooler_output = self.text_projection(pooled_output)
+
+ return text_outputs
+
+ @can_return_tuple
+ @auto_docstring
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ interpolate_pos_encoding: bool = True,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, CLIPSegModel
+ >>> from transformers.image_utils import load_image
+
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+
+ >>> with torch.inference_mode():
+ ... image_features = model.get_image_features(**inputs)
+ ```"""
+ vision_outputs: BaseModelOutputWithPooling = self.vision_model(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ return_dict=True,
+ **kwargs,
+ )
+ pooled_output = vision_outputs.pooler_output
+ vision_outputs.pooler_output = self.visual_projection(pooled_output)
+
+ return vision_outputs
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.LongTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ return_loss: bool | None = None,
+ interpolate_pos_encoding: bool = True,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CLIPSegOutput:
+ r"""
+ return_loss (`bool`, *optional*):
+ Whether or not to return the contrastive loss.
+
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, CLIPSegModel
+ >>> from transformers.image_utils import load_image
+
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> inputs = processor(
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
+ ... )
+
+ >>> with torch.inference_mode():
+ ... outputs = model(**inputs)
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
+ ```"""
+ vision_outputs: BaseModelOutputWithPooling = self.get_image_features(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+
+ text_outputs: BaseModelOutputWithPooling = self.get_text_features(
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ **kwargs,
+ )
+
+ image_embeds = vision_outputs.pooler_output
+ text_embeds = text_outputs.pooler_output
+
+ # normalized features
+ image_embeds = image_embeds / _get_vector_norm(image_embeds)
+ text_embeds = text_embeds / _get_vector_norm(text_embeds)
+
+ # cosine similarity as logits
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t().to(text_embeds.device))
+ logits_per_text = logits_per_text * self.logit_scale.exp().to(text_embeds.device)
+
+ logits_per_image = logits_per_text.t()
+
+ loss = None
+ if return_loss:
+ loss = image_text_contrastive_loss(logits_per_text)
+
+ return CLIPSegOutput(
+ loss=loss,
+ logits_per_image=logits_per_image,
+ logits_per_text=logits_per_text,
+ text_embeds=text_embeds,
+ image_embeds=image_embeds,
+ text_model_output=text_outputs,
+ vision_model_output=vision_outputs,
+ )
+
+
+@auto_docstring(
+ custom_intro="""
+ CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation.
+ """
+)
+class CLIPSegForImageSegmentation(CLIPSegPreTrainedModel):
+ config: CLIPSegConfig
+
+ def __init__(self, config: CLIPSegConfig):
+ super().__init__(config)
+ self.clip = CLIPSegModel(config)
+ self.extract_layers = config.extract_layers
+ self.decoder = CLIPSegDecoder(config)
+
+ self.post_init()
+
+ def get_conditional_embeddings(
+ self,
+ batch_size: int | None = None,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ conditional_pixel_values: torch.Tensor | None = None,
+ ) -> torch.FloatTensor:
+ if input_ids is not None:
+ # compute conditional embeddings from texts
+ if len(input_ids) != batch_size:
+ raise ValueError("Make sure to pass as many prompt texts as there are query images")
+ with torch.no_grad():
+ conditional_embeddings = self.clip.get_text_features(
+ input_ids, attention_mask=attention_mask, position_ids=position_ids
+ ).pooler_output
+ elif conditional_pixel_values is not None:
+ # compute conditional embeddings from images
+ if len(conditional_pixel_values) != batch_size:
+ raise ValueError("Make sure to pass as many prompt images as there are query images")
+ with torch.no_grad():
+ conditional_embeddings = self.clip.get_image_features(conditional_pixel_values).pooler_output
+ else:
+ raise ValueError(
+ "Invalid conditional, should be either provided as `input_ids` or `conditional_pixel_values`"
+ )
+
+ return conditional_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.FloatTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ conditional_pixel_values: torch.FloatTensor | None = None,
+ conditional_embeddings: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ interpolate_pos_encoding: bool = True,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CLIPSegOutput:
+ r"""
+ conditional_pixel_values (`torch.FloatTensor`, *optional*):
+ The pixel values of the conditional images.
+ conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, config.projection_dim)`, *optional*):
+ The conditional embeddings for the query images. If provided, the model will use this instead of computing
+ the embeddings from the conditional_pixel_values.
+ 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).
+
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, CLIPSegForImageSegmentation
+ >>> from transformers.image_utils import load_image
+
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> texts = ["a cat", "a remote", "a blanket"]
+ >>> inputs = processor(text=texts, images=[image] * len(texts), padding=True, return_tensors="pt")
+
+ >>> with torch.inference_mode():
+ ... outputs = model(**inputs)
+
+ >>> logits = outputs.logits
+ >>> print(logits.shape)
+ torch.Size([3, 352, 352])
+ ```"""
+ # step 1: forward the query images through the frozen CLIP vision encoder
+ with torch.no_grad():
+ kwargs["output_hidden_states"] = True # required to extract layers for the stages
+ vision_outputs = self.clip.get_image_features(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+ pooled_output = vision_outputs.pooler_output
+
+ hidden_states = vision_outputs.hidden_states
+ # we add +1 here as the hidden states also include the initial embeddings
+ activations = [hidden_states[i + 1] for i in self.extract_layers]
+
+ # update vision_outputs
+ vision_outputs = BaseModelOutputWithPooling(
+ last_hidden_state=vision_outputs.last_hidden_state,
+ pooler_output=vision_outputs.pooler_output,
+ hidden_states=vision_outputs.hidden_states,
+ attentions=vision_outputs.attentions,
+ )
+
+ # step 2: compute conditional embeddings, either from text, images or an own provided embedding
+ if conditional_embeddings is None:
+ conditional_embeddings = self.get_conditional_embeddings(
+ batch_size=pixel_values.shape[0],
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ conditional_pixel_values=conditional_pixel_values,
+ )
+ else:
+ if conditional_embeddings.shape[0] != pixel_values.shape[0]:
+ raise ValueError(
+ "Make sure to pass as many conditional embeddings as there are query images in the batch"
+ )
+ if conditional_embeddings.shape[1] != self.config.projection_dim:
+ raise ValueError(
+ "Make sure that the feature dimension of the conditional embeddings matches"
+ " `config.projection_dim`."
+ )
+
+ # step 3: forward both the pooled output and the activations through the lightweight decoder to predict masks
+ decoder_outputs = self.decoder(
+ activations,
+ conditional_embeddings,
+ **kwargs,
+ )
+ logits = decoder_outputs.logits
+
+ loss = None
+ if labels is not None:
+ # move labels to the correct device to enable PP
+ labels = labels.to(logits.device)
+ loss_fn = nn.BCEWithLogitsLoss()
+ loss = loss_fn(logits, labels)
+
+ return CLIPSegImageSegmentationOutput(
+ loss=loss,
+ logits=logits,
+ conditional_embeddings=conditional_embeddings,
+ pooled_output=pooled_output,
+ vision_model_output=vision_outputs,
+ decoder_output=decoder_outputs,
+ )
+
+
+__all__ = [
+ "CLIPSegModel",
+ "CLIPSegPreTrainedModel",
+ "CLIPSegTextModel",
+ "CLIPSegVisionModel",
+ "CLIPSegForImageSegmentation",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modular_clipseg.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modular_clipseg.py
new file mode 100644
index 0000000000000000000000000000000000000000..d84e916c33753219846d6954a039a42be9499a3c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/modular_clipseg.py
@@ -0,0 +1,681 @@
+# Copyright 2022 The OpenAI Team Authors 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.
+"""PyTorch CLIPSeg model."""
+
+import copy
+import math
+from dataclasses import dataclass
+from typing import Any
+
+import torch
+from huggingface_hub.dataclasses import strict
+from torch import nn
+
+from ... import initialization as init
+from ...modeling_outputs import BaseModelOutputWithPooling
+from ...processing_utils import Unpack
+from ...utils import ModelOutput, TransformersKwargs, auto_docstring
+from ...utils.generic import can_return_tuple, merge_with_config_defaults
+from ...utils.output_capturing import capture_outputs
+from ..clip.configuration_clip import CLIPConfig, CLIPTextConfig, CLIPVisionConfig
+from ..clip.modeling_clip import (
+ CLIPMLP,
+ CLIPAttention,
+ CLIPEncoder,
+ CLIPEncoderLayer,
+ CLIPModel,
+ CLIPOutput,
+ CLIPPreTrainedModel,
+ CLIPTextEmbeddings,
+ CLIPTextModel,
+ CLIPVisionEmbeddings,
+ CLIPVisionModel,
+)
+
+
+@auto_docstring(checkpoint="CIDAS/clipseg-rd64")
+@strict
+class CLIPSegTextConfig(CLIPTextConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import CLIPSegTextConfig, CLIPSegTextModel
+
+ >>> # Initializing a CLIPSegTextConfig with CIDAS/clipseg-rd64 style configuration
+ >>> configuration = CLIPSegTextConfig()
+
+ >>> # Initializing a CLIPSegTextModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
+ >>> model = CLIPSegTextModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ projection_dim = AttributeError()
+
+
+@auto_docstring(checkpoint="CIDAS/clipseg-rd64")
+@strict
+class CLIPSegVisionConfig(CLIPVisionConfig):
+ r"""
+ Example:
+
+ ```python
+ >>> from transformers import CLIPSegVisionConfig, CLIPSegVisionModel
+
+ >>> # Initializing a CLIPSegVisionConfig with CIDAS/clipseg-rd64 style configuration
+ >>> configuration = CLIPSegVisionConfig()
+
+ >>> # Initializing a CLIPSegVisionModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
+ >>> model = CLIPSegVisionModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ projection_dim = AttributeError()
+
+
+@auto_docstring(checkpoint="CIDAS/clipseg-rd64")
+@strict
+class CLIPSegConfig(CLIPConfig):
+ r"""
+ extract_layers (`list[int]`, *optional*, defaults to `[3, 6, 9]`):
+ Layers to extract when forwarding the query image through the frozen visual backbone of CLIP.
+ reduce_dim (`int`, *optional*, defaults to 64):
+ Dimensionality to reduce the CLIP vision embedding.
+ conditional_layer (`int`, *optional*, defaults to 0):
+ The layer to use of the Transformer encoder whose activations will be combined with the condition
+ embeddings using FiLM (Feature-wise Linear Modulation). If 0, the last layer is used.
+ use_complex_transposed_convolution (`bool`, *optional*, defaults to `False`):
+ Whether to use a more complex transposed convolution in the decoder, enabling more fine-grained
+ segmentation..
+
+ Example:
+
+ ```python
+ >>> from transformers import CLIPSegConfig, CLIPSegModel
+
+ >>> # Initializing a CLIPSegConfig with CIDAS/clipseg-rd64 style configuration
+ >>> configuration = CLIPSegConfig()
+
+ >>> # Initializing a CLIPSegModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
+ >>> model = CLIPSegModel(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+
+ >>> # We can also initialize a CLIPSegConfig from a CLIPSegTextConfig and a CLIPSegVisionConfig
+
+ >>> # Initializing a CLIPSegText and CLIPSegVision configuration
+ >>> config_text = CLIPSegTextConfig()
+ >>> config_vision = CLIPSegVisionConfig()
+
+ >>> config = CLIPSegConfig(text_config=config_text, vision_config=config_vision)
+ ```"""
+
+ extract_layers: list[int] | tuple[int, ...] = (3, 6, 9)
+ reduce_dim: int = 64
+ decoder_num_attention_heads: int = 4
+ decoder_attention_dropout: float | int = 0.0
+ decoder_hidden_act: str = "quick_gelu"
+ decoder_intermediate_size: int = 2048
+ conditional_layer: int = 0
+ use_complex_transposed_convolution: bool = False
+
+
+class CLIPSegOutput(CLIPOutput):
+ pass
+
+
+@dataclass
+@auto_docstring
+class CLIPSegDecoderOutput(ModelOutput):
+ r"""
+ logits (`torch.FloatTensor` of shape `(batch_size, height, width)`):
+ Classification scores for each pixel.
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*,):
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
+ Rreturned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`
+ attentions (`tuple(torch.FloatTensor)`, *optional*):
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
+ heads. Returned when `output_attentions=True` is passed or when `config.output_attentions=True`
+ """
+
+ logits: torch.FloatTensor | None = None
+ hidden_states: tuple[torch.FloatTensor, ...] | None = None
+ attentions: tuple[torch.FloatTensor, ...] | None = None
+
+
+@dataclass
+@auto_docstring
+class CLIPSegImageSegmentationOutput(ModelOutput):
+ r"""
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
+ Binary cross entropy loss for segmentation.
+ logits (`torch.FloatTensor` of shape `(batch_size, height, width)`):
+ Classification scores for each pixel.
+ conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, projection_dim)`):
+ Conditional embeddings used for segmentation.
+ pooled_output (`torch.FloatTensor` of shape `(batch_size, embed_dim)`):
+ Pooled output of the [`CLIPSegVisionModel`].
+ vision_model_output (`BaseModelOutputWithPooling`):
+ The output of the [`CLIPSegVisionModel`].
+ decoder_output (`CLIPSegDecoderOutput`):
+ The output of the [`CLIPSegDecoder`].
+ """
+
+ loss: torch.FloatTensor | None = None
+ logits: torch.FloatTensor | None = None
+ conditional_embeddings: torch.FloatTensor | None = None
+ pooled_output: torch.FloatTensor | None = None
+ vision_model_output: BaseModelOutputWithPooling = None
+ decoder_output: CLIPSegDecoderOutput = None
+
+ def to_tuple(self) -> tuple[Any]:
+ return tuple(v.to_tuple() if isinstance(v, ModelOutput) else v for v in self.values())
+
+
+class CLIPSegVisionEmbeddings(CLIPVisionEmbeddings):
+ # Different default for `interpolate_pos_encoding` from CLIP
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=True) -> torch.Tensor:
+ super().forward(pixel_values, interpolate_pos_encoding)
+
+
+class CLIPSegTextEmbeddings(CLIPTextEmbeddings):
+ pass
+
+
+class CLIPSegAttention(CLIPAttention):
+ pass
+
+
+class CLIPSegMLP(CLIPMLP):
+ pass
+
+
+class CLIPSegEncoderLayer(CLIPEncoderLayer):
+ pass
+
+
+class CLIPSegDecoderLayer(CLIPEncoderLayer):
+ """
+ CLIPSeg decoder layer, which is identical to `CLIPSegEncoderLayer`, except that normalization is applied after
+ self-attention/MLP, rather than before.
+ """
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ **kwargs,
+ ) -> tuple[torch.FloatTensor]:
+ residual = hidden_states
+
+ hidden_states, _ = self.self_attn(
+ hidden_states=hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+
+ hidden_states = residual + hidden_states
+ hidden_states = self.layer_norm1(hidden_states)
+
+ residual = hidden_states
+ hidden_states = self.mlp(hidden_states)
+ hidden_states = residual + hidden_states
+ hidden_states = self.layer_norm2(hidden_states)
+
+ return hidden_states
+
+
+@auto_docstring
+class CLIPSegPreTrainedModel(CLIPPreTrainedModel):
+ _can_record_outputs = {
+ "hidden_states": [CLIPSegEncoderLayer, CLIPSegDecoderLayer],
+ "attentions": CLIPSegAttention,
+ }
+
+ @torch.no_grad()
+ def _init_weights(self, module):
+ """Initialize the weights"""
+ factor = self.config.initializer_factor
+ if isinstance(module, CLIPSegTextEmbeddings):
+ init.normal_(module.token_embedding.weight, mean=0.0, std=factor * 0.02)
+ init.normal_(module.position_embedding.weight, mean=0.0, std=factor * 0.02)
+ init.copy_(module.position_ids, torch.arange(module.position_ids.shape[-1]).expand((1, -1)))
+ elif isinstance(module, CLIPSegVisionEmbeddings):
+ init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
+ init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
+ init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
+ init.copy_(module.position_ids, torch.arange(module.num_positions).expand((1, -1)))
+ elif isinstance(module, CLIPSegAttention):
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ out_proj_std = (module.embed_dim**-0.5) * factor
+ init.normal_(module.q_proj.weight, std=in_proj_std)
+ init.normal_(module.k_proj.weight, std=in_proj_std)
+ init.normal_(module.v_proj.weight, std=in_proj_std)
+ init.normal_(module.out_proj.weight, std=out_proj_std)
+ elif isinstance(module, CLIPSegMLP):
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
+ init.normal_(module.fc1.weight, std=fc_std)
+ init.normal_(module.fc2.weight, std=in_proj_std)
+ elif isinstance(module, CLIPSegModel):
+ init.normal_(
+ module.text_projection.weight,
+ std=module.text_embed_dim**-0.5 * factor,
+ )
+ init.normal_(
+ module.visual_projection.weight,
+ std=module.vision_embed_dim**-0.5 * factor,
+ )
+
+ if isinstance(module, nn.LayerNorm):
+ init.zeros_(module.bias)
+ init.ones_(module.weight)
+ if isinstance(module, nn.Linear) and module.bias is not None:
+ init.zeros_(module.bias)
+
+
+class CLIPSegEncoder(CLIPEncoder):
+ pass
+
+
+class CLIPSegDecoder(CLIPSegPreTrainedModel):
+ def __init__(self, config: CLIPSegConfig):
+ super().__init__(config)
+
+ self.conditional_layer = config.conditional_layer
+
+ self.film_mul = nn.Linear(config.projection_dim, config.reduce_dim)
+ self.film_add = nn.Linear(config.projection_dim, config.reduce_dim)
+
+ if config.use_complex_transposed_convolution:
+ transposed_kernels = (config.vision_config.patch_size // 4, config.vision_config.patch_size // 4)
+
+ self.transposed_convolution = nn.Sequential(
+ nn.Conv2d(config.reduce_dim, config.reduce_dim, kernel_size=3, padding=1),
+ nn.ReLU(),
+ nn.ConvTranspose2d(
+ config.reduce_dim,
+ config.reduce_dim // 2,
+ kernel_size=transposed_kernels[0],
+ stride=transposed_kernels[0],
+ ),
+ nn.ReLU(),
+ nn.ConvTranspose2d(
+ config.reduce_dim // 2, 1, kernel_size=transposed_kernels[1], stride=transposed_kernels[1]
+ ),
+ )
+ else:
+ self.transposed_convolution = nn.ConvTranspose2d(
+ config.reduce_dim, 1, config.vision_config.patch_size, stride=config.vision_config.patch_size
+ )
+
+ depth = len(config.extract_layers)
+ self.reduces = nn.ModuleList(
+ [nn.Linear(config.vision_config.hidden_size, config.reduce_dim) for _ in range(depth)]
+ )
+
+ decoder_config = copy.deepcopy(config.vision_config)
+ decoder_config.hidden_size = config.reduce_dim
+ decoder_config.num_attention_heads = config.decoder_num_attention_heads
+ decoder_config.intermediate_size = config.decoder_intermediate_size
+ decoder_config.hidden_act = "relu"
+ self.layers = nn.ModuleList([CLIPSegDecoderLayer(decoder_config) for _ in range(len(config.extract_layers))])
+
+ self.post_init()
+
+ @merge_with_config_defaults
+ @capture_outputs
+ @auto_docstring
+ def forward(
+ self,
+ hidden_states: tuple[torch.Tensor],
+ conditional_embeddings: torch.Tensor,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> CLIPSegDecoderOutput:
+ r"""
+ conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, config.projection_dim)`, *optional*):
+ The conditional embeddings for the query images. If provided, the model will use this instead of computing
+ the embeddings from the conditional_pixel_values.
+ """
+ activations = hidden_states[::-1]
+
+ output = None
+ for i, (activation, layer, reduce) in enumerate(zip(activations, self.layers, self.reduces)):
+ if output is not None:
+ output = reduce(activation) + output
+ else:
+ output = reduce(activation)
+
+ if i == self.conditional_layer:
+ output = self.film_mul(conditional_embeddings) * output.permute(1, 0, 2) + self.film_add(
+ conditional_embeddings
+ )
+ output = output.permute(1, 0, 2)
+
+ output = layer(output, attention_mask=None, **kwargs)
+
+ output = output[:, 1:, :].transpose(1, 2) # remove cls token and reshape to [batch_size, reduce_dim, seq_len]
+
+ size = int(math.sqrt(output.shape[2]))
+
+ batch_size = conditional_embeddings.shape[0]
+ output = output.view(batch_size, output.shape[1], size, size)
+
+ logits = self.transposed_convolution(output).squeeze(1)
+
+ return CLIPSegDecoderOutput(logits=logits)
+
+
+class CLIPSegTextModel(CLIPTextModel):
+ def forward(self, **super_kwargs) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> from transformers import AutoTokenizer, CLIPSegTextModel
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegTextModel.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
+ ```"""
+ return super().forward(**super_kwargs)
+
+
+class CLIPSegVisionModel(CLIPVisionModel):
+ def forward(
+ self,
+ pixel_values: torch.FloatTensor | None,
+ interpolate_pos_encoding: bool | None = True,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import httpx
+ >>> from io import BytesIO
+ >>> from PIL import Image
+ >>> from transformers import AutoProcessor, CLIPSegVisionModel
+
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegVisionModel.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read()))
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+
+ >>> outputs = model(**inputs)
+ >>> last_hidden_state = outputs.last_hidden_state
+ >>> pooled_output = outputs.pooler_output # pooled CLS states
+ ```"""
+ return super().forward(pixel_values, interpolate_pos_encoding, **kwargs)
+
+
+class CLIPSegModel(CLIPModel):
+ def get_text_features(self, **super_kwargs):
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, CLIPSegModel
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
+ >>> with torch.inference_mode():
+ ... text_features = model.get_text_features(**inputs)
+ ```"""
+ return super().get_text_features(**super_kwargs)
+
+ def get_image_features(
+ self,
+ pixel_values: torch.FloatTensor,
+ interpolate_pos_encoding: bool = True,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | BaseModelOutputWithPooling:
+ r"""
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, CLIPSegModel
+ >>> from transformers.image_utils import load_image
+
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> inputs = processor(images=image, return_tensors="pt")
+
+ >>> with torch.inference_mode():
+ ... image_features = model.get_image_features(**inputs)
+ ```"""
+ return super().get_image_features(pixel_values, interpolate_pos_encoding, **kwargs)
+
+ def forward(self, interpolate_pos_encoding: bool = True, **super_kwargs):
+ r"""
+ return_loss (`bool`, *optional*):
+ Whether or not to return the contrastive loss.
+
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, CLIPSegModel
+ >>> from transformers.image_utils import load_image
+
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> inputs = processor(
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
+ ... )
+
+ >>> with torch.inference_mode():
+ ... outputs = model(**inputs)
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
+ ```"""
+ super().forward(interpolate_pos_encoding=interpolate_pos_encoding, **super_kwargs)
+
+
+@auto_docstring(
+ custom_intro="""
+ CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation.
+ """
+)
+class CLIPSegForImageSegmentation(CLIPSegPreTrainedModel):
+ config: CLIPSegConfig
+
+ def __init__(self, config: CLIPSegConfig):
+ super().__init__(config)
+ self.clip = CLIPSegModel(config)
+ self.extract_layers = config.extract_layers
+ self.decoder = CLIPSegDecoder(config)
+
+ self.post_init()
+
+ def get_conditional_embeddings(
+ self,
+ batch_size: int | None = None,
+ input_ids: torch.Tensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.Tensor | None = None,
+ conditional_pixel_values: torch.Tensor | None = None,
+ ) -> torch.FloatTensor:
+ if input_ids is not None:
+ # compute conditional embeddings from texts
+ if len(input_ids) != batch_size:
+ raise ValueError("Make sure to pass as many prompt texts as there are query images")
+ with torch.no_grad():
+ conditional_embeddings = self.clip.get_text_features(
+ input_ids, attention_mask=attention_mask, position_ids=position_ids
+ ).pooler_output
+ elif conditional_pixel_values is not None:
+ # compute conditional embeddings from images
+ if len(conditional_pixel_values) != batch_size:
+ raise ValueError("Make sure to pass as many prompt images as there are query images")
+ with torch.no_grad():
+ conditional_embeddings = self.clip.get_image_features(conditional_pixel_values).pooler_output
+ else:
+ raise ValueError(
+ "Invalid conditional, should be either provided as `input_ids` or `conditional_pixel_values`"
+ )
+
+ return conditional_embeddings
+
+ @can_return_tuple
+ @auto_docstring
+ def forward(
+ self,
+ input_ids: torch.FloatTensor | None = None,
+ pixel_values: torch.FloatTensor | None = None,
+ conditional_pixel_values: torch.FloatTensor | None = None,
+ conditional_embeddings: torch.FloatTensor | None = None,
+ attention_mask: torch.Tensor | None = None,
+ position_ids: torch.LongTensor | None = None,
+ labels: torch.LongTensor | None = None,
+ interpolate_pos_encoding: bool = True,
+ **kwargs: Unpack[TransformersKwargs],
+ ) -> tuple | CLIPSegOutput:
+ r"""
+ conditional_pixel_values (`torch.FloatTensor`, *optional*):
+ The pixel values of the conditional images.
+ conditional_embeddings (`torch.FloatTensor` of shape `(batch_size, config.projection_dim)`, *optional*):
+ The conditional embeddings for the query images. If provided, the model will use this instead of computing
+ the embeddings from the conditional_pixel_values.
+ 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).
+
+ Examples:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoProcessor, CLIPSegForImageSegmentation
+ >>> from transformers.image_utils import load_image
+
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
+ >>> model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined")
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> image = load_image(url)
+
+ >>> texts = ["a cat", "a remote", "a blanket"]
+ >>> inputs = processor(text=texts, images=[image] * len(texts), padding=True, return_tensors="pt")
+
+ >>> with torch.inference_mode():
+ ... outputs = model(**inputs)
+
+ >>> logits = outputs.logits
+ >>> print(logits.shape)
+ torch.Size([3, 352, 352])
+ ```"""
+ # step 1: forward the query images through the frozen CLIP vision encoder
+ with torch.no_grad():
+ kwargs["output_hidden_states"] = True # required to extract layers for the stages
+ vision_outputs = self.clip.get_image_features(
+ pixel_values=pixel_values,
+ interpolate_pos_encoding=interpolate_pos_encoding,
+ **kwargs,
+ )
+ pooled_output = vision_outputs.pooler_output
+
+ hidden_states = vision_outputs.hidden_states
+ # we add +1 here as the hidden states also include the initial embeddings
+ activations = [hidden_states[i + 1] for i in self.extract_layers]
+
+ # update vision_outputs
+ vision_outputs = BaseModelOutputWithPooling(
+ last_hidden_state=vision_outputs.last_hidden_state,
+ pooler_output=vision_outputs.pooler_output,
+ hidden_states=vision_outputs.hidden_states,
+ attentions=vision_outputs.attentions,
+ )
+
+ # step 2: compute conditional embeddings, either from text, images or an own provided embedding
+ if conditional_embeddings is None:
+ conditional_embeddings = self.get_conditional_embeddings(
+ batch_size=pixel_values.shape[0],
+ input_ids=input_ids,
+ attention_mask=attention_mask,
+ position_ids=position_ids,
+ conditional_pixel_values=conditional_pixel_values,
+ )
+ else:
+ if conditional_embeddings.shape[0] != pixel_values.shape[0]:
+ raise ValueError(
+ "Make sure to pass as many conditional embeddings as there are query images in the batch"
+ )
+ if conditional_embeddings.shape[1] != self.config.projection_dim:
+ raise ValueError(
+ "Make sure that the feature dimension of the conditional embeddings matches"
+ " `config.projection_dim`."
+ )
+
+ # step 3: forward both the pooled output and the activations through the lightweight decoder to predict masks
+ decoder_outputs = self.decoder(
+ activations,
+ conditional_embeddings,
+ **kwargs,
+ )
+ logits = decoder_outputs.logits
+
+ loss = None
+ if labels is not None:
+ # move labels to the correct device to enable PP
+ labels = labels.to(logits.device)
+ loss_fn = nn.BCEWithLogitsLoss()
+ loss = loss_fn(logits, labels)
+
+ return CLIPSegImageSegmentationOutput(
+ loss=loss,
+ logits=logits,
+ conditional_embeddings=conditional_embeddings,
+ pooled_output=pooled_output,
+ vision_model_output=vision_outputs,
+ decoder_output=decoder_outputs,
+ )
+
+
+__all__ = [
+ "CLIPSegConfig",
+ "CLIPSegTextConfig",
+ "CLIPSegVisionConfig",
+ "CLIPSegModel",
+ "CLIPSegPreTrainedModel",
+ "CLIPSegTextModel",
+ "CLIPSegVisionModel",
+ "CLIPSegForImageSegmentation",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/processing_clipseg.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/processing_clipseg.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d2e0538401a4679540c386a42a6660907e4d956
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clipseg/processing_clipseg.py
@@ -0,0 +1,88 @@
+# 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.
+"""
+Image/Text processor class for CLIPSeg
+"""
+
+from ...processing_utils import ProcessorMixin
+from ...tokenization_utils_base import BatchEncoding
+from ...utils import auto_docstring
+
+
+@auto_docstring
+class CLIPSegProcessor(ProcessorMixin):
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
+ super().__init__(image_processor, tokenizer)
+
+ @auto_docstring
+ def __call__(self, text=None, images=None, visual_prompt=None, return_tensors=None, **kwargs):
+ r"""
+ visual_prompt (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
+ The visual prompt image or batch of images to be prepared. Each visual prompt image can be a PIL image,
+ NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape
+ (C, H, W), where C is a number of channels, H and W are image height and width.
+
+ Returns:
+ [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
+
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
+ `None`).
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
+ """
+ if text is None and visual_prompt is None and images is None:
+ raise ValueError("You have to specify either text, visual prompt or images.")
+
+ if text is not None and visual_prompt is not None:
+ raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt.")
+
+ output_kwargs = self._merge_kwargs(
+ self.valid_processor_kwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs
+ )
+
+ if text is not None:
+ encoding = self.tokenizer(text, return_tensors=return_tensors, **output_kwargs["text_kwargs"])
+
+ if visual_prompt is not None:
+ prompt_features = self.image_processor(
+ visual_prompt, return_tensors=return_tensors, **output_kwargs["images_kwargs"]
+ )
+
+ if images is not None:
+ image_features = self.image_processor(
+ images, return_tensors=return_tensors, **output_kwargs["images_kwargs"]
+ )
+
+ if visual_prompt is not None and images is not None:
+ encoding = {
+ "pixel_values": image_features.pixel_values,
+ "conditional_pixel_values": prompt_features.pixel_values,
+ }
+ return encoding
+ elif text is not None and images is not None:
+ encoding["pixel_values"] = image_features.pixel_values
+ return encoding
+ elif text is not None:
+ return encoding
+ elif visual_prompt is not None:
+ encoding = {
+ "conditional_pixel_values": prompt_features.pixel_values,
+ }
+ return encoding
+ else:
+ return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
+
+
+__all__ = ["CLIPSegProcessor"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/configuration_clvp.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/configuration_clvp.py
new file mode 100644
index 0000000000000000000000000000000000000000..008ef26c3a18f898851bd8ef7f6c147db4e4f932
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/models/clvp/configuration_clvp.py
@@ -0,0 +1,253 @@
+# 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.
+"""CLVP model configuration"""
+
+import os
+
+from huggingface_hub.dataclasses import strict
+
+from ...configuration_utils import PreTrainedConfig
+from ...utils import auto_docstring, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+@auto_docstring(checkpoint="susnato/clvp_dev")
+@strict
+class ClvpEncoderConfig(PreTrainedConfig):
+ r"""
+ use_rotary_embedding (`bool`, *optional*, defaults to `True`):
+ Whether to use rotary_embedding or not.
+ use_attention_bias (`bool`, *optional*, defaults to `False`):
+ Whether to use bias in Query, Key and Value layers during self attention.
+ summary_type (`str`, *optional*, defaults to `"mean"`):
+ What strategy to use to get pooler_output from the last_hidden_state. `"last"`, `"first"`, `"mean"` and
+ `"cls_index"` are supported.
+
+ Example:
+
+ ```python
+ >>> from transformers import ClvpEncoderConfig, ClvpEncoder
+
+ >>> # Initializing a ClvpEncoderConfig with susnato/clvp_dev style configuration
+ >>> encoder_configuration = ClvpEncoderConfig()
+
+ >>> # Initializing a ClvpEncoder (with random weights) from the susnato/clvp_dev style configuration
+ >>> model = ClvpEncoder(encoder_configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "clvp_encoder"
+ base_config_key = ["text_config", "speech_config"]
+
+ vocab_size: int = 256
+ hidden_size: int = 768
+ intermediate_size: int = 1536
+ projection_dim: int = 768
+ num_hidden_layers: int = 20
+ num_attention_heads: int = 12
+ hidden_act: str = "gelu"
+ layer_norm_eps: float = 1e-5
+ attention_dropout: float | int = 0.1
+ dropout: float | int = 0.1
+ use_rotary_embedding: bool = True
+ use_attention_bias: bool = False
+ summary_type: str = "mean"
+ initializer_factor: float = 1.0
+ bos_token_id: int | None = 255
+ eos_token_id: int | list[int] | None = 0
+ pad_token_id: int | None = None
+
+ @classmethod
+ def from_pretrained(
+ cls, pretrained_model_name_or_path: str | os.PathLike, config_type: str = "text_config", **kwargs
+ ):
+ config_dict, kwargs = cls.get_config_dict(pretrained_model_name_or_path, **kwargs)
+
+ # make sure to have the config_type be either "text_config" or "speech_config"
+ # this is to make sure that we can load only text or speech configs from the nested ClvpConfig.
+ if config_type not in cls.base_config_key:
+ raise ValueError(
+ f"We can only load either 'text_config' or 'speech_config' but you are trying to load{config_type}"
+ )
+
+ # get the text config dict if we are loading from ClvpConfig
+ if config_dict.get("model_type") == "clvp":
+ config_dict = config_dict[config_type]
+
+ 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)
+
+
+@auto_docstring(checkpoint="susnato/clvp_dev")
+@strict
+class ClvpDecoderConfig(PreTrainedConfig):
+ r"""
+ max_text_tokens (`int`, *optional*, defaults to 404):
+ The maximum sequence length of text tokens that this model might ever be used with. Similar to
+ `n_positions` in `GPT2Config`.
+ n_inner (`int`, *optional*):
+ Dimensionality of the inner feed-forward layers. `None` will set it to 4 times `hidden_size`.
+ num_mel_attn_blocks (`int`, *optional*, defaults to 6):
+ Denotes the number of self attention layers in [`ClvpConditioningEncoder`].
+ summary_type (`string`, *optional*, defaults to `"cls_index"`):
+ Argument used when doing sequence summary.
+ 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`):
+ Whether or not to add a projection after the vector extraction.
+ summary_activation (`str`, *optional*):
+ 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`):
+ Whether the projection outputs should have `config.num_labels` or `config.hidden_size` classes.
+ summary_first_dropout (`float`, *optional*, defaults to 0.1):
+ The dropout ratio to be used after the projection and activation.
+ feature_size (`int`, *optional*, defaults to 80):
+ The feature dimension of the extracted mel features. This value is used in [`ClvpConditioningEncoder`].
+ use_attention_bias (`bool`, *optional*, defaults to `True`):
+ Whether to use bias in Query, Key and Value layers during self attention.
+ decoder_fixing_codes (`list`, *optional*, defaults to `[83, 45, 45, 248]`):
+ These values are used in the method `fix_speech_decoder_output` to fix decoder generated outputs.
+
+ Example:
+
+ ```python
+ >>> from transformers import ClvpDecoderConfig, ClvpDecoder
+
+ >>> # Initializing a ClvpDecoderConfig with susnato/clvp_dev style configuration
+ >>> decoder_configuration = ClvpDecoderConfig()
+
+ >>> # Initializing a ClvpDecoder (with random weights) from the susnato/clvp_dev style configuration
+ >>> model = ClvpDecoder(decoder_configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+ ```"""
+
+ model_type = "clvp_decoder"
+ base_config_key = "decoder_config"
+
+ vocab_size: int = 8194
+ max_position_embeddings: int = 608
+ max_text_tokens: int = 404
+ hidden_size: int = 1024
+ num_hidden_layers: int = 30
+ num_attention_heads: int = 16
+ n_inner: int | None = None
+ num_mel_attn_blocks: int = 6
+ activation_function: str = "gelu_new"
+ resid_pdrop: float | int = 0.1
+ embd_pdrop: float | int = 0.1
+ attention_dropout: float | int = 0.1
+ layer_norm_epsilon: float = 1e-5
+ initializer_range: float = 0.02
+ summary_type: str = "cls_index"
+ summary_use_proj: bool = True
+ summary_activation: str | None = None
+ summary_proj_to_labels: bool = True
+ summary_first_dropout: float | int = 0.1
+ use_cache: bool = True
+ bos_token_id: int | None = 8192
+ eos_token_id: int | list[int] | None = 8193
+ pad_token_id: int | None = None
+ feature_size: int = 80
+ use_attention_bias: bool = True
+ initializer_factor: float = 1.0
+ decoder_fixing_codes: list[int] | tuple[int, ...] = (83, 45, 45, 248)
+ add_cross_attention: bool = False
+
+
+@auto_docstring(checkpoint="susnato/clvp_dev")
+@strict
+class ClvpConfig(PreTrainedConfig):
+ r"""
+ speech_config (`dict`, *optional*):
+ Dictionary of configuration options used to initialize CLVP speech encoder.
+ decoder_config (`dict`, *optional*):
+ Dictionary of configuration options used to initialize [`ClvpDecoderConfig`].
+
+ Example:
+
+ ```python
+ >>> from transformers import ClvpConfig, ClvpModelForConditionalGeneration
+
+ >>> # Initializing a ClvpConfig with susnato/clvp_dev style configuration
+ >>> configuration = ClvpConfig()
+
+ >>> # Initializing a ClvpModelForConditionalGeneration (with random weights) from the susnato/clvp_dev style configuration
+ >>> model = ClvpModelForConditionalGeneration(configuration)
+
+ >>> # Accessing the model configuration
+ >>> configuration = model.config
+
+ >>> # We can also initialize a CLVPConfig from a CLVPTextConfig, CLVPSpeechConfig and a CLVPAutoRegressiveConfig
+ >>> from transformers import ClvpEncoderConfig, ClvpDecoderConfig
+
+ >>> # Initializing a CLVP text, CLVP speech and CLVP decoder configuration
+ >>> config_text = ClvpEncoderConfig()
+ >>> config_speech = ClvpEncoderConfig()
+ >>> decoder_config = ClvpDecoderConfig()
+
+ >>> config = ClvpConfig(config_text, config_speech, decoder_config)
+ ```"""
+
+ model_type = "clvp"
+ sub_configs = {
+ "text_config": ClvpEncoderConfig,
+ "speech_config": ClvpEncoderConfig,
+ "decoder_config": ClvpDecoderConfig,
+ }
+
+ text_config: dict | PreTrainedConfig | None = None
+ speech_config: dict | PreTrainedConfig | None = None
+ decoder_config: dict | PreTrainedConfig | None = None
+ projection_dim: int = 768
+ logit_scale_init_value: float = 2.6592
+ initializer_factor: float = 1.0
+
+ def __post_init__(self, **kwargs):
+ if self.text_config is None:
+ self.text_config = ClvpEncoderConfig()
+ logger.info("`text_config` is `None`. initializing the `ClvpEncoderConfig` with default values.")
+ elif isinstance(self.text_config, dict):
+ self.text_config = ClvpEncoderConfig(**self.text_config)
+
+ if self.speech_config is None:
+ self.speech_config = ClvpEncoderConfig()
+ logger.info("`speech_config` is `None`. initializing the `ClvpEncoderConfig` with default values.")
+ elif isinstance(self.speech_config, dict):
+ self.speech_config = ClvpEncoderConfig(**self.speech_config)
+
+ if self.decoder_config is None:
+ self.decoder_config = ClvpDecoderConfig()
+ logger.info("`image_config` is `None`. initializing the `ClvpDecoderConfig` with default values.")
+ elif isinstance(self.decoder_config, dict):
+ self.decoder_config = ClvpDecoderConfig(**self.decoder_config)
+
+ super().__post_init__(**kwargs)
+
+
+__all__ = ["ClvpConfig", "ClvpDecoderConfig", "ClvpEncoderConfig"]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d11e00115142686de011a8a0243ac7be6be0683
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__init__.py
@@ -0,0 +1,1080 @@
+# 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.
+from __future__ import annotations
+
+import json
+import os
+import warnings
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, Optional, Union
+
+from huggingface_hub import is_offline_mode, model_info
+
+from ..configuration_utils import PreTrainedConfig
+from ..dynamic_module_utils import get_class_from_dynamic_module
+from ..feature_extraction_utils import FeatureExtractionMixin
+from ..image_processing_utils import BaseImageProcessor
+from ..models.auto.configuration_auto import AutoConfig
+from ..models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING, AutoFeatureExtractor
+from ..models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING, AutoImageProcessor
+from ..models.auto.modeling_auto import AutoModelForDepthEstimation, AutoModelForImageToImage
+from ..models.auto.processing_auto import PROCESSOR_MAPPING, AutoProcessor
+from ..models.auto.tokenization_auto import TOKENIZER_MAPPING, AutoTokenizer
+from ..processing_utils import ProcessorMixin
+from ..tokenization_python import PreTrainedTokenizer
+from ..utils import (
+ CONFIG_NAME,
+ cached_file,
+ extract_commit_hash,
+ find_adapter_config_file,
+ is_kenlm_available,
+ is_peft_available,
+ is_pyctcdecode_available,
+ is_torch_available,
+ logging,
+)
+from .any_to_any import AnyToAnyPipeline
+from .audio_classification import AudioClassificationPipeline
+from .automatic_speech_recognition import AutomaticSpeechRecognitionPipeline
+from .base import (
+ ArgumentHandler,
+ CsvPipelineDataFormat,
+ JsonPipelineDataFormat,
+ PipedPipelineDataFormat,
+ Pipeline,
+ PipelineDataFormat,
+ PipelineException,
+ PipelineRegistry,
+ get_default_model_and_revision,
+ load_model,
+)
+from .depth_estimation import DepthEstimationPipeline
+from .document_question_answering import DocumentQuestionAnsweringPipeline
+from .feature_extraction import FeatureExtractionPipeline
+from .fill_mask import FillMaskPipeline
+from .image_classification import ImageClassificationPipeline
+from .image_feature_extraction import ImageFeatureExtractionPipeline
+from .image_segmentation import ImageSegmentationPipeline
+from .image_text_to_text import ImageTextToTextPipeline
+from .keypoint_matching import KeypointMatchingPipeline
+from .mask_generation import MaskGenerationPipeline
+from .object_detection import ObjectDetectionPipeline
+from .table_question_answering import TableQuestionAnsweringArgumentHandler, TableQuestionAnsweringPipeline
+from .text_classification import TextClassificationPipeline
+from .text_generation import TextGenerationPipeline
+from .text_to_audio import TextToAudioPipeline
+from .token_classification import (
+ AggregationStrategy,
+ NerPipeline,
+ TokenClassificationArgumentHandler,
+ TokenClassificationPipeline,
+)
+from .video_classification import VideoClassificationPipeline
+from .zero_shot_audio_classification import ZeroShotAudioClassificationPipeline
+from .zero_shot_classification import ZeroShotClassificationArgumentHandler, ZeroShotClassificationPipeline
+from .zero_shot_image_classification import ZeroShotImageClassificationPipeline
+from .zero_shot_object_detection import ZeroShotObjectDetectionPipeline
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import (
+ AutoModel,
+ AutoModelForAudioClassification,
+ AutoModelForCausalLM,
+ AutoModelForCTC,
+ AutoModelForDocumentQuestionAnswering,
+ AutoModelForImageClassification,
+ AutoModelForImageSegmentation,
+ AutoModelForImageTextToText,
+ AutoModelForKeypointMatching,
+ AutoModelForMaskedLM,
+ AutoModelForMaskGeneration,
+ AutoModelForMultimodalLM,
+ AutoModelForObjectDetection,
+ AutoModelForQuestionAnswering,
+ AutoModelForSemanticSegmentation,
+ AutoModelForSeq2SeqLM,
+ AutoModelForSequenceClassification,
+ AutoModelForSpeechSeq2Seq,
+ AutoModelForTableQuestionAnswering,
+ AutoModelForTextToSpectrogram,
+ AutoModelForTextToWaveform,
+ AutoModelForTokenClassification,
+ AutoModelForVideoClassification,
+ AutoModelForVisualQuestionAnswering,
+ AutoModelForZeroShotImageClassification,
+ AutoModelForZeroShotObjectDetection,
+ )
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..tokenization_utils_tokenizers import PreTrainedTokenizerFast
+
+
+logger = logging.get_logger(__name__)
+
+
+# Register all the supported tasks here
+TASK_ALIASES = {
+ "sentiment-analysis": "text-classification",
+ "ner": "token-classification",
+ "text-to-speech": "text-to-audio",
+}
+SUPPORTED_TASKS = {
+ "audio-classification": {
+ "impl": AudioClassificationPipeline,
+ "pt": (AutoModelForAudioClassification,) if is_torch_available() else (),
+ "default": {"model": ("superb/wav2vec2-base-superb-ks", "372e048")},
+ "type": "audio",
+ },
+ "automatic-speech-recognition": {
+ "impl": AutomaticSpeechRecognitionPipeline,
+ "pt": (AutoModelForCTC, AutoModelForSpeechSeq2Seq) if is_torch_available() else (),
+ "default": {"model": ("facebook/wav2vec2-base-960h", "22aad52")},
+ "type": "multimodal",
+ },
+ "text-to-audio": {
+ "impl": TextToAudioPipeline,
+ "pt": (AutoModelForTextToWaveform, AutoModelForTextToSpectrogram) if is_torch_available() else (),
+ "default": {"model": ("suno/bark-small", "1dbd7a1")},
+ "type": "text",
+ },
+ "feature-extraction": {
+ "impl": FeatureExtractionPipeline,
+ "pt": (AutoModel,) if is_torch_available() else (),
+ "default": {"model": ("distilbert/distilbert-base-cased", "6ea8117")},
+ "type": "text",
+ },
+ "text-classification": {
+ "impl": TextClassificationPipeline,
+ "pt": (AutoModelForSequenceClassification,) if is_torch_available() else (),
+ "default": {"model": ("distilbert/distilbert-base-uncased-finetuned-sst-2-english", "714eb0f")},
+ "type": "text",
+ },
+ "token-classification": {
+ "impl": TokenClassificationPipeline,
+ "pt": (AutoModelForTokenClassification,) if is_torch_available() else (),
+ "default": {"model": ("dbmdz/bert-large-cased-finetuned-conll03-english", "4c53496")},
+ "type": "text",
+ },
+ "table-question-answering": {
+ "impl": TableQuestionAnsweringPipeline,
+ "pt": (AutoModelForTableQuestionAnswering,) if is_torch_available() else (),
+ "default": {"model": ("google/tapas-base-finetuned-wtq", "e3dde19")},
+ "type": "text",
+ },
+ "document-question-answering": {
+ "impl": DocumentQuestionAnsweringPipeline,
+ "pt": (AutoModelForDocumentQuestionAnswering,) if is_torch_available() else (),
+ "default": {"model": ("impira/layoutlm-document-qa", "beed3c4")},
+ "type": "multimodal",
+ },
+ "fill-mask": {
+ "impl": FillMaskPipeline,
+ "pt": (AutoModelForMaskedLM,) if is_torch_available() else (),
+ "default": {"model": ("distilbert/distilroberta-base", "fb53ab8")},
+ "type": "text",
+ },
+ "text-generation": {
+ "impl": TextGenerationPipeline,
+ "pt": (AutoModelForCausalLM,) if is_torch_available() else (),
+ "default": {"model": ("HuggingFaceTB/SmolLM3-3B", "a07cc9a")},
+ "type": "text",
+ },
+ "zero-shot-classification": {
+ "impl": ZeroShotClassificationPipeline,
+ "pt": (AutoModelForSequenceClassification,) if is_torch_available() else (),
+ "default": {
+ "model": ("facebook/bart-large-mnli", "d7645e1"),
+ "config": ("facebook/bart-large-mnli", "d7645e1"),
+ },
+ "type": "text",
+ },
+ "zero-shot-image-classification": {
+ "impl": ZeroShotImageClassificationPipeline,
+ "pt": (AutoModelForZeroShotImageClassification,) if is_torch_available() else (),
+ "default": {"model": ("openai/clip-vit-base-patch32", "3d74acf")},
+ "type": "multimodal",
+ },
+ "zero-shot-audio-classification": {
+ "impl": ZeroShotAudioClassificationPipeline,
+ "pt": (AutoModel,) if is_torch_available() else (),
+ "default": {"model": ("laion/clap-htsat-fused", "cca9e28")},
+ "type": "multimodal",
+ },
+ "image-classification": {
+ "impl": ImageClassificationPipeline,
+ "pt": (AutoModelForImageClassification,) if is_torch_available() else (),
+ "default": {"model": ("google/vit-base-patch16-224", "3f49326")},
+ "type": "image",
+ },
+ "image-feature-extraction": {
+ "impl": ImageFeatureExtractionPipeline,
+ "pt": (AutoModel,) if is_torch_available() else (),
+ "default": {"model": ("google/vit-base-patch16-224", "3f49326")},
+ "type": "image",
+ },
+ "image-segmentation": {
+ "impl": ImageSegmentationPipeline,
+ "pt": (AutoModelForImageSegmentation, AutoModelForSemanticSegmentation) if is_torch_available() else (),
+ "default": {"model": ("facebook/detr-resnet-50-panoptic", "d53b52a")},
+ "type": "multimodal",
+ },
+ "image-text-to-text": {
+ "impl": ImageTextToTextPipeline,
+ "pt": (AutoModelForImageTextToText,) if is_torch_available() else (),
+ "default": {"model": ("Qwen/Qwen3-VL-2B-Instruct", "8964489")},
+ "type": "multimodal",
+ },
+ "object-detection": {
+ "impl": ObjectDetectionPipeline,
+ "pt": (AutoModelForObjectDetection,) if is_torch_available() else (),
+ "default": {"model": ("facebook/detr-resnet-50", "1d5f47b")},
+ "type": "multimodal",
+ },
+ "zero-shot-object-detection": {
+ "impl": ZeroShotObjectDetectionPipeline,
+ "pt": (AutoModelForZeroShotObjectDetection,) if is_torch_available() else (),
+ "default": {"model": ("google/owlvit-base-patch32", "cbc355f")},
+ "type": "multimodal",
+ },
+ "depth-estimation": {
+ "impl": DepthEstimationPipeline,
+ "pt": (AutoModelForDepthEstimation,) if is_torch_available() else (),
+ "default": {"model": ("Intel/dpt-large", "bc15f29")},
+ "type": "image",
+ },
+ "video-classification": {
+ "impl": VideoClassificationPipeline,
+ "pt": (AutoModelForVideoClassification,) if is_torch_available() else (),
+ "default": {"model": ("MCG-NJU/videomae-base-finetuned-kinetics", "488eb9a")},
+ "type": "video",
+ },
+ "mask-generation": {
+ "impl": MaskGenerationPipeline,
+ "pt": (AutoModelForMaskGeneration,) if is_torch_available() else (),
+ "default": {"model": ("facebook/sam-vit-huge", "87aecf0")},
+ "type": "multimodal",
+ },
+ "keypoint-matching": {
+ "impl": KeypointMatchingPipeline,
+ "pt": (AutoModelForKeypointMatching,) if is_torch_available() else (),
+ "default": {"model": ("magic-leap-community/superglue_outdoor", "f4041f8")},
+ "type": "image",
+ },
+ "any-to-any": {
+ "impl": AnyToAnyPipeline,
+ "tf": (),
+ "pt": (AutoModelForMultimodalLM,) if is_torch_available() else (),
+ "default": {
+ "model": {
+ "pt": ("google/gemma-3n-E4B-it", "c1221e9"),
+ }
+ },
+ "type": "multimodal",
+ },
+}
+
+PIPELINE_REGISTRY = PipelineRegistry(supported_tasks=SUPPORTED_TASKS, task_aliases=TASK_ALIASES)
+
+
+def get_supported_tasks() -> list[str]:
+ """
+ Returns a list of supported task strings.
+ """
+ return PIPELINE_REGISTRY.get_supported_tasks()
+
+
+def get_task(model: str, token: str | None = None, **deprecated_kwargs) -> str:
+ if is_offline_mode():
+ raise RuntimeError("You cannot infer task automatically within `pipeline` when using offline mode")
+ try:
+ info = model_info(model, token=token)
+ except Exception as e:
+ raise RuntimeError(f"Instantiating a pipeline without a task set raised an error: {e}")
+ if not info.pipeline_tag:
+ raise RuntimeError(
+ f"The model {model} does not seem to have a correct `pipeline_tag` set to infer the task automatically"
+ )
+ if getattr(info, "library_name", "transformers") not in {"transformers", "timm"}:
+ raise RuntimeError(f"This model is meant to be used with {info.library_name} not with transformers")
+ task = info.pipeline_tag
+ return task
+
+
+def check_task(task: str) -> tuple[str, dict, Any]:
+ """
+ Checks an incoming task string, to validate it's correct and return the default Pipeline and Model classes, and
+ default models if they exist.
+
+ Args:
+ task (`str`):
+ The task defining which pipeline will be returned. Currently accepted tasks are:
+ - `"audio-classification"`
+ - `"automatic-speech-recognition"`
+ - `"conversational"`
+ - `"depth-estimation"`
+ - `"document-question-answering"`
+ - `"feature-extraction"`
+ - `"fill-mask"`
+ - `"image-classification"`
+ - `"image-feature-extraction"`
+ - `"image-segmentation"`
+ - `"keypoint-matching"`
+ - `"object-detection"`
+ - `"table-question-answering"`
+ - `"text-classification"` (alias `"sentiment-analysis"` available)
+ - `"text-generation"`
+ - `"text-to-audio"` (alias `"text-to-speech"` available)
+ - `"token-classification"` (alias `"ner"` available)
+ - `"video-classification"`
+ - `"zero-shot-classification"`
+ - `"zero-shot-image-classification"`
+ - `"zero-shot-object-detection"`
+
+ Returns:
+ (normalized_task: `str`, task_defaults: `dict`, task_options: (`tuple`, None)) The normalized task name
+ (removed alias and options).
+
+
+ """
+ return PIPELINE_REGISTRY.check_task(task)
+
+
+def clean_custom_task(task_info):
+ import transformers
+
+ if "impl" not in task_info:
+ raise RuntimeError("This model introduces a custom pipeline without specifying its implementation.")
+ pt_class_names = task_info.get("pt", ())
+ if isinstance(pt_class_names, str):
+ pt_class_names = [pt_class_names]
+ task_info["pt"] = tuple(getattr(transformers, c) for c in pt_class_names)
+ return task_info, None
+
+
+#
+# fmt: off
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# The part of the file below was automatically generated from the code.
+# Do NOT edit this part of the file manually as any edits will be overwritten by the generation
+# of the file. If any change should be done, please apply the changes to the `pipeline` function
+# below and run `python utils/check_pipeline_typing.py --fix_and_overwrite` to update the file.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+
+from typing import Literal, overload
+
+
+@overload
+def pipeline(task: Literal[None], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> Pipeline: ...
+@overload
+def pipeline(task: Literal["any-to-any"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AnyToAnyPipeline: ...
+@overload
+def pipeline(task: Literal["audio-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AudioClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["automatic-speech-recognition"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> AutomaticSpeechRecognitionPipeline: ...
+@overload
+def pipeline(task: Literal["depth-estimation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> DepthEstimationPipeline: ...
+@overload
+def pipeline(task: Literal["document-question-answering"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> DocumentQuestionAnsweringPipeline: ...
+@overload
+def pipeline(task: Literal["feature-extraction"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> FeatureExtractionPipeline: ...
+@overload
+def pipeline(task: Literal["fill-mask"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> FillMaskPipeline: ...
+@overload
+def pipeline(task: Literal["image-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["image-feature-extraction"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageFeatureExtractionPipeline: ...
+@overload
+def pipeline(task: Literal["image-segmentation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageSegmentationPipeline: ...
+@overload
+def pipeline(task: Literal["image-text-to-text"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ImageTextToTextPipeline: ...
+@overload
+def pipeline(task: Literal["keypoint-matching"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> KeypointMatchingPipeline: ...
+@overload
+def pipeline(task: Literal["mask-generation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> MaskGenerationPipeline: ...
+@overload
+def pipeline(task: Literal["object-detection"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ObjectDetectionPipeline: ...
+@overload
+def pipeline(task: Literal["table-question-answering"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TableQuestionAnsweringPipeline: ...
+@overload
+def pipeline(task: Literal["text-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["text-generation"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextGenerationPipeline: ...
+@overload
+def pipeline(task: Literal["text-to-audio"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TextToAudioPipeline: ...
+@overload
+def pipeline(task: Literal["token-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> TokenClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["video-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> VideoClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["zero-shot-audio-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotAudioClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["zero-shot-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["zero-shot-image-classification"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotImageClassificationPipeline: ...
+@overload
+def pipeline(task: Literal["zero-shot-object-detection"], model: str | PreTrainedModel | None = None, config: str | PreTrainedConfig | None = None, tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None, feature_extractor: str | FeatureExtractionMixin | None = None, image_processor: str | BaseImageProcessor | None = None, processor: str | ProcessorMixin | None = None, revision: str | None = None, use_fast: bool = True, token: str | bool | None = None, device: int | str | torch.device | None = None, device_map: str | dict[str, int | str] | None = None, dtype: str | torch.dtype | None = "auto", trust_remote_code: bool | None = None, model_kwargs: dict[str, Any] | None = None, pipeline_class: Any | None = None, **kwargs: Any) -> ZeroShotObjectDetectionPipeline: ...
+
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# The part of the file above was automatically generated from the code.
+# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
+# fmt: on
+#
+
+
+def _load_pipeline_component(load_flag, component, loader):
+ """Load an optional pipeline component, preserving the original soft-failure behavior."""
+ if not (load_flag or load_flag is None):
+ return component
+
+ try:
+ return loader(component)
+ except Exception:
+ if load_flag:
+ raise
+ return None
+
+
+def _infer_pipeline_component(
+ component,
+ model_name,
+ config,
+ error_message,
+ fallback_component=None,
+):
+ """Infer a component identifier from explicit input, then model/config fallbacks."""
+ if component is not None:
+ return component
+ if isinstance(model_name, str):
+ return model_name
+ if isinstance(config, str):
+ return config
+ if fallback_component is not None:
+ return fallback_component
+ raise Exception(error_message)
+
+
+def _get_tokenizer_loading_kwargs(tokenizer, use_fast, model_kwargs):
+ """Normalize tokenizer tuple/string inputs into `AutoTokenizer.from_pretrained` kwargs."""
+ if isinstance(tokenizer, tuple):
+ tokenizer_identifier = tokenizer[0]
+ tokenizer_kwargs = tokenizer[1].copy()
+ tokenizer_use_fast = tokenizer_kwargs.pop("use_fast", use_fast)
+ else:
+ tokenizer_identifier = tokenizer
+ tokenizer_kwargs = model_kwargs.copy()
+ tokenizer_kwargs.pop("torch_dtype", None)
+ tokenizer_kwargs.pop("dtype", None)
+ tokenizer_use_fast = use_fast
+
+ return tokenizer_identifier, tokenizer_kwargs, tokenizer_use_fast
+
+
+def _resolve_tokenizer(tokenizer, load_tokenizer, use_fast, model_name, config, task, hub_kwargs, model_kwargs):
+ """Resolve and optionally load the tokenizer required by the pipeline class."""
+
+ def load(tokenizer):
+ tokenizer = _infer_pipeline_component(
+ tokenizer,
+ model_name,
+ config,
+ "Impossible to guess which tokenizer to use. "
+ "Please provide a PreTrainedTokenizer class or a path/identifier to a pretrained tokenizer.",
+ )
+
+ if not isinstance(tokenizer, (str, tuple)):
+ return tokenizer
+
+ tokenizer_identifier, tokenizer_kwargs, tokenizer_use_fast = _get_tokenizer_loading_kwargs(
+ tokenizer, use_fast, model_kwargs
+ )
+ return AutoTokenizer.from_pretrained(
+ tokenizer_identifier,
+ use_fast=tokenizer_use_fast,
+ _from_pipeline=task,
+ **hub_kwargs,
+ **tokenizer_kwargs,
+ )
+
+ return _load_pipeline_component(load_tokenizer, tokenizer, load)
+
+
+def _resolve_image_processor(
+ image_processor,
+ feature_extractor,
+ load_image_processor,
+ model_name,
+ config,
+ task,
+ hub_kwargs,
+ model_kwargs,
+):
+ """Resolve and optionally load the image processor for vision-capable pipelines."""
+
+ def load(image_processor):
+ image_processor = _infer_pipeline_component(
+ image_processor,
+ model_name,
+ config,
+ "Impossible to guess which image processor to use. "
+ "Please provide a PreTrainedImageProcessor class or a path/identifier to a pretrained image processor.",
+ fallback_component=feature_extractor if isinstance(feature_extractor, BaseImageProcessor) else None,
+ )
+
+ if not isinstance(image_processor, (str, tuple)):
+ return image_processor
+
+ return AutoImageProcessor.from_pretrained(image_processor, _from_pipeline=task, **hub_kwargs, **model_kwargs)
+
+ return _load_pipeline_component(load_image_processor, image_processor, load)
+
+
+def _maybe_load_ctc_decoder(model_name, hub_kwargs, kwargs, pretrained_model_name_or_path):
+ """Attach a pyctcdecode decoder when the loaded feature extractor declares an LM-backed processor."""
+ config_dict, _ = FeatureExtractionMixin.get_feature_extractor_dict(
+ pretrained_model_name_or_path or model_name,
+ **hub_kwargs,
+ )
+ processor_class = config_dict.get("processor_class", None)
+
+ if processor_class is None or not processor_class.endswith("WithLM") or not isinstance(model_name, str):
+ return
+
+ try:
+ import kenlm # to trigger `ImportError` if not installed
+ from pyctcdecode import BeamSearchDecoderCTC
+
+ if os.path.isdir(model_name) or os.path.isfile(model_name):
+ decoder = BeamSearchDecoderCTC.load_from_dir(model_name)
+ else:
+ language_model_glob = os.path.join(BeamSearchDecoderCTC._LANGUAGE_MODEL_SERIALIZED_DIRECTORY, "*")
+ alphabet_filename = BeamSearchDecoderCTC._ALPHABET_SERIALIZED_FILENAME
+ allow_patterns = [language_model_glob, alphabet_filename]
+ decoder = BeamSearchDecoderCTC.load_from_hf_hub(model_name, allow_patterns=allow_patterns)
+
+ kwargs["decoder"] = decoder
+ except ImportError as error:
+ logger.warning(f"Could not load the `decoder` for {model_name}. Defaulting to raw CTC. Error: {error}")
+ if not is_kenlm_available():
+ logger.warning("Try to install `kenlm`: `pip install kenlm")
+
+ if not is_pyctcdecode_available():
+ logger.warning("Try to install `pyctcdecode`: `pip install pyctcdecode")
+
+
+def _resolve_feature_extractor(
+ feature_extractor,
+ load_feature_extractor,
+ model_name,
+ config,
+ task,
+ hub_kwargs,
+ model_kwargs,
+ kwargs,
+ pretrained_model_name_or_path,
+):
+ """Resolve and optionally load the feature extractor, including CTC decoder side-loading."""
+
+ def load(feature_extractor):
+ feature_extractor = _infer_pipeline_component(
+ feature_extractor,
+ model_name,
+ config,
+ "Impossible to guess which feature extractor to use. "
+ "Please provide a PreTrainedFeatureExtractor class or a path/identifier to a pretrained feature extractor.",
+ )
+
+ if not isinstance(feature_extractor, (str, tuple)):
+ return feature_extractor
+
+ feature_extractor = AutoFeatureExtractor.from_pretrained(
+ feature_extractor, _from_pipeline=task, **hub_kwargs, **model_kwargs
+ )
+ _maybe_load_ctc_decoder(model_name, hub_kwargs, kwargs, pretrained_model_name_or_path)
+ return feature_extractor
+
+ return _load_pipeline_component(load_feature_extractor, feature_extractor, load)
+
+
+def _resolve_processor(processor, load_processor, model_name, config, task, hub_kwargs, model_kwargs):
+ """Resolve and optionally load a multimodal processor."""
+
+ def load(processor):
+ processor = _infer_pipeline_component(
+ processor,
+ model_name,
+ config,
+ "Impossible to guess which processor to use. "
+ "Please provide a processor instance or a path/identifier to a processor.",
+ )
+
+ if not isinstance(processor, (str, tuple)):
+ return processor
+
+ processor = AutoProcessor.from_pretrained(processor, _from_pipeline=task, **hub_kwargs, **model_kwargs)
+ if not isinstance(processor, ProcessorMixin):
+ raise TypeError(
+ "Processor was loaded, but it is not an instance of `ProcessorMixin`. "
+ f"Got type `{type(processor)}` instead. Please check that you specified "
+ "correct pipeline task for the model and model has processor implemented and saved."
+ )
+ return processor
+
+ return _load_pipeline_component(load_processor, processor, load)
+
+
+def pipeline(
+ task: str | None = None,
+ model: str | PreTrainedModel | None = None,
+ config: str | PreTrainedConfig | None = None,
+ tokenizer: str | PreTrainedTokenizer | PreTrainedTokenizerFast | None = None,
+ feature_extractor: str | FeatureExtractionMixin | None = None,
+ image_processor: str | BaseImageProcessor | None = None,
+ processor: str | ProcessorMixin | None = None,
+ revision: str | None = None,
+ use_fast: bool = True,
+ token: str | bool | None = None,
+ device: int | str | torch.device | None = None,
+ device_map: str | dict[str, int | str] | None = None,
+ dtype: str | torch.dtype | None = "auto",
+ trust_remote_code: bool | None = None,
+ model_kwargs: dict[str, Any] | None = None,
+ pipeline_class: Any | None = None,
+ **kwargs: Any,
+) -> Pipeline:
+ """
+ Utility factory method to build a [`Pipeline`].
+
+ A pipeline consists of:
+
+ - One or more components for pre-processing model inputs, such as a [tokenizer](tokenizer),
+ [image_processor](image_processor), [feature_extractor](feature_extractor), or [processor](processors).
+ - A [model](model) that generates predictions from the inputs.
+ - Optional post-processing steps to refine the model's output, which can also be handled by processors.
+
+
+ While there are such optional arguments as `tokenizer`, `feature_extractor`, `image_processor`, and `processor`,
+ they shouldn't be specified all at once. If these components are not provided, `pipeline` will try to load
+ required ones automatically. In case you want to provide these components explicitly, please refer to a
+ specific pipeline in order to get more details regarding what components are required.
+
+
+ Args:
+ task (`str`):
+ The task defining which pipeline will be returned. Currently accepted tasks are:
+
+ - `"audio-classification"`: will return a [`AudioClassificationPipeline`].
+ - `"automatic-speech-recognition"`: will return a [`AutomaticSpeechRecognitionPipeline`].
+ - `"depth-estimation"`: will return a [`DepthEstimationPipeline`].
+ - `"document-question-answering"`: will return a [`DocumentQuestionAnsweringPipeline`].
+ - `"feature-extraction"`: will return a [`FeatureExtractionPipeline`].
+ - `"fill-mask"`: will return a [`FillMaskPipeline`]:.
+ - `"image-classification"`: will return a [`ImageClassificationPipeline`].
+ - `"image-feature-extraction"`: will return an [`ImageFeatureExtractionPipeline`].
+ - `"image-segmentation"`: will return a [`ImageSegmentationPipeline`].
+ - `"image-text-to-text"`: will return a [`ImageTextToTextPipeline`].
+ - `"keypoint-matching"`: will return a [`KeypointMatchingPipeline`].
+ - `"mask-generation"`: will return a [`MaskGenerationPipeline`].
+ - `"object-detection"`: will return a [`ObjectDetectionPipeline`].
+ - `"table-question-answering"`: will return a [`TableQuestionAnsweringPipeline`].
+ - `"text-classification"` (alias `"sentiment-analysis"` available): will return a
+ [`TextClassificationPipeline`].
+ - `"text-generation"`: will return a [`TextGenerationPipeline`]:.
+ - `"text-to-audio"` (alias `"text-to-speech"` available): will return a [`TextToAudioPipeline`]:.
+ - `"token-classification"` (alias `"ner"` available): will return a [`TokenClassificationPipeline`].
+ - `"video-classification"`: will return a [`VideoClassificationPipeline`].
+ - `"zero-shot-classification"`: will return a [`ZeroShotClassificationPipeline`].
+ - `"zero-shot-image-classification"`: will return a [`ZeroShotImageClassificationPipeline`].
+ - `"zero-shot-audio-classification"`: will return a [`ZeroShotAudioClassificationPipeline`].
+ - `"zero-shot-object-detection"`: will return a [`ZeroShotObjectDetectionPipeline`].
+
+ model (`str` or [`PreTrainedModel`], *optional*):
+ The model that will be used by the pipeline to make predictions. This can be a model identifier or an
+ actual instance of a pretrained model inheriting from [`PreTrainedModel`].
+
+ If not provided, the default for the `task` will be loaded.
+ config (`str` or [`PreTrainedConfig`], *optional*):
+ The configuration that will be used by the pipeline to instantiate the model. This can be a model
+ identifier or an actual pretrained model configuration inheriting from [`PreTrainedConfig`].
+
+ If not provided, the default configuration file for the requested model will be used. That means that if
+ `model` is given, its default configuration will be used. However, if `model` is not supplied, this
+ `task`'s default model's config is used instead.
+ tokenizer (`str` or [`PreTrainedTokenizer`], *optional*):
+ The tokenizer that will be used by the pipeline to encode data for the model. This can be a model
+ identifier or an actual pretrained tokenizer inheriting from [`PreTrainedTokenizer`].
+
+ If not provided, the default tokenizer for the given `model` will be loaded (if it is a string). If `model`
+ is not specified or not a string, then the default tokenizer for `config` is loaded (if it is a string).
+ However, if `config` is also not given or not a string, then the default tokenizer for the given `task`
+ will be loaded.
+ feature_extractor (`str` or [`FeatureExtractionMixin`], *optional*):
+ The feature extractor that will be used by the pipeline to encode data for the model. This can be a model
+ identifier or an actual pretrained feature extractor inheriting from [`FeatureExtractionMixin`].
+
+ Feature extractors are used for non-NLP models, such as Speech or Vision models as well as multi-modal
+ models. Multi-modal models will also require a tokenizer to be passed.
+
+ If not provided, the default feature extractor for the given `model` will be loaded (if it is a string). If
+ `model` is not specified or not a string, then the default feature extractor for `config` is loaded (if it
+ is a string). However, if `config` is also not given or not a string, then the default feature extractor
+ for the given `task` will be loaded.
+ image_processor (`str` or [`BaseImageProcessor`], *optional*):
+ The image processor that will be used by the pipeline to preprocess images for the model. This can be a
+ model identifier or an actual image processor inheriting from [`BaseImageProcessor`].
+
+ Image processors are used for Vision models and multi-modal models that require image inputs. Multi-modal
+ models will also require a tokenizer to be passed.
+
+ If not provided, the default image processor for the given `model` will be loaded (if it is a string). If
+ `model` is not specified or not a string, then the default image processor for `config` is loaded (if it is
+ a string).
+ processor (`str` or [`ProcessorMixin`], *optional*):
+ The processor that will be used by the pipeline to preprocess data for the model. This can be a model
+ identifier or an actual processor inheriting from [`ProcessorMixin`].
+
+ Processors are used for multi-modal models that require multi-modal inputs, for example, a model that
+ requires both text and image inputs.
+
+ If not provided, the default processor for the given `model` will be loaded (if it is a string). If `model`
+ is not specified or not a string, then the default processor for `config` is loaded (if it is a string).
+ revision (`str`, *optional*, defaults to `"main"`):
+ When passing a task name or a string model identifier: The specific model version to use. It can be a
+ branch name, a tag name, or a commit id, since we use a git-based system for storing models and other
+ artifacts on huggingface.co, so `revision` can be any identifier allowed by git.
+ use_fast (`bool`, *optional*, defaults to `True`):
+ Whether or not to use a Fast tokenizer if possible (a [`PreTrainedTokenizerFast`]).
+ token (`str` or *bool*, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
+ when running `hf auth login`.
+ device (`int` or `str` or `torch.device`):
+ Defines the device (*e.g.*, `"cpu"`, `"cuda:1"`, `"mps"`, or a GPU ordinal rank like `1`) on which this
+ pipeline will be allocated.
+ device_map (`str` or `dict[str, Union[int, str, torch.device]`, *optional*):
+ Sent directly as `model_kwargs` (just a simpler shortcut). When `accelerate` library is present, set
+ `device_map="auto"` to compute the most optimized `device_map` automatically (see
+ [here](https://huggingface.co/docs/accelerate/main/en/package_reference/big_modeling#accelerate.cpu_offload)
+ for more information).
+
+
+
+ Do not use `device_map` AND `device` at the same time as they will conflict
+
+
+
+ dtype (`str` or `torch.dtype`, *optional*):
+ Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model
+ (`torch.float16`, `torch.bfloat16`, ... or `"auto"`).
+ trust_remote_code (`bool`, *optional*, defaults to `False`):
+ Whether or not to allow for custom code defined on the Hub in their own modeling, configuration,
+ tokenization or even pipeline files. This option should only be set to `True` for repositories you trust
+ and in which you have read the code, as it will execute code present on the Hub on your local machine.
+ model_kwargs (`dict[str, Any]`, *optional*):
+ Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,
+ **model_kwargs)` function.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional keyword arguments passed along to the specific pipeline init (see the documentation for the
+ corresponding pipeline class for possible values).
+
+ Returns:
+ [`Pipeline`]: A suitable pipeline for the task.
+
+ Examples:
+
+ ```python
+ >>> from transformers import pipeline, AutoModelForTokenClassification, AutoTokenizer
+
+ >>> # Sentiment analysis pipeline
+ >>> analyzer = pipeline("sentiment-analysis")
+
+ >>> # Named entity recognition pipeline, passing in a specific model and tokenizer
+ >>> model = AutoModelForTokenClassification.from_pretrained("dbmdz/bert-large-cased-finetuned-conll03-english")
+ >>> tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased")
+ >>> recognizer = pipeline("ner", model=model, tokenizer=tokenizer)
+ ```"""
+ if model_kwargs is None:
+ model_kwargs = {}
+
+ code_revision = kwargs.pop("code_revision", None)
+ commit_hash = kwargs.pop("_commit_hash", None)
+ local_files_only = kwargs.get("local_files_only", False)
+
+ hub_kwargs = {
+ "revision": revision,
+ "token": token,
+ "trust_remote_code": trust_remote_code,
+ "_commit_hash": commit_hash,
+ "local_files_only": local_files_only,
+ }
+
+ if task is None and model is None:
+ raise RuntimeError(
+ "Impossible to instantiate a pipeline without either a task or a model "
+ "being specified. "
+ "Please provide a task class or a model"
+ )
+
+ if model is None and tokenizer is not None:
+ raise RuntimeError(
+ "Impossible to instantiate a pipeline with tokenizer specified but not the model as the provided tokenizer"
+ " may not be compatible with the default model. Please provide a PreTrainedModel class or a"
+ " path/identifier to a pretrained model when providing tokenizer."
+ )
+ if model is None and feature_extractor is not None:
+ raise RuntimeError(
+ "Impossible to instantiate a pipeline with feature_extractor specified but not the model as the provided"
+ " feature_extractor may not be compatible with the default model. Please provide a PreTrainedModel class"
+ " or a path/identifier to a pretrained model when providing feature_extractor."
+ )
+ if isinstance(model, Path):
+ model = str(model)
+
+ pretrained_model_name_or_path = None
+ if commit_hash is None:
+ if isinstance(config, str):
+ pretrained_model_name_or_path = config
+ elif config is None and isinstance(model, str):
+ pretrained_model_name_or_path = model
+
+ if not isinstance(config, PreTrainedConfig) and pretrained_model_name_or_path is not None:
+ # We make a call to the config file first (which may be absent) to get the commit hash as soon as possible
+ resolved_config_file = cached_file(
+ pretrained_model_name_or_path,
+ CONFIG_NAME,
+ _raise_exceptions_for_gated_repo=False,
+ _raise_exceptions_for_missing_entries=False,
+ _raise_exceptions_for_connection_errors=False,
+ cache_dir=model_kwargs.get("cache_dir"),
+ **hub_kwargs,
+ )
+ hub_kwargs["_commit_hash"] = extract_commit_hash(resolved_config_file, commit_hash)
+ else:
+ hub_kwargs["_commit_hash"] = getattr(config, "_commit_hash", None)
+
+ # Config is the primordial information item.
+ # Instantiate config if needed
+ adapter_path = None
+ if isinstance(config, str):
+ config = AutoConfig.from_pretrained(
+ config, _from_pipeline=task, code_revision=code_revision, **hub_kwargs, **model_kwargs
+ )
+ hub_kwargs["_commit_hash"] = config._commit_hash
+ elif config is None and isinstance(model, str):
+ # Check for an adapter file in the model path if PEFT is available
+ if is_peft_available():
+ # `find_adapter_config_file` doesn't accept `trust_remote_code`
+ _hub_kwargs = {k: v for k, v in hub_kwargs.items() if k != "trust_remote_code"}
+ maybe_adapter_path = find_adapter_config_file(
+ model,
+ token=hub_kwargs["token"],
+ revision=hub_kwargs["revision"],
+ _commit_hash=hub_kwargs["_commit_hash"],
+ )
+
+ if maybe_adapter_path is not None:
+ with open(maybe_adapter_path, "r", encoding="utf-8") as f:
+ adapter_config = json.load(f)
+ adapter_path = model
+ # Only override the model name/path if the current value doesn't point to a
+ # complete model with an embedded adapter so that local models with embedded
+ # adapters will load from the local base model rather than pull the base
+ # model named in the adapter's config from the hub.
+ if not os.path.exists(model) or not os.path.exists(os.path.join(model, CONFIG_NAME)):
+ model = adapter_config["base_model_name_or_path"]
+
+ config = AutoConfig.from_pretrained(
+ model, _from_pipeline=task, code_revision=code_revision, **hub_kwargs, **model_kwargs
+ )
+ hub_kwargs["_commit_hash"] = config._commit_hash
+
+ custom_tasks = {}
+ if config is not None and len(getattr(config, "custom_pipelines", {})) > 0:
+ custom_tasks = config.custom_pipelines
+ if task is None and trust_remote_code is not False:
+ if len(custom_tasks) == 1:
+ task = list(custom_tasks.keys())[0]
+ else:
+ raise RuntimeError(
+ "We can't infer the task automatically for this model as there are multiple tasks available. Pick "
+ f"one in {', '.join(custom_tasks.keys())}"
+ )
+
+ if task is None and model is not None:
+ if not isinstance(model, str):
+ raise RuntimeError(
+ "Inferring the task automatically requires to check the hub with a model_id defined as a `str`. "
+ f"{model} is not a valid model_id."
+ )
+ task = get_task(model, token)
+
+ # Retrieve the task
+ if task in custom_tasks:
+ targeted_task, task_options = clean_custom_task(custom_tasks[task])
+ if pipeline_class is None:
+ if not trust_remote_code:
+ raise ValueError(
+ "Loading this pipeline requires you to execute the code in the pipeline file in that"
+ " repo on your local machine. Make sure you have read the code there to avoid malicious use, then"
+ " set the option `trust_remote_code=True` to remove this error."
+ )
+ class_ref = targeted_task["impl"]
+ pipeline_class = get_class_from_dynamic_module(
+ class_ref,
+ model,
+ code_revision=code_revision,
+ **hub_kwargs,
+ )
+ else:
+ normalized_task, targeted_task, task_options = check_task(task)
+ if pipeline_class is None:
+ pipeline_class = targeted_task["impl"]
+
+ # Use default model/config/tokenizer for the task if no model is provided
+ if model is None:
+ model, default_revision = get_default_model_and_revision(targeted_task, task_options)
+ revision = revision if revision is not None else default_revision
+ logger.warning(
+ f"No model was supplied, defaulted to {model} and revision {revision}.\n"
+ "Using a pipeline without specifying a model name and revision in production is not recommended."
+ )
+ hub_kwargs["revision"] = revision
+ if config is None and isinstance(model, str):
+ config = AutoConfig.from_pretrained(model, _from_pipeline=task, **hub_kwargs, **model_kwargs)
+ hub_kwargs["_commit_hash"] = config._commit_hash
+
+ if device_map is not None:
+ if "device_map" in model_kwargs:
+ raise ValueError(
+ 'You cannot use both `pipeline(... device_map=..., model_kwargs={"device_map":...})` as those'
+ " arguments might conflict, use only one.)"
+ )
+ if device is not None:
+ logger.warning(
+ "Both `device` and `device_map` are specified. `device` will override `device_map`. You"
+ " will most likely encounter unexpected behavior. Please remove `device` and keep `device_map`."
+ )
+ model_kwargs["device_map"] = device_map
+
+ # BC for the `torch_dtype` argument
+ if (torch_dtype := kwargs.get("torch_dtype")) is not None:
+ logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!")
+ # If both are provided, keep `dtype`
+ dtype = torch_dtype if dtype == "auto" else dtype
+ if "torch_dtype" in model_kwargs or "dtype" in model_kwargs:
+ if "torch_dtype" in model_kwargs:
+ logger.warning_once("`torch_dtype` is deprecated! Use `dtype` instead!")
+ # If the user did not explicitly provide `dtype` (i.e. the function default "auto" is still
+ # present) but a value is supplied inside `model_kwargs`, we silently defer to the latter instead of
+ # raising. This prevents false positives like providing `dtype` only via `model_kwargs` while the
+ # top-level argument keeps its default value "auto".
+ if dtype == "auto":
+ dtype = None
+ else:
+ raise ValueError(
+ 'You cannot use both `pipeline(... dtype=..., model_kwargs={"dtype":...})` as those'
+ " arguments might conflict, use only one.)"
+ )
+ if dtype is not None:
+ if isinstance(dtype, str) and hasattr(torch, dtype):
+ dtype = getattr(torch, dtype)
+ model_kwargs["dtype"] = dtype
+
+ model_name = model if isinstance(model, str) else None
+
+ # Load the correct model if possible
+ if isinstance(model, str):
+ model_classes = targeted_task["pt"]
+ model = load_model(
+ adapter_path if adapter_path is not None else model,
+ model_classes=model_classes,
+ config=config,
+ task=task,
+ **hub_kwargs,
+ **model_kwargs,
+ )
+
+ hub_kwargs["_commit_hash"] = model.config._commit_hash
+
+ if pipeline_class is None:
+ raise RuntimeError("Failed to resolve a pipeline class.")
+
+ load_tokenizer = getattr(pipeline_class, "_load_tokenizer")
+ load_image_processor = getattr(pipeline_class, "_load_image_processor")
+ load_feature_extractor = getattr(pipeline_class, "_load_feature_extractor")
+ load_processor = getattr(pipeline_class, "_load_processor")
+
+ tokenizer = _resolve_tokenizer(
+ tokenizer=tokenizer,
+ load_tokenizer=load_tokenizer,
+ use_fast=use_fast,
+ model_name=model_name,
+ config=config,
+ task=task,
+ hub_kwargs=hub_kwargs,
+ model_kwargs=model_kwargs,
+ )
+ image_processor = _resolve_image_processor(
+ image_processor=image_processor,
+ feature_extractor=feature_extractor,
+ load_image_processor=load_image_processor,
+ model_name=model_name,
+ config=config,
+ task=task,
+ hub_kwargs=hub_kwargs,
+ model_kwargs=model_kwargs,
+ )
+ feature_extractor = _resolve_feature_extractor(
+ feature_extractor=feature_extractor,
+ load_feature_extractor=load_feature_extractor,
+ model_name=model_name,
+ config=config,
+ task=task,
+ hub_kwargs=hub_kwargs,
+ model_kwargs=model_kwargs,
+ kwargs=kwargs,
+ pretrained_model_name_or_path=pretrained_model_name_or_path,
+ )
+ processor = _resolve_processor(
+ processor=processor,
+ load_processor=load_processor,
+ model_name=model_name,
+ config=config,
+ task=task,
+ hub_kwargs=hub_kwargs,
+ model_kwargs=model_kwargs,
+ )
+
+ if tokenizer is not None:
+ kwargs["tokenizer"] = tokenizer
+
+ if feature_extractor is not None:
+ kwargs["feature_extractor"] = feature_extractor
+
+ if dtype is not None:
+ kwargs["dtype"] = dtype
+
+ if image_processor is not None:
+ kwargs["image_processor"] = image_processor
+
+ if device is not None:
+ kwargs["device"] = device
+
+ if processor is not None:
+ kwargs["processor"] = processor
+
+ return pipeline_class(model=model, task=task, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..01929afaeaf7aede65517e1f6c485b3a1cee4dd1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/any_to_any.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/any_to_any.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d347f3454d8861d95f6dac87f4871261d4564902
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/any_to_any.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_classification.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..666ea5b746119eb78e715a5e9313f668c312ab0c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_classification.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f087d148a7815a18df82784ee40ee847ed569448
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/audio_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..023cd4177dd49c5de1750ec5f7c6886c4145f4cc
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/automatic_speech_recognition.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05e9715d0607fd8c7666732d1230c38fd7cb24ca
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/depth_estimation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/depth_estimation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..acdbc91f61af36dfbda623259235125fc64b0703
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/depth_estimation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/document_question_answering.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/document_question_answering.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2730e05fd58d962001085f758ec384f1cb6e8924
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/document_question_answering.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/feature_extraction.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/feature_extraction.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cb940b6ff9da980e390b8d66f24fd515a4fb61ac
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/feature_extraction.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/fill_mask.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/fill_mask.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..9cc065e8dbfd20b5519cc14a9051d30f2d7ac408
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/fill_mask.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_classification.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3213747d97ce92f73d822475539a511e4835b8dd
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_classification.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_feature_extraction.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_feature_extraction.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ea35d30200b20a6ecf47b8ed668201c6f1e553ab
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_feature_extraction.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_segmentation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_segmentation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3852c4906b6d28dc4e4fc023e2eafebc9b89b05d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_segmentation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_text_to_text.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_text_to_text.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..db863adac1ee0992ef2e3a1790dc8cdd01f61302
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/image_text_to_text.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/keypoint_matching.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/keypoint_matching.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64ae278b9c23c146442650c5e38f10cacbc72cd9
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/keypoint_matching.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/mask_generation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/mask_generation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc3c90e62c5b8c0e3dae85250868894f23474c80
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/mask_generation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/object_detection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/object_detection.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..35214486817589ea0221240622c31216c130b565
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/object_detection.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/pt_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/pt_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e52e76c4af5d50bdb5511c451754baaddd99b5ce
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/pt_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/table_question_answering.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/table_question_answering.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4b68bf45c5b147558fbe2ff19fd014827c7bf3ac
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/table_question_answering.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_classification.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8296b911a02141facbdeebda7e41a6bbbb87c1ed
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_classification.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_generation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_generation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b319d4c98576f0a70870656374818352ce108102
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_generation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_to_audio.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_to_audio.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c5e8a96d9cdfa259c9a717a6c2d359906bca6990
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/text_to_audio.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/token_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/token_classification.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..6de4183c30da6532994fc2517541b9b049a77667
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/token_classification.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/video_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/video_classification.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4825e2ac9c7134ebfdf7ec28205e2c913f75ef13
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/video_classification.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..91904324c1b8f77a56d47d54524e0c4893eddb24
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_audio_classification.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_classification.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c76b213eba1726716713988d6552f6163bc16a41
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_classification.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..467a3785df558244a9103f5675eae1ef2acc892e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_image_classification.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..24acf6d4394d8bf6b3e517395d410aad5086d394
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/__pycache__/zero_shot_object_detection.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/any_to_any.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/any_to_any.py
new file mode 100644
index 0000000000000000000000000000000000000000..4ae91d5a176f19ab0aec3ab042be1d8c45030c47
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/any_to_any.py
@@ -0,0 +1,514 @@
+# 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.
+
+import enum
+import re
+from typing import Any, Union, overload
+
+import numpy as np
+
+from ..audio_utils import AudioInput
+from ..generation import GenerationConfig
+from ..image_utils import ImageInput
+from ..processing_utils import ProcessingKwargs, Unpack
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+from ..video_utils import VideoInput
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES
+ from .pt_utils import KeyDataset
+
+if is_vision_available():
+ from PIL import Image
+
+logger = logging.get_logger(__name__)
+
+
+class ReturnType(enum.Enum):
+ TENSORS = 0
+ NEW_TEXT = 1
+ FULL_TEXT = 2
+
+
+class Chat:
+ """This class is intended to just be used internally in this pipeline and not exposed to users. We convert chats
+ to this format because the rest of the pipeline code tends to assume that lists of messages are
+ actually a batch of samples rather than messages in the same conversation."""
+
+ def __init__(self, messages: list[dict]):
+ for message in messages:
+ if not ("role" in message and "content" in message):
+ raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.")
+ self.messages = messages
+
+
+@add_end_docstrings(build_pipeline_init_args(has_processor=True))
+class AnyToAnyPipeline(Pipeline):
+ """
+ Multimodal Generation pipeline using an `AutoModelForMultimodalLM`. This pipeline generates text given any
+ combination of multimodal data and text.When the underlying model is a conversational model, it can also
+ accept one or more chats, in which case the pipeline will operate in chat mode and will continue the
+ chat(s) by adding its response(s). Each chat takes the form of a list of dicts, where each dict contains
+ "role" and "content" keys.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> pipe = pipeline(task="any-to-any", model="google/gemma-3n-E4B-it")
+ >>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of")
+ [{'generated_text': 'a photo of two birds'}]
+ ```
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> pipe = pipeline("any-to-any", model="google/gemma-3n-E4B-it")
+ >>> messages = [
+ >>> {
+ >>> "role": "user",
+ >>> "content": [
+ >>> {
+ >>> "type": "image",
+ >>> "url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
+ >>> },
+ >>> {"type": "text", "text": "Describe this image."},
+ >>> ],
+ >>> },
+ >>> {
+ >>> "role": "assistant",
+ >>> "content": [
+ >>> {"type": "text", "text": "There is a dog and"},
+ >>> ],
+ >>> },
+ >>> ]
+ >>> pipe(text=messages, max_new_tokens=20, return_full_text=False)
+ [{'input_text': [{'role': 'user',
+ 'content': [{'type': 'image',
+ 'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'},
+ {'type': 'text', 'text': 'Describe this image.'}]},
+ {'role': 'assistant',
+ 'content': [{'type': 'text', 'text': 'There is a dog and'}]}],
+ 'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This multimodal pipeline can currently be loaded from pipeline() using the following task identifier:
+ "any-to-any".
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?pipeline_tag=any-to-any).
+ """
+
+ _load_processor = True
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ _pipeline_calls_generate = True
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ )
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ if "image" in self.model.input_modalities or "video" in self.model.input_modalities:
+ requires_backends(self, "vision")
+ requires_backends(self, "torchvision")
+ if "audio" in self.model.input_modalities:
+ requires_backends(self, "librosa")
+ self.check_model_type(MODEL_FOR_MULTIMODAL_LM_MAPPING_NAMES)
+
+ def _sanitize_parameters(
+ self,
+ max_new_tokens=None,
+ generate_kwargs=None,
+ timeout=None,
+ return_full_text=None,
+ return_tensors=None,
+ return_type=None,
+ clean_up_tokenization_spaces=None,
+ stop_sequence=None,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ generation_mode=None,
+ processor_kwargs=None,
+ **kwargs: Unpack[ProcessingKwargs],
+ ):
+ forward_kwargs = {}
+ preprocess_params = {}
+ postprocess_params = {}
+
+ # Preprocess params
+ preprocess_params.update(kwargs)
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+ if continue_final_message is not None:
+ preprocess_params["continue_final_message"] = continue_final_message
+ if processor_kwargs is not None:
+ preprocess_params["processor_kwargs"] = processor_kwargs
+
+ # Forward kwargs
+ forward_kwargs["generate_kwargs"] = generate_kwargs or {}
+ if generation_mode is not None and generation_mode != "text":
+ forward_kwargs["generate_kwargs"]["generation_mode"] = generation_mode
+ # Qwen-Omni models need to know the origin of audio, to align mm position ids
+ if kwargs.get("load_audio_from_video") and re.search(r"qwen\domni", self.model.__class__.__name__.lower()):
+ forward_kwargs["generate_kwargs"]["use_audio_in_video"] = True
+ if stop_sequence is not None:
+ if isinstance(stop_sequence, str):
+ stop_sequence = [stop_sequence]
+ forward_kwargs["generate_kwargs"]["stop_strings"] = stop_sequence
+ forward_kwargs["generate_kwargs"]["tokenizer"] = self.processor.tokenizer
+
+ if max_new_tokens is not None:
+ if generate_kwargs is not None and "max_new_tokens" in generate_kwargs:
+ raise ValueError(
+ "'max_new_tokens' is defined twice, once in 'generate_kwargs' and "
+ "once as a direct argument. Please use only one."
+ )
+ forward_kwargs["generate_kwargs"]["max_new_tokens"] = max_new_tokens
+
+ if return_full_text is not None and return_type is None:
+ if return_tensors is not None:
+ raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`")
+ return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
+ elif return_tensors is not None and return_type is None:
+ return_type = ReturnType.TENSORS
+ # We don't want to set the global default to FULLTEXT at init time. That is why
+ # `_postprocess_params` is checked before setting the default value
+ elif return_type is None and generation_mode in [None, "text"] and hasattr(self, "_postprocess_params"):
+ return_type = ReturnType.FULL_TEXT
+
+ # Postprocess params
+ if generation_mode not in [None, "text"] and return_type is not None:
+ raise ValueError(
+ f"`return_type` cannot be set to {return_type} when generation_mode={generation_mode}. "
+ "Set `return_type=None` or generation_mode='text'"
+ )
+ if generation_mode not in [None, "text", "image", "audio"]:
+ raise ValueError(
+ f"`generation_mode` can be only one of the `text`, `audio`, `image` but got generation_mode[={generation_mode}]"
+ )
+ elif generation_mode is not None and generation_mode not in self.model.output_modalities:
+ raise ValueError(
+ f"`generation_mode={generation_mode}` is not supported for {self.model.__class__.__name__}. "
+ f"The model can only output the following modalities: {self.model.output_modalities}"
+ )
+
+ if return_type is not None:
+ postprocess_params["return_type"] = return_type
+ if continue_final_message is not None:
+ postprocess_params["continue_final_message"] = continue_final_message
+ if clean_up_tokenization_spaces is not None:
+ postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces
+ if skip_special_tokens is not None:
+ postprocess_params["skip_special_tokens"] = skip_special_tokens
+ postprocess_params["generation_mode"] = generation_mode
+ return preprocess_params, forward_kwargs, postprocess_params
+
+ @overload
+ def __call__(
+ self,
+ text: str | None = None,
+ images: Union[str, "Image.Image"] | None = None,
+ videos: Union[str, "np.ndarray", "torch.Tensor"] | None = None,
+ audio: Union[str, "np.ndarray"] | None = None,
+ **kwargs: Any,
+ ) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(
+ self,
+ text: list[str] | None = None,
+ images: list[str] | list["Image.Image"] | None = None,
+ videos: list[str] | list["np.ndarray"] | list["torch.Tensor"] | None = None,
+ audio: list[str] | list["np.ndarray"] | None = None,
+ **kwargs: Any,
+ ) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self,
+ text: str | list[str] | list[dict],
+ images: str | list[str] | list[list[str]] | ImageInput | None = None,
+ videos: str | list[str] | VideoInput | None = None,
+ audio: str | list[str] | AudioInput | None = None,
+ **kwargs,
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Generate a text given text and optionally multimodal data passed as inputs.
+
+ Args:
+ text (`str`, `list[str]`, `list[dict]`):
+ The text to be used for generation. If a list of strings is passed, the length of the list should be
+ the same as the number of images. Text can also follow the chat format: a list of dictionaries where
+ each dictionary represents a message in a conversation. Each dictionary should have two keys: 'role'
+ and 'content'. 'role' should be one of 'user', 'system' or 'assistant'. 'content' should be a list of
+ dictionary containing the text of the message and the type of the message.
+ images (`str`, `list[str]`, `ImageInput`):
+ The pipeline handles three types of images:
+
+ - A string containing a HTTP(s) link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images. Finally, this pipeline also supports
+ the chat format (see `text`) containing images and text in this argument.
+ videos (`str`, `list[str]`, `VideoInput`):
+ The pipeline handles three types of videos:
+
+ - A string containing a HTTP(s) link pointing to a video
+ - A string containing a local path to a video
+ - A video loaded and decoded to array format
+
+ The pipeline accepts either a single video or a batch of videos. Finally, this pipeline also supports
+ the chat format (see `text`) containing videos and text in this argument.
+ audio (`str`, `list[str]`, `AudioInput`):
+ The pipeline handles three types of audios:
+
+ - A string containing a HTTP(s) link pointing to an audio
+ - A string containing a local path to an audio
+ - An audio loaded in PIL directly
+
+ The pipeline accepts either a single audios or a batch of audios. Finally, this pipeline also supports
+ the chat format (see `text`) containing audios and text in this argument.
+ return_tensors (`bool`, *optional*, defaults to `False`):
+ Returns the tensors of predictions (as token indices) in the outputs. If set to
+ `True`, the decoded text is not returned.
+ return_text (`bool`, *optional*):
+ Returns the decoded texts in the outputs.
+ return_full_text (`bool`, *optional*, defaults to `True`):
+ If set to `False` only added text is returned, otherwise the full text is returned. Cannot be
+ specified at the same time as `return_text`.
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
+ Whether or not to clean up the potential extra spaces in the text output.
+ continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the
+ last message in the input chat rather than starting a new one, allowing you to "prefill" its response.
+ By default this is `True` when the final message in the input chat has the `assistant` role and
+ `False` otherwise, but you can manually override that behaviour by setting this flag.
+
+ Return:
+ A list or a list of list of `dict`: Each result comes as a dictionary with the following key (cannot
+ return a combination of both `generated_text` and `generated_token_ids`):
+
+ - **generated_text** (`str`, present when `return_text=True` and `generation_mode="text"`) -- The generated text.
+ - **generated_audio** (`np.ndarray`, present when `generation_mode="audio"`) -- The generated audio.
+ - **generated_image** (`PIL.Image.Image`, present when `generation_mode="image"`) -- The generated image.
+ - **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True` and `generation_mode="text"`) -- The token
+ ids of the generated text.
+ - **input_text** (`str`) -- The input text.
+ """
+ if images is None and text is None:
+ raise ValueError("You must at least provide either text or images.")
+
+ if isinstance(text, (list, tuple, KeyDataset)) and isinstance(text[0], (list, tuple, dict)):
+ # We have one or more prompts in list-of-dicts format, so this is chat mode
+ if isinstance(text[0], dict) and "role" in text[0]:
+ return super().__call__(Chat(text), **kwargs)
+ elif isinstance(text[0], (list, tuple)) and isinstance(text[0][0], dict) and "role" in text[0][0]:
+ chats = [Chat(chat) for chat in text] # 🐈 🐈 🐈
+ return super().__call__(chats, **kwargs)
+
+ if text is not None and not (isinstance(text, str) or (isinstance(text, list) and isinstance(text[0], str))):
+ """
+ Supports the following format
+ - {"text": text, "image": image, "video": video, "audio": audio}
+ - [{"text": text, "image": image, "video": video, "audio": audio}]
+ - Generator and datasets
+ This is a common pattern in other multimodal pipelines, so we support it here as well.
+ """
+ return super().__call__(text, **kwargs)
+
+ # encourage the user to use the chat format if supported
+ if getattr(self.processor, "chat_template", None) is not None:
+ logger.warning_once(
+ "The input data was not formatted as a chat with dicts containing 'role' and 'content' keys, even "
+ "though this model supports chat. Consider using the chat format for better results. For more "
+ "information, see https://huggingface.co/docs/transformers/en/chat_templating"
+ )
+
+ return super().__call__({"text": text, "images": images, "video": videos, "audio": audio}, **kwargs)
+
+ def preprocess(self, inputs=None, timeout=None, continue_final_message=None, **processing_kwargs):
+ if isinstance(inputs, Chat):
+ # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default
+ # because very few models support multiple separate, consecutive assistant messages
+ if continue_final_message is None:
+ continue_final_message = inputs.messages[-1]["role"] == "assistant"
+
+ # Processor kwargs are passed separately from jinja kwargs to chat template
+ # but it was added only in https://github.com/huggingface/transformers/pull/44881
+ processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or {}
+
+ chat_template_kwargs = {
+ "continue_final_message": continue_final_message,
+ "return_tensors": "pt",
+ "tokenize": True,
+ "return_dict": True,
+ "add_generation_prompt": not continue_final_message,
+ "processor_kwargs": processor_kwargs,
+ **processing_kwargs,
+ }
+
+ # Handle Mistral tokenizer which does not accept processing kwargs
+ if self.processor.tokenizer.__class__.__name__ == "MistralCommonBackend":
+ chat_template_kwargs = {
+ k: v for k, v in chat_template_kwargs.items() if k in ["padding", "truncation", "max_length"]
+ }
+
+ model_inputs = self.processor.apply_chat_template(
+ inputs.messages,
+ **chat_template_kwargs,
+ ).to(dtype=self.dtype)
+ model_inputs["text"] = inputs
+ return model_inputs
+
+ # In case we only have text inputs
+ if isinstance(inputs, (list, tuple, str)):
+ text = inputs
+ inputs = {}
+ else:
+ inputs = inputs.copy() # avoid in-place changes if users passed dict
+ text = inputs.pop("text")
+
+ # Feature extractor do not load audio files and expect a decoded array
+ if inputs.get("audio", None) is not None and hasattr(self.processor, "feature_extractor"):
+ inputs["audio"] = self.processor.feature_extractor.fetch_audio(inputs["audio"])
+
+ # If batched text inputs, we set padding to True unless specified otherwise
+ processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or processing_kwargs
+ if isinstance(text, (list, tuple)) and len(text) > 1:
+ processor_kwargs.setdefault("padding", True)
+ model_inputs = self.processor(text=text, **inputs, return_tensors="pt", **processor_kwargs).to(
+ dtype=self.dtype
+ )
+ model_inputs["text"] = text
+ return model_inputs
+
+ def _forward(self, model_inputs, generate_kwargs=None):
+ generate_kwargs = {} if generate_kwargs is None else generate_kwargs
+ prompt_text = model_inputs.pop("text")
+ input_ids = model_inputs.get("input_ids", model_inputs.get("decoder_input_ids"))
+
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ generated_sequence = self.model.generate(**model_inputs, **generate_kwargs)
+ return {"generated_sequence": generated_sequence, "prompt_text": prompt_text, "input_ids": input_ids}
+
+ def postprocess(
+ self,
+ model_outputs,
+ return_type=None,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ **postprocess_kwargs,
+ ):
+ input_texts = model_outputs["prompt_text"]
+ input_texts = [input_texts] if isinstance(input_texts, (str, Chat)) else input_texts
+ generated_sequence = model_outputs["generated_sequence"]
+ input_ids = model_outputs["input_ids"]
+ if return_type == ReturnType.TENSORS:
+ return [
+ {"input_text": input_texts[i], "generated_token_ids": generated_sequence[i]}
+ for i in range(len(input_texts))
+ ]
+
+ # Decode inputs and outputs the same way to remove input text from generated text if present
+ skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True
+ if getattr(self.tokenizer, "response_schema", False):
+ skip_special_tokens = False
+ generation_mode = postprocess_kwargs["generation_mode"] or "text"
+ if generation_mode == "image" and hasattr(self.model, "decode_image_tokens"):
+ generated_sequence = self.model.decode_image_tokens(generated_sequence.to(self.model.device))
+ generated_outputs = self.processor.post_process_multimodal_output(
+ generated_sequence, skip_special_tokens=skip_special_tokens, **postprocess_kwargs
+ )
+
+ # Force consistent behavior for including the input text in the output
+ if return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
+ # Remove the input text from the generated text if the generated text starts with the input text
+ # (accounting for the possibility of a space between the input and generated text)
+ new_generated_texts = []
+ postprocess_kwargs["generation_mode"] = "text"
+ decoded_inputs = self.processor.post_process_multimodal_output(
+ input_ids, skip_special_tokens=skip_special_tokens, **postprocess_kwargs
+ )
+ for text_generated, decoded_input in zip(generated_outputs, decoded_inputs):
+ # There can be added characters before the input text, so we need to find the beginning of the input text in the generated text
+ index_input_text = text_generated.find(decoded_input)
+ # Limit the search to 2 residual characters, like spaces or new lines, to avoid removing a large part of the answer
+ if 0 <= index_input_text <= 2:
+ # If the input text is found, we remove it
+ new_generated_texts.append(text_generated[index_input_text + len(decoded_input) :])
+ else:
+ new_generated_texts.append(text_generated)
+ generated_outputs = new_generated_texts
+ if return_type == ReturnType.FULL_TEXT:
+ full_texts = []
+ for prompt_text, generated_text in zip(input_texts, generated_outputs):
+ if isinstance(prompt_text, str):
+ generated_text = prompt_text + generated_text
+ elif isinstance(prompt_text, Chat):
+ if continue_final_message is None:
+ # If the user passes a chat ending in an assistant message, we treat it as a prefill by
+ # default because very few models support multiple separate, consecutive assistant messages
+ continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
+ if continue_final_message:
+ # With assistant prefill, concat onto the end of the last message
+ new_text = dict(prompt_text.messages[-1]["content"][-1].items())
+ new_text["text"] += generated_text
+ generated_text = list(prompt_text.messages)[:-1] + [
+ {
+ "role": prompt_text.messages[-1]["role"],
+ "content": prompt_text.messages[-1]["content"][:-1] + [new_text],
+ }
+ ]
+ else:
+ # When we're not starting from a prefill, the output is a new assistant message
+ if getattr(self.tokenizer, "response_schema", False):
+ assistant_message = self.tokenizer.parse_response(generated_text)
+ else:
+ assistant_message = {"role": "assistant", "content": generated_text}
+ generated_text = list(prompt_text.messages) + [assistant_message]
+ full_texts.append(generated_text)
+ generated_outputs = full_texts
+
+ records = [
+ {
+ "input_text": input_text.messages if isinstance(input_text, Chat) else input_text,
+ f"generated_{generation_mode}": generated_output,
+ }
+ for input_text, generated_output in zip(input_texts, generated_outputs)
+ ]
+
+ return records
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e173111aa860dd2dd313b3c613cb04334a3ac72
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_classification.py
@@ -0,0 +1,260 @@
+# 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.
+import subprocess
+from typing import Any
+
+import httpx
+import numpy as np
+
+from ..utils import add_end_docstrings, is_torch_available, is_torchaudio_available, is_torchcodec_available, logging
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES
+
+logger = logging.get_logger(__name__)
+
+
+def ffmpeg_read(bpayload: bytes, sampling_rate: int) -> np.ndarray:
+ """
+ Helper function to read an audio file through ffmpeg.
+ """
+ ar = f"{sampling_rate}"
+ ac = "1"
+ format_for_conversion = "f32le"
+ ffmpeg_command = [
+ "ffmpeg",
+ "-i",
+ "pipe:0",
+ "-ac",
+ ac,
+ "-ar",
+ ar,
+ "-f",
+ format_for_conversion,
+ "-hide_banner",
+ "-loglevel",
+ "quiet",
+ "pipe:1",
+ ]
+
+ try:
+ ffmpeg_process = subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
+ except FileNotFoundError:
+ raise ValueError("ffmpeg was not found but is required to load audio files from filename")
+ output_stream = ffmpeg_process.communicate(bpayload)
+ out_bytes = output_stream[0]
+
+ audio = np.frombuffer(out_bytes, np.float32)
+ if audio.shape[0] == 0:
+ raise ValueError("Malformed soundfile")
+ return audio
+
+
+@add_end_docstrings(build_pipeline_init_args(has_feature_extractor=True))
+class AudioClassificationPipeline(Pipeline):
+ # no-format
+ """
+ Audio classification pipeline using any `AutoModelForAudioClassification`. This pipeline predicts the class of a
+ raw waveform or an audio file. In case of an audio file, ffmpeg should be installed to support multiple audio
+ formats.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> classifier = pipeline(model="superb/wav2vec2-base-superb-ks")
+ >>> classifier("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
+ [{'score': 0.997, 'label': '_unknown_'}, {'score': 0.002, 'label': 'left'}, {'score': 0.0, 'label': 'yes'}, {'score': 0.0, 'label': 'down'}, {'score': 0.0, 'label': 'stop'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+
+ This pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"audio-classification"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=audio-classification).
+ """
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = True
+ _load_tokenizer = False
+
+ def __init__(self, *args, **kwargs):
+ # Only set default top_k if explicitly provided
+ if "top_k" in kwargs and kwargs["top_k"] is None:
+ kwargs["top_k"] = None
+ elif "top_k" not in kwargs:
+ kwargs["top_k"] = 5
+ super().__init__(*args, **kwargs)
+
+ self.check_model_type(MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES)
+
+ def __call__(self, inputs: np.ndarray | bytes | str | dict, **kwargs: Any) -> list[dict[str, Any]]:
+ """
+ Classify the sequence(s) given as inputs. See the [`AutomaticSpeechRecognitionPipeline`] documentation for more
+ information.
+
+ Args:
+ inputs (`np.ndarray` or `bytes` or `str` or `dict`):
+ The inputs is either :
+ - `str` that is the filename of the audio file, the file will be read at the correct sampling rate
+ to get the waveform using *ffmpeg*. This requires *ffmpeg* to be installed on the system.
+ - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the
+ same way.
+ - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`)
+ Raw audio at the correct sampling rate (no further check will be done)
+ - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this
+ pipeline do the resampling. The dict must be either be in the format `{"sampling_rate": int,
+ "raw": np.array}`, or `{"sampling_rate": int, "array": np.array}`, where the key `"raw"` or
+ `"array"` is used to denote the raw audio waveform.
+ top_k (`int`, *optional*, defaults to None):
+ The number of top labels that will be returned by the pipeline. If the provided number is `None` or
+ higher than the number of labels available in the model configuration, it will default to the number of
+ labels.
+ function_to_apply (`str`, *optional*, defaults to "softmax"):
+ The function to apply to the model output. By default, the pipeline will apply the softmax function to
+ the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Python's
+ built-in `None` will default to "softmax", so you need to pass the string "none" to disable any
+ post-processing.
+
+ Return:
+ A list of `dict` with the following keys:
+
+ - **label** (`str`) -- The label predicted.
+ - **score** (`float`) -- The corresponding probability.
+ """
+ return super().__call__(inputs, **kwargs)
+
+ def _sanitize_parameters(self, top_k=None, function_to_apply=None, **kwargs):
+ postprocess_params = {}
+
+ # If top_k is None, use all labels
+ if top_k is None:
+ postprocess_params["top_k"] = self.model.config.num_labels
+ else:
+ if top_k > self.model.config.num_labels:
+ top_k = self.model.config.num_labels
+ postprocess_params["top_k"] = top_k
+
+ if function_to_apply is not None:
+ if function_to_apply not in ["softmax", "sigmoid", "none"]:
+ raise ValueError(
+ f"Invalid value for `function_to_apply`: {function_to_apply}. "
+ "Valid options are ['softmax', 'sigmoid', 'none']"
+ )
+ postprocess_params["function_to_apply"] = function_to_apply
+ else:
+ postprocess_params["function_to_apply"] = "softmax"
+ return {}, {}, postprocess_params
+
+ def preprocess(self, inputs):
+ if isinstance(inputs, str):
+ if inputs.startswith("http://") or inputs.startswith("https://"):
+ # We need to actually check for a real protocol, otherwise it's impossible to use a local file
+ # like http_huggingface_co.png
+ inputs = httpx.get(inputs, follow_redirects=True).content
+ else:
+ with open(inputs, "rb") as f:
+ inputs = f.read()
+
+ if isinstance(inputs, bytes):
+ inputs = ffmpeg_read(inputs, self.feature_extractor.sampling_rate)
+
+ if is_torch_available():
+ import torch
+
+ if isinstance(inputs, torch.Tensor):
+ inputs = inputs.cpu().numpy()
+
+ if is_torchcodec_available():
+ import torch
+ import torchcodec
+
+ if isinstance(inputs, torchcodec.decoders.AudioDecoder):
+ _audio_samples = inputs.get_all_samples()
+ _array = _audio_samples.data
+ inputs = {"array": _array, "sampling_rate": _audio_samples.sample_rate}
+
+ if isinstance(inputs, dict):
+ inputs = inputs.copy() # So we don't mutate the original dictionary outside the pipeline
+ # Accepting `"array"` which is the key defined in `datasets` for
+ # better integration
+ if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)):
+ raise ValueError(
+ "When passing a dictionary to AudioClassificationPipeline, the dict needs to contain a "
+ '"raw" key containing the numpy array or torch tensor representing the audio and a "sampling_rate" key, '
+ "containing the sampling_rate associated with that array"
+ )
+
+ _inputs = inputs.pop("raw", None)
+ if _inputs is None:
+ # Remove path which will not be used from `datasets`.
+ inputs.pop("path", None)
+ _inputs = inputs.pop("array", None)
+ in_sampling_rate = inputs.pop("sampling_rate")
+ inputs = _inputs
+ if in_sampling_rate != self.feature_extractor.sampling_rate:
+ import torch
+
+ if is_torchaudio_available():
+ from torchaudio import functional as F
+ else:
+ raise ImportError(
+ "torchaudio is required to resample audio samples in AudioClassificationPipeline. "
+ "The torchaudio package can be installed through: `pip install torchaudio`."
+ )
+
+ inputs = F.resample(
+ torch.from_numpy(inputs) if isinstance(inputs, np.ndarray) else inputs,
+ in_sampling_rate,
+ self.feature_extractor.sampling_rate,
+ ).numpy()
+
+ if not isinstance(inputs, np.ndarray):
+ raise TypeError("We expect a numpy ndarray or torch tensor as input")
+ if len(inputs.shape) != 1:
+ raise ValueError("We expect a single channel audio input for AudioClassificationPipeline")
+
+ processed = self.feature_extractor(
+ inputs, sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt"
+ )
+ if self.dtype is not None:
+ processed = processed.to(dtype=self.dtype)
+ return processed
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ return model_outputs
+
+ def postprocess(self, model_outputs, top_k=5, function_to_apply="softmax"):
+ if function_to_apply == "softmax":
+ probs = model_outputs.logits[0].softmax(-1)
+ elif function_to_apply == "sigmoid":
+ probs = model_outputs.logits[0].sigmoid()
+ else:
+ probs = model_outputs.logits[0]
+ scores, ids = probs.topk(top_k)
+
+ scores = scores.tolist()
+ ids = ids.tolist()
+
+ labels = [{"score": score, "label": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)]
+
+ return labels
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e3e0bcd521572f751202c4f618e0a0be0251a16
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/audio_utils.py
@@ -0,0 +1,295 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+import datetime
+import platform
+import subprocess
+
+import numpy as np
+
+
+def ffmpeg_read(bpayload: bytes, sampling_rate: int) -> np.ndarray:
+ """
+ Helper function to read an audio file through ffmpeg.
+ """
+ ar = f"{sampling_rate}"
+ ac = "1"
+ format_for_conversion = "f32le"
+ ffmpeg_command = [
+ "ffmpeg",
+ "-i",
+ "pipe:0",
+ "-ac",
+ ac,
+ "-ar",
+ ar,
+ "-f",
+ format_for_conversion,
+ "-hide_banner",
+ "-loglevel",
+ "quiet",
+ "pipe:1",
+ ]
+
+ try:
+ with subprocess.Popen(ffmpeg_command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) as ffmpeg_process:
+ output_stream = ffmpeg_process.communicate(bpayload)
+ except FileNotFoundError as error:
+ raise ValueError("ffmpeg was not found but is required to load audio files from filename") from error
+ out_bytes = output_stream[0]
+ audio = np.frombuffer(out_bytes, np.float32)
+ if audio.shape[0] == 0:
+ raise ValueError(
+ "Soundfile is either not in the correct format or is malformed. Ensure that the soundfile has "
+ "a valid audio file extension (e.g. wav, flac or mp3) and is not corrupted. If reading from a remote "
+ "URL, ensure that the URL is the full address to **download** the audio file."
+ )
+ return audio
+
+
+def ffmpeg_microphone(
+ sampling_rate: int,
+ chunk_length_s: float,
+ format_for_conversion: str = "f32le",
+ ffmpeg_input_device: str | None = None,
+ ffmpeg_additional_args: list[str] | None = None,
+):
+ """
+ Helper function to read audio from a microphone using ffmpeg. The default input device will be used unless another
+ input device is specified using the `ffmpeg_input_device` argument. Uses 'alsa' on Linux, 'avfoundation' on MacOS and
+ 'dshow' on Windows.
+
+ Arguments:
+ sampling_rate (`int`):
+ The sampling_rate to use when reading the data from the microphone. Try using the model's sampling_rate to
+ avoid resampling later.
+ chunk_length_s (`float` or `int`):
+ The length of the maximum chunk of audio to be sent returned.
+ format_for_conversion (`str`, defaults to `f32le`):
+ The name of the format of the audio samples to be returned by ffmpeg. The standard is `f32le`, `s16le`
+ could also be used.
+ ffmpeg_input_device (`str`, *optional*):
+ The identifier of the input device to be used by ffmpeg (i.e. ffmpeg's '-i' argument). If unset,
+ the default input device will be used. See `https://www.ffmpeg.org/ffmpeg-devices.html#Input-Devices`
+ for how to specify and list input devices.
+ ffmpeg_additional_args (`list[str]`, *optional*):
+ Additional arguments to pass to ffmpeg, can include arguments like -nostdin for running as a background
+ process. For example, to pass -nostdin to the ffmpeg process, pass in ["-nostdin"]. If passing in flags
+ with multiple arguments, use the following convention (eg ["flag", "arg1", "arg2]).
+
+ Returns:
+ A generator yielding audio chunks of `chunk_length_s` seconds as `bytes` objects of length
+ `int(round(sampling_rate * chunk_length_s)) * size_of_sample`.
+ """
+ ar = f"{sampling_rate}"
+ ac = "1"
+ if format_for_conversion == "s16le":
+ size_of_sample = 2
+ elif format_for_conversion == "f32le":
+ size_of_sample = 4
+ else:
+ raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`")
+
+ system = platform.system()
+
+ if system == "Linux":
+ format_ = "alsa"
+ input_ = ffmpeg_input_device or "default"
+ elif system == "Darwin":
+ format_ = "avfoundation"
+ input_ = ffmpeg_input_device or ":default"
+ elif system == "Windows":
+ format_ = "dshow"
+ input_ = ffmpeg_input_device or _get_microphone_name()
+
+ ffmpeg_additional_args = [] if ffmpeg_additional_args is None else ffmpeg_additional_args
+
+ ffmpeg_command = [
+ "ffmpeg",
+ "-f",
+ format_,
+ "-i",
+ input_,
+ "-ac",
+ ac,
+ "-ar",
+ ar,
+ "-f",
+ format_for_conversion,
+ "-fflags",
+ "nobuffer",
+ "-hide_banner",
+ "-loglevel",
+ "quiet",
+ "pipe:1",
+ ]
+
+ ffmpeg_command.extend(ffmpeg_additional_args)
+
+ chunk_len = int(round(sampling_rate * chunk_length_s)) * size_of_sample
+ iterator = _ffmpeg_stream(ffmpeg_command, chunk_len)
+ yield from iterator
+
+
+def ffmpeg_microphone_live(
+ sampling_rate: int,
+ chunk_length_s: float,
+ stream_chunk_s: int | None = None,
+ stride_length_s: tuple[float, float] | float | None = None,
+ format_for_conversion: str = "f32le",
+ ffmpeg_input_device: str | None = None,
+ ffmpeg_additional_args: list[str] | None = None,
+):
+ """
+ Helper function to read audio from a microphone using ffmpeg. This will output `partial` overlapping chunks starting
+ from `stream_chunk_s` (if it is defined) until `chunk_length_s` is reached. It will make use of striding to avoid
+ errors on the "sides" of the various chunks. The default input device will be used unless another input device is
+ specified using the `ffmpeg_input_device` argument. Uses 'alsa' on Linux, 'avfoundation' on MacOS and 'dshow' on Windows.
+
+ Arguments:
+ sampling_rate (`int`):
+ The sampling_rate to use when reading the data from the microphone. Try using the model's sampling_rate to
+ avoid resampling later.
+ chunk_length_s (`float` or `int`):
+ The length of the maximum chunk of audio to be sent returned. This includes the eventual striding.
+ stream_chunk_s (`float` or `int`):
+ The length of the minimal temporary audio to be returned.
+ stride_length_s (`float` or `int` or `(float, float)`, *optional*):
+ The length of the striding to be used. Stride is used to provide context to a model on the (left, right) of
+ an audio sample but without using that part to actually make the prediction. Setting this does not change
+ the length of the chunk.
+ format_for_conversion (`str`, *optional*, defaults to `f32le`):
+ The name of the format of the audio samples to be returned by ffmpeg. The standard is `f32le`, `s16le`
+ could also be used.
+ ffmpeg_input_device (`str`, *optional*):
+ The identifier of the input device to be used by ffmpeg (i.e. ffmpeg's '-i' argument). If unset,
+ the default input device will be used. See `https://www.ffmpeg.org/ffmpeg-devices.html#Input-Devices`
+ for how to specify and list input devices.
+ ffmpeg_additional_args (`list[str]`, *optional*):
+ Additional arguments to pass to ffmpeg, can include arguments like -nostdin for running as a background
+ process. For example, to pass -nostdin to the ffmpeg process, pass in ["-nostdin"]. If passing in flags
+ with multiple arguments, use the following convention (eg ["flag", "arg1", "arg2]).
+
+ Return:
+ A generator yielding dictionaries of the following form
+
+ `{"sampling_rate": int, "raw": np.ndarray, "partial" bool}` With optionally a `"stride" (int, int)` key if
+ `stride_length_s` is defined.
+
+ `stride` and `raw` are all expressed in `samples`, and `partial` is a boolean saying if the current yield item
+ is a whole chunk, or a partial temporary result to be later replaced by another larger chunk.
+ """
+ if stream_chunk_s is not None:
+ chunk_s = stream_chunk_s
+ else:
+ chunk_s = chunk_length_s
+
+ microphone = ffmpeg_microphone(
+ sampling_rate,
+ chunk_s,
+ format_for_conversion=format_for_conversion,
+ ffmpeg_input_device=ffmpeg_input_device,
+ ffmpeg_additional_args=[] if ffmpeg_additional_args is None else ffmpeg_additional_args,
+ )
+
+ if format_for_conversion == "s16le":
+ dtype = np.int16
+ size_of_sample = 2
+ elif format_for_conversion == "f32le":
+ dtype = np.float32
+ size_of_sample = 4
+ else:
+ raise ValueError(f"Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`")
+
+ if stride_length_s is None:
+ stride_length_s = chunk_length_s / 6
+ chunk_len = int(round(sampling_rate * chunk_length_s)) * size_of_sample
+ if isinstance(stride_length_s, (int, float)):
+ stride_length_s = [stride_length_s, stride_length_s]
+
+ stride_left = int(round(sampling_rate * stride_length_s[0])) * size_of_sample
+ stride_right = int(round(sampling_rate * stride_length_s[1])) * size_of_sample
+ audio_time = datetime.datetime.now()
+ delta = datetime.timedelta(seconds=chunk_s)
+ for item in chunk_bytes_iter(microphone, chunk_len, stride=(stride_left, stride_right), stream=True):
+ # Put everything back in numpy scale
+ item["raw"] = np.frombuffer(item["raw"], dtype=dtype)
+ item["stride"] = (
+ item["stride"][0] // size_of_sample,
+ item["stride"][1] // size_of_sample,
+ )
+ item["sampling_rate"] = sampling_rate
+ audio_time += delta
+ if datetime.datetime.now() > audio_time + 10 * delta:
+ # We're late !! SKIP
+ continue
+ yield item
+
+
+def chunk_bytes_iter(iterator, chunk_len: int, stride: tuple[int, int], stream: bool = False):
+ """
+ Reads raw bytes from an iterator and does chunks of length `chunk_len`. Optionally adds `stride` to each chunks to
+ get overlaps. `stream` is used to return partial results even if a full `chunk_len` is not yet available.
+ """
+ acc = b""
+ stride_left, stride_right = stride
+ if stride_left + stride_right >= chunk_len:
+ raise ValueError(
+ f"Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}"
+ )
+ _stride_left = 0
+ for raw in iterator:
+ acc += raw
+ if stream and len(acc) < chunk_len:
+ stride = (_stride_left, 0)
+ yield {"raw": acc[:chunk_len], "stride": stride, "partial": True}
+ else:
+ while len(acc) >= chunk_len:
+ # We are flushing the accumulator
+ stride = (_stride_left, stride_right)
+ item = {"raw": acc[:chunk_len], "stride": stride}
+ if stream:
+ item["partial"] = False
+ yield item
+ _stride_left = stride_left
+ acc = acc[chunk_len - stride_left - stride_right :]
+ # Last chunk
+ if len(acc) > stride_left:
+ item = {"raw": acc, "stride": (_stride_left, 0)}
+ if stream:
+ item["partial"] = False
+ yield item
+
+
+def _ffmpeg_stream(ffmpeg_command, buflen: int):
+ """
+ Internal function to create the generator of data through ffmpeg
+ """
+ bufsize = 2**24 # 16Mo
+ try:
+ with subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, bufsize=bufsize) as ffmpeg_process:
+ while True:
+ raw = ffmpeg_process.stdout.read(buflen)
+ if raw == b"":
+ break
+ yield raw
+ except FileNotFoundError as error:
+ raise ValueError("ffmpeg was not found but is required to stream audio files from filename") from error
+
+
+def _get_microphone_name():
+ """
+ Retrieve the microphone name in Windows .
+ """
+ command = ["ffmpeg", "-list_devices", "true", "-f", "dshow", "-i", ""]
+
+ try:
+ ffmpeg_devices = subprocess.run(command, text=True, stderr=subprocess.PIPE, encoding="utf-8")
+ microphone_lines = [line for line in ffmpeg_devices.stderr.splitlines() if "(audio)" in line]
+
+ if microphone_lines:
+ microphone_name = microphone_lines[0].split('"')[1]
+ print(f"Using microphone: {microphone_name}")
+ return f"audio={microphone_name}"
+ except FileNotFoundError:
+ print("ffmpeg was not found. Please install it or make sure it is in your system PATH.")
+
+ return "default"
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/automatic_speech_recognition.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/automatic_speech_recognition.py
new file mode 100644
index 0000000000000000000000000000000000000000..4817b4b2d37d0e11d34cc24c15df162c1f4cee48
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/automatic_speech_recognition.py
@@ -0,0 +1,693 @@
+# 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 collections import defaultdict
+from typing import TYPE_CHECKING, Any, Union
+
+import httpx
+import numpy as np
+
+from ..generation import GenerationConfig
+from ..tokenization_python import PreTrainedTokenizer
+from ..utils import is_torch_available, is_torchaudio_available, is_torchcodec_available, logging
+from .audio_utils import ffmpeg_read
+from .base import ChunkPipeline
+
+
+if TYPE_CHECKING:
+ from pyctcdecode import BeamSearchDecoderCTC
+
+ from ..feature_extraction_sequence_utils import SequenceFeatureExtractor
+ from ..modeling_utils import PreTrainedModel
+
+logger = logging.get_logger(__name__)
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES
+
+
+def rescale_stride(stride, ratio):
+ """
+ Rescales the stride values from audio space to tokens/logits space.
+
+ (160_000, 16_000, 16_000) -> (2000, 200, 200) for instance.
+ """
+ # Shape is [B, SEQ] for tokens
+ # [B, SEQ, V] for logits
+
+ new_strides = []
+ for input_n, left, right in stride:
+ token_n = int(round(input_n * ratio))
+ left = int(round(left / input_n * token_n))
+ right = int(round(right / input_n * token_n))
+ new_stride = (token_n, left, right)
+ new_strides.append(new_stride)
+
+ return new_strides
+
+
+def chunk_iter(inputs, feature_extractor, chunk_len, stride_left, stride_right, dtype=None):
+ inputs_len = inputs.shape[0]
+ step = chunk_len - stride_left - stride_right
+ for chunk_start_idx in range(0, inputs_len, step):
+ chunk_end_idx = chunk_start_idx + chunk_len
+ chunk = inputs[chunk_start_idx:chunk_end_idx]
+ processed = feature_extractor(
+ chunk,
+ sampling_rate=feature_extractor.sampling_rate,
+ return_tensors="pt",
+ return_attention_mask=True,
+ )
+ if dtype is not None:
+ processed = processed.to(dtype=dtype)
+ _stride_left = 0 if chunk_start_idx == 0 else stride_left
+ is_last = chunk_end_idx >= inputs_len
+ _stride_right = 0 if is_last else stride_right
+
+ chunk_len = chunk.shape[0]
+ stride = (chunk_len, _stride_left, _stride_right)
+ if chunk.shape[0] > _stride_left:
+ yield {"is_last": is_last, "stride": stride, **processed}
+ if is_last:
+ break
+
+
+def _find_longest_common_sequence(sequences, tokenizer):
+ # TODO Use a faster algorithm this can probably be done in O(n)
+ # using suffix array.
+ # It might be tedious to do because of fault tolerance.
+ # We actually have a really good property which is that the total sequence
+ # MUST be those subsequences in order.
+ # Also the algorithm should be more tolerant to errors.
+ sequence = [tok_id for tok_id in sequences[0][0].tolist() if tok_id not in tokenizer.all_special_ids]
+ for new_seq in sequences[1:]:
+ new_sequence = [tok_id for tok_id in new_seq[0].tolist() if tok_id not in tokenizer.all_special_ids]
+
+ index = 0
+ max_ = 0.0
+ for i in range(1, len(new_sequence) + 1):
+ # epsilon to favor long perfect matches
+ eps = i / 10000.0
+ matches = np.sum(np.array(sequence[-i:]) == np.array(new_sequence[:i]))
+ matching = matches / i + eps
+ if matches > 1 and matching > max_:
+ index = i
+ max_ = matching
+ sequence.extend(new_sequence[index:])
+ return np.array(sequence)
+
+
+class AutomaticSpeechRecognitionPipeline(ChunkPipeline):
+ """
+ Pipeline that aims at extracting spoken text contained within some audio.
+
+ The input can be either a raw waveform or a audio file. In case of the audio file, ffmpeg should be installed for
+ to support multiple audio formats
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+ - num_beams: 5
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> transcriber = pipeline(model="openai/whisper-base")
+ >>> transcriber("https://huggingface.co/datasets/Narsil/asr_dummy/resolve/main/1.flac")
+ {'text': ' He hoped there would be stew for dinner, turnips and carrots and bruised potatoes and fat mutton pieces to be ladled out in thick, peppered flour-fatten sauce.'}
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ Arguments:
+ model ([`PreTrainedModel`]):
+ The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from
+ [`PreTrainedModel`].
+ feature_extractor ([`SequenceFeatureExtractor`], *optional*):
+ The feature extractor that will be used by the pipeline to encode waveform for the model.
+ tokenizer ([`PreTrainedTokenizer`], *optional*):
+ The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from
+ [`PreTrainedTokenizer`].
+ decoder (`pyctcdecode.BeamSearchDecoderCTC`, *optional*):
+ [PyCTCDecode's
+ BeamSearchDecoderCTC](https://github.com/kensho-technologies/pyctcdecode/blob/2fd33dc37c4111417e08d89ccd23d28e9b308d19/pyctcdecode/decoder.py#L180)
+ can be passed for language model boosted decoding. See [`Wav2Vec2ProcessorWithLM`] for more information.
+ device (Union[`int`, `torch.device`], *optional*):
+ Device ordinal for CPU/GPU supports. Setting this to `None` will leverage CPU, a positive will run the
+ model on the associated CUDA device id.
+ """
+
+ _pipeline_calls_generate = True
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = True
+ _load_tokenizer = True
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ num_beams=5, # follows openai's whisper implementation
+ )
+
+ def __init__(
+ self,
+ model: "PreTrainedModel",
+ feature_extractor: Union["SequenceFeatureExtractor", str] | None = None,
+ tokenizer: PreTrainedTokenizer | None = None,
+ decoder: Union["BeamSearchDecoderCTC", str] | None = None,
+ device: Union[int, "torch.device"] | None = None,
+ **kwargs,
+ ):
+ # set the model type so we can check we have the right pre- and post-processing parameters
+ if model.config.model_type == "whisper":
+ self.type = "seq2seq_whisper"
+ elif model.__class__.__name__ in MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES.values():
+ self.type = "seq2seq"
+ elif decoder is not None:
+ self.decoder = decoder
+ self.type = "ctc_with_lm"
+ else:
+ self.type = "ctc"
+
+ super().__init__(model, tokenizer, feature_extractor, device=device, **kwargs)
+
+ def __call__(self, inputs: np.ndarray | bytes | str | dict, **kwargs: Any) -> list[dict[str, Any]]:
+ """
+ Transcribe the audio sequence(s) given as inputs to text. See the [`AutomaticSpeechRecognitionPipeline`]
+ documentation for more information.
+
+ Args:
+ inputs (`np.ndarray` or `bytes` or `str` or `dict`):
+ The inputs is either :
+ - `str` that is either the filename of a local audio file, or a public URL address to download the
+ audio file. The file will be read at the correct sampling rate to get the waveform using
+ *ffmpeg*. This requires *ffmpeg* to be installed on the system.
+ - `bytes` it is supposed to be the content of an audio file and is interpreted by *ffmpeg* in the
+ same way.
+ - (`np.ndarray` of shape (n, ) of type `np.float32` or `np.float64`)
+ Raw audio at the correct sampling rate (no further check will be done)
+ - `dict` form can be used to pass raw audio sampled at arbitrary `sampling_rate` and let this
+ pipeline do the resampling. The dict must be in the format `{"sampling_rate": int, "raw":
+ np.array}` with optionally a `"stride": (left: int, right: int)` than can ask the pipeline to
+ treat the first `left` samples and last `right` samples to be ignored in decoding (but used at
+ inference to provide more context to the model). Only use `stride` with CTC models.
+ return_timestamps (*optional*, `str` or `bool`):
+ Only available for pure CTC models (Wav2Vec2, HuBERT, etc) and the Whisper model. Not available for
+ other sequence-to-sequence models.
+
+ For CTC models, timestamps can take one of two formats:
+ - `"char"`: the pipeline will return timestamps along the text for every character in the text. For
+ instance, if you get `[{"text": "h", "timestamp": (0.5, 0.6)}, {"text": "i", "timestamp": (0.7,
+ 0.9)}]`, then it means the model predicts that the letter "h" was spoken after `0.5` and before
+ `0.6` seconds.
+ - `"word"`: the pipeline will return timestamps along the text for every word in the text. For
+ instance, if you get `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text": "there", "timestamp":
+ (1.0, 1.5)}]`, then it means the model predicts that the word "hi" was spoken after `0.5` and
+ before `0.9` seconds.
+
+ For the Whisper model, timestamps can take one of two formats:
+ - `"word"`: same as above for word-level CTC timestamps. Word-level timestamps are predicted
+ through the *dynamic-time warping (DTW)* algorithm, an approximation to word-level timestamps
+ by inspecting the cross-attention weights.
+ - `True`: the pipeline will return timestamps along the text for *segments* of words in the text.
+ For instance, if you get `[{"text": " Hi there!", "timestamp": (0.5, 1.5)}]`, then it means the
+ model predicts that the segment "Hi there!" was spoken after `0.5` and before `1.5` seconds.
+ Note that a segment of text refers to a sequence of one or more words, rather than individual
+ words as with word-level timestamps.
+ generate_kwargs (`dict`, *optional*):
+ The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a
+ complete overview of generate, check the [following
+ guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation).
+
+ Return:
+ `Dict`: A dictionary with the following keys:
+ - **text** (`str`): The recognized text.
+ - **chunks** (*optional(, `list[Dict]`)
+ When using `return_timestamps`, the `chunks` will become a list containing all the various text
+ chunks identified by the model, *e.g.* `[{"text": "hi ", "timestamp": (0.5, 0.9)}, {"text":
+ "there", "timestamp": (1.0, 1.5)}]`. The original full text can roughly be recovered by doing
+ `"".join(chunk["text"] for chunk in output["chunks"])`.
+ """
+ return super().__call__(inputs, **kwargs)
+
+ def _sanitize_parameters(
+ self,
+ chunk_length_s=None,
+ stride_length_s=None,
+ ignore_warning=None,
+ decoder_kwargs=None,
+ return_timestamps=None,
+ return_language=None,
+ **generate_kwargs,
+ ):
+ preprocess_params = {}
+ forward_params = {}
+ postprocess_params = {}
+
+ # Preprocess params
+ if chunk_length_s is not None:
+ if self.type in ["seq2seq", "seq2seq_whisper"] and not ignore_warning:
+ type_warning = (
+ "Using `chunk_length_s` is very experimental with seq2seq models. The results will not necessarily"
+ " be entirely accurate and will have caveats. More information:"
+ " https://github.com/huggingface/transformers/pull/20104. Ignore this warning with pipeline(...,"
+ " ignore_warning=True)."
+ )
+ if self.type == "seq2seq_whisper":
+ type_warning += (
+ " To use Whisper for long-form transcription, use rather the model's `generate` method directly "
+ "as the model relies on it's own chunking mechanism (cf. Whisper original paper, section 3.8. "
+ "Long-form Transcription)."
+ )
+ logger.warning(type_warning)
+ preprocess_params["chunk_length_s"] = chunk_length_s
+ if stride_length_s is not None:
+ preprocess_params["stride_length_s"] = stride_length_s
+
+ # Forward params
+ # BC: accept a dictionary of generation kwargs (as opposed to **generate_kwargs)
+ if "generate_kwargs" in generate_kwargs:
+ forward_params.update(generate_kwargs.pop("generate_kwargs"))
+ # Default use for kwargs: they are generation-time kwargs
+ forward_params.update(generate_kwargs)
+
+ if getattr(self, "assistant_model", None) is not None:
+ forward_params["assistant_model"] = self.assistant_model
+ if getattr(self, "assistant_tokenizer", None) is not None:
+ forward_params["tokenizer"] = self.tokenizer
+ forward_params["assistant_tokenizer"] = self.assistant_tokenizer
+
+ # Postprocess params
+ if decoder_kwargs is not None:
+ postprocess_params["decoder_kwargs"] = decoder_kwargs
+ if return_language is not None:
+ if self.type != "seq2seq_whisper":
+ raise ValueError("Only Whisper can return language for now.")
+ postprocess_params["return_language"] = return_language
+ forward_params["return_language"] = return_language
+
+ # Parameter used in more than one place
+ # in some models like whisper, the generation config has a `return_timestamps` key
+ if hasattr(self, "generation_config") and hasattr(self.generation_config, "return_timestamps"):
+ return_timestamps = return_timestamps or self.generation_config.return_timestamps
+
+ if return_timestamps is not None:
+ # Check whether we have a valid setting for return_timestamps and throw an error before we perform a forward pass
+ if self.type == "seq2seq" and return_timestamps:
+ raise ValueError("We cannot return_timestamps yet on non-CTC models apart from Whisper!")
+ if self.type == "ctc_with_lm" and return_timestamps != "word":
+ raise ValueError("CTC with LM can only predict word level timestamps, set `return_timestamps='word'`")
+ if self.type == "ctc" and return_timestamps not in ["char", "word"]:
+ raise ValueError(
+ "CTC can either predict character level timestamps, or word level timestamps. "
+ "Set `return_timestamps='char'` or `return_timestamps='word'` as required."
+ )
+ if self.type == "seq2seq_whisper" and return_timestamps == "char":
+ raise ValueError(
+ "Whisper cannot return `char` timestamps, only word level or segment level timestamps. "
+ "Use `return_timestamps='word'` or `return_timestamps=True` respectively."
+ )
+ forward_params["return_timestamps"] = return_timestamps
+ postprocess_params["return_timestamps"] = return_timestamps
+
+ return preprocess_params, forward_params, postprocess_params
+
+ @property
+ def _align_to(self):
+ """Sample stride per output."""
+ # XXX: Carefully, this variable will not exist in `seq2seq` setting.
+ # Currently chunking is not possible at this level for `seq2seq` so
+ # it's ok.
+ align_to = getattr(self.model.config, "inputs_to_logits_ratio", 1)
+ if self.model.config.model_type == "lasr_ctc":
+ # TODO: find a standard for that but not easy because input length -> mel length depends on the feature extractor
+ # specific way of doing it
+ # means the model take mel features as input, we align according to the hop length
+ align_to *= self.feature_extractor.hop_length
+ return align_to
+
+ def preprocess(self, inputs, chunk_length_s=0, stride_length_s=None):
+ if isinstance(inputs, str):
+ if inputs.startswith("http://") or inputs.startswith("https://"):
+ # We need to actually check for a real protocol, otherwise it's impossible to use a local file
+ # like http_huggingface_co.png
+ inputs = httpx.get(inputs, follow_redirects=True).content
+ else:
+ with open(inputs, "rb") as f:
+ inputs = f.read()
+
+ if isinstance(inputs, bytes):
+ inputs = ffmpeg_read(inputs, self.feature_extractor.sampling_rate)
+
+ stride = None
+ extra = {}
+
+ if is_torch_available():
+ import torch
+
+ if isinstance(inputs, torch.Tensor):
+ inputs = inputs.cpu().numpy()
+
+ if is_torchcodec_available():
+ import torchcodec
+
+ if isinstance(inputs, torchcodec.decoders.AudioDecoder):
+ _audio_samples = inputs.get_all_samples()
+
+ # torchcodec always returns (num_channels, num_samples)
+ # while before (datasets < 4.0) we had (2, num_samples) if stereo, (num_samples,) if mono
+ _array = _audio_samples.data
+ _array = _array[0] if _array.ndim == 2 and _array.shape[0] == 1 else _array
+ inputs = {"array": _array, "sampling_rate": _audio_samples.sample_rate}
+
+ if isinstance(inputs, dict):
+ stride = inputs.pop("stride", None)
+ # Accepting `"array"` which is the key defined in `datasets` for
+ # better integration
+ if not ("sampling_rate" in inputs and ("raw" in inputs or "array" in inputs)):
+ raise ValueError(
+ "When passing a dictionary to AutomaticSpeechRecognitionPipeline, the dict needs to contain a "
+ '"raw" key containing the numpy array or torch tensor representing the audio and a "sampling_rate" key, '
+ "containing the sampling_rate associated with that array"
+ )
+
+ _inputs = inputs.pop("raw", None)
+ if _inputs is None:
+ # Remove path which will not be used from `datasets`.
+ inputs.pop("path", None)
+ _inputs = inputs.pop("array", None)
+ in_sampling_rate = inputs.pop("sampling_rate")
+ extra = inputs
+ inputs = _inputs
+ if in_sampling_rate != self.feature_extractor.sampling_rate:
+ if is_torchaudio_available():
+ from torchaudio import functional as F
+ else:
+ raise ImportError(
+ "torchaudio is required to resample audio samples in AutomaticSpeechRecognitionPipeline. "
+ "The torchaudio package can be installed through: `pip install torchaudio`."
+ )
+
+ inputs = F.resample(
+ torch.from_numpy(inputs) if isinstance(inputs, np.ndarray) else inputs,
+ in_sampling_rate,
+ self.feature_extractor.sampling_rate,
+ ).numpy()
+ ratio = self.feature_extractor.sampling_rate / in_sampling_rate
+ else:
+ ratio = 1
+ if stride is not None:
+ if stride[0] + stride[1] > inputs.shape[0]:
+ raise ValueError("Stride is too large for input")
+
+ # Stride needs to get the chunk length here, it's going to get
+ # swallowed by the `feature_extractor` later, and then batching
+ # can add extra data in the inputs, so we need to keep track
+ # of the original length in the stride so we can cut properly.
+ stride = (inputs.shape[0], int(round(stride[0] * ratio)), int(round(stride[1] * ratio)))
+ if not isinstance(inputs, (np.ndarray, torch.Tensor)):
+ raise TypeError(f"We expect a numpy ndarray or torch tensor as input, got `{type(inputs)}`")
+ if inputs.ndim != 1:
+ logger.warning(
+ f"We expect a single channel audio input for AutomaticSpeechRecognitionPipeline, got {inputs.ndim}. Taking the mean of the channels for mono conversion."
+ )
+ inputs = inputs.mean(axis=0)
+
+ if chunk_length_s:
+ if stride_length_s is None:
+ stride_length_s = chunk_length_s / 6
+
+ if isinstance(stride_length_s, (int, float)):
+ stride_length_s = [stride_length_s, stride_length_s]
+
+ align_to = self._align_to
+ chunk_len = int(round(chunk_length_s * self.feature_extractor.sampling_rate / align_to) * align_to)
+ stride_left = int(round(stride_length_s[0] * self.feature_extractor.sampling_rate / align_to) * align_to)
+ stride_right = int(round(stride_length_s[1] * self.feature_extractor.sampling_rate / align_to) * align_to)
+
+ if chunk_len < stride_left + stride_right:
+ raise ValueError("Chunk length must be superior to stride length")
+
+ for item in chunk_iter(inputs, self.feature_extractor, chunk_len, stride_left, stride_right, self.dtype):
+ yield {**item, **extra}
+ else:
+ if self.type == "seq2seq_whisper" and inputs.shape[0] > self.feature_extractor.n_samples:
+ processed = self.feature_extractor(
+ inputs,
+ sampling_rate=self.feature_extractor.sampling_rate,
+ truncation=False,
+ padding="longest",
+ return_tensors="pt",
+ return_attention_mask=True,
+ )
+ else:
+ if self.type == "seq2seq_whisper" and stride is None:
+ processed = self.feature_extractor(
+ inputs,
+ sampling_rate=self.feature_extractor.sampling_rate,
+ return_tensors="pt",
+ return_attention_mask=True,
+ )
+ else:
+ processed = self.feature_extractor(
+ inputs,
+ sampling_rate=self.feature_extractor.sampling_rate,
+ return_tensors="pt",
+ return_attention_mask=True,
+ )
+ if self.dtype is not None:
+ processed = processed.to(dtype=self.dtype)
+ if stride is not None:
+ if self.type == "seq2seq":
+ raise ValueError("Stride is only usable with CTC models, try removing it !")
+
+ processed["stride"] = stride
+ yield {"is_last": True, **processed, **extra}
+
+ def _forward(self, model_inputs, return_timestamps=False, return_language=None, **generate_kwargs):
+ attention_mask = model_inputs.pop("attention_mask", None)
+ stride = model_inputs.pop("stride", None)
+ num_frames = model_inputs.pop("num_frames", None)
+ is_last = model_inputs.pop("is_last")
+
+ if stride is not None and num_frames is not None:
+ raise ValueError("num_frames must be used only when stride is None")
+
+ if self.type in {"seq2seq", "seq2seq_whisper"}:
+ # Consume values so we can let extra information flow freely through
+ # the pipeline (important for `partial` in microphone)
+ if "input_features" in model_inputs:
+ inputs = model_inputs.pop("input_features")
+ elif "input_values" in model_inputs:
+ inputs = model_inputs.pop("input_values")
+ else:
+ raise ValueError(
+ "Seq2Seq speech recognition model requires either a "
+ f"`input_features` or `input_values` key, but only has {model_inputs.keys()}"
+ )
+
+ # custom processing for Whisper timestamps and word-level timestamps
+ return_timestamps = return_timestamps or getattr(self.generation_config, "return_timestamps", False)
+ if return_timestamps and self.type == "seq2seq_whisper":
+ generate_kwargs["return_timestamps"] = bool(return_timestamps)
+ if return_timestamps == "word":
+ generate_kwargs["return_token_timestamps"] = True
+ generate_kwargs["return_segments"] = True
+
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ main_input_name = self.model.main_input_name if hasattr(self.model, "main_input_name") else "inputs"
+ generate_kwargs = {
+ main_input_name: inputs,
+ "attention_mask": attention_mask,
+ **generate_kwargs,
+ }
+ # When return_language is requested, use return_segments to retrieve
+ # the full generated sequences (including init tokens with the language token)
+ # since generate() strips them from the main output.
+ if return_language and self.type == "seq2seq_whisper":
+ generate_kwargs["return_segments"] = True
+
+ tokens = self.model.generate(**generate_kwargs)
+
+ # whisper longform generation stores timestamps in "segments"
+ if return_timestamps == "word" and self.type == "seq2seq_whisper":
+ if "segments" not in tokens:
+ out = {"tokens": tokens["sequences"], "token_timestamps": tokens["token_timestamps"]}
+ else:
+ token_timestamps = [
+ torch.cat([segment["token_timestamps"] for segment in segment_list])
+ for segment_list in tokens["segments"]
+ ]
+ out = {"tokens": tokens["sequences"], "token_timestamps": token_timestamps}
+ elif isinstance(tokens, dict) and "sequences" in tokens:
+ out = {"tokens": tokens["sequences"]}
+ else:
+ out = {"tokens": tokens}
+ if self.type == "seq2seq_whisper":
+ if stride is not None:
+ out["stride"] = stride
+ if return_language and isinstance(tokens, dict) and "segments" in tokens:
+ # Extract the language token from the full unstripped sequence
+ # stored in segments[batch][segment]["result"]. The result is either
+ # a 1D tensor (full sequence) or a dict with a "sequences" key.
+ segments = tokens["segments"]
+ if segments and segments[0]:
+ result = segments[0][0]["result"]
+ full_seq = result["sequences"] if isinstance(result, dict) else result
+ gen_config = generate_kwargs.get("generation_config", self.generation_config)
+ if hasattr(gen_config, "lang_to_id"):
+ lang_ids = set(gen_config.lang_to_id.values())
+ for token_id in full_seq.tolist():
+ if token_id in lang_ids:
+ out["lang_id"] = torch.tensor([token_id])
+ break
+
+ else:
+ inputs = {
+ self.model.main_input_name: model_inputs.pop(self.model.main_input_name),
+ "attention_mask": attention_mask,
+ }
+ outputs = self.model(**inputs)
+ logits = outputs.logits
+
+ if self.type == "ctc_with_lm":
+ out = {"logits": logits}
+ else:
+ out = {"tokens": logits.argmax(dim=-1)}
+ if stride is not None:
+ # Send stride to `postprocess`.
+ # it needs to be handled there where
+ # the pieces are to be concatenated.
+ ratio = 1 / self._align_to
+ if isinstance(stride, tuple):
+ out["stride"] = rescale_stride([stride], ratio)[0]
+ else:
+ out["stride"] = rescale_stride(stride, ratio)
+ # Leftover
+ extra = model_inputs
+ return {"is_last": is_last, **out, **extra}
+
+ def postprocess(
+ self, model_outputs, decoder_kwargs: dict | None = None, return_timestamps=None, return_language=None
+ ):
+ # Optional return types
+ optional = {}
+
+ final_items = []
+ key = "logits" if self.type == "ctc_with_lm" else "tokens"
+ stride = None
+ for outputs in model_outputs:
+ if outputs[key].dtype in (torch.bfloat16, torch.float16):
+ items = outputs[key].to(torch.float32).numpy()
+ else:
+ items = outputs[key].numpy()
+ stride = outputs.get("stride", None)
+ if stride is not None and self.type in {"ctc", "ctc_with_lm"}:
+ total_n, left, right = stride
+ # Total_n might be < logits.shape[1]
+ # because of padding, that's why
+ # we need to reconstruct this information
+ # This won't work with left padding (which doesn't exist right now)
+ right_n = total_n - right
+ items = items[:, left:right_n]
+ final_items.append(items)
+
+ if stride and self.type == "seq2seq":
+ items = _find_longest_common_sequence(final_items, self.tokenizer)
+ elif self.type == "seq2seq_whisper":
+ time_precision = self.feature_extractor.chunk_length / self.model.config.max_source_positions
+ # Send the chunking back to seconds, it's easier to handle in whisper
+ sampling_rate = self.feature_extractor.sampling_rate
+ for output in model_outputs:
+ if "stride" in output:
+ chunk_len, stride_left, stride_right = output["stride"]
+ # Go back in seconds
+ chunk_len /= sampling_rate
+ stride_left /= sampling_rate
+ stride_right /= sampling_rate
+ output["stride"] = chunk_len, stride_left, stride_right
+
+ # Since Whisper's generate() strips init tokens (including the language token)
+ # from the output, we need to re-prepend the detected language token so that
+ # _decode_asr can find it and populate the language field in chunks.
+ if return_language:
+ for output in model_outputs:
+ if "lang_id" in output:
+ lang_id = output["lang_id"]
+ if lang_id.dim() == 0:
+ lang_id = lang_id.unsqueeze(0)
+ lang_token = lang_id.unsqueeze(0).to(dtype=output["tokens"].dtype)
+ output["tokens"] = torch.cat([lang_token, output["tokens"]], dim=-1)
+
+ text, optional = self.tokenizer._decode_asr(
+ model_outputs,
+ return_timestamps=return_timestamps,
+ return_language=return_language,
+ time_precision=time_precision,
+ )
+ else:
+ items = np.concatenate(final_items, axis=1)
+ items = items.squeeze(0)
+
+ if self.type == "ctc_with_lm":
+ if decoder_kwargs is None:
+ decoder_kwargs = {}
+ beams = self.decoder.decode_beams(items, **decoder_kwargs)
+ text = beams[0][0]
+ if return_timestamps:
+ # Simply cast from pyctcdecode format to wav2vec2 format to leverage
+ # pre-existing code later
+ chunk_offset = beams[0][2]
+ offsets = []
+ for word, (start_offset, end_offset) in chunk_offset:
+ offsets.append({"word": word, "start_offset": start_offset, "end_offset": end_offset})
+ elif self.type != "seq2seq_whisper":
+ skip_special_tokens = self.type != "ctc"
+ text = self.tokenizer.decode(items, skip_special_tokens=skip_special_tokens)
+ if return_timestamps:
+ offsets = self.tokenizer.decode(
+ items, skip_special_tokens=skip_special_tokens, output_char_offsets=True
+ )["char_offsets"]
+ if return_timestamps == "word":
+ offsets = self.tokenizer._get_word_offsets(offsets, self.tokenizer.replace_word_delimiter_char)
+
+ if return_timestamps and self.type not in {"seq2seq", "seq2seq_whisper"}:
+ chunks = []
+ align_to = self._align_to
+ for item in offsets:
+ start = item["start_offset"] * align_to
+ start /= self.feature_extractor.sampling_rate
+
+ stop = item["end_offset"] * align_to
+ stop /= self.feature_extractor.sampling_rate
+
+ chunks.append({"text": item[return_timestamps], "timestamp": (start, stop)})
+ optional["chunks"] = chunks
+
+ extra = defaultdict(list)
+ for output in model_outputs:
+ output.pop("tokens", None)
+ output.pop("logits", None)
+ output.pop("is_last", None)
+ output.pop("stride", None)
+ output.pop("token_timestamps", None)
+ output.pop("lang_id", None)
+ for k, v in output.items():
+ extra[k].append(v)
+ return {"text": text, **optional, **extra}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebcb55d1baf376dc8417926cf1e0e411c3a269ce
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/base.py
@@ -0,0 +1,1372 @@
+# 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.
+from __future__ import annotations
+
+import collections
+import copy
+import csv
+import importlib
+import json
+import os
+import pickle
+import sys
+import traceback
+import types
+from abc import ABC, abstractmethod
+from collections import UserDict
+from contextlib import contextmanager
+from os.path import abspath, exists
+from typing import TYPE_CHECKING, Any, Union
+
+from ..dynamic_module_utils import custom_object_save
+from ..feature_extraction_utils import PreTrainedFeatureExtractor
+from ..generation import GenerationConfig
+from ..image_processing_utils import BaseImageProcessor
+from ..models.auto import AutoConfig, AutoTokenizer
+from ..processing_utils import ProcessorMixin
+from ..tokenization_python import PreTrainedTokenizer
+from ..utils import (
+ ModelOutput,
+ PushToHubMixin,
+ add_end_docstrings,
+ copy_func,
+ is_torch_available,
+ is_torch_cuda_available,
+ is_torch_hpu_available,
+ is_torch_mlu_available,
+ is_torch_mps_available,
+ is_torch_musa_available,
+ is_torch_npu_available,
+ is_torch_xpu_available,
+ logging,
+)
+from ..utils.chat_template_utils import Chat, is_valid_message
+
+
+GenericTensor = Union[list["GenericTensor"], "torch.Tensor"]
+
+if is_torch_available() or TYPE_CHECKING:
+ import torch
+ from torch.utils.data import DataLoader, Dataset
+
+ from ..modeling_utils import PreTrainedModel
+ from .pt_utils import KeyDataset
+else:
+ Dataset = None
+
+
+logger = logging.get_logger(__name__)
+
+
+def no_collate_fn(items):
+ if len(items) != 1:
+ raise ValueError("This collate_fn is meant to be used with batch_size=1")
+ return items[0]
+
+
+def _pad(items, key, padding_value, padding_side):
+ batch_size = len(items)
+ if isinstance(items[0][key], torch.Tensor):
+ # Others include `attention_mask` etc...
+ shape = items[0][key].shape
+ dim = items[0][key].ndim
+ if dim == 1:
+ # We have a list of 1-dim torch tensors, which can be stacked without padding
+ return torch.cat([item[key] for item in items], dim=0)
+ if key in ["pixel_values", "image"]:
+ # This is probable image so padding shouldn't be necessary
+ # B, C, H, W
+ return torch.cat([item[key] for item in items], dim=0)
+ elif dim == 4 and key == "input_features":
+ # this is probably a mel spectrogram batched
+ return torch.cat([item[key] for item in items], dim=0)
+ max_length = max(item[key].shape[1] for item in items)
+ min_length = min(item[key].shape[1] for item in items)
+ dtype = items[0][key].dtype
+
+ if dim == 2 and max_length == min_length:
+ # Bypass for `ImageGPT` which doesn't provide a padding value, yet
+ # we can consistently pad since the size should be matching
+ return torch.cat([item[key] for item in items], dim=0)
+ else:
+ tensor = torch.full([batch_size, max_length] + list(shape[2:]), fill_value=padding_value, dtype=dtype)
+
+ for i, item in enumerate(items):
+ if padding_side == "left":
+ tensor[i, -len(item[key][0]) :] = item[key][0]
+ else:
+ tensor[i, : len(item[key][0])] = item[key][0]
+
+ return tensor
+ else:
+ return [item[key] for item in items]
+
+
+def pad_collate_fn(tokenizer, feature_extractor):
+ # Tokenizer
+ t_padding_side = None
+ # Feature extractor
+ f_padding_side = None
+ if tokenizer is None and feature_extractor is None:
+ raise ValueError("Pipeline without tokenizer or feature_extractor cannot do batching")
+ if tokenizer is not None:
+ if tokenizer.pad_token_id is None:
+ raise ValueError(
+ "Pipeline with tokenizer without pad_token cannot do batching. You can try to set it with "
+ "`pipe.tokenizer.pad_token_id = model.config.eos_token_id`."
+ )
+ else:
+ t_padding_value = tokenizer.pad_token_id
+ t_padding_side = tokenizer.padding_side
+ if feature_extractor is not None:
+ # Feature extractor can be images, where no padding is expected
+ f_padding_value = getattr(feature_extractor, "padding_value", None)
+ f_padding_side = getattr(feature_extractor, "padding_side", None)
+
+ if t_padding_side is not None and f_padding_side is not None and t_padding_side != f_padding_side:
+ raise ValueError(
+ f"The feature extractor, and tokenizer don't agree on padding side {t_padding_side} != {f_padding_side}"
+ )
+ padding_side = "right"
+ if t_padding_side is not None:
+ padding_side = t_padding_side
+ if f_padding_side is not None:
+ padding_side = f_padding_side
+
+ def inner(items):
+ keys = set(items[0].keys())
+ for item in items:
+ if set(item.keys()) != keys:
+ raise ValueError(
+ f"The elements of the batch contain different keys. Cannot batch them ({set(item.keys())} !="
+ f" {keys})"
+ )
+ # input_values, input_pixels, input_ids, ...
+ padded = {}
+ for key in keys:
+ if key == "input_ids":
+ # ImageGPT uses a feature extractor
+ if tokenizer is None and feature_extractor is not None:
+ _padding_value = f_padding_value
+ else:
+ _padding_value = t_padding_value
+ elif key in {"input_values", "pixel_values", "input_features"}:
+ _padding_value = f_padding_value
+ elif key in {"p_mask", "special_tokens_mask"}:
+ _padding_value = 1
+ elif key in {"attention_mask", "token_type_ids"}:
+ _padding_value = 0
+ else:
+ # This is likely another random key maybe even user provided
+ _padding_value = 0
+ padded[key] = _pad(items, key, _padding_value, padding_side)
+ return padded
+
+ return inner
+
+
+def load_model(
+ model,
+ config: AutoConfig,
+ model_classes: tuple[type, ...] | None = None,
+ task: str | None = None,
+ **model_kwargs,
+):
+ """
+ Load a model.
+
+ If `model` is instantiated, this function will just return it. Otherwise `model` is
+ actually a checkpoint name and this method will try to instantiate it using `model_classes`. Since we don't want to
+ instantiate the model twice, this model is returned for use by the pipeline.
+
+ Args:
+ model (`str`, or [`PreTrainedModel`]):
+ If `str`, a checkpoint name. The model to load.
+ config ([`AutoConfig`]):
+ The config associated with the model to help using the correct class
+ model_classes (`tuple[type]`, *optional*):
+ A tuple of model classes.
+ task (`str`):
+ The task defining which pipeline will be returned.
+ model_kwargs:
+ Additional dictionary of keyword arguments passed along to the model's `from_pretrained(...,
+ **model_kwargs)` function.
+
+ Returns:
+ The model.
+ """
+ if not is_torch_available():
+ raise RuntimeError("PyTorch should be installed. Please follow the instructions at https://pytorch.org/.")
+
+ if isinstance(model, str):
+ model_kwargs["_from_pipeline"] = task
+ class_tuple = model_classes if model_classes is not None else ()
+ if config.architectures:
+ classes = []
+ for architecture in config.architectures:
+ transformers_module = importlib.import_module("transformers")
+ _class = getattr(transformers_module, architecture, None)
+ if _class is not None:
+ classes.append(_class)
+ class_tuple = class_tuple + tuple(classes)
+
+ if len(class_tuple) == 0:
+ raise ValueError(f"Pipeline cannot infer suitable model classes from {model}")
+
+ all_traceback = {}
+ for model_class in class_tuple:
+ kwargs = model_kwargs.copy()
+
+ try:
+ model = model_class.from_pretrained(model, **kwargs)
+ # Stop loading on the first successful load.
+ break
+ except (OSError, ValueError, TypeError, RuntimeError):
+ # `from_pretrained` may raise a `TypeError` or `RuntimeError` when the requested `dtype`
+ # is not supported on the execution device (e.g. bf16 on a consumer GPU). We capture those so
+ # we can transparently retry the load in float32 before surfacing an error to the user.
+ fallback_tried = False
+ if "dtype" in kwargs:
+ import torch
+
+ fallback_tried = True
+ fp32_kwargs = kwargs.copy()
+ fp32_kwargs["dtype"] = torch.float32
+
+ try:
+ model = model_class.from_pretrained(model, **fp32_kwargs)
+ logger.warning(
+ "Falling back to torch.float32 because loading with the original dtype failed on the"
+ " target device."
+ )
+ break
+ except Exception:
+ # If it still fails, capture the traceback and continue to the next class.
+ all_traceback[model_class.__name__] = traceback.format_exc()
+ continue
+
+ # If no fallback was attempted or it also failed, record the original traceback.
+ if not fallback_tried:
+ all_traceback[model_class.__name__] = traceback.format_exc()
+ continue
+
+ if isinstance(model, str):
+ error = ""
+ for class_name, trace in all_traceback.items():
+ error += f"while loading with {class_name}, an error is thrown:\n{trace}\n"
+ raise ValueError(
+ f"Could not load model {model} with any of the following classes: {class_tuple}. See the original errors:\n\n{error}\n"
+ )
+
+ return model
+
+
+def get_default_model_and_revision(targeted_task: dict, task_options: Any | None) -> tuple[str, str]:
+ """
+ Select a default model to use for a given task.
+
+ Args:
+ targeted_task (`Dict`):
+ Dictionary representing the given task, that should contain default models
+
+ task_options (`Any`, None)
+ Any further value required by the task to get fully specified.
+
+ Returns
+
+ Tuple:
+ - `str` The model string representing the default model for this pipeline.
+ - `str` The revision of the model.
+ """
+ defaults = targeted_task["default"]
+ if task_options:
+ if task_options not in defaults:
+ raise ValueError(f"The task does not provide any default models for options {task_options}")
+ default_models = defaults[task_options]["model"]
+ elif "model" in defaults:
+ default_models = targeted_task["default"]["model"]
+ else:
+ raise ValueError("The task defaults can't be correctly selected.")
+
+ return default_models
+
+
+def load_assistant_model(
+ model: PreTrainedModel,
+ assistant_model: str | PreTrainedModel | None,
+ assistant_tokenizer: PreTrainedTokenizer | None,
+) -> tuple[PreTrainedModel | None, PreTrainedTokenizer | None]:
+ """
+ Prepares the assistant model and the assistant tokenizer for a pipeline whose model that can call `generate`.
+
+ Args:
+ model ([`PreTrainedModel`]):
+ The main model that will be used by the pipeline to make predictions.
+ assistant_model (`str` or [`PreTrainedModel`], *optional*):
+ The assistant model that will be used by the pipeline to make predictions.
+ assistant_tokenizer ([`PreTrainedTokenizer`], *optional*):
+ The assistant tokenizer that will be used by the pipeline to encode data for the model.
+
+ Returns:
+ Tuple: The loaded assistant model and (optionally) the loaded tokenizer.
+ """
+ if not model.can_generate() or assistant_model is None:
+ return None, None
+
+ # If the model is passed as a string, load the model and the corresponding tokenizer
+ if isinstance(assistant_model, str):
+ assistant_config = AutoConfig.from_pretrained(assistant_model)
+ loaded_assistant_model = load_model(assistant_model, config=assistant_config)
+ loaded_assistant_model = loaded_assistant_model.to(device=model.device, dtype=model.dtype)
+ loaded_assistant_tokenizer = AutoTokenizer.from_pretrained(assistant_model)
+ else:
+ loaded_assistant_model = assistant_model
+ loaded_assistant_tokenizer = assistant_tokenizer
+
+ # Finally, let's check the tokenizers: if the two models have different tokenizers, we need to keep the assistant
+ # tokenizer
+ model_text_config = model.config.get_text_config()
+ assistant_text_config = loaded_assistant_model.config.get_text_config()
+ same_vocab_size = model_text_config.vocab_size == assistant_text_config.vocab_size
+ same_special_tokens = all(
+ getattr(model_text_config, token) == getattr(assistant_text_config, token)
+ for token in ("eos_token_id", "pad_token_id", "bos_token_id")
+ )
+ if same_vocab_size and same_special_tokens:
+ loaded_assistant_tokenizer = None
+ elif loaded_assistant_tokenizer is None:
+ raise ValueError(
+ "The assistant model has a different tokenizer than the main model. You should pass the assistant "
+ "tokenizer."
+ )
+
+ return loaded_assistant_model, loaded_assistant_tokenizer
+
+
+class PipelineException(Exception):
+ """
+ Raised by a [`Pipeline`] when handling __call__.
+
+ Args:
+ task (`str`): The task of the pipeline.
+ model (`str`): The model used by the pipeline.
+ reason (`str`): The error message to display.
+ """
+
+ def __init__(self, task: str, model: str, reason: str):
+ super().__init__(reason)
+
+ self.task = task
+ self.model = model
+
+
+class ArgumentHandler(ABC):
+ """
+ Base interface for handling arguments for each [`~pipelines.Pipeline`].
+ """
+
+ @abstractmethod
+ def __call__(self, *args, **kwargs):
+ raise NotImplementedError()
+
+
+class PipelineDataFormat:
+ """
+ Base class for all the pipeline supported data format both for reading and writing. Supported data formats
+ currently includes:
+
+ - JSON
+ - CSV
+ - stdin/stdout (pipe)
+
+ `PipelineDataFormat` also includes some utilities to work with multi-columns like mapping from datasets columns to
+ pipelines keyword arguments through the `dataset_kwarg_1=dataset_column_1` format.
+
+ Args:
+ output_path (`str`): Where to save the outgoing data.
+ input_path (`str`): Where to look for the input data.
+ column (`str`): The column to read.
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether or not to overwrite the `output_path`.
+ """
+
+ SUPPORTED_FORMATS = ["json", "csv", "pipe"]
+
+ def __init__(
+ self,
+ output_path: str | None,
+ input_path: str | None,
+ column: str | None,
+ overwrite: bool = False,
+ ):
+ self.output_path = output_path
+ self.input_path = input_path
+ self.column = column.split(",") if column is not None else [""]
+ self.is_multi_columns = len(self.column) > 1
+
+ if self.is_multi_columns:
+ self.column = [tuple(c.split("=")) if "=" in c else (c, c) for c in self.column]
+
+ if output_path is not None and not overwrite:
+ if exists(abspath(self.output_path)):
+ raise OSError(f"{self.output_path} already exists on disk")
+
+ if input_path is not None:
+ if not exists(abspath(self.input_path)):
+ raise OSError(f"{self.input_path} doesn't exist on disk")
+
+ @abstractmethod
+ def __iter__(self):
+ raise NotImplementedError()
+
+ @abstractmethod
+ def save(self, data: dict | list[dict]):
+ """
+ Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`].
+
+ Args:
+ data (`dict` or list of `dict`): The data to store.
+ """
+ raise NotImplementedError()
+
+ def save_binary(self, data: dict | list[dict]) -> str:
+ """
+ Save the provided data object as a pickle-formatted binary data on the disk.
+
+ Args:
+ data (`dict` or list of `dict`): The data to store.
+
+ Returns:
+ `str`: Path where the data has been saved.
+ """
+ path, _ = os.path.splitext(self.output_path)
+ binary_path = os.path.extsep.join((path, "pickle"))
+
+ with open(binary_path, "wb+") as f_output:
+ pickle.dump(data, f_output)
+
+ return binary_path
+
+ @staticmethod
+ def from_str(
+ format: str,
+ output_path: str | None,
+ input_path: str | None,
+ column: str | None,
+ overwrite=False,
+ ) -> PipelineDataFormat:
+ """
+ Creates an instance of the right subclass of [`~pipelines.PipelineDataFormat`] depending on `format`.
+
+ Args:
+ format (`str`):
+ The format of the desired pipeline. Acceptable values are `"json"`, `"csv"` or `"pipe"`.
+ output_path (`str`, *optional*):
+ Where to save the outgoing data.
+ input_path (`str`, *optional*):
+ Where to look for the input data.
+ column (`str`, *optional*):
+ The column to read.
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether or not to overwrite the `output_path`.
+
+ Returns:
+ [`~pipelines.PipelineDataFormat`]: The proper data format.
+ """
+ if format == "json":
+ return JsonPipelineDataFormat(output_path, input_path, column, overwrite=overwrite)
+ elif format == "csv":
+ return CsvPipelineDataFormat(output_path, input_path, column, overwrite=overwrite)
+ elif format == "pipe":
+ return PipedPipelineDataFormat(output_path, input_path, column, overwrite=overwrite)
+ else:
+ raise KeyError(f"Unknown reader {format} (Available reader are json/csv/pipe)")
+
+
+class CsvPipelineDataFormat(PipelineDataFormat):
+ """
+ Support for pipelines using CSV data format.
+
+ Args:
+ output_path (`str`): Where to save the outgoing data.
+ input_path (`str`): Where to look for the input data.
+ column (`str`): The column to read.
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether or not to overwrite the `output_path`.
+ """
+
+ def __init__(
+ self,
+ output_path: str | None,
+ input_path: str | None,
+ column: str | None,
+ overwrite=False,
+ ):
+ super().__init__(output_path, input_path, column, overwrite=overwrite)
+
+ def __iter__(self):
+ with open(self.input_path, "r") as f:
+ reader = csv.DictReader(f)
+ for row in reader:
+ if self.is_multi_columns:
+ yield {k: row[c] for k, c in self.column}
+ else:
+ yield row[self.column[0]]
+
+ def save(self, data: list[dict]):
+ """
+ Save the provided data object with the representation for the current [`~pipelines.PipelineDataFormat`].
+
+ Args:
+ data (`list[dict]`): The data to store.
+ """
+ with open(self.output_path, "w") as f:
+ if len(data) > 0:
+ writer = csv.DictWriter(f, list(data[0].keys()))
+ writer.writeheader()
+ writer.writerows(data)
+
+
+class JsonPipelineDataFormat(PipelineDataFormat):
+ """
+ Support for pipelines using JSON file format.
+
+ Args:
+ output_path (`str`): Where to save the outgoing data.
+ input_path (`str`): Where to look for the input data.
+ column (`str`): The column to read.
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether or not to overwrite the `output_path`.
+ """
+
+ def __init__(
+ self,
+ output_path: str | None,
+ input_path: str | None,
+ column: str | None,
+ overwrite=False,
+ ):
+ super().__init__(output_path, input_path, column, overwrite=overwrite)
+
+ with open(input_path, "r") as f:
+ self._entries = json.load(f)
+
+ def __iter__(self):
+ for entry in self._entries:
+ if self.is_multi_columns:
+ yield {k: entry[c] for k, c in self.column}
+ else:
+ yield entry[self.column[0]]
+
+ def save(self, data: dict):
+ """
+ Save the provided data object in a json file.
+
+ Args:
+ data (`dict`): The data to store.
+ """
+ with open(self.output_path, "w") as f:
+ json.dump(data, f)
+
+
+class PipedPipelineDataFormat(PipelineDataFormat):
+ """
+ Read data from piped input to the python process. For multi columns data, columns should separated by \t
+
+ If columns are provided, then the output will be a dictionary with {column_x: value_x}
+
+ Args:
+ output_path (`str`): Where to save the outgoing data.
+ input_path (`str`): Where to look for the input data.
+ column (`str`): The column to read.
+ overwrite (`bool`, *optional*, defaults to `False`):
+ Whether or not to overwrite the `output_path`.
+ """
+
+ def __iter__(self):
+ for line in sys.stdin:
+ # Split for multi-columns
+ if "\t" in line:
+ line = line.split("\t")
+ if self.column:
+ # Dictionary to map arguments
+ yield {kwargs: l for (kwargs, _), l in zip(self.column, line)}
+ else:
+ yield tuple(line)
+
+ # No dictionary to map arguments
+ else:
+ yield line
+
+ def save(self, data: dict):
+ """
+ Print the data.
+
+ Args:
+ data (`dict`): The data to store.
+ """
+ print(data)
+
+ def save_binary(self, data: dict | list[dict]) -> str:
+ if self.output_path is None:
+ raise KeyError(
+ "When using piped input on pipeline outputting large object requires an output file path. "
+ "Please provide such output path through --output argument."
+ )
+
+ return super().save_binary(data)
+
+
+class _ScikitCompat(ABC):
+ """
+ Interface layer for the Scikit and Keras compatibility.
+ """
+
+ @abstractmethod
+ def transform(self, X):
+ raise NotImplementedError()
+
+ @abstractmethod
+ def predict(self, X):
+ raise NotImplementedError()
+
+
+def build_pipeline_init_args(
+ has_tokenizer: bool = False,
+ has_feature_extractor: bool = False,
+ has_image_processor: bool = False,
+ has_processor: bool = False,
+ supports_binary_output: bool = True,
+) -> str:
+ docstring = r"""
+ Arguments:
+ model ([`PreTrainedModel`]):
+ The model that will be used by the pipeline to make predictions. This needs to be a model inheriting from
+ [`PreTrainedModel`]."""
+ if has_tokenizer:
+ docstring += r"""
+ tokenizer ([`PreTrainedTokenizer`]):
+ The tokenizer that will be used by the pipeline to encode data for the model. This object inherits from
+ [`PreTrainedTokenizer`]."""
+ if has_feature_extractor:
+ docstring += r"""
+ feature_extractor ([`SequenceFeatureExtractor`]):
+ The feature extractor that will be used by the pipeline to encode data for the model. This object inherits from
+ [`SequenceFeatureExtractor`]."""
+ if has_image_processor:
+ docstring += r"""
+ image_processor ([`BaseImageProcessor`]):
+ The image processor that will be used by the pipeline to encode data for the model. This object inherits from
+ [`BaseImageProcessor`]."""
+ if has_processor:
+ docstring += r"""
+ processor ([`ProcessorMixin`]):
+ The processor that will be used by the pipeline to encode data for the model. This object inherits from
+ [`ProcessorMixin`]. Processor is a composite object that might contain `tokenizer`, `feature_extractor`, and
+ `image_processor`."""
+ docstring += r"""
+ task (`str`, defaults to `""`):
+ A task-identifier for the pipeline.
+ num_workers (`int`, *optional*, defaults to 8):
+ When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the number of
+ workers to be used.
+ batch_size (`int`, *optional*, defaults to 1):
+ When the pipeline will use *DataLoader* (when passing a dataset, on GPU for a Pytorch model), the size of
+ the batch to use, for inference this is not always beneficial, please read [Batching with
+ pipelines](https://huggingface.co/transformers/main_classes/pipelines.html#pipeline-batching) .
+ args_parser ([`~pipelines.ArgumentHandler`], *optional*):
+ Reference to the object in charge of parsing supplied pipeline parameters.
+ device (`int`, *optional*, defaults to -1):
+ Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on
+ the associated CUDA device id. You can pass native `torch.device` or a `str` too
+ dtype (`str` or `torch.dtype`, *optional*):
+ Sent directly as `model_kwargs` (just a simpler shortcut) to use the available precision for this model
+ (`torch.float16`, `torch.bfloat16`, ... or `"auto"`)"""
+ if supports_binary_output:
+ docstring += r"""
+ binary_output (`bool`, *optional*, defaults to `False`):
+ Flag indicating if the output the pipeline should happen in a serialized format (i.e., pickle) or as
+ the raw output data e.g. text."""
+ return docstring
+
+
+PIPELINE_INIT_ARGS = build_pipeline_init_args(
+ has_tokenizer=True,
+ has_feature_extractor=True,
+ has_image_processor=True,
+ has_processor=True,
+ supports_binary_output=True,
+)
+
+SUPPORTED_PEFT_TASKS = {
+ "document-question-answering": ["PeftModelForQuestionAnswering"],
+ "feature-extraction": ["PeftModelForFeatureExtraction", "PeftModel"],
+ "summarization": ["PeftModelForSeq2SeqLM"],
+ "table-question-answering": ["PeftModelForQuestionAnswering"],
+ "text-classification": ["PeftModelForSequenceClassification"],
+ "sentiment-analysis": ["PeftModelForSequenceClassification"],
+ "text-generation": ["PeftModelForCausalLM"],
+ "token-classification": ["PeftModelForTokenClassification"],
+ "ner": ["PeftModelForTokenClassification"],
+ "zero-shot-classification": ["PeftModelForSequenceClassification"],
+}
+
+if is_torch_available():
+ from transformers.pipelines.pt_utils import (
+ PipelineChunkIterator,
+ PipelineDataset,
+ PipelineIterator,
+ PipelinePackIterator,
+ )
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(
+ has_tokenizer=True, has_feature_extractor=True, has_image_processor=True, has_processor=True
+ )
+)
+class Pipeline(_ScikitCompat, PushToHubMixin):
+ """
+ The Pipeline class is the class from which all pipelines inherit. Refer to this class for methods shared across
+ different pipelines.
+
+ Base class implementing pipelined operations. Pipeline workflow is defined as a sequence of the following
+ operations:
+
+ Input -> Tokenization -> Model Inference -> Post-Processing (task dependent) -> Output
+
+ Pipeline supports running on CPU or GPU through the device argument (see below).
+
+ Some pipeline, like for instance [`FeatureExtractionPipeline`] (`'feature-extraction'`) output large tensor object
+ as nested-lists. In order to avoid dumping such large structure as textual data we provide the `binary_output`
+ constructor argument. If set to `True`, the output will be stored in the pickle format.
+ """
+
+ # These flags should be overridden for downstream pipelines. They indicate which preprocessing classes are
+ # used by each pipeline. The possible values are:
+ # - True (the class is mandatory, raise an error if it's not present in the repo)
+ # - None (the class is optional; it should be loaded if present in the repo but the pipeline can work without it)
+ # - False (the class is never used by the pipeline and should not be loaded even if present)
+ _load_processor = None
+ _load_image_processor = None
+ _load_feature_extractor = None
+ _load_tokenizer = None
+
+ # Pipelines that call `generate` have shared logic, e.g. preparing the generation config.
+ _pipeline_calls_generate = False
+
+ default_input_names = None
+
+ def __init__(
+ self,
+ model: PreTrainedModel,
+ tokenizer: PreTrainedTokenizer | None = None,
+ feature_extractor: PreTrainedFeatureExtractor | None = None,
+ image_processor: BaseImageProcessor | None = None,
+ processor: ProcessorMixin | None = None,
+ task: str = "",
+ device: int | torch.device | None = None,
+ binary_output: bool = False,
+ **kwargs,
+ ):
+ # We need to pop them for _sanitize_parameters call later
+ _, _, _ = kwargs.pop("args_parser", None), kwargs.pop("torch_dtype", None), kwargs.pop("dtype", None)
+
+ self.task = task
+ self.model = model
+ self.tokenizer = tokenizer
+ self.feature_extractor = feature_extractor
+ self.image_processor = image_processor
+ self.processor = processor
+
+ # `accelerate` device map
+ hf_device_map = getattr(self.model, "hf_device_map", None)
+
+ if hf_device_map is not None and device is not None:
+ raise ValueError(
+ "The model has been loaded with `accelerate` and therefore cannot be moved to a specific device. Please "
+ "discard the `device` argument when creating your pipeline object."
+ )
+
+ if device is None:
+ if hf_device_map is not None:
+ # Take the first device used by `accelerate`.
+ device = next(iter(hf_device_map.values()))
+ else:
+ device = 0
+
+ if device == -1 and self.model.device is not None:
+ device = self.model.device
+ if isinstance(device, torch.device):
+ if (device.type == "xpu" and not is_torch_xpu_available(check_device=True)) or (
+ device.type == "hpu" and not is_torch_hpu_available()
+ ):
+ raise ValueError(f'{device} is not available, you should use device="cpu" instead')
+
+ self.device = device
+ elif isinstance(device, str):
+ if ("xpu" in device and not is_torch_xpu_available(check_device=True)) or (
+ "hpu" in device and not is_torch_hpu_available()
+ ):
+ raise ValueError(f'{device} is not available, you should use device="cpu" instead')
+
+ self.device = torch.device(device)
+ elif device < 0:
+ self.device = torch.device("cpu")
+ elif is_torch_mlu_available():
+ self.device = torch.device(f"mlu:{device}")
+ elif is_torch_musa_available():
+ self.device = torch.device(f"musa:{device}")
+ elif is_torch_cuda_available():
+ self.device = torch.device(f"cuda:{device}")
+ elif is_torch_npu_available():
+ self.device = torch.device(f"npu:{device}")
+ elif is_torch_hpu_available():
+ self.device = torch.device(f"hpu:{device}")
+ elif is_torch_xpu_available(check_device=True):
+ self.device = torch.device(f"xpu:{device}")
+ elif is_torch_mps_available():
+ self.device = torch.device(f"mps:{device}")
+ else:
+ self.device = torch.device("cpu")
+
+ if torch.distributed.is_available() and torch.distributed.is_initialized():
+ self.device = self.model.device
+ logger.debug(f"Device set to use {self.device}")
+
+ self.binary_output = binary_output
+
+ # We shouldn't call `model.to()` for models loaded with accelerate as well as the case that model is already on device
+ if (
+ self.model.device != self.device
+ and not (isinstance(self.device, int) and self.device < 0)
+ and hf_device_map is None
+ ):
+ self.model.to(self.device)
+
+ # If it's a generation pipeline and the model can generate:
+ # 1 - create a local generation config. This is done to avoid side-effects on the model as we apply local
+ # tweaks to the generation config.
+ # 2 - load the assistant model if it is passed.
+ if self._pipeline_calls_generate and self.model.can_generate():
+ self.assistant_model, self.assistant_tokenizer = load_assistant_model(
+ self.model, kwargs.pop("assistant_model", None), kwargs.pop("assistant_tokenizer", None)
+ )
+ self.prefix = self.model.config.prefix if hasattr(self.model.config, "prefix") else None
+ # each pipeline with text generation capabilities should define its own default generation in a
+ # `_default_generation_config` class attribute
+ default_pipeline_generation_config = getattr(self, "_default_generation_config", GenerationConfig())
+ if hasattr(self.model, "_prepare_generation_config"):
+ # Uses `generate`'s logic to enforce the following priority of arguments:
+ # 1. user-defined config options in `**kwargs`
+ # 2. model's generation config values
+ # 3. pipeline's default generation config values
+ # NOTE: _prepare_generation_config creates a deep copy of the generation config before updating it,
+ # and returns all kwargs that were not used to update the generation config
+ prepared_generation_config, kwargs = self.model._prepare_generation_config(
+ generation_config=default_pipeline_generation_config, **kwargs
+ )
+ self.generation_config = prepared_generation_config
+ # if the `max_new_tokens` is set to the pipeline default, but `max_length` is set to a non-default
+ # value: let's honor `max_length`. E.g. we want Whisper's default `max_length=448` take precedence
+ # over over the pipeline's length default.
+ if (
+ default_pipeline_generation_config.max_new_tokens is not None # there's a pipeline default
+ and self.generation_config.max_new_tokens == default_pipeline_generation_config.max_new_tokens
+ and self.generation_config.max_length is not None
+ and self.generation_config.max_length != 20 # global default
+ ):
+ self.generation_config.max_new_tokens = None
+ else:
+ # TODO (joao): no PT model should reach this line. However, some audio models with complex
+ # inheritance patterns do. Streamline those models such that this line is no longer needed.
+ # In those models, the default generation config is not (yet) used.
+ self.generation_config = copy.deepcopy(self.model.generation_config)
+ # Update the generation config with task specific params if they exist.
+ # NOTE: 1. `prefix` is pipeline-specific and doesn't exist in the generation config.
+ # 2. `task_specific_params` is a legacy feature and should be removed in a future version.
+ task_specific_params = getattr(self.model.config, "task_specific_params", None)
+ if task_specific_params is not None and task in task_specific_params:
+ this_task_params = task_specific_params.get(task)
+ if "prefix" in this_task_params:
+ self.prefix = this_task_params.pop("prefix")
+ self.generation_config.update(**this_task_params)
+ # If the tokenizer has a pad token but the model doesn't, set it so that `generate` is aware of it.
+ if (
+ self.tokenizer is not None
+ and self.tokenizer.pad_token_id is not None
+ and self.generation_config.pad_token_id is None
+ ):
+ self.generation_config.pad_token_id = self.tokenizer.pad_token_id
+
+ self.call_count = 0
+ self._batch_size = kwargs.pop("batch_size", None)
+ self._num_workers = kwargs.pop("num_workers", None)
+ self._preprocess_params, self._forward_params, self._postprocess_params = self._sanitize_parameters(**kwargs)
+
+ # In processor only mode, we can get the modality processors from the processor
+ if self.processor is not None and all(
+ [self.tokenizer is None, self.feature_extractor is None, self.image_processor is None]
+ ):
+ self.tokenizer = getattr(self.processor, "tokenizer", None)
+ self.feature_extractor = getattr(self.processor, "feature_extractor", None)
+ self.image_processor = getattr(self.processor, "image_processor", None)
+
+ if self.image_processor is None and self.feature_extractor is not None:
+ if isinstance(self.feature_extractor, BaseImageProcessor):
+ # Backward compatible change, if users called
+ # ImageSegmentationPipeline(.., feature_extractor=MyFeatureExtractor())
+ # then we should keep working
+ self.image_processor = self.feature_extractor
+
+ def __repr__(self):
+ pipe_information = {
+ "model": self.model.__class__.__name__,
+ "dtype": str(self.dtype).split(".")[-1],
+ "device": self.device.type,
+ "input_modalities": self.model.input_modalities,
+ }
+ if self.model.can_generate():
+ pipe_information["output_modalities"] = self.model.output_modalities
+ return f"{self.__class__.__name__}: {pipe_information}"
+
+ def save_pretrained(self, save_directory: str | os.PathLike, **kwargs: Any):
+ """
+ Save the pipeline's model and tokenizer.
+
+ Args:
+ save_directory (`str` or `os.PathLike`):
+ A path to the directory where to saved. It will be created if it doesn't exist.
+ kwargs (`dict[str, Any]`, *optional*):
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
+ """
+ if os.path.isfile(save_directory):
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
+ return
+ os.makedirs(save_directory, exist_ok=True)
+
+ if hasattr(self, "_registered_impl"):
+ # Add info to the config
+ pipeline_info = self._registered_impl.copy()
+ custom_pipelines = {}
+ for task, info in pipeline_info.items():
+ if info["impl"] != self.__class__:
+ continue
+
+ info = info.copy()
+ module_name = info["impl"].__module__
+ last_module = module_name.split(".")[-1]
+ # Change classes into their names/full names
+ info["impl"] = f"{last_module}.{info['impl'].__name__}"
+ info["pt"] = tuple(c.__name__ for c in info["pt"])
+
+ custom_pipelines[task] = info
+ self.model.config.custom_pipelines = custom_pipelines
+ # Save the pipeline custom code
+ custom_object_save(self, save_directory)
+
+ self.model.save_pretrained(save_directory, **kwargs)
+
+ if self.tokenizer is not None:
+ self.tokenizer.save_pretrained(save_directory, **kwargs)
+
+ if self.feature_extractor is not None:
+ self.feature_extractor.save_pretrained(save_directory, **kwargs)
+
+ if self.image_processor is not None:
+ self.image_processor.save_pretrained(save_directory, **kwargs)
+
+ def transform(self, X):
+ """
+ Scikit / Keras interface to transformers' pipelines. This method will forward to __call__().
+ """
+ return self(X)
+
+ def predict(self, X):
+ """
+ Scikit / Keras interface to transformers' pipelines. This method will forward to __call__().
+ """
+ return self(X)
+
+ @property
+ def dtype(self) -> torch.dtype | None:
+ """
+ Dtype of the model (if it's Pytorch model), `None` otherwise.
+ """
+ return getattr(self.model, "dtype", None)
+
+ @property
+ def torch_dtype(self) -> torch.dtype | None:
+ """
+ Torch dtype of the model (if it's Pytorch model), `None` otherwise.
+ """
+ logger.warning_once("`torch_dtype` attribute is deprecated. Use `dtype` instead!")
+ return getattr(self.model, "dtype", None)
+
+ @contextmanager
+ def device_placement(self):
+ """
+ Context Manager allowing tensor allocation on the user-specified device.
+
+ Returns:
+ Context manager
+
+ Examples:
+
+ ```python
+ # Explicitly ask for tensor allocation on CUDA device :0
+ pipe = pipeline(..., device=0)
+ with pipe.device_placement():
+ # Every tensor allocation will be done on the request device
+ output = pipe(...)
+ ```"""
+ if self.device.type == "cuda":
+ with torch.cuda.device(self.device):
+ yield
+ elif self.device.type == "mlu":
+ with torch.mlu.device(self.device):
+ yield
+ elif self.device.type == "musa":
+ with torch.musa.device(self.device):
+ yield
+ elif self.device.type == "xpu":
+ with torch.xpu.device(self.device):
+ yield
+ else:
+ yield
+
+ def ensure_tensor_on_device(self, **inputs):
+ """
+ Ensure PyTorch tensors are on the specified device.
+
+ Args:
+ inputs (keyword arguments that should be `torch.Tensor`, the rest is ignored):
+ The tensors to place on `self.device`.
+ Recursive on lists **only**.
+
+ Return:
+ `dict[str, torch.Tensor]`: The same as `inputs` but on the proper device.
+ """
+ return self._ensure_tensor_on_device(inputs, self.device)
+
+ def _ensure_tensor_on_device(self, inputs, device):
+ if isinstance(inputs, ModelOutput):
+ return ModelOutput(
+ {name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()}
+ )
+ elif isinstance(inputs, dict):
+ return {name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()}
+ elif isinstance(inputs, UserDict):
+ return UserDict({name: self._ensure_tensor_on_device(tensor, device) for name, tensor in inputs.items()})
+ elif isinstance(inputs, list):
+ return [self._ensure_tensor_on_device(item, device) for item in inputs]
+ elif isinstance(inputs, tuple):
+ return tuple(self._ensure_tensor_on_device(item, device) for item in inputs)
+ elif isinstance(inputs, torch.Tensor):
+ return inputs.to(device)
+ else:
+ return inputs
+
+ def check_model_type(self, supported_models: list[str] | dict):
+ """
+ Check if the model class is in supported by the pipeline.
+
+ Args:
+ supported_models (`list[str]` or `dict`):
+ The list of models supported by the pipeline, or a dictionary with model class values.
+ """
+ if not isinstance(supported_models, list): # Create from a model mapping
+ supported_models_names = []
+ if self.task in SUPPORTED_PEFT_TASKS:
+ supported_models_names.extend(SUPPORTED_PEFT_TASKS[self.task])
+
+ model_name = None
+ for model_name in supported_models.values():
+ # Mapping can now contain tuples of models for the same configuration.
+ if isinstance(model_name, tuple):
+ supported_models_names.extend(list(model_name))
+ else:
+ supported_models_names.append(model_name)
+ if hasattr(supported_models, "_model_mapping"):
+ for model in supported_models._model_mapping._extra_content.values():
+ if isinstance(model_name, tuple):
+ supported_models_names.extend([m.__name__ for m in model])
+ else:
+ supported_models_names.append(model.__name__)
+ supported_models = supported_models_names
+ if self.model.__class__.__name__ not in supported_models:
+ logger.error(
+ f"The model '{self.model.__class__.__name__}' is not supported for {self.task}. Supported models are"
+ f" {supported_models}."
+ )
+
+ @abstractmethod
+ def _sanitize_parameters(self, **pipeline_parameters):
+ """
+ _sanitize_parameters will be called with any excessive named arguments from either `__init__` or `__call__`
+ methods. It should return 3 dictionaries of the resolved parameters used by the various `preprocess`,
+ `forward` and `postprocess` methods. Do not fill dictionaries if the caller didn't specify a kwargs. This
+ lets you keep defaults in function signatures, which is more "natural".
+
+ It is not meant to be called directly, it will be automatically called and the final parameters resolved by
+ `__init__` and `__call__`
+ """
+ raise NotImplementedError("_sanitize_parameters not implemented")
+
+ @abstractmethod
+ def preprocess(self, input_: Any, **preprocess_parameters: dict) -> dict[str, GenericTensor]:
+ """
+ Preprocess will take the `input_` of a specific pipeline and return a dictionary of everything necessary for
+ `_forward` to run properly. It should contain at least one tensor, but might have arbitrary other items.
+ """
+ raise NotImplementedError("preprocess not implemented")
+
+ @abstractmethod
+ def _forward(self, input_tensors: dict[str, GenericTensor], **forward_parameters: dict) -> ModelOutput:
+ """
+ _forward will receive the prepared dictionary from `preprocess` and run it on the model. This method might
+ involve the GPU or the CPU and should be agnostic to it. Isolating this function is the reason for `preprocess`
+ and `postprocess` to exist, so that the hot path, this method generally can run as fast as possible.
+
+ It is not meant to be called directly, `forward` is preferred. It is basically the same but contains additional
+ code surrounding `_forward` making sure tensors and models are on the same device, disabling the training part
+ of the code (leading to faster inference).
+ """
+ raise NotImplementedError("_forward not implemented")
+
+ @abstractmethod
+ def postprocess(self, model_outputs: ModelOutput, **postprocess_parameters: dict) -> Any:
+ """
+ Postprocess will receive the raw outputs of the `_forward` method, generally tensors, and reformat them into
+ something more friendly. Generally it will output a list or a dict or results (containing just strings and
+ numbers).
+ """
+ raise NotImplementedError("postprocess not implemented")
+
+ def get_inference_context(self):
+ return torch.no_grad
+
+ def forward(self, model_inputs, **forward_params):
+ with self.device_placement():
+ inference_context = self.get_inference_context()
+ with inference_context():
+ model_inputs = self._ensure_tensor_on_device(model_inputs, device=self.device)
+ model_outputs = self._forward(model_inputs, **forward_params)
+ model_outputs = self._ensure_tensor_on_device(model_outputs, device=torch.device("cpu"))
+ return model_outputs
+
+ def get_iterator(
+ self, inputs, num_workers: int, batch_size: int, preprocess_params, forward_params, postprocess_params
+ ):
+ if isinstance(inputs, collections.abc.Sized):
+ dataset = PipelineDataset(inputs, self.preprocess, preprocess_params)
+ else:
+ if num_workers > 1:
+ logger.warning(
+ "For iterable dataset using num_workers>1 is likely to result"
+ " in errors since everything is iterable, setting `num_workers=1`"
+ " to guarantee correctness."
+ )
+ num_workers = 1
+ dataset = PipelineIterator(inputs, self.preprocess, preprocess_params)
+ if "TOKENIZERS_PARALLELISM" not in os.environ:
+ logger.info("Disabling tokenizer parallelism, we're using DataLoader multithreading already")
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ # TODO hack by collating feature_extractor and image_processor
+ feature_extractor = self.feature_extractor if self.feature_extractor is not None else self.image_processor
+ collate_fn = no_collate_fn if batch_size == 1 else pad_collate_fn(self.tokenizer, feature_extractor)
+ dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, collate_fn=collate_fn)
+ model_iterator = PipelineIterator(dataloader, self.forward, forward_params, loader_batch_size=batch_size)
+ final_iterator = PipelineIterator(model_iterator, self.postprocess, postprocess_params)
+ return final_iterator
+
+ def __call__(self, inputs, *args, num_workers=None, batch_size=None, **kwargs):
+ if args:
+ logger.warning(f"Ignoring args : {args}")
+
+ # Detect if inputs are a chat-style input(s) and cast as `Chat` or list of `Chat`
+ container_types = (list, tuple, types.GeneratorType)
+ if is_torch_available():
+ container_types = (*container_types, KeyDataset)
+ if isinstance(inputs, container_types):
+ if isinstance(inputs, types.GeneratorType):
+ inputs = list(inputs)
+ if is_valid_message(inputs[0]):
+ inputs = Chat(inputs)
+ elif isinstance(inputs[0], (list, tuple)) and all(chat and is_valid_message(chat[0]) for chat in inputs):
+ inputs = [Chat(chat) for chat in inputs]
+
+ if num_workers is None:
+ if self._num_workers is None:
+ num_workers = 0
+ else:
+ num_workers = self._num_workers
+ if batch_size is None:
+ if self._batch_size is None:
+ batch_size = 1
+ else:
+ batch_size = self._batch_size
+
+ preprocess_params, forward_params, postprocess_params = self._sanitize_parameters(**kwargs)
+
+ # Fuse __init__ params and __call__ params without modifying the __init__ ones.
+ preprocess_params = {**self._preprocess_params, **preprocess_params}
+ forward_params = {**self._forward_params, **forward_params}
+ postprocess_params = {**self._postprocess_params, **postprocess_params}
+
+ self.call_count += 1
+ if self.call_count > 10 and self.device.type == "cuda":
+ logger.warning_once(
+ "You seem to be using the pipelines sequentially on GPU. In order to maximize efficiency please use a"
+ " dataset",
+ )
+
+ is_dataset = Dataset is not None and isinstance(inputs, Dataset)
+ is_generator = isinstance(inputs, types.GeneratorType)
+ is_list = isinstance(inputs, list)
+
+ is_iterable = is_dataset or is_generator or is_list
+ can_use_iterator = is_dataset or is_generator or is_list
+
+ if is_list:
+ if can_use_iterator:
+ final_iterator = self.get_iterator(
+ inputs, num_workers, batch_size, preprocess_params, forward_params, postprocess_params
+ )
+ outputs = list(final_iterator)
+ return outputs
+ else:
+ return self.run_multi(inputs, preprocess_params, forward_params, postprocess_params)
+ elif can_use_iterator:
+ return self.get_iterator(
+ inputs, num_workers, batch_size, preprocess_params, forward_params, postprocess_params
+ )
+ elif is_iterable:
+ return self.iterate(inputs, preprocess_params, forward_params, postprocess_params)
+ elif isinstance(self, ChunkPipeline):
+ return next(
+ iter(
+ self.get_iterator(
+ [inputs], num_workers, batch_size, preprocess_params, forward_params, postprocess_params
+ )
+ )
+ )
+ else:
+ return self.run_single(inputs, preprocess_params, forward_params, postprocess_params)
+
+ def run_multi(self, inputs, preprocess_params, forward_params, postprocess_params):
+ return [self.run_single(item, preprocess_params, forward_params, postprocess_params) for item in inputs]
+
+ def run_single(self, inputs, preprocess_params, forward_params, postprocess_params):
+ model_inputs = self.preprocess(inputs, **preprocess_params)
+ model_outputs = self.forward(model_inputs, **forward_params)
+ outputs = self.postprocess(model_outputs, **postprocess_params)
+ return outputs
+
+ def iterate(self, inputs, preprocess_params, forward_params, postprocess_params):
+ # This function should become `get_iterator` again, this is a temporary
+ # easy solution.
+ for input_ in inputs:
+ yield self.run_single(input_, preprocess_params, forward_params, postprocess_params)
+
+
+Pipeline.push_to_hub = copy_func(Pipeline.push_to_hub)
+if Pipeline.push_to_hub.__doc__ is not None:
+ Pipeline.push_to_hub.__doc__ = Pipeline.push_to_hub.__doc__.format(
+ object="pipe", object_class="pipeline", object_files="pipeline file"
+ ).replace(".from_pretrained", "")
+
+
+class ChunkPipeline(Pipeline):
+ def run_single(self, inputs, preprocess_params, forward_params, postprocess_params):
+ all_outputs = []
+ for model_inputs in self.preprocess(inputs, **preprocess_params):
+ model_outputs = self.forward(model_inputs, **forward_params)
+ all_outputs.append(model_outputs)
+ outputs = self.postprocess(all_outputs, **postprocess_params)
+ return outputs
+
+ def get_iterator(
+ self, inputs, num_workers: int, batch_size: int, preprocess_params, forward_params, postprocess_params
+ ):
+ if "TOKENIZERS_PARALLELISM" not in os.environ:
+ logger.info("Disabling tokenizer parallelism, we're using DataLoader multithreading already")
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+ if num_workers > 1:
+ logger.warning(
+ "For ChunkPipeline using num_workers>0 is likely to result in errors since everything is iterable,"
+ " setting `num_workers=1` to guarantee correctness."
+ )
+ num_workers = 1
+ dataset = PipelineChunkIterator(inputs, self.preprocess, preprocess_params)
+
+ # TODO hack by collating feature_extractor and image_processor
+ feature_extractor = self.feature_extractor if self.feature_extractor is not None else self.image_processor
+ collate_fn = no_collate_fn if batch_size == 1 else pad_collate_fn(self.tokenizer, feature_extractor)
+ dataloader = DataLoader(dataset, num_workers=num_workers, batch_size=batch_size, collate_fn=collate_fn)
+ model_iterator = PipelinePackIterator(dataloader, self.forward, forward_params, loader_batch_size=batch_size)
+ final_iterator = PipelineIterator(model_iterator, self.postprocess, postprocess_params)
+ return final_iterator
+
+
+class PipelineRegistry:
+ def __init__(self, supported_tasks: dict[str, Any], task_aliases: dict[str, str]) -> None:
+ self.supported_tasks = supported_tasks
+ self.task_aliases = task_aliases
+
+ def get_supported_tasks(self) -> list[str]:
+ supported_task = list(self.supported_tasks.keys()) + list(self.task_aliases.keys())
+ supported_task.sort()
+ return supported_task
+
+ def check_task(self, task: str) -> tuple[str, dict, Any]:
+ if task in self.task_aliases:
+ task = self.task_aliases[task]
+ if task in self.supported_tasks:
+ targeted_task = self.supported_tasks[task]
+ return task, targeted_task, None
+
+ raise KeyError(f"Unknown task {task}, available tasks are {self.get_supported_tasks()}")
+
+ def register_pipeline(
+ self,
+ task: str,
+ pipeline_class: type,
+ pt_model: type | tuple[type] | None = None,
+ default: dict | None = None,
+ type: str | None = None,
+ ) -> None:
+ if task in self.supported_tasks:
+ logger.warning(f"{task} is already registered. Overwriting pipeline for task {task}...")
+
+ if pt_model is None:
+ pt_model = ()
+ elif not isinstance(pt_model, tuple):
+ pt_model = (pt_model,)
+
+ task_impl = {"impl": pipeline_class, "pt": pt_model}
+
+ if default is not None:
+ if "model" not in default:
+ default = {"model": default}
+ task_impl["default"] = default
+
+ if type is not None:
+ task_impl["type"] = type
+
+ self.supported_tasks[task] = task_impl
+ pipeline_class._registered_impl = {task: task_impl}
+
+ def to_dict(self):
+ return self.supported_tasks
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/depth_estimation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/depth_estimation.py
new file mode 100644
index 0000000000000000000000000000000000000000..03ee70673d6cecf8a0e710bf66db8d7cfc06727e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/depth_estimation.py
@@ -0,0 +1,145 @@
+from typing import Any, Union, overload
+
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class DepthEstimationPipeline(Pipeline):
+ """
+ Depth estimation pipeline using any `AutoModelForDepthEstimation`. This pipeline predicts the depth of an image.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> depth_estimator = pipeline(task="depth-estimation", model="LiheYoung/depth-anything-base-hf")
+ >>> output = depth_estimator("http://images.cocodataset.org/val2017/000000039769.jpg")
+ >>> # This is a tensor with the values being the depth expressed in meters for each pixel
+ >>> output["predicted_depth"].shape
+ torch.Size([1, 384, 384])
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+
+ This depth estimation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"depth-estimation"`.
+
+ See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=depth-estimation).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ requires_backends(self, "vision")
+ self.check_model_type(MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES)
+
+ @overload
+ def __call__(self, inputs: Union[str, "Image.Image"], **kwargs: Any) -> dict[str, Any]: ...
+
+ @overload
+ def __call__(self, inputs: list[Union[str, "Image.Image"]], **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ def __call__(
+ self, inputs: Union[str, list[str], "Image.Image", list["Image.Image"]], **kwargs: Any
+ ) -> dict[str, Any] | list[dict[str, Any]]:
+ """
+ Predict the depth(s) of the image(s) passed as inputs.
+
+ Args:
+ inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
+ Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
+ images.
+ parameters (`Dict`, *optional*):
+ A dictionary of argument names to parameter values, to control pipeline behaviour.
+ The only parameter available right now is `timeout`, which is the length of time, in seconds,
+ that the pipeline should wait before giving up on trying to download an image.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ A dictionary or a list of dictionaries containing result. If the input is a single image, will return a
+ dictionary, if the input is a list of several images, will return a list of dictionaries corresponding to
+ the images.
+
+ The dictionaries contain the following keys:
+
+ - **predicted_depth** (`torch.Tensor`) -- The predicted depth by the model as a `torch.Tensor`.
+ - **depth** (`PIL.Image`) -- The predicted depth by the model as a `PIL.Image`.
+ """
+ # After deprecation of this is completed, remove the default `None` value for `images`
+ if "images" in kwargs:
+ inputs = kwargs.pop("images")
+ if inputs is None:
+ raise ValueError("Cannot call the depth-estimation pipeline without an inputs argument!")
+ return super().__call__(inputs, **kwargs)
+
+ def _sanitize_parameters(self, timeout=None, parameters=None, **kwargs):
+ preprocess_params = {}
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+ if isinstance(parameters, dict) and "timeout" in parameters:
+ preprocess_params["timeout"] = parameters["timeout"]
+ return preprocess_params, {}, {}
+
+ def preprocess(self, image, timeout=None):
+ image = load_image(image, timeout)
+ model_inputs = self.image_processor(images=image, return_tensors="pt")
+ model_inputs = model_inputs.to(self.dtype)
+ model_inputs["target_size"] = image.size[::-1]
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ target_size = model_inputs.pop("target_size")
+ model_outputs = self.model(**model_inputs)
+ model_outputs["target_size"] = target_size
+ return model_outputs
+
+ def postprocess(self, model_outputs):
+ outputs = self.image_processor.post_process_depth_estimation(
+ model_outputs,
+ # this acts as `source_sizes` for ZoeDepth and as `target_sizes` for the rest of the models so do *not*
+ # replace with `target_sizes = [model_outputs["target_size"]]`
+ [model_outputs["target_size"]],
+ )
+
+ formatted_outputs = []
+ for output in outputs:
+ depth = output["predicted_depth"].detach().cpu().numpy()
+ depth = (depth - depth.min()) / (depth.max() - depth.min())
+ depth = Image.fromarray((depth * 255).astype("uint8"))
+
+ formatted_outputs.append({"predicted_depth": output["predicted_depth"], "depth": depth})
+
+ return formatted_outputs[0] if len(outputs) == 1 else formatted_outputs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/document_question_answering.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/document_question_answering.py
new file mode 100644
index 0000000000000000000000000000000000000000..de976f9d8750719397ae8be2fcedd25800da8bbf
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/document_question_answering.py
@@ -0,0 +1,649 @@
+# Copyright 2022 The Impira Team 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.
+
+import re
+from typing import Any, Union, overload
+
+import numpy as np
+
+from ..generation import GenerationConfig
+from ..utils import (
+ ExplicitEnum,
+ add_end_docstrings,
+ is_pytesseract_available,
+ is_torch_available,
+ is_vision_available,
+ logging,
+)
+from .base import ChunkPipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES
+
+TESSERACT_LOADED = False
+if is_pytesseract_available():
+ TESSERACT_LOADED = True
+ import pytesseract
+
+logger = logging.get_logger(__name__)
+
+
+# normalize_bbox() and apply_tesseract() are derived from apply_tesseract in models/layoutlmv3/feature_extraction_layoutlmv3.py.
+# However, because the pipeline may evolve from what layoutlmv3 currently does, it's copied (vs. imported) to avoid creating an
+# unnecessary dependency.
+def normalize_box(box, width, height):
+ return [
+ int(1000 * (box[0] / width)),
+ int(1000 * (box[1] / height)),
+ int(1000 * (box[2] / width)),
+ int(1000 * (box[3] / height)),
+ ]
+
+
+def decode_spans(
+ start: np.ndarray, end: np.ndarray, topk: int, max_answer_len: int, undesired_tokens: np.ndarray
+) -> tuple:
+ """
+ Take the output of any `ModelForQuestionAnswering` and will generate probabilities for each span to be the actual
+ answer.
+
+ In addition, it filters out some unwanted/impossible cases like answer len being greater than max_answer_len or
+ answer end position being before the starting position. The method supports output the k-best answer through the
+ topk argument.
+
+ Args:
+ start (`np.ndarray`): Individual start probabilities for each token.
+ end (`np.ndarray`): Individual end probabilities for each token.
+ topk (`int`): Indicates how many possible answer span(s) to extract from the model output.
+ max_answer_len (`int`): Maximum size of the answer to extract from the model's output.
+ undesired_tokens (`np.ndarray`): Mask determining tokens that can be part of the answer
+ """
+ # Ensure we have batch axis
+ if start.ndim == 1:
+ start = start[None]
+
+ if end.ndim == 1:
+ end = end[None]
+
+ # Compute the score of each tuple(start, end) to be the real answer
+ outer = np.matmul(np.expand_dims(start, -1), np.expand_dims(end, 1))
+
+ # Remove candidate with end < start and end - start > max_answer_len
+ candidates = np.tril(np.triu(outer), max_answer_len - 1)
+
+ # Inspired by Chen & al. (https://github.com/facebookresearch/DrQA)
+ scores_flat = candidates.flatten()
+ if topk == 1:
+ idx_sort = [np.argmax(scores_flat)]
+ elif len(scores_flat) <= topk:
+ idx_sort = np.argsort(-scores_flat)
+ else:
+ idx = np.argpartition(-scores_flat, topk)[0:topk]
+ idx_sort = idx[np.argsort(-scores_flat[idx])]
+
+ starts, ends = np.unravel_index(idx_sort, candidates.shape)[1:]
+ desired_spans = np.isin(starts, undesired_tokens.nonzero()) & np.isin(ends, undesired_tokens.nonzero())
+ starts = starts[desired_spans]
+ ends = ends[desired_spans]
+ scores = candidates[0, starts, ends]
+
+ return starts, ends, scores
+
+
+def select_starts_ends(
+ start: np.ndarray,
+ end: np.ndarray,
+ p_mask: np.ndarray,
+ attention_mask: np.ndarray,
+ min_null_score=1000000,
+ top_k=1,
+ handle_impossible_answer=False,
+ max_answer_len=15,
+):
+ """
+ Takes the raw output of any `ModelForQuestionAnswering` and first normalizes its outputs and then uses
+ `decode_spans()` to generate probabilities for each span to be the actual answer.
+
+ Args:
+ start (`np.ndarray`): Individual start logits for each token.
+ end (`np.ndarray`): Individual end logits for each token.
+ p_mask (`np.ndarray`): A mask with 1 for values that cannot be in the answer
+ attention_mask (`np.ndarray`): The attention mask generated by the tokenizer
+ min_null_score(`float`): The minimum null (empty) answer score seen so far.
+ topk (`int`): Indicates how many possible answer span(s) to extract from the model output.
+ handle_impossible_answer(`bool`): Whether to allow null (empty) answers
+ max_answer_len (`int`): Maximum size of the answer to extract from the model's output.
+ """
+ # Ensure padded tokens & question tokens cannot belong to the set of candidate answers.
+ undesired_tokens = np.abs(np.array(p_mask) - 1)
+
+ if attention_mask is not None:
+ undesired_tokens = undesired_tokens & attention_mask
+
+ # Generate mask
+ undesired_tokens_mask = undesired_tokens == 0.0
+
+ # Make sure non-context indexes in the tensor cannot contribute to the softmax
+ start = np.where(undesired_tokens_mask, -10000.0, start)
+ end = np.where(undesired_tokens_mask, -10000.0, end)
+
+ # Normalize logits and spans to retrieve the answer
+ start = np.exp(start - start.max(axis=-1, keepdims=True))
+ start = start / start.sum()
+
+ end = np.exp(end - end.max(axis=-1, keepdims=True))
+ end = end / end.sum()
+
+ if handle_impossible_answer:
+ min_null_score = min(min_null_score, (start[0, 0] * end[0, 0]).item())
+
+ # Mask CLS
+ start[0, 0] = end[0, 0] = 0.0
+
+ starts, ends, scores = decode_spans(start, end, top_k, max_answer_len, undesired_tokens)
+ return starts, ends, scores, min_null_score
+
+
+def apply_tesseract(image: "Image.Image", lang: str | None, tesseract_config: str | None):
+ """Applies Tesseract OCR on a document image, and returns recognized words + normalized bounding boxes."""
+ # apply OCR
+ data = pytesseract.image_to_data(image, lang=lang, output_type="dict", config=tesseract_config)
+ words, left, top, width, height = data["text"], data["left"], data["top"], data["width"], data["height"]
+
+ # filter empty words and corresponding coordinates
+ irrelevant_indices = [idx for idx, word in enumerate(words) if not word.strip()]
+ words = [word for idx, word in enumerate(words) if idx not in irrelevant_indices]
+ left = [coord for idx, coord in enumerate(left) if idx not in irrelevant_indices]
+ top = [coord for idx, coord in enumerate(top) if idx not in irrelevant_indices]
+ width = [coord for idx, coord in enumerate(width) if idx not in irrelevant_indices]
+ height = [coord for idx, coord in enumerate(height) if idx not in irrelevant_indices]
+
+ # turn coordinates into (left, top, left+width, top+height) format
+ actual_boxes = []
+ for x, y, w, h in zip(left, top, width, height):
+ actual_box = [x, y, x + w, y + h]
+ actual_boxes.append(actual_box)
+
+ image_width, image_height = image.size
+
+ # finally, normalize the bounding boxes
+ normalized_boxes = []
+ for box in actual_boxes:
+ normalized_boxes.append(normalize_box(box, image_width, image_height))
+
+ if len(words) != len(normalized_boxes):
+ raise ValueError("Not as many words as there are bounding boxes")
+
+ return words, normalized_boxes
+
+
+class ModelType(ExplicitEnum):
+ LayoutLM = "layoutlm"
+ LayoutLMv2andv3 = "layoutlmv2andv3"
+ VisionEncoderDecoder = "vision_encoder_decoder"
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True, has_tokenizer=True))
+class DocumentQuestionAnsweringPipeline(ChunkPipeline):
+ # TODO: Update task_summary docs to include an example with document QA and then update the first sentence
+ """
+ Document Question Answering pipeline using any `AutoModelForDocumentQuestionAnswering`. The inputs/outputs are
+ similar to the (extractive) question answering pipeline; however, the pipeline takes an image (and optional OCR'd
+ words/boxes) as input instead of text context.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> document_qa = pipeline(model="impira/layoutlm-document-qa")
+ >>> document_qa(
+ ... image="https://huggingface.co/spaces/impira/docquery/resolve/2359223c1837a7587402bda0f2643382a6eefeab/invoice.png",
+ ... question="What is the invoice number?",
+ ... )
+ [{'score': 0.425, 'answer': 'us-001', 'start': 16, 'end': 16}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This document question answering pipeline can currently be loaded from [`pipeline`] using the following task
+ identifier: `"document-question-answering"`.
+
+ The models that this pipeline can use are models that have been fine-tuned on a document question answering task.
+ See the up-to-date list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=document-question-answering).
+ """
+
+ _pipeline_calls_generate = True
+ _load_processor = False
+ _load_image_processor = None
+ _load_feature_extractor = None
+ _load_tokenizer = True
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ )
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ if self.tokenizer is not None and not (
+ self.tokenizer.__class__.__name__.endswith("Fast") or self.tokenizer.backend == "tokenizers"
+ ):
+ raise ValueError(
+ "`DocumentQuestionAnsweringPipeline` requires a fast tokenizer, but a slow tokenizer "
+ f"(`{self.tokenizer.__class__.__name__}`) is provided."
+ )
+
+ if self.model.config.__class__.__name__ == "VisionEncoderDecoderConfig":
+ self.model_type = ModelType.VisionEncoderDecoder
+ if self.model.config.encoder.model_type != "donut-swin":
+ raise ValueError("Currently, the only supported VisionEncoderDecoder model is Donut")
+ else:
+ self.check_model_type(MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES)
+ if self.model.config.__class__.__name__ == "LayoutLMConfig":
+ self.model_type = ModelType.LayoutLM
+ else:
+ self.model_type = ModelType.LayoutLMv2andv3
+
+ def _sanitize_parameters(
+ self,
+ padding=None,
+ doc_stride=None,
+ max_question_len=None,
+ lang: str | None = None,
+ tesseract_config: str | None = None,
+ max_answer_len=None,
+ max_seq_len=None,
+ top_k=None,
+ handle_impossible_answer=None,
+ timeout=None,
+ **kwargs,
+ ):
+ preprocess_params, postprocess_params = {}, {}
+ if padding is not None:
+ preprocess_params["padding"] = padding
+ if doc_stride is not None:
+ preprocess_params["doc_stride"] = doc_stride
+ if max_question_len is not None:
+ preprocess_params["max_question_len"] = max_question_len
+ if max_seq_len is not None:
+ preprocess_params["max_seq_len"] = max_seq_len
+ if lang is not None:
+ preprocess_params["lang"] = lang
+ if tesseract_config is not None:
+ preprocess_params["tesseract_config"] = tesseract_config
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+
+ if top_k is not None:
+ if top_k < 1:
+ raise ValueError(f"top_k parameter should be >= 1 (got {top_k})")
+ postprocess_params["top_k"] = top_k
+ if max_answer_len is not None:
+ if max_answer_len < 1:
+ raise ValueError(f"max_answer_len parameter should be >= 1 (got {max_answer_len})")
+ postprocess_params["max_answer_len"] = max_answer_len
+ if handle_impossible_answer is not None:
+ postprocess_params["handle_impossible_answer"] = handle_impossible_answer
+
+ forward_params = {}
+ if getattr(self, "assistant_model", None) is not None:
+ forward_params["assistant_model"] = self.assistant_model
+ if getattr(self, "assistant_tokenizer", None) is not None:
+ forward_params["tokenizer"] = self.tokenizer
+ forward_params["assistant_tokenizer"] = self.assistant_tokenizer
+
+ return preprocess_params, forward_params, postprocess_params
+
+ @overload
+ def __call__(
+ self,
+ image: Union["Image.Image", str],
+ question: str,
+ word_boxes: tuple[str, list[float]] | None = None,
+ **kwargs: Any,
+ ) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, image: dict[str, Any], **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, image: list[dict[str, Any]], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self,
+ image: Union["Image.Image", str, list[dict[str, Any]]],
+ question: str | None = None,
+ word_boxes: tuple[str, list[float]] | None = None,
+ **kwargs: Any,
+ ) -> dict[str, Any] | list[dict[str, Any]]:
+ """
+ Answer the question(s) given as inputs by using the document(s). A document is defined as an image and an
+ optional list of (word, box) tuples which represent the text in the document. If the `word_boxes` are not
+ provided, it will use the Tesseract OCR engine (if available) to extract the words and boxes automatically for
+ LayoutLM-like models which require them as input. For Donut, no OCR is run.
+
+ You can invoke the pipeline several ways:
+
+ - `pipeline(image=image, question=question)`
+ - `pipeline(image=image, question=question, word_boxes=word_boxes)`
+ - `pipeline([{"image": image, "question": question}])`
+ - `pipeline([{"image": image, "question": question, "word_boxes": word_boxes}])`
+
+ Args:
+ image (`str` or `PIL.Image`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images. If given a single image, it can be
+ broadcasted to multiple questions.
+ question (`str`):
+ A question to ask of the document.
+ word_boxes (`list[str, tuple[float, float, float, float]]`, *optional*):
+ A list of words and bounding boxes (normalized 0->1000). If you provide this optional input, then the
+ pipeline will use these words and boxes instead of running OCR on the image to derive them for models
+ that need them (e.g. LayoutLM). This allows you to reuse OCR'd results across many invocations of the
+ pipeline without having to re-run it each time.
+ top_k (`int`, *optional*, defaults to 1):
+ The number of answers to return (will be chosen by order of likelihood). Note that we return less than
+ top_k answers if there are not enough options available within the context.
+ doc_stride (`int`, *optional*, defaults to 128):
+ If the words in the document are too long to fit with the question for the model, it will be split in
+ several chunks with some overlap. This argument controls the size of that overlap.
+ max_answer_len (`int`, *optional*, defaults to 15):
+ The maximum length of predicted answers (e.g., only answers with a shorter length are considered).
+ max_seq_len (`int`, *optional*, defaults to 384):
+ The maximum length of the total sentence (context + question) in tokens of each chunk passed to the
+ model. The context will be split in several chunks (using `doc_stride` as overlap) if needed.
+ max_question_len (`int`, *optional*, defaults to 64):
+ The maximum length of the question after tokenization. It will be truncated if needed.
+ handle_impossible_answer (`bool`, *optional*, defaults to `False`):
+ Whether or not we accept impossible as an answer.
+ lang (`str`, *optional*):
+ Language to use while running OCR. Defaults to english.
+ tesseract_config (`str`, *optional*):
+ Additional flags to pass to tesseract while running OCR.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:
+
+ - **score** (`float`) -- The probability associated to the answer.
+ - **start** (`int`) -- The start word index of the answer (in the OCR'd version of the input or provided
+ `word_boxes`).
+ - **end** (`int`) -- The end word index of the answer (in the OCR'd version of the input or provided
+ `word_boxes`).
+ - **answer** (`str`) -- The answer to the question.
+ - **words** (`list[int]`) -- The index of each word/box pair that is in the answer
+ """
+ if isinstance(question, str):
+ inputs = {"question": question, "image": image}
+ if word_boxes is not None:
+ inputs["word_boxes"] = word_boxes
+ else:
+ inputs = image
+ return super().__call__(inputs, **kwargs)
+
+ def preprocess(
+ self,
+ input,
+ padding="do_not_pad",
+ doc_stride=None,
+ max_seq_len=None,
+ word_boxes: tuple[str, list[float]] | None = None,
+ lang=None,
+ tesseract_config="",
+ timeout=None,
+ ):
+ # NOTE: This code mirrors the code in question answering and will be implemented in a follow up PR
+ # to support documents with enough tokens that overflow the model's window
+ if max_seq_len is None:
+ max_seq_len = self.tokenizer.model_max_length
+
+ if doc_stride is None:
+ doc_stride = min(max_seq_len // 2, 256)
+
+ image = None
+ image_features = {}
+ if input.get("image", None) is not None:
+ image = load_image(input["image"], timeout=timeout)
+ if self.image_processor is not None:
+ image_inputs = self.image_processor(images=image, return_tensors="pt")
+ image_inputs = image_inputs.to(self.dtype)
+ image_features.update(image_inputs)
+ elif self.feature_extractor is not None:
+ image_features.update(self.feature_extractor(images=image, return_tensors="pt"))
+ elif self.model_type == ModelType.VisionEncoderDecoder:
+ raise ValueError("If you are using a VisionEncoderDecoderModel, you must provide a feature extractor")
+
+ words, boxes = None, None
+ if self.model_type != ModelType.VisionEncoderDecoder:
+ if "word_boxes" in input:
+ words = [x[0] for x in input["word_boxes"]]
+ boxes = [x[1] for x in input["word_boxes"]]
+ elif "words" in image_features and "boxes" in image_features:
+ words = image_features.pop("words")[0]
+ boxes = image_features.pop("boxes")[0]
+ elif image is not None:
+ if not TESSERACT_LOADED:
+ raise ValueError(
+ "If you provide an image without word_boxes, then the pipeline will run OCR using Tesseract,"
+ " but pytesseract is not available"
+ )
+ if TESSERACT_LOADED:
+ words, boxes = apply_tesseract(image, lang=lang, tesseract_config=tesseract_config)
+ else:
+ raise ValueError(
+ "You must provide an image or word_boxes. If you provide an image, the pipeline will automatically"
+ " run OCR to derive words and boxes"
+ )
+
+ if self.tokenizer.padding_side != "right":
+ raise ValueError(
+ "Document question answering only supports tokenizers whose padding side is 'right', not"
+ f" {self.tokenizer.padding_side}"
+ )
+
+ if self.model_type == ModelType.VisionEncoderDecoder:
+ task_prompt = f"{input['question']}"
+ # Adapted from https://huggingface.co/spaces/nielsr/donut-docvqa/blob/main/app.py
+ encoding = {
+ "inputs": image_features["pixel_values"],
+ "decoder_input_ids": self.tokenizer(
+ task_prompt, add_special_tokens=False, return_tensors="pt"
+ ).input_ids,
+ "return_dict_in_generate": True,
+ }
+ yield {
+ **encoding,
+ "p_mask": None,
+ "word_ids": None,
+ "words": None,
+ "output_attentions": True,
+ "is_last": True,
+ }
+ else:
+ tokenizer_kwargs = {}
+ if self.model_type == ModelType.LayoutLM:
+ tokenizer_kwargs["text"] = input["question"].split()
+ tokenizer_kwargs["text_pair"] = words
+ tokenizer_kwargs["is_split_into_words"] = True
+ else:
+ tokenizer_kwargs["text"] = [input["question"]]
+ tokenizer_kwargs["text_pair"] = [words]
+ tokenizer_kwargs["boxes"] = [boxes]
+
+ encoding = self.tokenizer(
+ padding=padding,
+ max_length=max_seq_len,
+ stride=doc_stride,
+ return_token_type_ids=True,
+ truncation="only_second",
+ return_overflowing_tokens=True,
+ **tokenizer_kwargs,
+ )
+ # TODO: check why slower `LayoutLMTokenizer` and `LayoutLMv2Tokenizer` don't have this key in outputs
+ # FIXME: ydshieh and/or Narsil
+ encoding.pop("overflow_to_sample_mapping", None) # We do not use this
+
+ num_spans = len(encoding["input_ids"])
+
+ # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer)
+ # We put 0 on the tokens from the context and 1 everywhere else (question and special tokens)
+ # This logic mirrors the logic in the question_answering pipeline
+ p_mask = [[tok != 1 for tok in encoding.sequence_ids(span_id)] for span_id in range(num_spans)]
+ for span_idx in range(num_spans):
+ span_encoding = {k: torch.tensor(v[span_idx : span_idx + 1]) for (k, v) in encoding.items()}
+ if "pixel_values" in image_features:
+ span_encoding["image"] = image_features["pixel_values"]
+
+ input_ids_span_idx = encoding["input_ids"][span_idx]
+ # keep the cls_token unmasked (some models use it to indicate unanswerable questions)
+ if self.tokenizer.cls_token_id is not None:
+ cls_indices = np.nonzero(np.array(input_ids_span_idx) == self.tokenizer.cls_token_id)[0]
+ for cls_index in cls_indices:
+ p_mask[span_idx][cls_index] = 0
+
+ # For each span, place a bounding box [0,0,0,0] for question and CLS tokens, [1000,1000,1000,1000]
+ # for SEP tokens, and the word's bounding box for words in the original document.
+ if "boxes" not in tokenizer_kwargs:
+ bbox = []
+ for input_id, sequence_id, word_id in zip(
+ encoding.input_ids[span_idx],
+ encoding.sequence_ids(span_idx),
+ encoding.word_ids(span_idx),
+ ):
+ if sequence_id == 1:
+ bbox.append(boxes[word_id])
+ elif input_id == self.tokenizer.sep_token_id:
+ bbox.append([1000] * 4)
+ else:
+ bbox.append([0] * 4)
+
+ span_encoding["bbox"] = torch.tensor(bbox).unsqueeze(0)
+ yield {
+ **span_encoding,
+ "p_mask": p_mask[span_idx],
+ "word_ids": encoding.word_ids(span_idx),
+ "words": words,
+ "is_last": span_idx == num_spans - 1,
+ }
+
+ def _forward(self, model_inputs, **generate_kwargs):
+ p_mask = model_inputs.pop("p_mask", None)
+ word_ids = model_inputs.pop("word_ids", None)
+ words = model_inputs.pop("words", None)
+ is_last = model_inputs.pop("is_last", False)
+
+ if self.model_type == ModelType.VisionEncoderDecoder:
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ model_outputs = self.model.generate(**model_inputs, **generate_kwargs)
+ else:
+ model_outputs = self.model(**model_inputs)
+
+ model_outputs = dict(model_outputs.items())
+ model_outputs["p_mask"] = p_mask
+ model_outputs["word_ids"] = word_ids
+ model_outputs["words"] = words
+ model_outputs["attention_mask"] = model_inputs.get("attention_mask", None)
+ model_outputs["is_last"] = is_last
+ return model_outputs
+
+ def postprocess(self, model_outputs, top_k=1, **kwargs):
+ if self.model_type == ModelType.VisionEncoderDecoder:
+ answers = [self.postprocess_encoder_decoder_single(o) for o in model_outputs]
+ else:
+ answers = self.postprocess_extractive_qa(model_outputs, top_k=top_k, **kwargs)
+
+ answers = sorted(answers, key=lambda x: x.get("score", 0), reverse=True)[:top_k]
+ return answers
+
+ def postprocess_encoder_decoder_single(self, model_outputs, **kwargs):
+ sequence = self.tokenizer.batch_decode(model_outputs["sequences"])[0]
+
+ # TODO: A lot of this logic is specific to Donut and should probably be handled in the tokenizer
+ # (see https://github.com/huggingface/transformers/pull/18414/files#r961747408 for more context).
+ sequence = sequence.replace(self.tokenizer.eos_token, "").replace(self.tokenizer.pad_token, "")
+ sequence = re.sub(r"<.*?>", "", sequence, count=1).strip() # remove first task start token
+ ret = {
+ "answer": None,
+ }
+
+ answer = re.search(r"(.*)", sequence)
+ if answer is not None:
+ ret["answer"] = answer.group(1).strip()
+ return ret
+
+ def postprocess_extractive_qa(
+ self, model_outputs, top_k=1, handle_impossible_answer=False, max_answer_len=15, **kwargs
+ ):
+ min_null_score = 1000000 # large and positive
+ answers = []
+ for output in model_outputs:
+ words = output["words"]
+
+ if output["start_logits"].dtype in (torch.bfloat16, torch.float16):
+ output["start_logits"] = output["start_logits"].float()
+ if output["end_logits"].dtype in (torch.bfloat16, torch.float16):
+ output["end_logits"] = output["end_logits"].float()
+
+ starts, ends, scores, min_null_score = select_starts_ends(
+ start=output["start_logits"],
+ end=output["end_logits"],
+ p_mask=output["p_mask"],
+ attention_mask=output["attention_mask"].numpy()
+ if output.get("attention_mask", None) is not None
+ else None,
+ min_null_score=min_null_score,
+ top_k=top_k,
+ handle_impossible_answer=handle_impossible_answer,
+ max_answer_len=max_answer_len,
+ )
+ word_ids = output["word_ids"]
+ for start, end, score in zip(starts, ends, scores):
+ word_start, word_end = word_ids[start], word_ids[end]
+ if word_start is not None and word_end is not None:
+ answers.append(
+ {
+ "score": float(score),
+ "answer": " ".join(words[word_start : word_end + 1]),
+ "start": word_start,
+ "end": word_end,
+ }
+ )
+
+ if handle_impossible_answer:
+ answers.append({"score": min_null_score, "answer": "", "start": 0, "end": 0})
+
+ return answers
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/feature_extraction.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/feature_extraction.py
new file mode 100644
index 0000000000000000000000000000000000000000..a37f147605f04347efa34f587d7fdebe8074f3b5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/feature_extraction.py
@@ -0,0 +1,88 @@
+from typing import Any
+
+from ..utils import add_end_docstrings
+from .base import GenericTensor, Pipeline, build_pipeline_init_args
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_tokenizer=True, supports_binary_output=False),
+ r"""
+ tokenize_kwargs (`dict`, *optional*):
+ Additional dictionary of keyword arguments passed along to the tokenizer.
+ return_tensors (`bool`, *optional*):
+ If `True`, returns a tensor according to the specified framework, otherwise returns a list.""",
+)
+class FeatureExtractionPipeline(Pipeline):
+ """
+ Feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base
+ transformer, which can be used as features in downstream tasks.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> extractor = pipeline(model="google-bert/bert-base-uncased", task="feature-extraction")
+ >>> result = extractor("This is a simple test.", return_tensors=True)
+ >>> result.shape # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input string.
+ torch.Size([1, 8, 768])
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This feature extraction pipeline can currently be loaded from [`pipeline`] using the task identifier:
+ `"feature-extraction"`.
+
+ All models may be used for this pipeline. See a list of all models, including community-contributed models on
+ [huggingface.co/models](https://huggingface.co/models).
+ """
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ def _sanitize_parameters(self, truncation=None, tokenize_kwargs=None, return_tensors=None, **kwargs):
+ if tokenize_kwargs is None:
+ tokenize_kwargs = {}
+
+ if truncation is not None:
+ if "truncation" in tokenize_kwargs:
+ raise ValueError(
+ "truncation parameter defined twice (given as keyword argument as well as in tokenize_kwargs)"
+ )
+ tokenize_kwargs["truncation"] = truncation
+
+ preprocess_params = tokenize_kwargs
+
+ postprocess_params = {}
+ if return_tensors is not None:
+ postprocess_params["return_tensors"] = return_tensors
+
+ return preprocess_params, {}, postprocess_params
+
+ def preprocess(self, inputs, **tokenize_kwargs) -> dict[str, GenericTensor]:
+ model_inputs = self.tokenizer(inputs, return_tensors="pt", **tokenize_kwargs)
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ return model_outputs
+
+ def postprocess(self, model_outputs, return_tensors=False):
+ # [0] is the first available tensor, logits or last_hidden_state.
+ if return_tensors:
+ return model_outputs[0]
+ return model_outputs[0].tolist()
+
+ def __call__(self, *args: str | list[str], **kwargs: Any) -> Any | list[Any]:
+ """
+ Extract the features of the input(s) text.
+
+ Args:
+ args (`str` or `list[str]`): One or several texts (or one list of texts) to get the features of.
+
+ Return:
+ A nested list of `float`: The features computed by the model.
+ """
+ return super().__call__(*args, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/fill_mask.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/fill_mask.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ea7c487be76458ff66508a6506bc11437937cb1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/fill_mask.py
@@ -0,0 +1,259 @@
+from typing import Any, overload
+
+import numpy as np
+
+from ..utils import add_end_docstrings, is_torch_available, logging
+from .base import GenericTensor, Pipeline, PipelineException, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_tokenizer=True),
+ r"""
+ top_k (`int`, *optional*, defaults to 5):
+ The number of predictions to return.
+ targets (`str` or `list[str]`, *optional*):
+ When passed, the model will limit the scores to the passed targets instead of looking up in the whole
+ vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
+ token will be used (with a warning, and that might be slower).
+ tokenizer_kwargs (`dict`, *optional*):
+ Additional dictionary of keyword arguments passed along to the tokenizer.""",
+)
+class FillMaskPipeline(Pipeline):
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ """
+ Masked language modeling prediction pipeline using any `ModelWithLMHead`. See the [masked language modeling
+ examples](../task_summary#masked-language-modeling) for more information.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
+ >>> fill_masker("This is a simple [MASK].")
+ [{'score': 0.042, 'token': 3291, 'token_str': 'problem', 'sequence': 'this is a simple problem.'}, {'score': 0.031, 'token': 3160, 'token_str': 'question', 'sequence': 'this is a simple question.'}, {'score': 0.03, 'token': 8522, 'token_str': 'equation', 'sequence': 'this is a simple equation.'}, {'score': 0.027, 'token': 2028, 'token_str': 'one', 'sequence': 'this is a simple one.'}, {'score': 0.024, 'token': 3627, 'token_str': 'rule', 'sequence': 'this is a simple rule.'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This mask filling pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"fill-mask"`.
+
+ The models that this pipeline can use are models that have been trained with a masked language modeling objective,
+ which includes the bi-directional models in the library. See the up-to-date list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=fill-mask).
+
+
+
+ This pipeline only works for inputs with exactly one token masked. Experimental: We added support for multiple
+ masks. The returned values are raw model output, and correspond to disjoint probabilities where one might expect
+ joint probabilities (See [discussion](https://github.com/huggingface/transformers/pull/10222)).
+
+
+
+
+
+ This pipeline now supports tokenizer_kwargs. For example try:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> fill_masker = pipeline(model="google-bert/bert-base-uncased")
+ >>> tokenizer_kwargs = {"truncation": True}
+ >>> fill_masker(
+ ... "This is a simple [MASK]. " + "...with a large amount of repeated text appended. " * 100,
+ ... tokenizer_kwargs=tokenizer_kwargs,
+ ... )
+ ```
+
+
+
+
+
+ """
+
+ def get_masked_index(self, input_ids: GenericTensor) -> np.ndarray:
+ masked_index = torch.nonzero(input_ids == self.tokenizer.mask_token_id, as_tuple=False)
+ return masked_index
+
+ def _ensure_exactly_one_mask_token(self, input_ids: GenericTensor) -> np.ndarray:
+ masked_index = self.get_masked_index(input_ids)
+ numel = np.prod(masked_index.shape)
+ if numel < 1:
+ raise PipelineException(
+ "fill-mask",
+ self.model.base_model_prefix,
+ f"No mask_token ({self.tokenizer.mask_token}) found on the input",
+ )
+
+ def ensure_exactly_one_mask_token(self, model_inputs: GenericTensor):
+ if isinstance(model_inputs, list):
+ for model_input in model_inputs:
+ self._ensure_exactly_one_mask_token(model_input["input_ids"][0])
+ else:
+ for input_ids in model_inputs["input_ids"]:
+ self._ensure_exactly_one_mask_token(input_ids)
+
+ def preprocess(
+ self, inputs, return_tensors=None, tokenizer_kwargs=None, **preprocess_parameters
+ ) -> dict[str, GenericTensor]:
+ if return_tensors is None:
+ return_tensors = "pt"
+ if tokenizer_kwargs is None:
+ tokenizer_kwargs = {}
+
+ model_inputs = self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs)
+ self.ensure_exactly_one_mask_token(model_inputs)
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ model_outputs["input_ids"] = model_inputs["input_ids"]
+ return model_outputs
+
+ def postprocess(self, model_outputs, top_k=5, target_ids=None):
+ # Cap top_k if there are targets
+ if target_ids is not None and target_ids.shape[0] < top_k:
+ top_k = target_ids.shape[0]
+ input_ids = model_outputs["input_ids"][0]
+ outputs = model_outputs["logits"]
+
+ masked_index = torch.nonzero(input_ids == self.tokenizer.mask_token_id, as_tuple=False).squeeze(-1)
+ # Fill mask pipeline supports only one ${mask_token} per sample
+
+ logits = outputs[0, masked_index, :]
+ probs = logits.softmax(dim=-1)
+ if target_ids is not None:
+ probs = probs[..., target_ids]
+
+ values, predictions = probs.topk(top_k)
+
+ result = []
+ single_mask = values.shape[0] == 1
+ for i, (_values, _predictions) in enumerate(zip(values.tolist(), predictions.tolist())):
+ row = []
+ for v, p in zip(_values, _predictions):
+ # Copy is important since we're going to modify this array in place
+ tokens = input_ids.numpy().copy()
+ if target_ids is not None:
+ p = target_ids[p].tolist()
+
+ tokens[masked_index[i]] = p
+ # Filter padding out:
+ tokens = tokens[np.where(tokens != self.tokenizer.pad_token_id)]
+ # Originally we skip special tokens to give readable output.
+ # For multi masks though, the other [MASK] would be removed otherwise
+ # making the output look odd, so we add them back
+ sequence = self.tokenizer.decode(tokens, skip_special_tokens=single_mask)
+ proposition = {"score": v, "token": p, "token_str": self.tokenizer.decode([p]), "sequence": sequence}
+ row.append(proposition)
+ result.append(row)
+ if single_mask:
+ return result[0]
+ return result
+
+ def get_target_ids(self, targets):
+ if isinstance(targets, str):
+ targets = [targets]
+ try:
+ vocab = self.tokenizer.get_vocab()
+ except Exception:
+ vocab = {}
+ target_ids = []
+ for target in targets:
+ id_ = vocab.get(target)
+ if id_ is None:
+ input_ids = self.tokenizer(
+ target,
+ add_special_tokens=False,
+ return_attention_mask=False,
+ return_token_type_ids=False,
+ max_length=1,
+ truncation=True,
+ )["input_ids"]
+ if len(input_ids) == 0:
+ logger.warning(
+ f"The specified target token `{target}` does not exist in the model vocabulary. "
+ "We cannot replace it with anything meaningful, ignoring it"
+ )
+ continue
+ id_ = input_ids[0]
+ # XXX: If users encounter this pass
+ # it becomes pretty slow, so let's make sure
+ # The warning enables them to fix the input to
+ # get faster performance.
+ logger.warning(
+ f"The specified target token `{target}` does not exist in the model vocabulary. "
+ f"Replacing with `{self.tokenizer.convert_ids_to_tokens(id_)}`."
+ )
+ target_ids.append(id_)
+ target_ids = list(set(target_ids))
+ if len(target_ids) == 0:
+ raise ValueError("At least one target must be provided when passed.")
+ target_ids = np.array(target_ids)
+ return target_ids
+
+ def _sanitize_parameters(self, top_k=None, targets=None, tokenizer_kwargs=None):
+ preprocess_params = {}
+
+ if tokenizer_kwargs is not None:
+ preprocess_params["tokenizer_kwargs"] = tokenizer_kwargs
+
+ postprocess_params = {}
+
+ if targets is not None:
+ target_ids = self.get_target_ids(targets)
+ postprocess_params["target_ids"] = target_ids
+
+ if top_k is not None:
+ postprocess_params["top_k"] = top_k
+
+ if self.tokenizer.mask_token_id is None:
+ raise PipelineException(
+ "fill-mask", self.model.base_model_prefix, "The tokenizer does not define a `mask_token`."
+ )
+ return preprocess_params, {}, postprocess_params
+
+ @overload
+ def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(self, inputs: str | list[str], **kwargs: Any) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Fill the masked token in the text(s) given as inputs.
+
+ Args:
+ inputs (`str` or `list[str]`):
+ One or several texts (or one list of prompts) with masked tokens.
+ targets (`str` or `list[str]`, *optional*):
+ When passed, the model will limit the scores to the passed targets instead of looking up in the whole
+ vocab. If the provided targets are not in the model vocab, they will be tokenized and the first
+ resulting token will be used (with a warning, and that might be slower).
+ top_k (`int`, *optional*):
+ When passed, overrides the number of predictions to return.
+
+ Return:
+ A list or a list of list of `dict`: Each result comes as list of dictionaries with the following keys:
+
+ - **sequence** (`str`) -- The corresponding input with the mask token prediction.
+ - **score** (`float`) -- The corresponding probability.
+ - **token** (`int`) -- The predicted token id (to replace the masked one).
+ - **token_str** (`str`) -- The predicted token (to replace the masked one).
+ """
+ outputs = super().__call__(inputs, **kwargs)
+ if isinstance(inputs, list) and len(inputs) == 1:
+ return outputs[0]
+ return outputs
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..18a570df6e21f8e7ebd15d7771408cf324e306de
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_classification.py
@@ -0,0 +1,229 @@
+# 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 Any, Union, overload
+
+import numpy as np
+
+from ..utils import (
+ ExplicitEnum,
+ add_end_docstrings,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES
+
+logger = logging.get_logger(__name__)
+
+
+# Copied from transformers.pipelines.text_classification.sigmoid
+def sigmoid(_outputs):
+ return 1.0 / (1.0 + np.exp(-_outputs))
+
+
+# Copied from transformers.pipelines.text_classification.softmax
+def softmax(_outputs):
+ maxes = np.max(_outputs, axis=-1, keepdims=True)
+ shifted_exp = np.exp(_outputs - maxes)
+ return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
+
+
+# Copied from transformers.pipelines.text_classification.ClassificationFunction
+class ClassificationFunction(ExplicitEnum):
+ SIGMOID = "sigmoid"
+ SOFTMAX = "softmax"
+ NONE = "none"
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_image_processor=True),
+ r"""
+ function_to_apply (`str`, *optional*, defaults to `"default"`):
+ The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
+
+ - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
+ has several labels, will apply the softmax function on the output.
+ - `"sigmoid"`: Applies the sigmoid function on the output.
+ - `"softmax"`: Applies the softmax function on the output.
+ - `"none"`: Does not apply any function on the output.""",
+)
+class ImageClassificationPipeline(Pipeline):
+ """
+ Image classification pipeline using any `AutoModelForImageClassification`. This pipeline predicts the class of an
+ image.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> classifier = pipeline(model="microsoft/beit-base-patch16-224-pt22k-ft22k")
+ >>> classifier("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
+ [{'score': 0.442, 'label': 'macaw'}, {'score': 0.088, 'label': 'popinjay'}, {'score': 0.075, 'label': 'parrot'}, {'score': 0.073, 'label': 'parodist, lampooner'}, {'score': 0.046, 'label': 'poll, poll_parrot'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"image-classification"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=image-classification).
+ """
+
+ function_to_apply: ClassificationFunction = ClassificationFunction.NONE
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ requires_backends(self, "vision")
+ self.check_model_type(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES)
+
+ def _sanitize_parameters(self, top_k=None, function_to_apply=None, timeout=None):
+ preprocess_params = {}
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+ postprocess_params = {}
+ if top_k is not None:
+ postprocess_params["top_k"] = top_k
+ if isinstance(function_to_apply, str):
+ function_to_apply = ClassificationFunction(function_to_apply.lower())
+ if function_to_apply is not None:
+ postprocess_params["function_to_apply"] = function_to_apply
+ return preprocess_params, {}, postprocess_params
+
+ @overload
+ def __call__(self, inputs: Union[str, "Image.Image"], **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, inputs: list[str] | list["Image.Image"], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self, inputs: Union[str, list[str], "Image.Image", list["Image.Image"]], **kwargs: Any
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Assign labels to the image(s) passed as inputs.
+
+ Args:
+ inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
+ Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
+ images.
+ function_to_apply (`str`, *optional*, defaults to `"default"`):
+ The function to apply to the model outputs in order to retrieve the scores. Accepts four different
+ values:
+
+ If this argument is not specified, then it will apply the following functions according to the number
+ of labels:
+
+ - If the model has a single label, will apply the sigmoid function on the output.
+ - If the model has several labels, will apply the softmax function on the output.
+
+ Possible values are:
+
+ - `"sigmoid"`: Applies the sigmoid function on the output.
+ - `"softmax"`: Applies the softmax function on the output.
+ - `"none"`: Does not apply any function on the output.
+ top_k (`int`, *optional*, defaults to 5):
+ The number of top labels that will be returned by the pipeline. If the provided number is higher than
+ the number of labels available in the model configuration, it will default to the number of labels.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ A dictionary or a list of dictionaries containing result. If the input is a single image, will return a
+ dictionary, if the input is a list of several images, will return a list of dictionaries corresponding to
+ the images.
+
+ The dictionaries contain the following keys:
+
+ - **label** (`str`) -- The label identified by the model.
+ - **score** (`int`) -- The score attributed by the model for that label.
+ """
+ # After deprecation of this is completed, remove the default `None` value for `images`
+ if "images" in kwargs:
+ inputs = kwargs.pop("images")
+ if inputs is None:
+ raise ValueError("Cannot call the image-classification pipeline without an inputs argument!")
+ return super().__call__(inputs, **kwargs)
+
+ def preprocess(self, image, timeout=None):
+ image = load_image(image, timeout=timeout)
+ model_inputs = self.image_processor(images=image, return_tensors="pt")
+ model_inputs = model_inputs.to(self.dtype)
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ return model_outputs
+
+ def postprocess(self, model_outputs, function_to_apply=None, top_k=5):
+ if function_to_apply is None:
+ if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
+ function_to_apply = ClassificationFunction.SIGMOID
+ elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
+ function_to_apply = ClassificationFunction.SOFTMAX
+ elif hasattr(self.model.config, "function_to_apply") and function_to_apply is None:
+ function_to_apply = self.model.config.function_to_apply
+ else:
+ function_to_apply = ClassificationFunction.NONE
+
+ if top_k > self.model.config.num_labels:
+ top_k = self.model.config.num_labels
+
+ outputs = model_outputs["logits"][0]
+ if outputs.dtype in (torch.bfloat16, torch.float16):
+ outputs = outputs.to(torch.float32).numpy()
+ else:
+ outputs = outputs.numpy()
+
+ if function_to_apply == ClassificationFunction.SIGMOID:
+ scores = sigmoid(outputs)
+ elif function_to_apply == ClassificationFunction.SOFTMAX:
+ scores = softmax(outputs)
+ elif function_to_apply == ClassificationFunction.NONE:
+ scores = outputs
+ else:
+ raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}")
+
+ dict_scores = [
+ {"label": self.model.config.id2label[i], "score": score.item()} for i, score in enumerate(scores)
+ ]
+ dict_scores.sort(key=lambda x: x["score"], reverse=True)
+ if top_k is not None:
+ dict_scores = dict_scores[:top_k]
+
+ return dict_scores
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_feature_extraction.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_feature_extraction.py
new file mode 100644
index 0000000000000000000000000000000000000000..d049957a4138ac44a3a097832a4e754a3fddd0d7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_feature_extraction.py
@@ -0,0 +1,115 @@
+from typing import Any, Union
+
+from ..utils import add_end_docstrings, is_vision_available
+from .base import GenericTensor, Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_image_processor=True),
+ """
+ image_processor_kwargs (`dict`, *optional*):
+ Additional dictionary of keyword arguments passed along to the image processor e.g.
+ {"size": {"height": 100, "width": 100}}
+ pool (`bool`, *optional*, defaults to `False`):
+ Whether or not to return the pooled output. If `False`, the model will return the raw hidden states.
+ """,
+)
+class ImageFeatureExtractionPipeline(Pipeline):
+ """
+ Image feature extraction pipeline uses no model head. This pipeline extracts the hidden states from the base
+ transformer, which can be used as features in downstream tasks.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> extractor = pipeline(model="google/vit-base-patch16-224", task="image-feature-extraction")
+ >>> result = extractor("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", return_tensors=True)
+ >>> result.shape # This is a tensor of shape [1, sequence_length, hidden_dimension] representing the input image.
+ torch.Size([1, 197, 768])
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This image feature extraction pipeline can currently be loaded from [`pipeline`] using the task identifier:
+ `"image-feature-extraction"`.
+
+ All vision models may be used for this pipeline. See a list of all models, including community-contributed models on
+ [huggingface.co/models](https://huggingface.co/models).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def _sanitize_parameters(self, image_processor_kwargs=None, return_tensors=None, pool=None, **kwargs):
+ preprocess_params = {} if image_processor_kwargs is None else image_processor_kwargs
+
+ postprocess_params = {}
+ if pool is not None:
+ postprocess_params["pool"] = pool
+ if return_tensors is not None:
+ postprocess_params["return_tensors"] = return_tensors
+
+ if "timeout" in kwargs:
+ preprocess_params["timeout"] = kwargs["timeout"]
+
+ return preprocess_params, {}, postprocess_params
+
+ def preprocess(self, image, timeout=None, **image_processor_kwargs) -> dict[str, GenericTensor]:
+ image = load_image(image, timeout=timeout)
+ model_inputs = self.image_processor(image, return_tensors="pt", **image_processor_kwargs)
+ model_inputs = model_inputs.to(self.dtype)
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ return model_outputs
+
+ def postprocess(self, model_outputs, pool=None, return_tensors=False):
+ pool = pool if pool is not None else False
+
+ if pool:
+ if "pooler_output" not in model_outputs:
+ raise ValueError(
+ "No pooled output was returned. Make sure the model has a `pooler` layer when using the `pool` option."
+ )
+ outputs = model_outputs["pooler_output"]
+ else:
+ # [0] is the first available tensor, logits or last_hidden_state.
+ outputs = model_outputs[0]
+
+ if return_tensors:
+ return outputs
+ return outputs.tolist()
+
+ def __call__(self, *args: Union[str, "Image.Image", list["Image.Image"], list[str]], **kwargs: Any) -> list[Any]:
+ """
+ Extract the features of the input(s).
+
+ Args:
+ images (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images, which must then be passed as a string.
+ Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
+ images.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is used and
+ the call may block forever.
+ Return:
+ A nested list of `float`: The features computed by the model.
+ """
+ return super().__call__(*args, **kwargs)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_segmentation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_segmentation.py
new file mode 100644
index 0000000000000000000000000000000000000000..49854beb5a40b1c3017febba20b72678e81b9374
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_segmentation.py
@@ -0,0 +1,223 @@
+from typing import Any, Union, overload
+
+import numpy as np
+
+from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import (
+ MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES,
+ MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES,
+ MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES,
+ MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES,
+ )
+
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class ImageSegmentationPipeline(Pipeline):
+ """
+ Image segmentation pipeline using any `AutoModelForXXXSegmentation`. This pipeline predicts masks of objects and
+ their classes.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> segmenter = pipeline(model="facebook/detr-resnet-50-panoptic")
+ >>> segments = segmenter("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
+ >>> len(segments)
+ 2
+
+ >>> segments[0]["label"]
+ 'bird'
+
+ >>> segments[1]["label"]
+ 'bird'
+
+ >>> type(segments[0]["mask"]) # This is a black and white mask showing where is the bird on the original image.
+
+
+ >>> segments[0]["mask"].size
+ (768, 512)
+ ```
+
+
+ This image segmentation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"image-segmentation"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=image-segmentation).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = None # Oneformer uses it but no-one else does
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ requires_backends(self, "vision")
+ mapping = MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES.copy()
+ mapping.update(MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES)
+ mapping.update(MODEL_FOR_INSTANCE_SEGMENTATION_MAPPING_NAMES)
+ mapping.update(MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES)
+ self.check_model_type(mapping)
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_kwargs = {}
+ postprocess_kwargs = {}
+ if "subtask" in kwargs:
+ postprocess_kwargs["subtask"] = kwargs["subtask"]
+ preprocess_kwargs["subtask"] = kwargs["subtask"]
+ if "threshold" in kwargs:
+ postprocess_kwargs["threshold"] = kwargs["threshold"]
+ if "mask_threshold" in kwargs:
+ postprocess_kwargs["mask_threshold"] = kwargs["mask_threshold"]
+ if "overlap_mask_area_threshold" in kwargs:
+ postprocess_kwargs["overlap_mask_area_threshold"] = kwargs["overlap_mask_area_threshold"]
+ if "timeout" in kwargs:
+ preprocess_kwargs["timeout"] = kwargs["timeout"]
+
+ return preprocess_kwargs, {}, postprocess_kwargs
+
+ @overload
+ def __call__(self, inputs: Union[str, "Image.Image"], **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, inputs: list[str] | list["Image.Image"], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self, inputs: Union[str, "Image.Image", list[str], list["Image.Image"]], **kwargs: Any
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Perform segmentation (detect masks & classes) in the image(s) passed as inputs.
+
+ Args:
+ inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing an HTTP(S) link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the
+ same format: all as HTTP(S) links, all as local paths, or all as PIL images.
+ subtask (`str`, *optional*):
+ Segmentation task to be performed, choose [`semantic`, `instance` and `panoptic`] depending on model
+ capabilities. If not set, the pipeline will attempt tp resolve in the following order:
+ `panoptic`, `instance`, `semantic`.
+ threshold (`float`, *optional*, defaults to 0.9):
+ Probability threshold to filter out predicted masks.
+ mask_threshold (`float`, *optional*, defaults to 0.5):
+ Threshold to use when turning the predicted masks into binary values.
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.5):
+ Mask overlap threshold to eliminate small, disconnected segments.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ If the input is a single image, will return a list of dictionaries, if the input is a list of several images,
+ will return a list of list of dictionaries corresponding to each image.
+
+ The dictionaries contain the mask, label and score (where applicable) of each detected object and contains
+ the following keys:
+
+ - **label** (`str`) -- The class label identified by the model.
+ - **mask** (`PIL.Image`) -- A binary mask of the detected object as a Pil Image of shape (width, height) of
+ the original image. Returns a mask filled with zeros if no object is found.
+ - **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of the
+ "object" described by the label and the mask.
+ """
+ # After deprecation of this is completed, remove the default `None` value for `images`
+ if "images" in kwargs:
+ inputs = kwargs.pop("images")
+ if inputs is None:
+ raise ValueError("Cannot call the image-classification pipeline without an inputs argument!")
+ return super().__call__(inputs, **kwargs)
+
+ def preprocess(self, image, subtask=None, timeout=None):
+ image = load_image(image, timeout=timeout)
+ target_size = [(image.height, image.width)]
+ if self.model.config.__class__.__name__ == "OneFormerConfig":
+ if subtask is None:
+ kwargs = {}
+ else:
+ kwargs = {"task_inputs": [subtask]}
+ inputs = self.image_processor(images=[image], return_tensors="pt", **kwargs)
+ inputs = inputs.to(self.dtype)
+ inputs["task_inputs"] = self.tokenizer(
+ inputs["task_inputs"],
+ padding="max_length",
+ max_length=self.model.config.task_seq_len,
+ return_tensors="pt",
+ )["input_ids"]
+ else:
+ inputs = self.image_processor(images=[image], return_tensors="pt")
+ inputs = inputs.to(self.dtype)
+ inputs["target_size"] = target_size
+ return inputs
+
+ def _forward(self, model_inputs):
+ target_size = model_inputs.pop("target_size")
+ model_outputs = self.model(**model_inputs)
+ model_outputs["target_size"] = target_size
+ return model_outputs
+
+ def postprocess(
+ self, model_outputs, subtask=None, threshold=0.9, mask_threshold=0.5, overlap_mask_area_threshold=0.5
+ ):
+ fn = None
+ if subtask in {"panoptic", None} and hasattr(self.image_processor, "post_process_panoptic_segmentation"):
+ fn = self.image_processor.post_process_panoptic_segmentation
+ elif subtask in {"instance", None} and hasattr(self.image_processor, "post_process_instance_segmentation"):
+ fn = self.image_processor.post_process_instance_segmentation
+
+ if fn is not None:
+ outputs = fn(
+ model_outputs,
+ threshold=threshold,
+ mask_threshold=mask_threshold,
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
+ target_sizes=model_outputs["target_size"],
+ )[0]
+
+ annotation = []
+ segmentation = outputs["segmentation"]
+
+ for segment in outputs["segments_info"]:
+ mask = (segmentation == segment["id"]) * 255
+ mask = Image.fromarray(mask.numpy().astype(np.uint8), mode="L")
+ label = self.model.config.id2label[segment["label_id"]]
+ score = segment["score"]
+ annotation.append({"score": score, "label": label, "mask": mask})
+
+ elif subtask in {"semantic", None} and hasattr(self.image_processor, "post_process_semantic_segmentation"):
+ outputs = self.image_processor.post_process_semantic_segmentation(
+ model_outputs, target_sizes=model_outputs["target_size"]
+ )[0]
+
+ annotation = []
+ segmentation = outputs.numpy()
+ labels = np.unique(segmentation)
+
+ for label in labels:
+ mask = (segmentation == label) * 255
+ mask = Image.fromarray(mask.astype(np.uint8), mode="L")
+ label = self.model.config.id2label[label]
+ annotation.append({"score": None, "label": label, "mask": mask})
+ else:
+ raise ValueError(f"Subtask {subtask} is not supported for model {type(self.model)}")
+ return annotation
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_text_to_text.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_text_to_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d28b91ab2ab9a8db3110f3aff05ded52454ec7b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/image_text_to_text.py
@@ -0,0 +1,480 @@
+# 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.
+
+import enum
+from typing import Any, Union, overload
+
+from ..generation import GenerationConfig
+from ..processing_utils import ProcessingKwargs, Unpack
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+from ..utils.chat_template_utils import Chat
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_images, valid_images
+
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES
+ from .pt_utils import KeyDataset
+
+logger = logging.get_logger(__name__)
+
+IMAGE_TOKEN = ""
+
+
+class ReturnType(enum.Enum):
+ TENSORS = 0
+ NEW_TEXT = 1
+ FULL_TEXT = 2
+
+
+@add_end_docstrings(build_pipeline_init_args(has_processor=True))
+class ImageTextToTextPipeline(Pipeline):
+ """
+ Image-text-to-text pipeline using an `AutoModelForImageTextToText`. This pipeline generates text given an image and text.
+ When the underlying model is a conversational model, it can also accept one or more chats,
+ in which case the pipeline will operate in chat mode and will continue the chat(s) by adding its response(s).
+ Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> pipe = pipeline(task="image-text-to-text", model="Salesforce/blip-image-captioning-base")
+ >>> pipe("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", text="A photo of")
+ [{'generated_text': 'a photo of two birds'}]
+ ```
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf")
+ >>> messages = [
+ >>> {
+ >>> "role": "user",
+ >>> "content": [
+ >>> {
+ >>> "type": "image",
+ >>> "url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg",
+ >>> },
+ >>> {"type": "text", "text": "Describe this image."},
+ >>> ],
+ >>> },
+ >>> {
+ >>> "role": "assistant",
+ >>> "content": [
+ >>> {"type": "text", "text": "There is a dog and"},
+ >>> ],
+ >>> },
+ >>> ]
+ >>> pipe(text=messages, max_new_tokens=20, return_full_text=False)
+ [{'input_text': [{'role': 'user',
+ 'content': [{'type': 'image',
+ 'url': 'https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen-VL/assets/demo.jpeg'},
+ {'type': 'text', 'text': 'Describe this image.'}]},
+ {'role': 'assistant',
+ 'content': [{'type': 'text', 'text': 'There is a dog and'}]}],
+ 'generated_text': ' a person in the image. The dog is sitting on the sand, and the person is sitting on'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This image-text to text pipeline can currently be loaded from pipeline() using the following task identifier:
+ "image-text-to-text".
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?pipeline_tag=image-text-to-text).
+ """
+
+ _load_processor = True
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ _pipeline_calls_generate = True
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ )
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ requires_backends(self, "vision")
+ self.check_model_type(MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES)
+
+ def _sanitize_parameters(
+ self,
+ max_new_tokens=None,
+ generate_kwargs=None,
+ timeout=None,
+ return_full_text=None,
+ return_tensors=None,
+ return_type=None,
+ clean_up_tokenization_spaces=None,
+ stop_sequence=None,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ processor_kwargs=None,
+ **kwargs: Unpack[ProcessingKwargs],
+ ):
+ forward_kwargs = {}
+ preprocess_params = {}
+ postprocess_params = {}
+
+ # Preprocess params
+ preprocess_params.update(kwargs)
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+ if continue_final_message is not None:
+ preprocess_params["continue_final_message"] = continue_final_message
+ if processor_kwargs is not None:
+ preprocess_params["processor_kwargs"] = processor_kwargs
+
+ # Forward kwargs
+ if generate_kwargs is not None:
+ forward_kwargs["generate_kwargs"] = generate_kwargs
+ if stop_sequence is not None:
+ stop_sequence_ids = self.processor.tokenizer.encode(stop_sequence, add_special_tokens=False)
+ if len(stop_sequence_ids) > 1:
+ logger.warning_once(
+ "Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
+ " the stop sequence will be used as the stop sequence string in the interim."
+ )
+ generate_kwargs["eos_token_id"] = stop_sequence_ids[0]
+ if generate_kwargs is not None:
+ forward_kwargs["generate_kwargs"] = generate_kwargs
+ if max_new_tokens is not None:
+ if "generate_kwargs" not in forward_kwargs:
+ forward_kwargs["generate_kwargs"] = {}
+ if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
+ raise ValueError(
+ "'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,"
+ " please use only one"
+ )
+ forward_kwargs["generate_kwargs"]["max_new_tokens"] = max_new_tokens
+
+ # Postprocess params
+ if return_full_text is not None and return_type is None:
+ if return_tensors is not None:
+ raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`")
+ return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
+ if return_tensors is not None and return_type is None:
+ return_type = ReturnType.TENSORS
+ if return_type is not None:
+ postprocess_params["return_type"] = return_type
+ if continue_final_message is not None:
+ postprocess_params["continue_final_message"] = continue_final_message
+ if clean_up_tokenization_spaces is not None:
+ postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces
+ if skip_special_tokens is not None:
+ postprocess_params["skip_special_tokens"] = skip_special_tokens
+
+ return preprocess_params, forward_kwargs, postprocess_params
+
+ @overload
+ def __call__(
+ self,
+ image: Union[str, "Image.Image"] | None = None,
+ text: str | None = None,
+ **kwargs: Any,
+ ) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(
+ self,
+ image: list[str] | list["Image.Image"] | None = None,
+ text: list[str] | None = None,
+ **kwargs: Any,
+ ) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self,
+ images: Union[
+ str, list[str], list[list[str]], "Image.Image", list["Image.Image"], list[list["Image.Image"]], list[dict]
+ ]
+ | None = None,
+ text: str | list[str] | list[dict] | None = None,
+ **kwargs,
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Generate a text given text and the image(s) passed as inputs.
+
+ Args:
+ images (`str`, `list[str]`, `PIL.Image, `list[PIL.Image]`, `list[dict[str, Union[str, PIL.Image]]]`):
+ The pipeline handles three types of images:
+
+ - A string containing a HTTP(s) link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images. Finally, this pipeline also supports
+ the chat format (see `text`) containing images and text in this argument.
+ text (str, list[str], `list[dict[str, Union[str, PIL.Image]]]`):
+ The text to be used for generation. If a list of strings is passed, the length of the list should be
+ the same as the number of images. Text can also follow the chat format: a list of dictionaries where
+ each dictionary represents a message in a conversation. Each dictionary should have two keys: 'role'
+ and 'content'. 'role' should be one of 'user', 'system' or 'assistant'. 'content' should be a list of
+ dictionary containing the text of the message and the type of the message. The type of the message
+ can be either 'text' or 'image'. If the type is 'image', no text is needed.
+ return_tensors (`bool`, *optional*, defaults to `False`):
+ Returns the tensors of predictions (as token indices) in the outputs. If set to
+ `True`, the decoded text is not returned.
+ return_text (`bool`, *optional*):
+ Returns the decoded texts in the outputs.
+ return_full_text (`bool`, *optional*, defaults to `True`):
+ If set to `False` only added text is returned, otherwise the full text is returned. Cannot be
+ specified at the same time as `return_text`.
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
+ Whether or not to clean up the potential extra spaces in the text output.
+ continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the
+ last message in the input chat rather than starting a new one, allowing you to "prefill" its response.
+ By default this is `True` when the final message in the input chat has the `assistant` role and
+ `False` otherwise, but you can manually override that behaviour by setting this flag.
+
+ Return:
+ A list or a list of list of `dict`: Each result comes as a dictionary with the following key (cannot
+ return a combination of both `generated_text` and `generated_token_ids`):
+
+ - **generated_text** (`str`, present when `return_text=True`) -- The generated text.
+ - **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token
+ ids of the generated text.
+ - **input_text** (`str`) -- The input text.
+ """
+ if images is None and text is None:
+ raise ValueError("You must at least provide either text or images.")
+
+ def _is_chat(arg):
+ return isinstance(arg, (list, tuple, KeyDataset)) and isinstance(arg[0], (list, tuple, dict))
+
+ if _is_chat(text):
+ if images is not None:
+ raise ValueError(
+ "Invalid input: you passed `chat` and `images` as separate input arguments. "
+ "Images must be placed inside the chat message's `content`. For example, "
+ "'content': ["
+ " {'type': 'image', 'url': 'image_url'}, {'type': 'text', 'text': 'Describe the image.'}}"
+ "]"
+ )
+ # We have one or more prompts in list-of-dicts format, so this is chat mode
+ if isinstance(text[0], dict):
+ return super().__call__(Chat(text), **kwargs)
+ else:
+ chats = [Chat(chat) for chat in text] # 🐈 🐈 🐈
+ return super().__call__(chats, **kwargs)
+
+ # Same as above, but the `images` argument contains the chat. This can happen e.g. is the user only passes a
+ # chat as a positional argument.
+ elif text is None and _is_chat(images):
+ # We have one or more prompts in list-of-dicts format, so this is chat mode
+ if isinstance(images[0], dict):
+ return super().__call__(Chat(images), **kwargs)
+ else:
+ chats = [Chat(image) for image in images] # 🐈 🐈 🐈
+ return super().__call__(chats, **kwargs)
+
+ elif images is not None and text is None and not valid_images(images):
+ """
+ Supports the following format
+ - {"image": image, "text": text}
+ - [{"image": image, "text": text}]
+ - Generator and datasets
+ This is a common pattern in other multimodal pipelines, so we support it here as well.
+ """
+ return super().__call__(images, **kwargs)
+
+ # encourage the user to use the chat format if supported
+ if getattr(self.processor, "chat_template", None) is not None:
+ logger.warning_once(
+ "The input data was not formatted as a chat with dicts containing 'role' and 'content' keys, even "
+ "though this model supports chat. Consider using the chat format for better results. For more "
+ "information, see https://huggingface.co/docs/transformers/en/chat_templating"
+ )
+
+ # support text only generation
+ if images is None:
+ return super().__call__(text, **kwargs)
+ if text is None:
+ raise ValueError("You must provide text for this pipeline.")
+
+ return super().__call__({"images": images, "text": text}, **kwargs)
+
+ def preprocess(self, inputs=None, timeout=None, continue_final_message=None, **processing_kwargs):
+ if isinstance(inputs, Chat):
+ # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default
+ # because very few models support multiple separate, consecutive assistant messages
+ if continue_final_message is None:
+ continue_final_message = inputs.messages[-1]["role"] == "assistant"
+
+ # Processor kwargs are passed separately from jinja kwargs to chat template
+ # but it was added only in https://github.com/huggingface/transformers/pull/44881
+ processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or {}
+
+ chat_template_kwargs = {
+ "continue_final_message": continue_final_message,
+ "return_tensors": "pt",
+ "tokenize": True,
+ "return_dict": True,
+ "add_generation_prompt": not continue_final_message,
+ "processor_kwargs": processor_kwargs,
+ **processing_kwargs,
+ }
+
+ # Handle Mistral tokenizer which does not accept processing kwargs
+ if self.processor.tokenizer.__class__.__name__ == "MistralCommonBackend":
+ chat_template_kwargs = {
+ k: v for k, v in chat_template_kwargs.items() if k in ["padding", "truncation", "max_length"]
+ }
+
+ model_inputs = self.processor.apply_chat_template(
+ inputs.messages,
+ **chat_template_kwargs,
+ ).to(dtype=self.dtype)
+ model_inputs["text"] = inputs
+ return model_inputs
+
+ # In case we only have text inputs
+ if isinstance(inputs, (list, tuple, str)):
+ images = None
+ text = inputs
+ inputs_text = inputs
+ else:
+ images = load_images(inputs["images"], timeout=timeout)
+ text = inputs["text"]
+ inputs_text = inputs["text"]
+
+ # if batched text inputs, we set padding to True unless specified otherwise
+ processor_kwargs = processing_kwargs.pop("processor_kwargs", None) or processing_kwargs
+ if isinstance(text, (list, tuple)) and len(text) > 1:
+ processor_kwargs.setdefault("padding", True)
+ model_inputs = self.processor(images=images, text=text, return_tensors="pt", **processor_kwargs).to(
+ dtype=self.dtype
+ )
+
+ model_inputs["text"] = inputs_text
+
+ return model_inputs
+
+ def _forward(self, model_inputs, generate_kwargs=None):
+ generate_kwargs = {} if generate_kwargs is None else generate_kwargs
+ prompt_text = model_inputs.pop("text")
+ input_ids = (
+ model_inputs["input_ids"] if "input_ids" in model_inputs else model_inputs["decoder_input_ids"]
+ ) # for decoder-only models
+
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ generated_sequence = self.model.generate(**model_inputs, **generate_kwargs)
+
+ return {"generated_sequence": generated_sequence, "prompt_text": prompt_text, "input_ids": input_ids}
+
+ def postprocess(
+ self,
+ model_outputs,
+ return_type=ReturnType.FULL_TEXT,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ **postprocess_kwargs,
+ ):
+ input_texts = model_outputs["prompt_text"]
+ input_texts = [input_texts] if isinstance(input_texts, (str, Chat)) else input_texts
+ generated_sequence = model_outputs["generated_sequence"]
+ input_ids = model_outputs["input_ids"]
+ if return_type == ReturnType.TENSORS:
+ return [
+ {"input_text": input_texts[i], "generated_token_ids": generated_sequence[i]}
+ for i in range(len(input_texts))
+ ]
+
+ # Decode inputs and outputs the same way to remove input text from generated text if present
+ skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True
+ if getattr(self.tokenizer, "response_schema", False):
+ skip_special_tokens = False
+ generated_texts = self.processor.post_process_image_text_to_text(
+ generated_sequence, skip_special_tokens=skip_special_tokens, **postprocess_kwargs
+ )
+ decoded_inputs = self.processor.post_process_image_text_to_text(
+ input_ids, skip_special_tokens=skip_special_tokens, **postprocess_kwargs
+ )
+
+ # Force consistent behavior for including the input text in the output
+ if return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
+ # Remove the input text from the generated text if the generated text starts with the input text
+ # (accounting for the possibility of a space between the input and generated text)
+ new_generated_texts = []
+ for text_generated, decoded_input in zip(generated_texts, decoded_inputs):
+ # There can be added characters before the input text, so we need to find the beginning of the input text in the generated text
+ index_input_text = text_generated.find(decoded_input)
+ # Limit the search to 2 residual characters, like spaces or new lines, to avoid removing a large part of the answer
+ if 0 <= index_input_text <= 2:
+ # If the input text is found, we remove it
+ new_generated_texts.append(text_generated[index_input_text + len(decoded_input) :])
+ else:
+ new_generated_texts.append(text_generated)
+ generated_texts = new_generated_texts
+ if return_type == ReturnType.FULL_TEXT:
+ full_texts = []
+ for prompt_text, generated_text in zip(input_texts, generated_texts):
+ if isinstance(prompt_text, str):
+ generated_text = prompt_text + generated_text
+ elif isinstance(prompt_text, Chat):
+ if continue_final_message is None:
+ # If the user passes a chat ending in an assistant message, we treat it as a prefill by
+ # default because very few models support multiple separate, consecutive assistant messages
+ continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
+ if continue_final_message:
+ # With assistant prefill, concat onto the end of the last message
+ new_text = dict(prompt_text.messages[-1]["content"][-1].items())
+ new_text["text"] += generated_text
+ generated_text = list(prompt_text.messages)[:-1] + [
+ {
+ "role": prompt_text.messages[-1]["role"],
+ "content": prompt_text.messages[-1]["content"][:-1] + [new_text],
+ }
+ ]
+ else:
+ # When we're not starting from a prefill, the output is a new assistant message
+ if getattr(self.tokenizer, "response_schema", False):
+ assistant_message = self.tokenizer.parse_response(generated_text)
+ else:
+ assistant_message = {"role": "assistant", "content": generated_text}
+ generated_text = list(prompt_text.messages) + [assistant_message]
+ full_texts.append(generated_text)
+ generated_texts = full_texts
+
+ records = [
+ {
+ "input_text": input_text.messages if isinstance(input_text, Chat) else input_text,
+ "generated_text": generated_text,
+ }
+ for input_text, generated_text in zip(input_texts, generated_texts)
+ ]
+
+ return records
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/keypoint_matching.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/keypoint_matching.py
new file mode 100644
index 0000000000000000000000000000000000000000..d75656a7db3b301476faf02401c0a5df5d2c5691
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/keypoint_matching.py
@@ -0,0 +1,176 @@
+# Copyright 2025 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 collections.abc import Sequence
+from typing import Any, TypeAlias, TypedDict, Union
+
+from typing_extensions import overload
+
+from ..image_utils import is_pil_image
+from ..utils import is_vision_available, requires_backends
+from .base import Pipeline
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+
+ImagePair: TypeAlias = Sequence[Union["Image.Image", str]]
+
+
+class Keypoint(TypedDict):
+ x: float
+ y: float
+
+
+class Match(TypedDict):
+ keypoint_image_0: Keypoint
+ keypoint_image_1: Keypoint
+ score: float
+
+
+def validate_image_pairs(images: Any) -> Sequence[Sequence[ImagePair]]:
+ error_message = (
+ "Input images must be a one of the following :",
+ " - A pair of images.",
+ " - A list of pairs of images.",
+ )
+
+ def _is_valid_image(image):
+ """images is a PIL Image or a string."""
+ return is_pil_image(image) or isinstance(image, str)
+
+ if isinstance(images, Sequence):
+ if len(images) == 2 and all((_is_valid_image(image)) for image in images):
+ return [images]
+ if all(
+ isinstance(image_pair, Sequence)
+ and len(image_pair) == 2
+ and all(_is_valid_image(image) for image in image_pair)
+ for image_pair in images
+ ):
+ return images
+ raise ValueError(error_message)
+
+
+class KeypointMatchingPipeline(Pipeline):
+ """
+ Keypoint matching pipeline using any `AutoModelForKeypointMatching`. This pipeline matches keypoints between two images.
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ requires_backends(self, "vision")
+
+ def _sanitize_parameters(self, threshold=None, timeout=None):
+ preprocess_params = {}
+ if timeout is not None:
+ preprocess_params["timeout"] = timeout
+ postprocess_params = {}
+ if threshold is not None:
+ postprocess_params["threshold"] = threshold
+ return preprocess_params, {}, postprocess_params
+
+ @overload
+ def __call__(self, inputs: ImagePair, threshold: float = 0.0, **kwargs: Any) -> list[Match]: ...
+
+ @overload
+ def __call__(self, inputs: list[ImagePair], threshold: float = 0.0, **kwargs: Any) -> list[list[Match]]: ...
+
+ def __call__(
+ self,
+ inputs: list[ImagePair] | ImagePair,
+ threshold: float = 0.0,
+ **kwargs: Any,
+ ) -> list[Match] | list[list[Match]]:
+ """
+ Find matches between keypoints in two images.
+
+ Args:
+ inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single pair of images or a batch of image pairs, which must then be passed as a string.
+ Images in a batch must all be in the same format: all as http links, all as local paths, or all as PIL
+ images.
+
+ threshold (`float`, *optional*, defaults to 0.0):
+ The threshold to use for keypoint matching. Keypoints matched with a lower matching score will be filtered out.
+ A value of 0 means that all matched keypoints will be returned.
+
+ kwargs:
+ `timeout (`float`, *optional*, defaults to None)`
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ Union[list[Match], list[list[Match]]]:
+ A list of matches or a list if a single image pair is provided, or of lists of matches if a batch
+ of image pairs is provided. Each match is a dictionary containing the following keys:
+
+ - **keypoint_image_0** (`Keypoint`): The keypoint in the first image (x, y coordinates).
+ - **keypoint_image_1** (`Keypoint`): The keypoint in the second image (x, y coordinates).
+ - **score** (`float`): The matching score between the two keypoints.
+ """
+ if inputs is None:
+ raise ValueError("Cannot call the keypoint-matching pipeline without an inputs argument!")
+ formatted_inputs = validate_image_pairs(inputs)
+ outputs = super().__call__(formatted_inputs, threshold=threshold, **kwargs)
+ if len(formatted_inputs) == 1:
+ return outputs[0]
+ return outputs
+
+ def preprocess(self, images, timeout=None):
+ images = [load_image(image, timeout=timeout) for image in images]
+ model_inputs = self.image_processor(images=images, return_tensors="pt")
+ model_inputs = model_inputs.to(self.dtype)
+ target_sizes = [image.size for image in images]
+ preprocess_outputs = {"model_inputs": model_inputs, "target_sizes": target_sizes}
+ return preprocess_outputs
+
+ def _forward(self, preprocess_outputs):
+ model_inputs = preprocess_outputs["model_inputs"]
+ model_outputs = self.model(**model_inputs)
+ forward_outputs = {"model_outputs": model_outputs, "target_sizes": [preprocess_outputs["target_sizes"]]}
+ return forward_outputs
+
+ def postprocess(self, forward_outputs, threshold=0.0) -> list[Match]:
+ model_outputs = forward_outputs["model_outputs"]
+ target_sizes = forward_outputs["target_sizes"]
+ postprocess_outputs = self.image_processor.post_process_keypoint_matching(
+ model_outputs, target_sizes=target_sizes, threshold=threshold
+ )
+ postprocess_outputs = postprocess_outputs[0]
+ pair_result = []
+ for kp_0, kp_1, score in zip(
+ postprocess_outputs["keypoints0"],
+ postprocess_outputs["keypoints1"],
+ postprocess_outputs["matching_scores"],
+ ):
+ kp_0 = Keypoint(x=kp_0[0].item(), y=kp_0[1].item())
+ kp_1 = Keypoint(x=kp_1[0].item(), y=kp_1[1].item())
+ pair_result.append(Match(keypoint_image_0=kp_0, keypoint_image_1=kp_1, score=score.item()))
+ pair_result = sorted(pair_result, key=lambda x: x["score"], reverse=True)
+ return pair_result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/mask_generation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/mask_generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..920ce9d0a39cecc451b329c5a241cccaa4f5b5e7
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/mask_generation.py
@@ -0,0 +1,335 @@
+from collections import defaultdict
+from typing import TYPE_CHECKING, Any, Union, overload
+
+from ..image_utils import load_image
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ logging,
+ requires_backends,
+)
+from .base import ChunkPipeline, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING_NAMES
+
+if TYPE_CHECKING:
+ from PIL import Image
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_image_processor=True),
+ r"""
+ points_per_batch (*optional*, int, default to 64):
+ Sets the number of points run simultaneously by the model. Higher numbers may be faster but use more GPU
+ memory.
+ output_bboxes_mask (`bool`, *optional*, default to `False`):
+ Whether or not to output the bounding box predictions.
+ output_rle_masks (`bool`, *optional*, default to `False`):
+ Whether or not to output the masks in `RLE` format""",
+)
+class MaskGenerationPipeline(ChunkPipeline):
+ """
+ Automatic mask generation for images using `SamForMaskGeneration`. This pipeline predicts binary masks for an
+ image, given an image. It is a `ChunkPipeline` because you can separate the points in a mini-batch in order to
+ avoid OOM issues. Use the `points_per_batch` argument to control the number of points that will be processed at the
+ same time. Default is `64`.
+
+ The pipeline works in 3 steps:
+ 1. `preprocess`: A grid of 1024 points evenly separated is generated along with bounding boxes and point
+ labels.
+ For more details on how the points and bounding boxes are created, check the `_generate_crop_boxes`
+ function. The image is also preprocessed using the `image_processor`. This function `yields` a minibatch of
+ `points_per_batch`.
+
+ 2. `forward`: feeds the outputs of `preprocess` to the model. The image embedding is computed only once.
+ Calls both `self.model.get_image_embeddings` and makes sure that the gradients are not computed, and the
+ tensors and models are on the same device.
+
+ 3. `postprocess`: The most important part of the automatic mask generation happens here. Three steps
+ are induced:
+ - image_processor.postprocess_masks (run on each minibatch loop): takes in the raw output masks,
+ resizes them according
+ to the image size, and transforms there to binary masks.
+ - image_processor.filter_masks (on each minibatch loop): uses both `pred_iou_thresh` and
+ `stability_scores`. Also
+ applies a variety of filters based on non maximum suppression to remove bad masks.
+ - image_processor.postprocess_masks_for_amg applies the NSM on the mask to only keep relevant ones.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> generator = pipeline(model="facebook/sam-vit-base", task="mask-generation")
+ >>> outputs = generator(
+ ... "http://images.cocodataset.org/val2017/000000039769.jpg",
+ ... )
+
+ >>> outputs = generator(
+ ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png", points_per_batch=128
+ ... )
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This segmentation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"mask-generation"`.
+
+ See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=mask-generation).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ requires_backends(self, "vision")
+ requires_backends(self, "torch")
+
+ self.check_model_type(MODEL_FOR_MASK_GENERATION_MAPPING_NAMES)
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_kwargs = {}
+ postprocess_kwargs = {}
+ forward_params = {}
+ # preprocess args
+ if "points_per_batch" in kwargs:
+ preprocess_kwargs["points_per_batch"] = kwargs["points_per_batch"]
+ if "points_per_crop" in kwargs:
+ preprocess_kwargs["points_per_crop"] = kwargs["points_per_crop"]
+ if "crops_n_layers" in kwargs:
+ preprocess_kwargs["crops_n_layers"] = kwargs["crops_n_layers"]
+ if "crop_overlap_ratio" in kwargs:
+ preprocess_kwargs["crop_overlap_ratio"] = kwargs["crop_overlap_ratio"]
+ if "crop_n_points_downscale_factor" in kwargs:
+ preprocess_kwargs["crop_n_points_downscale_factor"] = kwargs["crop_n_points_downscale_factor"]
+ if "timeout" in kwargs:
+ preprocess_kwargs["timeout"] = kwargs["timeout"]
+ # postprocess args
+ if "pred_iou_thresh" in kwargs:
+ forward_params["pred_iou_thresh"] = kwargs["pred_iou_thresh"]
+ if "stability_score_offset" in kwargs:
+ forward_params["stability_score_offset"] = kwargs["stability_score_offset"]
+ if "mask_threshold" in kwargs:
+ forward_params["mask_threshold"] = kwargs["mask_threshold"]
+ if "stability_score_thresh" in kwargs:
+ forward_params["stability_score_thresh"] = kwargs["stability_score_thresh"]
+ if "max_hole_area" in kwargs:
+ forward_params["max_hole_area"] = kwargs["max_hole_area"]
+ if "max_sprinkle_area" in kwargs:
+ forward_params["max_sprinkle_area"] = kwargs["max_sprinkle_area"]
+ if "crops_nms_thresh" in kwargs:
+ postprocess_kwargs["crops_nms_thresh"] = kwargs["crops_nms_thresh"]
+ if "output_rle_mask" in kwargs:
+ postprocess_kwargs["output_rle_mask"] = kwargs["output_rle_mask"]
+ if "output_bboxes_mask" in kwargs:
+ postprocess_kwargs["output_bboxes_mask"] = kwargs["output_bboxes_mask"]
+ return preprocess_kwargs, forward_params, postprocess_kwargs
+
+ @overload
+ def __call__(self, image: Union[str, "Image.Image"], *args: Any, **kwargs: Any) -> dict[str, Any]: ...
+
+ @overload
+ def __call__(self, image: list[str] | list["Image.Image"], *args: Any, **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ def __call__(
+ self, image: Union[str, "Image.Image", list[str], list["Image.Image"]], *args: Any, **kwargs: Any
+ ) -> dict[str, Any] | list[dict[str, Any]]:
+ """
+ Generates binary segmentation masks
+
+ Args:
+ image (`str`, `List[str]`, `PIL.Image` or `List[PIL.Image]`):
+ Image or list of images.
+ mask_threshold (`float`, *optional*, defaults to 0.0):
+ Threshold to use when turning the predicted masks into binary values.
+ pred_iou_thresh (`float`, *optional*, defaults to 0.88):
+ A filtering threshold in `[0,1]` applied on the model's predicted mask quality.
+ stability_score_thresh (`float`, *optional*, defaults to 0.95):
+ A filtering threshold in `[0,1]`, using the stability of the mask under changes to the cutoff used to
+ binarize the model's mask predictions.
+ stability_score_offset (`int`, *optional*, defaults to 1):
+ The amount to shift the cutoff when calculated the stability score.
+ crops_nms_thresh (`float`, *optional*, defaults to 0.7):
+ The box IoU cutoff used by non-maximal suppression to filter duplicate masks.
+ crops_n_layers (`int`, *optional*, defaults to 0):
+ If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of
+ layers to run, where each layer has 2**i_layer number of image crops.
+ crop_overlap_ratio (`float`, *optional*, defaults to `512 / 1500`):
+ Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of
+ the image length. Later layers with more crops scale down this overlap.
+ crop_n_points_downscale_factor (`int`, *optional*, defaults to `1`):
+ The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ `Dict`: A dictionary with the following keys:
+ - **mask** (`PIL.Image`) -- A binary mask of the detected object as a PIL Image of shape `(width,
+ height)` of the original image. Returns a mask filled with zeros if no object is found.
+ - **score** (*optional* `float`) -- Optionally, when the model is capable of estimating a confidence of
+ the "object" described by the label and the mask.
+
+ """
+ num_workers = kwargs.pop("num_workers", None)
+ batch_size = kwargs.pop("batch_size", None)
+ return super().__call__(image, *args, num_workers=num_workers, batch_size=batch_size, **kwargs)
+
+ def preprocess(
+ self,
+ image,
+ points_per_batch=64,
+ crops_n_layers: int = 0,
+ crop_overlap_ratio: float = 512 / 1500,
+ points_per_crop: int = 32,
+ crop_n_points_downscale_factor: int = 1,
+ timeout: float | None = None,
+ ):
+ image = load_image(image, timeout=timeout)
+ target_size = self.image_processor.size.get("longest_edge", self.image_processor.size.get("height"))
+ crop_boxes, grid_points, cropped_images, input_labels = self.image_processor.generate_crop_boxes(
+ image, target_size, crops_n_layers, crop_overlap_ratio, points_per_crop, crop_n_points_downscale_factor
+ )
+ model_inputs = self.image_processor(images=cropped_images, return_tensors="pt")
+ model_inputs = model_inputs.to(self.dtype)
+
+ with self.device_placement():
+ inference_context = self.get_inference_context()
+ with inference_context():
+ model_inputs = self._ensure_tensor_on_device(model_inputs, device=self.device)
+ embeddings = self.model.get_image_embeddings(model_inputs.pop("pixel_values"))
+
+ # Handle both SAM (single tensor) and SAM-HQ (tuple) outputs
+ if isinstance(embeddings, tuple):
+ image_embeddings, intermediate_embeddings = embeddings
+ model_inputs["intermediate_embeddings"] = intermediate_embeddings
+ else:
+ image_embeddings = embeddings
+ # TODO: Identifying the model by the type of its returned embeddings is brittle.
+ # Consider using a more robust method for distinguishing model types here.
+
+ model_inputs["image_embeddings"] = image_embeddings
+
+ n_points = grid_points.shape[1]
+ points_per_batch = points_per_batch if points_per_batch is not None else n_points
+
+ if points_per_batch <= 0:
+ raise ValueError(
+ "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. "
+ "To return all points at once, set points_per_batch to None"
+ )
+
+ for i in range(0, n_points, points_per_batch):
+ batched_points = grid_points[:, i : i + points_per_batch, :, :]
+ labels = input_labels[:, i : i + points_per_batch]
+ is_last = i == n_points - points_per_batch
+ yield {
+ "input_points": batched_points,
+ "input_labels": labels,
+ "input_boxes": crop_boxes,
+ "is_last": is_last,
+ **model_inputs,
+ }
+
+ def _forward(
+ self,
+ model_inputs,
+ pred_iou_thresh=0.88,
+ stability_score_thresh=0.95,
+ mask_threshold=0,
+ stability_score_offset=1,
+ max_hole_area=None,
+ max_sprinkle_area=None,
+ ):
+ input_boxes = model_inputs.pop("input_boxes")
+ is_last = model_inputs.pop("is_last")
+ original_sizes = model_inputs.pop("original_sizes").tolist()
+ reshaped_input_sizes = model_inputs.pop("reshaped_input_sizes", None)
+ reshaped_input_sizes = reshaped_input_sizes.tolist() if reshaped_input_sizes is not None else None
+
+ model_outputs = self.model(**model_inputs)
+
+ # post processing happens here in order to avoid CPU GPU copies of ALL the masks
+ low_resolution_masks = model_outputs["pred_masks"]
+ postprocess_kwargs = {}
+ if max_hole_area is not None:
+ postprocess_kwargs["max_hole_area"] = max_hole_area
+ if max_sprinkle_area is not None and max_sprinkle_area > 0:
+ postprocess_kwargs["max_sprinkle_area"] = max_sprinkle_area
+ if postprocess_kwargs:
+ low_resolution_masks = self.image_processor.post_process_masks(
+ low_resolution_masks,
+ original_sizes,
+ mask_threshold=mask_threshold,
+ reshaped_input_sizes=reshaped_input_sizes,
+ binarize=False,
+ **postprocess_kwargs,
+ )
+ masks = self.image_processor.post_process_masks(
+ low_resolution_masks,
+ original_sizes,
+ mask_threshold=mask_threshold,
+ reshaped_input_sizes=reshaped_input_sizes,
+ binarize=False,
+ )
+ iou_scores = model_outputs["iou_scores"]
+ masks, iou_scores, boxes = self.image_processor.filter_masks(
+ masks[0],
+ iou_scores[0],
+ original_sizes[0],
+ input_boxes[0],
+ pred_iou_thresh,
+ stability_score_thresh,
+ mask_threshold,
+ stability_score_offset,
+ )
+ return {
+ "masks": masks,
+ "is_last": is_last,
+ "boxes": boxes,
+ "iou_scores": iou_scores,
+ }
+
+ def postprocess(
+ self,
+ model_outputs,
+ output_rle_mask=False,
+ output_bboxes_mask=False,
+ crops_nms_thresh=0.7,
+ ):
+ all_scores = []
+ all_masks = []
+ all_boxes = []
+ for model_output in model_outputs:
+ all_scores.append(model_output.pop("iou_scores"))
+ all_masks.extend(model_output.pop("masks"))
+ all_boxes.append(model_output.pop("boxes"))
+
+ all_scores = torch.cat(all_scores)
+ all_boxes = torch.cat(all_boxes)
+ output_masks, iou_scores, rle_mask, bounding_boxes = self.image_processor.post_process_for_mask_generation(
+ all_masks, all_scores, all_boxes, crops_nms_thresh
+ )
+
+ extra = defaultdict(list)
+ for output in model_outputs:
+ for k, v in output.items():
+ extra[k].append(v)
+
+ optional = {}
+ if output_rle_mask:
+ optional["rle_mask"] = rle_mask
+
+ if output_bboxes_mask:
+ optional["bounding_boxes"] = bounding_boxes
+
+ return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/object_detection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/object_detection.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a4fba996d7d364283371c17e9cf6adbc43d0c23
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/object_detection.py
@@ -0,0 +1,197 @@
+from typing import TYPE_CHECKING, Any, Union, overload
+
+from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from ..image_utils import load_image
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import (
+ MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES,
+ MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
+ )
+
+if TYPE_CHECKING:
+ from PIL import Image
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class ObjectDetectionPipeline(Pipeline):
+ """
+ Object detection pipeline using any `AutoModelForObjectDetection`. This pipeline predicts bounding boxes of objects
+ and their classes.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> detector = pipeline(model="facebook/detr-resnet-50")
+ >>> detector("https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png")
+ [{'score': 0.997, 'label': 'bird', 'box': {'xmin': 69, 'ymin': 171, 'xmax': 396, 'ymax': 507}}, {'score': 0.999, 'label': 'bird', 'box': {'xmin': 398, 'ymin': 105, 'xmax': 767, 'ymax': 507}}]
+
+ >>> # x, y are expressed relative to the top left hand corner.
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"object-detection"`.
+
+ See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=object-detection).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = None
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ requires_backends(self, "vision")
+ mapping = MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES.copy()
+ mapping.update(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES)
+ self.check_model_type(mapping)
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_params = {}
+ if "timeout" in kwargs:
+ preprocess_params["timeout"] = kwargs["timeout"]
+ postprocess_kwargs = {}
+ if "threshold" in kwargs:
+ postprocess_kwargs["threshold"] = kwargs["threshold"]
+ return preprocess_params, {}, postprocess_kwargs
+
+ @overload
+ def __call__(self, image: Union[str, "Image.Image"], *args: Any, **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(
+ self, image: list[str] | list["Image.Image"], *args: Any, **kwargs: Any
+ ) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(self, *args, **kwargs) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
+
+ Args:
+ inputs (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing an HTTP(S) link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ The pipeline accepts either a single image or a batch of images. Images in a batch must all be in the
+ same format: all as HTTP(S) links, all as local paths, or all as PIL images.
+ threshold (`float`, *optional*, defaults to 0.5):
+ The probability necessary to make a prediction.
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ A list of dictionaries or a list of list of dictionaries containing the result. If the input is a single
+ image, will return a list of dictionaries, if the input is a list of several images, will return a list of
+ list of dictionaries corresponding to each image.
+
+ The dictionaries contain the following keys:
+
+ - **label** (`str`) -- The class label identified by the model.
+ - **score** (`float`) -- The score attributed by the model for that label.
+ - **box** (`list[dict[str, int]]`) -- The bounding box of detected object in image's original size.
+ """
+ # After deprecation of this is completed, remove the default `None` value for `images`
+ if "images" in kwargs and "inputs" not in kwargs:
+ kwargs["inputs"] = kwargs.pop("images")
+ return super().__call__(*args, **kwargs)
+
+ def preprocess(self, image, timeout=None):
+ image = load_image(image, timeout=timeout)
+ target_size = torch.IntTensor([[image.height, image.width]])
+ inputs = self.image_processor(images=[image], return_tensors="pt")
+ inputs = inputs.to(self.dtype)
+ if self.tokenizer is not None:
+ inputs = self.tokenizer(text=inputs["words"], boxes=inputs["boxes"], return_tensors="pt")
+ inputs["target_size"] = target_size
+ return inputs
+
+ def _forward(self, model_inputs):
+ target_size = model_inputs.pop("target_size")
+ outputs = self.model(**model_inputs)
+ model_outputs = outputs.__class__({"target_size": target_size, **outputs})
+ if self.tokenizer is not None:
+ model_outputs["bbox"] = model_inputs["bbox"]
+ return model_outputs
+
+ def postprocess(self, model_outputs, threshold=0.5):
+ target_size = model_outputs["target_size"]
+ if self.tokenizer is not None:
+ # This is a LayoutLMForTokenClassification variant.
+ # The OCR got the boxes and the model classified the words.
+ height, width = target_size[0].tolist()
+
+ def unnormalize(bbox):
+ return self._get_bounding_box(
+ torch.Tensor(
+ [
+ (width * bbox[0] / 1000),
+ (height * bbox[1] / 1000),
+ (width * bbox[2] / 1000),
+ (height * bbox[3] / 1000),
+ ]
+ )
+ )
+
+ scores, classes = model_outputs["logits"].squeeze(0).softmax(dim=-1).max(dim=-1)
+ labels = [self.model.config.id2label[prediction] for prediction in classes.tolist()]
+ boxes = [unnormalize(bbox) for bbox in model_outputs["bbox"].squeeze(0)]
+ keys = ["score", "label", "box"]
+ annotation = [dict(zip(keys, vals)) for vals in zip(scores.tolist(), labels, boxes) if vals[0] > threshold]
+ else:
+ # This is a regular ForObjectDetectionModel
+ raw_annotations = self.image_processor.post_process_object_detection(model_outputs, threshold, target_size)
+ raw_annotation = raw_annotations[0]
+ scores = raw_annotation["scores"]
+ labels = raw_annotation["labels"]
+ boxes = raw_annotation["boxes"]
+
+ raw_annotation["scores"] = scores.tolist()
+ raw_annotation["labels"] = [self.model.config.id2label[label.item()] for label in labels]
+ raw_annotation["boxes"] = [self._get_bounding_box(box) for box in boxes]
+
+ # {"scores": [...], ...} --> [{"score":x, ...}, ...]
+ keys = ["score", "label", "box"]
+ annotation = [
+ dict(zip(keys, vals))
+ for vals in zip(raw_annotation["scores"], raw_annotation["labels"], raw_annotation["boxes"])
+ ]
+
+ return annotation
+
+ def _get_bounding_box(self, box: "torch.Tensor") -> dict[str, int]:
+ """
+ Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... }
+
+ Args:
+ box (`torch.Tensor`): Tensor containing the coordinates in corners format.
+
+ Returns:
+ bbox (`dict[str, int]`): Dict containing the coordinates in corners format.
+ """
+ xmin, ymin, xmax, ymax = box.int().tolist()
+ bbox = {
+ "xmin": xmin,
+ "ymin": ymin,
+ "xmax": xmax,
+ "ymax": ymax,
+ }
+ return bbox
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/pt_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/pt_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3857805962a93f796e407ed88c89495b46fd0bd0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/pt_utils.py
@@ -0,0 +1,323 @@
+import numpy as np
+import torch
+from torch.utils.data import Dataset, IterableDataset
+
+from ..utils.generic import ModelOutput
+
+
+class PipelineDataset(Dataset):
+ def __init__(self, dataset, process, params):
+ self.dataset = dataset
+ self.process = process
+ self.params = params
+
+ def __len__(self):
+ return len(self.dataset)
+
+ def __getitem__(self, i):
+ item = self.dataset[i]
+ processed = self.process(item, **self.params)
+ return processed
+
+
+class PipelineIterator(IterableDataset):
+ def __init__(self, loader, infer, params, loader_batch_size=None):
+ """
+ Roughly equivalent to
+
+ ```
+ for item in loader:
+ yield infer(item, **params)
+ ```
+
+ Arguments:
+ loader (`torch.utils.data.DataLoader` or `Iterable`):
+ The iterator that will be used to apply `infer` on.
+ infer (any function):
+ The function to apply of each element of `loader`.
+ params (`dict`):
+ The parameters passed to `infer` along with every item
+ loader_batch_size (`int`, *optional*):
+ If specified, the items of `loader` are supposed to come as batch, and are loader_batched here
+ making it roughly behave as
+
+
+ ```
+ for items in loader:
+ for i in loader_batch_size:
+ item = items[i]
+ yield infer(item, **params)
+ ```"""
+ self.loader = loader
+ self.infer = infer
+ self.params = params
+ if loader_batch_size == 1:
+ # Let's spare some time by deactivating altogether
+ loader_batch_size = None
+ self.loader_batch_size = loader_batch_size
+
+ # Internal bookkeeping
+ self._loader_batch_index = None
+ self._loader_batch_data = None
+
+ def __len__(self):
+ return len(self.loader)
+
+ def __iter__(self):
+ self.iterator = iter(self.loader)
+ return self
+
+ def loader_batch_item(self):
+ """
+ Return item located at `loader_batch_index` within the current `loader_batch_data`.
+ """
+ if isinstance(self._loader_batch_data, torch.Tensor):
+ # Batch data is simple tensor, just fetch the slice
+ result = self._loader_batch_data[self._loader_batch_index].unsqueeze(0)
+ else:
+ # Batch data is assumed to be BaseModelOutput (or dict)
+ loader_batched = {}
+ for k, element in self._loader_batch_data.items():
+ if isinstance(element, ModelOutput):
+ # Convert ModelOutput to tuple first
+ element = element.to_tuple()
+ if isinstance(element[0], torch.Tensor):
+ loader_batched[k] = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element)
+ elif isinstance(element[0], np.ndarray):
+ loader_batched[k] = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element)
+ continue
+ if k in {"hidden_states", "attentions"} and isinstance(element, tuple):
+ # Those are stored as lists of tensors so need specific unbatching.
+ if isinstance(element[0], torch.Tensor):
+ loader_batched[k] = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element)
+ elif isinstance(element[0], np.ndarray):
+ loader_batched[k] = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element)
+ continue
+ if k == "past_key_values":
+ continue
+ if element is None:
+ # This can happen for optional data that get passed around
+ loader_batched[k] = None
+ elif isinstance(element[self._loader_batch_index], torch.Tensor):
+ # Take correct batch data, but make it looked like batch_size=1
+ # For compatibility with other methods within transformers
+
+ loader_batched[k] = element[self._loader_batch_index].unsqueeze(0)
+ elif isinstance(element[self._loader_batch_index], np.ndarray):
+ # Take correct batch data, but make it looked like batch_size=1
+ # For compatibility with other methods within transformers
+ loader_batched[k] = np.expand_dims(element[self._loader_batch_index], 0)
+ else:
+ # This is typically a list, so no need to `unsqueeze`.
+ loader_batched[k] = element[self._loader_batch_index]
+ # Recreate the element by reusing the original class to make it look
+ # batch_size=1
+ result = self._loader_batch_data.__class__(loader_batched)
+ self._loader_batch_index += 1
+ return result
+
+ def __next__(self):
+ if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
+ # We are currently unrolling a batch so we just need to return
+ # the current item within a batch
+ return self.loader_batch_item()
+
+ # We're out of items within a batch
+ item = next(self.iterator)
+ processed = self.infer(item, **self.params)
+ # We now have a batch of "inferred things".
+ if self.loader_batch_size is not None:
+ # Try to infer the size of the batch
+ if isinstance(processed, torch.Tensor):
+ first_tensor = processed
+ elif isinstance(processed, tuple):
+ first_tensor = processed[0]
+ else:
+ key = list(processed.keys())[0]
+ first_tensor = processed[key]
+
+ if isinstance(first_tensor, list):
+ observed_batch_size = len(first_tensor)
+ else:
+ observed_batch_size = first_tensor.shape[0]
+ if 0 < observed_batch_size < self.loader_batch_size:
+ # could be last batch so we can't unroll as many
+ # elements.
+ self.loader_batch_size = observed_batch_size
+ # Setting internal index to unwrap the batch
+ self._loader_batch_data = processed[0] if isinstance(processed, tuple) else processed
+ self._loader_batch_index = 0
+ return self.loader_batch_item()
+ else:
+ # We're not unrolling batches
+ return processed
+
+
+class PipelineChunkIterator(PipelineIterator):
+ def __init__(self, loader, infer, params, loader_batch_size=None):
+ """
+ Roughly equivalent to
+
+ ```
+ for iterator in loader:
+ for item in iterator:
+ yield infer(item, **params)
+ ```
+
+ Arguments:
+ loader (`torch.utils.data.DataLoader` or `Iterable`):
+ The iterator that will be used to apply `infer` on.
+ infer (any function):
+ The function to apply of each element of `loader`.
+ params (`dict`):
+ The parameters passed to `infer` along with every item
+ """
+ super().__init__(loader, infer, params)
+
+ def __iter__(self):
+ self.iterator = iter(self.loader)
+ self.subiterator = None
+ return self
+
+ def __next__(self):
+ if self.subiterator is None:
+ "Subiterator None means we haven't started a `preprocess` iterator. so start it"
+ self.subiterator = self.infer(next(self.iterator), **self.params)
+ try:
+ # Try to return next item
+ processed = next(self.subiterator)
+ except StopIteration:
+ # When a preprocess iterator ends, we can start looking at the next item
+ # ChunkIterator will keep feeding until ALL elements of iterator
+ # all have created their subiterator and have been iterating against.
+ #
+ # Another way to look at it, is we're basically flattening lists of lists
+ # into a single list, but with generators
+ self.subiterator = self.infer(next(self.iterator), **self.params)
+ processed = next(self.subiterator)
+ return processed
+
+
+class PipelinePackIterator(PipelineIterator):
+ """
+ Roughly equivalent to
+
+ ```
+ packed = []
+ for item in loader:
+ packed.append(item)
+ if item["is_last"]:
+ yield packed
+ packed = []
+ ```
+
+ but it also handles cases where `item` are batched (meaning it's a dict of Tensor with first dimension > 1. In
+ that case it does
+
+ ```
+ packed = []
+ for batch in loader:
+ # item is batched
+ for item in batch:
+ packed.append(item)
+ if item["is_last"]:
+ yield packed
+ packed = []
+ ```
+
+ Arguments:
+ loader (`torch.utils.data.DataLoader` or `Iterable`):
+ The iterator that will be used to apply `infer` on.
+ infer (any function):
+ The function to apply of each element of `loader`.
+ params (`dict`):
+ The parameters passed to `infer` along with every item
+ loader_batch_size (`int`, *optional*):
+ If specified, the items of `loader` are supposed to come as batch, and are loader_batched here making
+ it roughly behave as
+
+
+ ```
+ for items in loader:
+ for i in loader_batch_size:
+ item = items[i]
+ yield infer(item, **params)
+ ```"""
+
+ def __iter__(self):
+ self.iterator = iter(self.loader)
+ return self
+
+ def __next__(self):
+ # Extremely similar to PipelineIterator in its unpacking mechanism
+ # BUT, we have an extra required item which is the presence of `is_last`
+ # That is because everything is flattened by `PipelineChunkIterator` we
+ # need to keep track of how to regroup here in the original `process`
+ # boundaries so that `process` and `postprocess` see the same data.
+
+ # This iterator accumulates items (possibly while unbatching) until it
+ # its a `is_last` and then just passes it on to the caller.
+ is_last = False
+ accumulator = []
+ if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size:
+ while self._loader_batch_index < self.loader_batch_size:
+ item = self.loader_batch_item()
+ is_last = item.pop("is_last")
+ accumulator.append(item)
+ if is_last:
+ return accumulator
+
+ while not is_last:
+ processed = self.infer(next(self.iterator), **self.params)
+ if self.loader_batch_size is not None:
+ if isinstance(processed, torch.Tensor):
+ first_tensor = processed
+ else:
+ key = list(processed.keys())[0]
+ first_tensor = processed[key]
+ if isinstance(first_tensor, list):
+ observed_batch_size = len(first_tensor)
+ else:
+ observed_batch_size = first_tensor.shape[0]
+ if 0 < observed_batch_size < self.loader_batch_size:
+ # could be last batch so we can't unroll as many
+ # elements.
+ self.loader_batch_size = observed_batch_size
+ self._loader_batch_data = processed
+ self._loader_batch_index = 0
+ while self._loader_batch_index < self.loader_batch_size:
+ item = self.loader_batch_item()
+ is_last = item.pop("is_last")
+ accumulator.append(item)
+ if is_last:
+ return accumulator
+ else:
+ item = processed
+ is_last = item.pop("is_last")
+ accumulator.append(item)
+ return accumulator
+
+
+class KeyDataset(Dataset):
+ def __init__(self, dataset: Dataset, key: str):
+ self.dataset = dataset
+ self.key = key
+
+ def __len__(self):
+ return len(self.dataset)
+
+ def __getitem__(self, i):
+ return self.dataset[i][self.key]
+
+
+class KeyPairDataset(Dataset):
+ def __init__(self, dataset: Dataset, key1: str, key2: str):
+ self.dataset = dataset
+ self.key1 = key1
+ self.key2 = key2
+
+ def __len__(self):
+ return len(self.dataset)
+
+ def __getitem__(self, i):
+ return {"text": self.dataset[i][self.key1], "text_pair": self.dataset[i][self.key2]}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/table_question_answering.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/table_question_answering.py
new file mode 100644
index 0000000000000000000000000000000000000000..96bcc863cbe791dde19497d876df754d4fdaf683
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/table_question_answering.py
@@ -0,0 +1,382 @@
+import collections
+import types
+
+import numpy as np
+
+from ..generation import GenerationConfig
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ requires_backends,
+)
+from .base import ArgumentHandler, Dataset, Pipeline, PipelineException, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import (
+ MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,
+ MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES,
+ )
+
+
+class TableQuestionAnsweringArgumentHandler(ArgumentHandler):
+ """
+ Handles arguments for the TableQuestionAnsweringPipeline
+ """
+
+ def __call__(self, table=None, query=None, **kwargs):
+ # Returns tqa_pipeline_inputs of shape:
+ # [
+ # {"table": pd.DataFrame, "query": list[str]},
+ # ...,
+ # {"table": pd.DataFrame, "query" : list[str]}
+ # ]
+ requires_backends(self, "pandas")
+ import pandas as pd
+
+ if table is None:
+ raise ValueError("Keyword argument `table` cannot be None.")
+ elif query is None:
+ if isinstance(table, dict) and table.get("query") is not None and table.get("table") is not None:
+ tqa_pipeline_inputs = [table]
+ elif isinstance(table, list) and len(table) > 0:
+ if not all(isinstance(d, dict) for d in table):
+ raise ValueError(
+ f"Keyword argument `table` should be a list of dict, but is {(type(d) for d in table)}"
+ )
+
+ if table[0].get("query") is not None and table[0].get("table") is not None:
+ tqa_pipeline_inputs = table
+ else:
+ raise ValueError(
+ "If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`"
+ f" and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys."
+ )
+ elif Dataset is not None and isinstance(table, Dataset) or isinstance(table, types.GeneratorType):
+ return table
+ else:
+ raise ValueError(
+ "Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but "
+ f"is {type(table)})"
+ )
+ else:
+ tqa_pipeline_inputs = [{"table": table, "query": query}]
+
+ for tqa_pipeline_input in tqa_pipeline_inputs:
+ if not isinstance(tqa_pipeline_input["table"], pd.DataFrame):
+ if tqa_pipeline_input["table"] is None:
+ raise ValueError("Table cannot be None.")
+
+ tqa_pipeline_input["table"] = pd.DataFrame(tqa_pipeline_input["table"])
+
+ return tqa_pipeline_inputs
+
+
+@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
+class TableQuestionAnsweringPipeline(Pipeline):
+ """
+ Table Question Answering pipeline using a `ModelForTableQuestionAnswering`. This pipeline is only available in
+ PyTorch.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> oracle = pipeline(model="google/tapas-base-finetuned-wtq")
+ >>> table = {
+ ... "Repository": ["Transformers", "Datasets", "Tokenizers"],
+ ... "Stars": ["36542", "4512", "3934"],
+ ... "Contributors": ["651", "77", "34"],
+ ... "Programming language": ["Python", "Python", "Rust, Python and NodeJS"],
+ ... }
+ >>> oracle(query="How many stars does the transformers repository have?", table=table)
+ {'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'}
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This tabular question answering pipeline can currently be loaded from [`pipeline`] using the following task
+ identifier: `"table-question-answering"`.
+
+ The models that this pipeline can use are models that have been fine-tuned on a tabular question answering task.
+ See the up-to-date list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=table-question-answering).
+ """
+
+ default_input_names = "table,query"
+
+ _pipeline_calls_generate = True
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ )
+
+ def __init__(self, args_parser=TableQuestionAnsweringArgumentHandler(), **kwargs):
+ super().__init__(**kwargs)
+ self._args_parser = args_parser
+
+ mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES.copy()
+ mapping.update(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES)
+ self.check_model_type(mapping)
+
+ self.aggregate = getattr(self.model.config, "aggregation_labels", None) and getattr(
+ self.model.config, "num_aggregation_labels", None
+ )
+ self.type = "tapas" if hasattr(self.model.config, "aggregation_labels") else None
+
+ def batch_inference(self, **inputs):
+ return self.model(**inputs)
+
+ def sequential_inference(self, **inputs):
+ """
+ Inference used for models that need to process sequences in a sequential fashion, like the SQA models which
+ handle conversational query related to a table.
+ """
+ all_logits = []
+ all_aggregations = []
+ prev_answers = None
+ batch_size = inputs["input_ids"].shape[0]
+
+ input_ids = inputs["input_ids"].to(self.device)
+ attention_mask = inputs["attention_mask"].to(self.device)
+ token_type_ids = inputs["token_type_ids"].to(self.device)
+ token_type_ids_example = None
+
+ for index in range(batch_size):
+ # If sequences have already been processed, the token type IDs will be created according to the previous
+ # answer.
+ if prev_answers is not None:
+ prev_labels_example = token_type_ids_example[:, 3] # shape (seq_len,)
+ model_labels = np.zeros_like(prev_labels_example.cpu().numpy()) # shape (seq_len,)
+
+ token_type_ids_example = token_type_ids[index] # shape (seq_len, 7)
+ for i in range(model_labels.shape[0]):
+ segment_id = token_type_ids_example[:, 0].tolist()[i]
+ col_id = token_type_ids_example[:, 1].tolist()[i] - 1
+ row_id = token_type_ids_example[:, 2].tolist()[i] - 1
+
+ if row_id >= 0 and col_id >= 0 and segment_id == 1:
+ model_labels[i] = int(prev_answers[(col_id, row_id)])
+
+ token_type_ids_example[:, 3] = torch.from_numpy(model_labels).type(torch.long).to(self.device)
+
+ input_ids_example = input_ids[index]
+ attention_mask_example = attention_mask[index] # shape (seq_len,)
+ token_type_ids_example = token_type_ids[index] # shape (seq_len, 7)
+ outputs = self.model(
+ input_ids=input_ids_example.unsqueeze(0),
+ attention_mask=attention_mask_example.unsqueeze(0),
+ token_type_ids=token_type_ids_example.unsqueeze(0),
+ )
+ logits = outputs.logits
+
+ if self.aggregate:
+ all_aggregations.append(outputs.logits_aggregation)
+
+ all_logits.append(logits)
+
+ dist_per_token = torch.distributions.Bernoulli(logits=logits)
+ probabilities = dist_per_token.probs * attention_mask_example.type(torch.float32).to(
+ dist_per_token.probs.device
+ )
+
+ coords_to_probs = collections.defaultdict(list)
+ for i, p in enumerate(probabilities.squeeze().tolist()):
+ segment_id = token_type_ids_example[:, 0].tolist()[i]
+ col = token_type_ids_example[:, 1].tolist()[i] - 1
+ row = token_type_ids_example[:, 2].tolist()[i] - 1
+ if col >= 0 and row >= 0 and segment_id == 1:
+ coords_to_probs[(col, row)].append(p)
+
+ prev_answers = {key: np.array(coords_to_probs[key]).mean() > 0.5 for key in coords_to_probs}
+
+ logits_batch = torch.cat(tuple(all_logits), 0)
+
+ return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(all_aggregations), 0))
+
+ def __call__(self, *args, **kwargs):
+ r"""
+ Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below:
+
+ - `pipeline(table, query)`
+ - `pipeline(table, [query])`
+ - `pipeline(table=table, query=query)`
+ - `pipeline(table=table, query=[query])`
+ - `pipeline({"table": table, "query": query})`
+ - `pipeline({"table": table, "query": [query]})`
+ - `pipeline([{"table": table, "query": query}, {"table": table, "query": query}])`
+
+ The `table` argument should be a dict or a DataFrame built from that dict, containing the whole table:
+
+ Example:
+
+ ```python
+ data = {
+ "actors": ["brad pitt", "leonardo di caprio", "george clooney"],
+ "age": ["56", "45", "59"],
+ "number of movies": ["87", "53", "69"],
+ "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"],
+ }
+ ```
+
+ This dictionary can be passed in as such, or can be converted to a pandas DataFrame:
+
+ Example:
+
+ ```python
+ import pandas as pd
+
+ table = pd.DataFrame.from_dict(data)
+ ```
+
+ Args:
+ table (`pd.DataFrame` or `Dict`):
+ Pandas DataFrame or dictionary that will be converted to a DataFrame containing all the table values.
+ See above for an example of dictionary.
+ query (`str` or `list[str]`):
+ Query or list of queries that will be sent to the model alongside the table.
+ sequential (`bool`, *optional*, defaults to `False`):
+ Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the
+ inference to be done sequentially to extract relations within sequences, given their conversational
+ nature.
+ padding (`bool`, `str` or [`~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` or [`TapasTruncationStrategy`], *optional*, defaults to `False`):
+ Activates and controls truncation. Accepts the following values:
+
+ - `True` or `'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.
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
+ greater than the model maximum admissible input size).
+
+
+ Return:
+ A dictionary or a list of dictionaries containing results: Each result is a dictionary with the following
+ keys:
+
+ - **answer** (`str`) -- The answer of the query given the table. If there is an aggregator, the answer will
+ be preceded by `AGGREGATOR >`.
+ - **coordinates** (`list[tuple[int, int]]`) -- Coordinates of the cells of the answers.
+ - **cells** (`list[str]`) -- List of strings made up of the answer cell values.
+ - **aggregator** (`str`) -- If the model has an aggregator, this returns the aggregator.
+ """
+ pipeline_inputs = self._args_parser(*args, **kwargs)
+
+ results = super().__call__(pipeline_inputs, **kwargs)
+ if len(results) == 1:
+ return results[0]
+ return results
+
+ def _sanitize_parameters(self, sequential=None, padding=None, truncation=None, **kwargs):
+ preprocess_params = {}
+ if padding is not None:
+ preprocess_params["padding"] = padding
+ if truncation is not None:
+ preprocess_params["truncation"] = truncation
+
+ forward_params = {}
+ if sequential is not None:
+ forward_params["sequential"] = sequential
+
+ if getattr(self, "assistant_model", None) is not None:
+ forward_params["assistant_model"] = self.assistant_model
+ if getattr(self, "assistant_tokenizer", None) is not None:
+ forward_params["tokenizer"] = self.tokenizer
+ forward_params["assistant_tokenizer"] = self.assistant_tokenizer
+
+ return preprocess_params, forward_params, {}
+
+ def preprocess(self, pipeline_input, padding=True, truncation=None):
+ if truncation is None:
+ if self.type == "tapas":
+ truncation = "drop_rows_to_fit"
+ else:
+ truncation = "do_not_truncate"
+
+ table, query = pipeline_input["table"], pipeline_input["query"]
+ if table.empty:
+ raise ValueError("table is empty")
+ if query is None or query == "":
+ raise ValueError("query is empty")
+ inputs = self.tokenizer(table, query, return_tensors="pt", truncation=truncation, padding=padding)
+ inputs["table"] = table
+ return inputs
+
+ def _forward(self, model_inputs, sequential=False, **generate_kwargs):
+ table = model_inputs.pop("table")
+
+ if self.type == "tapas":
+ if sequential:
+ outputs = self.sequential_inference(**model_inputs)
+ else:
+ outputs = self.batch_inference(**model_inputs)
+ else:
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ outputs = self.model.generate(**model_inputs, **generate_kwargs)
+ model_outputs = {"model_inputs": model_inputs, "table": table, "outputs": outputs}
+ return model_outputs
+
+ def postprocess(self, model_outputs):
+ inputs = model_outputs["model_inputs"]
+ table = model_outputs["table"]
+ outputs = model_outputs["outputs"]
+ if self.type == "tapas":
+ if self.aggregate:
+ logits, logits_agg = outputs[:2]
+ predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits, logits_agg)
+ answer_coordinates_batch, agg_predictions = predictions
+ aggregators = {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(agg_predictions)}
+
+ no_agg_label_index = self.model.config.no_aggregation_label_index
+ aggregators_prefix = {
+ i: aggregators[i] + " > " for i, pred in enumerate(agg_predictions) if pred != no_agg_label_index
+ }
+ else:
+ logits = outputs[0]
+ predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits)
+ answer_coordinates_batch = predictions[0]
+ aggregators = {}
+ aggregators_prefix = {}
+ answers = []
+ for index, coordinates in enumerate(answer_coordinates_batch):
+ cells = [table.iat[coordinate] for coordinate in coordinates]
+ aggregator = aggregators.get(index, "")
+ aggregator_prefix = aggregators_prefix.get(index, "")
+ answer = {
+ "answer": aggregator_prefix + ", ".join(cells),
+ "coordinates": coordinates,
+ "cells": [table.iat[coordinate] for coordinate in coordinates],
+ }
+ if aggregator:
+ answer["aggregator"] = aggregator
+
+ answers.append(answer)
+ if len(answer) == 0:
+ raise PipelineException("Table question answering", self.model.name_or_path, "Empty answer")
+ else:
+ answers = [{"answer": answer} for answer in self.tokenizer.batch_decode(outputs, skip_special_tokens=True)]
+
+ return answers if len(answers) > 1 else answers[0]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab9a5d8efbc4ae9f60e0d39782f418863d773b7a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_classification.py
@@ -0,0 +1,219 @@
+import inspect
+from typing import Any
+
+import numpy as np
+
+from ..utils import ExplicitEnum, add_end_docstrings, is_torch_available
+from .base import GenericTensor, Pipeline, build_pipeline_init_args
+
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
+
+
+def sigmoid(_outputs):
+ return 1.0 / (1.0 + np.exp(-_outputs))
+
+
+def softmax(_outputs):
+ maxes = np.max(_outputs, axis=-1, keepdims=True)
+ shifted_exp = np.exp(_outputs - maxes)
+ return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
+
+
+class ClassificationFunction(ExplicitEnum):
+ SIGMOID = "sigmoid"
+ SOFTMAX = "softmax"
+ NONE = "none"
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_tokenizer=True),
+ r"""
+ function_to_apply (`str`, *optional*, defaults to `"default"`):
+ The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:
+
+ - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
+ has several labels, will apply the softmax function on the output. In case of regression tasks, will not
+ apply any function on the output.
+ - `"sigmoid"`: Applies the sigmoid function on the output.
+ - `"softmax"`: Applies the softmax function on the output.
+ - `"none"`: Does not apply any function on the output.""",
+)
+class TextClassificationPipeline(Pipeline):
+ """
+ Text classification pipeline using any `ModelForSequenceClassification`. See the [sequence classification
+ examples](../task_summary#sequence-classification) for more information.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
+ >>> classifier("This movie is disgustingly good !")
+ [{'label': 'POSITIVE', 'score': 1.0}]
+
+ >>> classifier("Director tried too much.")
+ [{'label': 'NEGATIVE', 'score': 0.996}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This text classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"sentiment-analysis"` (for classifying sequences according to positive or negative sentiments).
+
+ If multiple classification labels are available (`model.config.num_labels >= 2`), the pipeline will run a softmax
+ over the results. If there is a single label, the pipeline will run a sigmoid over the result. In case of regression
+ tasks (`model.config.problem_type == "regression"`), will not apply any function on the output.
+
+ The models that this pipeline can use are models that have been fine-tuned on a sequence classification task. See
+ the up-to-date list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=text-classification).
+ """
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ function_to_apply = ClassificationFunction.NONE
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ self.check_model_type(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES)
+
+ def _sanitize_parameters(self, function_to_apply=None, top_k="", **tokenizer_kwargs):
+ # Using "" as default argument because we're going to use `top_k=None` in user code to declare
+ # "No top_k"
+ preprocess_params = tokenizer_kwargs
+
+ postprocess_params = {}
+
+ if isinstance(top_k, int) or top_k is None:
+ postprocess_params["top_k"] = top_k
+ postprocess_params["_legacy"] = False
+
+ if isinstance(function_to_apply, str):
+ function_to_apply = ClassificationFunction[function_to_apply.upper()]
+
+ if function_to_apply is not None:
+ postprocess_params["function_to_apply"] = function_to_apply
+ return preprocess_params, {}, postprocess_params
+
+ def __call__(
+ self,
+ inputs: str | list[str] | dict[str, str] | list[dict[str, str]],
+ **kwargs: Any,
+ ) -> list[dict[str, Any]]:
+ """
+ Classify the text(s) given as inputs.
+
+ Args:
+ inputs (`str` or `list[str]` or `dict[str]`, or `list[dict[str]]`):
+ One or several texts to classify. In order to use text pairs for your classification, you can send a
+ dictionary containing `{"text", "text_pair"}` keys, or a list of those.
+ top_k (`int`, *optional*, defaults to `1`):
+ How many results to return.
+ function_to_apply (`str`, *optional*, defaults to `"default"`):
+ The function to apply to the model outputs in order to retrieve the scores. Accepts four different
+ values:
+
+ If this argument is not specified, then it will apply the following functions according to the number
+ of labels:
+
+ - If problem type is regression, will not apply any function on the output.
+ - If the model has a single label, will apply the sigmoid function on the output.
+ - If the model has several labels, will apply the softmax function on the output.
+
+ Possible values are:
+
+ - `"sigmoid"`: Applies the sigmoid function on the output.
+ - `"softmax"`: Applies the softmax function on the output.
+ - `"none"`: Does not apply any function on the output.
+
+ Return:
+ A list of `dict`: Each result comes as list of dictionaries with the following keys:
+
+ - **label** (`str`) -- The label predicted.
+ - **score** (`float`) -- The corresponding probability.
+
+ If `top_k` is used, one such dictionary is returned per label.
+ """
+ inputs = (inputs,)
+ result = super().__call__(*inputs, **kwargs)
+ # TODO try and retrieve it in a nicer way from _sanitize_parameters.
+ _legacy = "top_k" not in kwargs
+ if isinstance(inputs[0], str) and _legacy:
+ # This pipeline is odd, and return a list when single item is run
+ return [result]
+ else:
+ return result
+
+ def preprocess(self, inputs, **tokenizer_kwargs) -> dict[str, GenericTensor]:
+ return_tensors = "pt"
+ if isinstance(inputs, dict):
+ return self.tokenizer(**inputs, return_tensors=return_tensors, **tokenizer_kwargs)
+ elif isinstance(inputs, list) and len(inputs) == 1 and isinstance(inputs[0], list) and len(inputs[0]) == 2:
+ # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
+ return self.tokenizer(
+ text=inputs[0][0], text_pair=inputs[0][1], return_tensors=return_tensors, **tokenizer_kwargs
+ )
+ elif isinstance(inputs, list):
+ # This is likely an invalid usage of the pipeline attempting to pass text pairs.
+ raise ValueError(
+ "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a"
+ ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'
+ )
+ return self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs)
+
+ def _forward(self, model_inputs):
+ # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
+ model_forward = self.model.forward
+ if "use_cache" in inspect.signature(model_forward).parameters:
+ model_inputs["use_cache"] = False
+ return self.model(**model_inputs)
+
+ def postprocess(self, model_outputs, function_to_apply=None, top_k=1, _legacy=True):
+ # `_legacy` is used to determine if we're running the naked pipeline and in backward
+ # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
+ # the more natural result containing the list.
+ # Default value before `set_parameters`
+ if function_to_apply is None:
+ if self.model.config.problem_type == "regression":
+ function_to_apply = ClassificationFunction.NONE
+ elif self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
+ function_to_apply = ClassificationFunction.SIGMOID
+ elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
+ function_to_apply = ClassificationFunction.SOFTMAX
+ elif hasattr(self.model.config, "function_to_apply") and function_to_apply is None:
+ function_to_apply = self.model.config.function_to_apply
+ else:
+ function_to_apply = ClassificationFunction.NONE
+
+ outputs = model_outputs["logits"][0]
+
+ # To enable using fp16 and bf16
+ outputs = outputs.float().numpy()
+
+ if function_to_apply == ClassificationFunction.SIGMOID:
+ scores = sigmoid(outputs)
+ elif function_to_apply == ClassificationFunction.SOFTMAX:
+ scores = softmax(outputs)
+ elif function_to_apply == ClassificationFunction.NONE:
+ scores = outputs
+ else:
+ raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}")
+
+ if top_k == 1 and _legacy:
+ return {"label": self.model.config.id2label[scores.argmax().item()], "score": scores.max().item()}
+
+ dict_scores = [
+ {"label": self.model.config.id2label[i], "score": score.item()} for i, score in enumerate(scores)
+ ]
+ if not _legacy:
+ dict_scores.sort(key=lambda x: x["score"], reverse=True)
+ if top_k is not None:
+ dict_scores = dict_scores[:top_k]
+ return dict_scores
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_generation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_generation.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a0b2966d07cbfba9aaf2738f5453a336278c136
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_generation.py
@@ -0,0 +1,508 @@
+import enum
+from typing import Any, overload
+
+from ..generation import GenerationConfig
+from ..utils import ModelOutput, add_end_docstrings, is_torch_available
+from ..utils.chat_template_utils import Chat, ChatType
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES
+
+
+class ReturnType(enum.Enum):
+ TENSORS = 0
+ NEW_TEXT = 1
+ FULL_TEXT = 2
+
+
+@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
+class TextGenerationPipeline(Pipeline):
+ """
+ Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`. This pipeline predicts the words
+ that will follow a specified text prompt. When the underlying model is a conversational model, it can also accept
+ one or more chats, in which case the pipeline will operate in chat mode and will continue the chat(s) by adding
+ its response(s). Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+ - do_sample: True
+ - temperature: 0.7
+
+ Examples:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> generator = pipeline(model="openai-community/gpt2")
+ >>> generator("I can't believe you did such a ", do_sample=False)
+ [{'generated_text': "I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I"}]
+
+ >>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions.
+ >>> outputs = generator("My tart needs some", num_return_sequences=4, return_full_text=False)
+ ```
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> generator = pipeline(model="HuggingFaceH4/zephyr-7b-beta")
+ >>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string
+ >>> generator([{"role": "user", "content": "What is the capital of France? Answer in one word."}], do_sample=False, max_new_tokens=2)
+ [{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text
+ generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about
+ text generation parameters in [Text generation strategies](../generation_strategies) and [Text
+ generation](text_generation).
+
+ This language generation pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"text-generation"`.
+
+ The models that this pipeline can use are models that have been trained with an autoregressive language modeling
+ objective. See the list of available [text completion models](https://huggingface.co/models?filter=text-generation)
+ and the list of [conversational models](https://huggingface.co/models?other=conversational)
+ on [huggingface.co/models].
+ """
+
+ # Prefix text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
+ # in https://github.com/rusiaaman/XLNet-gen#methodology
+ # and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
+
+ XL_PREFIX = """
+ In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
+ voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
+ Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
+ and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
+ accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
+ the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
+ begging for his blessing.
+ """
+
+ _pipeline_calls_generate = True
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ do_sample=True, # free-form text generation often uses sampling
+ temperature=0.7,
+ )
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.check_model_type(MODEL_FOR_CAUSAL_LM_MAPPING_NAMES)
+ # Decoder-only models require left-padding for correct batched generation.
+ # Only override when there is no feature_extractor, to avoid padding_side conflicts
+ # (e.g., WhisperForCausalLM has a feature_extractor that pads on the right).
+ if self.tokenizer is not None and self.tokenizer.padding_side == "right":
+ self.tokenizer.padding_side = "left"
+
+ if "prefix" not in self._preprocess_params:
+ # This is very specific. The logic is quite complex and needs to be done
+ # as a "default".
+ # It also defines both some preprocess_kwargs and generate_kwargs
+ # which is why we cannot put them in their respective methods.
+ prefix = None
+ if self.prefix is not None:
+ prefix = self.prefix
+ if prefix is None and self.model.__class__.__name__ in [
+ "XLNetLMHeadModel",
+ "TransfoXLLMHeadModel",
+ ]:
+ # For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
+ prefix = self.XL_PREFIX
+ if prefix is not None:
+ # Recalculate some generate_kwargs linked to prefix.
+ preprocess_params, forward_params, _ = self._sanitize_parameters(prefix=prefix, **self._forward_params)
+ self._preprocess_params = {**self._preprocess_params, **preprocess_params}
+ self._forward_params = {**self._forward_params, **forward_params}
+
+ def _sanitize_parameters(
+ self,
+ return_full_text=None,
+ return_tensors=None,
+ return_text=None,
+ return_type=None,
+ clean_up_tokenization_spaces=None,
+ prefix=None,
+ handle_long_generation=None,
+ stop_sequence=None,
+ truncation=None,
+ max_length=None,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ tokenizer_encode_kwargs=None,
+ tools=None,
+ documents=None,
+ **generate_kwargs,
+ ):
+ # preprocess kwargs
+ preprocess_params = {}
+ add_special_tokens = False
+ if "add_special_tokens" in generate_kwargs:
+ add_special_tokens = preprocess_params["add_special_tokens"] = generate_kwargs.pop("add_special_tokens")
+
+ if "padding" in generate_kwargs:
+ preprocess_params["padding"] = generate_kwargs.pop("padding")
+
+ if truncation is not None:
+ preprocess_params["truncation"] = truncation
+
+ if max_length is not None:
+ preprocess_params["max_length"] = max_length
+ generate_kwargs["max_length"] = max_length
+
+ if tools is not None:
+ preprocess_params["tools"] = tools
+ if documents is not None:
+ preprocess_params["documents"] = documents
+
+ if prefix is not None:
+ preprocess_params["prefix"] = prefix
+ if prefix:
+ prefix_inputs = self.tokenizer(
+ prefix, padding=False, add_special_tokens=add_special_tokens, return_tensors="pt"
+ )
+ generate_kwargs["prefix_length"] = prefix_inputs["input_ids"].shape[-1]
+
+ if handle_long_generation is not None:
+ if handle_long_generation != "hole":
+ raise ValueError(
+ f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"
+ " [None, 'hole']"
+ )
+ preprocess_params["handle_long_generation"] = handle_long_generation
+
+ if continue_final_message is not None:
+ preprocess_params["continue_final_message"] = continue_final_message
+
+ if tokenizer_encode_kwargs is not None:
+ preprocess_params["tokenizer_encode_kwargs"] = tokenizer_encode_kwargs
+
+ preprocess_params.update(generate_kwargs)
+
+ # forward kwargs
+ if stop_sequence is not None:
+ stop_sequence_ids = self.tokenizer.encode(stop_sequence, add_special_tokens=False)
+ generate_kwargs["eos_token_id"] = stop_sequence_ids
+ forward_params = generate_kwargs
+ if self.assistant_model is not None:
+ forward_params["assistant_model"] = self.assistant_model
+ if self.assistant_tokenizer is not None:
+ forward_params["tokenizer"] = self.tokenizer
+ forward_params["assistant_tokenizer"] = self.assistant_tokenizer
+
+ # postprocess kwargs
+ postprocess_params = {}
+ if return_full_text is not None and return_type is None:
+ if return_text is not None:
+ raise ValueError("`return_text` is mutually exclusive with `return_full_text`")
+ if return_tensors is not None:
+ raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`")
+ return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
+ if return_tensors is not None and return_type is None:
+ if return_text is not None:
+ raise ValueError("`return_text` is mutually exclusive with `return_tensors`")
+ return_type = ReturnType.TENSORS
+ if return_type is not None:
+ postprocess_params["return_type"] = return_type
+ if clean_up_tokenization_spaces is not None:
+ postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces
+ if continue_final_message is not None:
+ postprocess_params["continue_final_message"] = continue_final_message
+ if skip_special_tokens is not None:
+ postprocess_params["skip_special_tokens"] = skip_special_tokens
+
+ return preprocess_params, forward_params, postprocess_params
+
+ # overriding _parse_and_tokenize to allow for unusual language-modeling tokenizer arguments
+ def _parse_and_tokenize(self, *args, **kwargs):
+ """
+ Parse arguments and tokenize
+ """
+ # Parse arguments
+ if self.model.__class__.__name__ == "TransfoXLLMHeadModel":
+ kwargs.update({"add_space_before_punct_symbol": True})
+
+ return super()._parse_and_tokenize(*args, **kwargs)
+
+ @overload
+ def __call__(self, text_inputs: str, **kwargs: Any) -> list[dict[str, str]]: ...
+
+ @overload
+ def __call__(self, text_inputs: list[str], **kwargs: Any) -> list[list[dict[str, str]]]: ...
+
+ @overload
+ def __call__(self, text_inputs: ChatType, **kwargs: Any) -> list[dict[str, ChatType]]: ...
+
+ @overload
+ def __call__(self, text_inputs: list[ChatType], **kwargs: Any) -> list[list[dict[str, ChatType]]]: ...
+
+ def __call__(self, text_inputs, **kwargs):
+ """
+ Complete the prompt(s) given as inputs.
+
+ Args:
+ text_inputs (`str`, `list[str]`, `ChatType`, or `list[ChatType]`):
+ One or several prompts (or one list of prompts) to complete. If strings or a list of string are
+ passed, this pipeline will continue each prompt. Alternatively, a "chat", in the form of a list
+ of dicts with "role" and "content" keys, can be passed, or a list of such chats. When chats are passed,
+ the model's chat template will be used to format them before passing them to the model.
+ return_tensors (`bool`, *optional*, defaults to `False`):
+ Returns the tensors of predictions (as token indices) in the outputs. If set to
+ `True`, the decoded text is not returned.
+ return_text (`bool`, *optional*):
+ Returns the decoded texts in the outputs.
+ return_full_text (`bool`, *optional*, defaults to `True`):
+ If set to `False` only added text is returned, otherwise the full text is returned. Cannot be
+ specified at the same time as `return_text`.
+ clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`):
+ Whether or not to clean up the potential extra spaces in the text output.
+ continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the
+ last message in the input chat rather than starting a new one, allowing you to "prefill" its response.
+ By default this is `True` when the final message in the input chat has the `assistant` role and
+ `False` otherwise, but you can manually override that behaviour by setting this flag.
+ prefix (`str`, *optional*):
+ Prefix added to prompt.
+ handle_long_generation (`str`, *optional*):
+ By default, this pipelines does not handle long generation (ones that exceed in one form or the other
+ the model maximum length). There is no perfect way to address this (more info
+ :https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227). This provides common
+ strategies to work around that problem depending on your use case.
+
+ - `None` : default strategy where nothing in particular happens
+ - `"hole"`: Truncates left of input, and leaves a gap wide enough to let generation happen (might
+ truncate a lot of the prompt and not suitable when generation exceed the model capacity)
+ tokenizer_encode_kwargs (`dict`, *optional*):
+ Additional keyword arguments to pass along to the encoding step of the tokenizer. If the text input is
+ a chat, it is passed to `apply_chat_template`. Otherwise, it is passed to `__call__`.
+ generate_kwargs (`dict`, *optional*):
+ Additional keyword arguments to pass along to the generate method of the model (see the generate method
+ [here](./text_generation)).
+
+ Return:
+ A list or a list of lists of `dict`: Returns one of the following dictionaries (cannot return a combination
+ of both `generated_text` and `generated_token_ids`):
+
+ - **generated_text** (`str`, present when `return_text=True`) -- The generated text.
+ - **generated_token_ids** (`torch.Tensor`, present when `return_tensors=True`) -- The token
+ ids of the generated text.
+ """
+ return super().__call__(text_inputs, **kwargs)
+
+ def preprocess(
+ self,
+ prompt_text,
+ prefix="",
+ handle_long_generation=None,
+ add_special_tokens=None,
+ truncation=None,
+ padding=None,
+ max_length=None,
+ continue_final_message=None,
+ tokenizer_encode_kwargs=None,
+ tools=None,
+ documents=None,
+ **generate_kwargs,
+ ):
+ # Only set non-None tokenizer kwargs, so as to rely on the tokenizer's defaults
+ tokenizer_kwargs = {
+ "add_special_tokens": add_special_tokens,
+ "truncation": truncation,
+ "padding": padding,
+ "max_length": max_length, # NOTE: `max_length` is also a `generate` arg. Use `tokenizer_encode_kwargs` to avoid a name clash
+ }
+ tokenizer_kwargs = {key: value for key, value in tokenizer_kwargs.items() if value is not None}
+ tokenizer_kwargs.update(tokenizer_encode_kwargs or {})
+
+ if isinstance(prompt_text, Chat):
+ tokenizer_kwargs.pop("add_special_tokens", None) # ignore add_special_tokens on chats
+ # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default
+ # because very few models support multiple separate, consecutive assistant messages
+ if continue_final_message is None:
+ continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
+ inputs = self.tokenizer.apply_chat_template(
+ prompt_text.messages,
+ add_generation_prompt=not continue_final_message,
+ continue_final_message=continue_final_message,
+ return_dict=True,
+ return_tensors="pt",
+ tools=tools,
+ documents=documents,
+ **tokenizer_kwargs,
+ )
+ else:
+ inputs = self.tokenizer(prefix + prompt_text, return_tensors="pt", **tokenizer_kwargs)
+
+ inputs["prompt_text"] = prompt_text
+
+ if handle_long_generation == "hole":
+ cur_len = inputs["input_ids"].shape[-1]
+ if "max_new_tokens" in generate_kwargs:
+ new_tokens = generate_kwargs["max_new_tokens"]
+ else:
+ new_tokens = generate_kwargs.get("max_length", self.generation_config.max_length) - cur_len
+ if new_tokens < 0:
+ raise ValueError("We cannot infer how many new tokens are expected")
+ if cur_len + new_tokens > self.tokenizer.model_max_length:
+ keep_length = self.tokenizer.model_max_length - new_tokens
+ if keep_length <= 0:
+ raise ValueError(
+ "We cannot use `hole` to handle this generation the number of desired tokens exceeds the"
+ " models max length"
+ )
+
+ inputs["input_ids"] = inputs["input_ids"][:, -keep_length:]
+ if "attention_mask" in inputs:
+ inputs["attention_mask"] = inputs["attention_mask"][:, -keep_length:]
+
+ return inputs
+
+ def _forward(self, model_inputs, **generate_kwargs):
+ input_ids = model_inputs["input_ids"]
+ attention_mask = model_inputs.get("attention_mask", None)
+ # Allow empty prompts
+ if input_ids.shape[1] == 0:
+ input_ids = None
+ attention_mask = None
+ in_b = 1
+ else:
+ in_b = input_ids.shape[0]
+ prompt_text = model_inputs.pop("prompt_text")
+
+ # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
+ # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
+ prefix_length = generate_kwargs.pop("prefix_length", 0)
+ if prefix_length > 0:
+ has_max_new_tokens = "max_new_tokens" in generate_kwargs or (
+ "generation_config" in generate_kwargs
+ and generate_kwargs["generation_config"].max_new_tokens is not None
+ )
+ if not has_max_new_tokens:
+ generate_kwargs["max_length"] = generate_kwargs.get("max_length") or self.generation_config.max_length
+ generate_kwargs["max_length"] += prefix_length
+ has_min_new_tokens = "min_new_tokens" in generate_kwargs or (
+ "generation_config" in generate_kwargs
+ and generate_kwargs["generation_config"].min_new_tokens is not None
+ )
+ if not has_min_new_tokens and "min_length" in generate_kwargs:
+ generate_kwargs["min_length"] += prefix_length
+
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ output = self.model.generate(input_ids=input_ids, attention_mask=attention_mask, **generate_kwargs)
+
+ if isinstance(output, ModelOutput):
+ generated_sequence = output.sequences
+ other_outputs = {k: v for k, v in output.items() if k not in {"sequences", "past_key_values"}}
+ out_b = generated_sequence.shape[0]
+
+ for key, value in other_outputs.items():
+ if isinstance(value, torch.Tensor) and value.shape[0] == out_b:
+ other_outputs[key] = value.reshape(in_b, out_b // in_b, *value.shape[1:])
+ if isinstance(value, tuple) and len(value[0]) == out_b:
+ value = torch.stack(value).swapaxes(0, 1)
+ other_outputs[key] = value
+ else:
+ generated_sequence = output
+ other_outputs = {}
+
+ out_b = generated_sequence.shape[0]
+ generated_sequence = generated_sequence.reshape(in_b, out_b // in_b, *generated_sequence.shape[1:])
+
+ model_outputs = {
+ "generated_sequence": generated_sequence,
+ "input_ids": input_ids,
+ "prompt_text": prompt_text,
+ }
+ if other_outputs:
+ model_outputs.update({"additional_outputs": other_outputs})
+ return model_outputs
+
+ def postprocess(
+ self,
+ model_outputs,
+ return_type=ReturnType.FULL_TEXT,
+ clean_up_tokenization_spaces=True,
+ continue_final_message=None,
+ skip_special_tokens=None,
+ ):
+ generated_sequence = model_outputs["generated_sequence"][0]
+ input_ids = model_outputs["input_ids"]
+ prompt_text = model_outputs["prompt_text"]
+ generated_sequence = generated_sequence.numpy().tolist()
+ records = []
+ other_outputs = model_outputs.get("additional_outputs", {})
+ split_keys = {}
+ if other_outputs:
+ for k, v in other_outputs.items():
+ if isinstance(v, torch.Tensor) and v.shape[0] == len(generated_sequence):
+ split_keys[k] = v.numpy().tolist()
+
+ skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True
+ if getattr(self.tokenizer, "response_schema", False):
+ skip_special_tokens = False
+ for idx, sequence in enumerate(generated_sequence):
+ if return_type == ReturnType.TENSORS:
+ record = {"generated_token_ids": sequence}
+ elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
+ # Decode text
+ text = self.tokenizer.decode(
+ sequence,
+ skip_special_tokens=skip_special_tokens,
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
+ )
+
+ # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
+ if input_ids is None:
+ prompt_length = 0
+ else:
+ prompt_length = len(
+ self.tokenizer.decode(
+ input_ids[0],
+ skip_special_tokens=skip_special_tokens,
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
+ )
+ )
+
+ all_text = text[prompt_length:]
+ if return_type == ReturnType.FULL_TEXT:
+ if isinstance(prompt_text, str):
+ all_text = prompt_text + all_text
+ elif isinstance(prompt_text, Chat):
+ if continue_final_message is None:
+ # If the user passes a chat ending in an assistant message, we treat it as a prefill by
+ # default because very few models support multiple separate, consecutive assistant messages
+ continue_final_message = prompt_text.messages[-1]["role"] == "assistant"
+ if continue_final_message:
+ # With assistant prefill, concat onto the end of the last message
+ all_text = list(prompt_text.messages)[:-1] + [
+ {
+ "role": prompt_text.messages[-1]["role"],
+ "content": prompt_text.messages[-1]["content"] + all_text,
+ }
+ ]
+ else:
+ # When we're not starting from a prefill, the output is a new assistant message
+ if getattr(self.tokenizer, "response_schema", False):
+ assistant_message = self.tokenizer.parse_response(all_text)
+ else:
+ # If there's no schema, then we have to assume it's all content
+ assistant_message = {"role": "assistant", "content": all_text}
+ all_text = list(prompt_text.messages) + [assistant_message]
+ record = {"generated_text": all_text}
+ for key, values in split_keys.items():
+ record[key] = values[idx]
+ records.append(record)
+
+ return records
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_to_audio.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_to_audio.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4d70912dd634802fe6e8816e7cbb5acc36f5ed0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/text_to_audio.py
@@ -0,0 +1,316 @@
+# 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 List, Union
+
+from typing import Any, TypedDict, overload
+
+from ..audio_utils import AudioInput
+from ..generation import GenerationConfig
+from ..utils import is_torch_available
+from ..utils.chat_template_utils import Chat, ChatType
+from .base import Pipeline
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING
+ from ..models.speecht5.modeling_speecht5 import SpeechT5HifiGan
+
+DEFAULT_VOCODER_ID = "microsoft/speecht5_hifigan"
+
+
+class AudioOutput(TypedDict, total=False):
+ """
+ audio (`AudioInput`):
+ The generated audio waveform.
+ sampling_rate (`int`):
+ The sampling rate of the generated audio waveform.
+ """
+
+ audio: AudioInput
+ sampling_rate: int
+
+
+class TextToAudioPipeline(Pipeline):
+ """
+ Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`. This
+ pipeline generates an audio file from an input text and optional other conditional inputs.
+
+ Unless the model you're using explicitly sets these generation parameters in its configuration files
+ (`generation_config.json`), the following default values will be used:
+ - max_new_tokens: 256
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> pipe = pipeline(model="suno/bark-small")
+ >>> output = pipe("Hey it's HuggingFace on the phone!")
+
+ >>> audio = output["audio"]
+ >>> sampling_rate = output["sampling_rate"]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+
+
+ You can specify parameters passed to the model by using [`TextToAudioPipeline.__call__.forward_params`] or
+ [`TextToAudioPipeline.__call__.generate_kwargs`].
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small")
+
+ >>> # diversify the music generation by adding randomness with a high temperature and set a maximum music length
+ >>> generate_kwargs = {
+ ... "do_sample": True,
+ ... "temperature": 0.7,
+ ... "max_new_tokens": 35,
+ ... }
+
+ >>> outputs = music_generator("Techno music with high melodic riffs", generate_kwargs=generate_kwargs)
+ ```
+
+
+
+ This pipeline can currently be loaded from [`pipeline`] using the following task identifiers: `"text-to-speech"` or
+ `"text-to-audio"`.
+
+ See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=text-to-speech).
+ """
+
+ _pipeline_calls_generate = True
+ _load_processor = None # prioritize processors as some models require it
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ # Make sure the docstring is updated when the default generation config is changed
+ _default_generation_config = GenerationConfig(
+ max_new_tokens=256,
+ )
+
+ def __init__(self, *args, vocoder=None, sampling_rate=None, **kwargs):
+ super().__init__(*args, **kwargs)
+
+ self.vocoder = None
+ if self.model.__class__ in MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING.values():
+ self.vocoder = (
+ SpeechT5HifiGan.from_pretrained(DEFAULT_VOCODER_ID).to(self.model.device)
+ if vocoder is None
+ else vocoder
+ )
+
+ if self.model.config.model_type in ["musicgen", "speecht5"]:
+ # MusicGen and SpeechT5 expect to use their tokenizer instead
+ self.processor = None
+
+ self.sampling_rate = sampling_rate
+ if self.vocoder is not None:
+ self.sampling_rate = self.vocoder.config.sampling_rate
+
+ if self.sampling_rate is None:
+ # get sampling_rate from config and generation config
+
+ config = self.model.config
+ gen_config = self.model.__dict__.get("generation_config", None)
+ if gen_config is not None:
+ config.update({k: v for k, v in gen_config.to_dict().items() if v is not None})
+
+ for sampling_rate_name in ["sample_rate", "sampling_rate"]:
+ sampling_rate = getattr(config, sampling_rate_name, None)
+ if sampling_rate is not None:
+ self.sampling_rate = sampling_rate
+ elif getattr(config, "codec_config", None) is not None:
+ sampling_rate = getattr(config.codec_config, sampling_rate_name, None)
+ if sampling_rate is not None:
+ self.sampling_rate = sampling_rate
+
+ # last fallback to get the sampling rate based on processor
+ if self.sampling_rate is None and self.processor is not None and hasattr(self.processor, "feature_extractor"):
+ self.sampling_rate = self.processor.feature_extractor.sampling_rate
+
+ def preprocess(self, text, **kwargs):
+ if isinstance(text, str):
+ text = [text]
+
+ if self.model.config.model_type == "bark":
+ # bark Tokenizer is called with BarkProcessor which uses those kwargs
+ # Check if generation_config has semantic_config (BarkGenerationConfig) or use default
+ max_length = 256
+ if hasattr(self.generation_config, "semantic_config"):
+ max_length = getattr(self.generation_config.semantic_config, "max_input_semantic_length", 256)
+ new_kwargs = {
+ "max_length": max_length,
+ "add_special_tokens": False,
+ "return_attention_mask": True,
+ "return_token_type_ids": False,
+ }
+
+ # priority is given to kwargs
+ new_kwargs.update(kwargs)
+ kwargs = new_kwargs
+
+ preprocessor = self.processor if self.processor is not None else self.tokenizer
+ if isinstance(text, Chat):
+ output = preprocessor.apply_chat_template(
+ text.messages,
+ tokenize=True,
+ return_dict=True,
+ **kwargs,
+ )
+ else:
+ # Add speaker ID if needed and user didn't insert at start of text
+ if self.model.config.model_type == "csm":
+ text = [f"[0]{t}" if not t.startswith("[") else t for t in text]
+ kwargs.setdefault("add_special_tokens", True)
+ if self.model.config.model_type == "dia":
+ text = [f"[S1] {t}" if not t.startswith("[") else t for t in text]
+ output = preprocessor(text, **kwargs, return_tensors="pt")
+
+ return output
+
+ def _forward(self, model_inputs, **kwargs):
+ # we expect some kwargs to be additional tensors which need to be on the right device
+ kwargs = self._ensure_tensor_on_device(kwargs, device=self.device)
+ forward_params = kwargs["forward_params"]
+ generate_kwargs = kwargs["generate_kwargs"]
+
+ if self.model.can_generate():
+ # we expect some kwargs to be additional tensors which need to be on the right device
+ generate_kwargs = self._ensure_tensor_on_device(generate_kwargs, device=self.device)
+
+ # User-defined `generation_config` passed to the pipeline call take precedence
+ if "generation_config" not in generate_kwargs:
+ generate_kwargs["generation_config"] = self.generation_config
+
+ # generate_kwargs get priority over forward_params
+ forward_params.update(generate_kwargs)
+
+ # ensure dict output to facilitate postprocessing
+ forward_params.update({"return_dict_in_generate": True})
+
+ if self.model.config.model_type in ["csm"]:
+ # NOTE (ebezzam): CSM does not have the audio tokenizer in the processor therefore `output_audio=True`
+ # needed for decoding to audio
+ if "output_audio" not in forward_params:
+ forward_params["output_audio"] = True
+
+ output = self.model.generate(**model_inputs, **forward_params)
+ else:
+ if len(generate_kwargs):
+ raise ValueError(
+ "You're using the `TextToAudioPipeline` with a forward-only model, but `generate_kwargs` is non "
+ "empty. For forward-only TTA models, please use `forward_params` instead of `generate_kwargs`. "
+ f"For reference, the `generate_kwargs` used here are: {generate_kwargs.keys()}"
+ )
+ output = self.model(**model_inputs, **forward_params)[0]
+
+ if self.vocoder is not None:
+ # in that case, the output is a spectrogram that needs to be converted into a waveform
+ output = self.vocoder(output)
+
+ return output
+
+ @overload
+ def __call__(self, text_inputs: str, **forward_params: Any) -> AudioOutput: ...
+
+ @overload
+ def __call__(self, text_inputs: list[str], **forward_params: Any) -> list[AudioOutput]: ...
+
+ @overload
+ def __call__(self, text_inputs: ChatType, **forward_params: Any) -> AudioOutput: ...
+
+ @overload
+ def __call__(self, text_inputs: list[ChatType], **forward_params: Any) -> list[AudioOutput]: ...
+
+ def __call__(self, text_inputs, **forward_params):
+ """
+ Generates speech/audio from the inputs. See the [`TextToAudioPipeline`] documentation for more information.
+
+ Args:
+ text_inputs (`str`, `list[str]`, `ChatType`, or `list[ChatType]`):
+ One or several texts to generate. If strings or a list of string are passed, this pipeline will
+ generate the corresponding text. Alternatively, a "chat", in the form of a list of dicts with "role"
+ and "content" keys, can be passed, or a list of such chats. When chats are passed, the model's chat
+ template will be used to format them before passing them to the model.
+ forward_params (`dict`, *optional*):
+ Parameters passed to the model generation/forward method. `forward_params` are always passed to the
+ underlying model.
+ generate_kwargs (`dict`, *optional*):
+ The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a
+ complete overview of generate, check the [following
+ guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation). `generate_kwargs` are
+ only passed to the underlying model if the latter is a generative model.
+
+ Return:
+ `AudioOutput` or a list of `AudioOutput`, which is a `TypedDict` with two keys:
+
+ - **audio** (`np.ndarray` of shape `(nb_channels, audio_length)`) -- The generated audio waveform.
+ - **sampling_rate** (`int`) -- The sampling rate of the generated audio waveform.
+ """
+ return super().__call__(text_inputs, **forward_params)
+
+ def _sanitize_parameters(
+ self,
+ preprocess_params=None,
+ forward_params=None,
+ generate_kwargs=None,
+ ):
+ if getattr(self, "assistant_model", None) is not None:
+ generate_kwargs["assistant_model"] = self.assistant_model
+ if getattr(self, "assistant_tokenizer", None) is not None:
+ generate_kwargs["tokenizer"] = self.tokenizer
+ generate_kwargs["assistant_tokenizer"] = self.assistant_tokenizer
+
+ params = {
+ "forward_params": forward_params if forward_params else {},
+ "generate_kwargs": generate_kwargs if generate_kwargs else {},
+ }
+
+ if preprocess_params is None:
+ preprocess_params = {}
+ postprocess_params = {}
+
+ return preprocess_params, params, postprocess_params
+
+ def postprocess(self, audio):
+ needs_decoding = False
+ if isinstance(audio, dict):
+ if "audio" in audio:
+ audio = audio["audio"]
+ else:
+ needs_decoding = True
+ audio = audio["sequences"]
+ elif isinstance(audio, tuple):
+ audio = audio[0]
+
+ if needs_decoding and self.processor is not None:
+ audio = self.processor.decode(audio)
+
+ if isinstance(audio, list):
+ audio = [el.to(device="cpu", dtype=torch.float).numpy().squeeze() for el in audio]
+ audio = audio if len(audio) > 1 else audio[0]
+ else:
+ audio = audio.to(device="cpu", dtype=torch.float).numpy().squeeze()
+
+ return AudioOutput(
+ audio=audio,
+ sampling_rate=self.sampling_rate,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/token_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/token_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..7deca9dc900ac006932996acee4ba2bf3e1f2ab1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/token_classification.py
@@ -0,0 +1,622 @@
+import types
+import warnings
+from typing import Any, overload
+
+import numpy as np
+
+from ..models.bert.tokenization_bert_legacy import BasicTokenizer
+from ..utils import (
+ ExplicitEnum,
+ add_end_docstrings,
+ is_torch_available,
+)
+from .base import ArgumentHandler, ChunkPipeline, Dataset, build_pipeline_init_args
+
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES
+
+
+class TokenClassificationArgumentHandler(ArgumentHandler):
+ """
+ Handles arguments for token classification.
+ """
+
+ def __call__(self, inputs: str | list[str], **kwargs):
+ is_split_into_words = kwargs.get("is_split_into_words", False)
+ delimiter = kwargs.get("delimiter")
+
+ if inputs is not None and isinstance(inputs, (list, tuple)) and len(inputs) > 0:
+ inputs = list(inputs)
+ batch_size = len(inputs)
+ elif isinstance(inputs, str):
+ inputs = [inputs]
+ batch_size = 1
+ elif Dataset is not None and isinstance(inputs, Dataset) or isinstance(inputs, types.GeneratorType):
+ return inputs, is_split_into_words, None, delimiter
+ else:
+ raise ValueError("At least one input is required.")
+
+ offset_mapping = kwargs.get("offset_mapping")
+ if offset_mapping:
+ if isinstance(offset_mapping, list) and isinstance(offset_mapping[0], tuple):
+ offset_mapping = [offset_mapping]
+ if len(offset_mapping) != batch_size:
+ raise ValueError("offset_mapping should have the same batch size as the input")
+ return inputs, is_split_into_words, offset_mapping, delimiter
+
+
+class AggregationStrategy(ExplicitEnum):
+ """All the valid aggregation strategies for TokenClassificationPipeline"""
+
+ NONE = "none"
+ SIMPLE = "simple"
+ FIRST = "first"
+ AVERAGE = "average"
+ MAX = "max"
+
+
+@add_end_docstrings(
+ build_pipeline_init_args(has_tokenizer=True),
+ r"""
+ ignore_labels (`list[str]`, defaults to `["O"]`):
+ A list of labels to ignore.
+ stride (`int`, *optional*):
+ If stride is provided, the pipeline is applied on all the text. The text is split into chunks of size
+ model_max_length. Works only with fast tokenizers and `aggregation_strategy` different from `NONE`. The
+ value of this argument defines the number of overlapping tokens between chunks. In other words, the model
+ will shift forward by `tokenizer.model_max_length - stride` tokens each step.
+ aggregation_strategy (`str`, *optional*, defaults to `"none"`):
+ The strategy to fuse (or not) tokens based on the model prediction.
+
+ - "none" : Will simply not do any aggregation and simply return raw results from the model
+ - "simple" : Will attempt to group entities following the default schema. (A, B-TAG), (B, I-TAG), (C,
+ I-TAG), (D, B-TAG2) (E, B-TAG2) will end up being [{"word": ABC, "entity": "TAG"}, {"word": "D",
+ "entity": "TAG2"}, {"word": "E", "entity": "TAG2"}] Notice that two consecutive B tags will end up as
+ different entities. On word based languages, we might end up splitting words undesirably : Imagine
+ Microsoft being tagged as [{"word": "Micro", "entity": "ENTERPRISE"}, {"word": "soft", "entity":
+ "NAME"}]. Look for FIRST, MAX, AVERAGE for ways to mitigate that and disambiguate words (on languages
+ that support that meaning, which is basically tokens separated by a space). These mitigations will
+ only work on real words, "New york" might still be tagged with two different entities.
+ - "first" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot
+ end up with different tags. Words will simply use the tag of the first token of the word when there
+ is ambiguity.
+ - "average" : (works only on word based models) Will use the `SIMPLE` strategy except that words,
+ cannot end up with different tags. scores will be averaged first across tokens, and then the maximum
+ label is applied.
+ - "max" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot
+ end up with different tags. Word entity will simply be the token with the maximum score.""",
+)
+class TokenClassificationPipeline(ChunkPipeline):
+ """
+ Named Entity Recognition pipeline using any `ModelForTokenClassification`. See the [named entity recognition
+ examples](../task_summary#named-entity-recognition) for more information.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> token_classifier = pipeline(model="Jean-Baptiste/camembert-ner", aggregation_strategy="simple")
+ >>> sentence = "Je m'appelle jean-baptiste et je vis à montréal"
+ >>> tokens = token_classifier(sentence)
+ >>> tokens
+ [{'entity_group': 'PER', 'score': 0.9931, 'word': 'jean-baptiste', 'start': 12, 'end': 26}, {'entity_group': 'LOC', 'score': 0.998, 'word': 'montréal', 'start': 38, 'end': 47}]
+
+ >>> token = tokens[0]
+ >>> # Start and end provide an easy way to highlight words in the original text.
+ >>> sentence[token["start"] : token["end"]]
+ ' jean-baptiste'
+
+ >>> # Some models use the same idea to do part of speech.
+ >>> syntaxer = pipeline(model="vblagoje/bert-english-uncased-finetuned-pos", aggregation_strategy="simple")
+ >>> syntaxer("My name is Sarah and I live in London")
+ [{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_group': 'NOUN', 'score': 0.997, 'word': 'name', 'start': 3, 'end': 7}, {'entity_group': 'AUX', 'score': 0.994, 'word': 'is', 'start': 8, 'end': 10}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'sarah', 'start': 11, 'end': 16}, {'entity_group': 'CCONJ', 'score': 0.999, 'word': 'and', 'start': 17, 'end': 20}, {'entity_group': 'PRON', 'score': 0.999, 'word': 'i', 'start': 21, 'end': 22}, {'entity_group': 'VERB', 'score': 0.998, 'word': 'live', 'start': 23, 'end': 27}, {'entity_group': 'ADP', 'score': 0.999, 'word': 'in', 'start': 28, 'end': 30}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'london', 'start': 31, 'end': 37}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This token recognition pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"ner"` (for predicting the classes of tokens in a sequence: person, organisation, location or miscellaneous).
+
+ The models that this pipeline can use are models that have been fine-tuned on a token classification task. See the
+ up-to-date list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=token-classification).
+ """
+
+ default_input_names = "sequences"
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ def __init__(self, args_parser=TokenClassificationArgumentHandler(), **kwargs):
+ super().__init__(**kwargs)
+
+ self.check_model_type(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES)
+
+ self._basic_tokenizer = BasicTokenizer(do_lower_case=False)
+ self._args_parser = args_parser
+
+ def _sanitize_parameters(
+ self,
+ ignore_labels=None,
+ aggregation_strategy: AggregationStrategy | None = None,
+ offset_mapping: list[tuple[int, int]] | None = None,
+ is_split_into_words: bool = False,
+ stride: int | None = None,
+ delimiter: str | None = None,
+ ):
+ preprocess_params = {}
+ preprocess_params["is_split_into_words"] = is_split_into_words
+
+ if is_split_into_words:
+ preprocess_params["delimiter"] = " " if delimiter is None else delimiter
+
+ if offset_mapping is not None:
+ preprocess_params["offset_mapping"] = offset_mapping
+
+ postprocess_params = {}
+ if aggregation_strategy is not None:
+ if isinstance(aggregation_strategy, str):
+ aggregation_strategy = AggregationStrategy[aggregation_strategy.upper()]
+ if (
+ aggregation_strategy
+ in {AggregationStrategy.FIRST, AggregationStrategy.MAX, AggregationStrategy.AVERAGE}
+ and not self.tokenizer.is_fast
+ ):
+ raise ValueError(
+ "Slow tokenizers cannot handle subwords. Please set the `aggregation_strategy` option"
+ ' to `"simple"` or use a fast tokenizer.'
+ )
+ postprocess_params["aggregation_strategy"] = aggregation_strategy
+ if ignore_labels is not None:
+ postprocess_params["ignore_labels"] = ignore_labels
+ if stride is not None:
+ if stride >= self.tokenizer.model_max_length:
+ raise ValueError(
+ "`stride` must be less than `tokenizer.model_max_length` (or even lower if the tokenizer adds special tokens)"
+ )
+ if aggregation_strategy == AggregationStrategy.NONE:
+ raise ValueError(
+ "`stride` was provided to process all the text but `aggregation_strategy="
+ f'"{aggregation_strategy}"`, please select another one instead.'
+ )
+ else:
+ if self.tokenizer.is_fast:
+ tokenizer_params = {
+ "return_overflowing_tokens": True,
+ "padding": True,
+ "stride": stride,
+ }
+ preprocess_params["tokenizer_params"] = tokenizer_params
+ else:
+ raise ValueError(
+ "`stride` was provided to process all the text but you're using a slow tokenizer."
+ " Please use a fast tokenizer."
+ )
+ return preprocess_params, {}, postprocess_params
+
+ @overload
+ def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, str]]: ...
+
+ @overload
+ def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, str]]]: ...
+
+ def __call__(self, inputs: str | list[str], **kwargs: Any) -> list[dict[str, str]] | list[list[dict[str, str]]]:
+ """
+ Classify each token of the text(s) given as inputs.
+
+ Args:
+ inputs (`str` or `List[str]`):
+ One or several texts (or one list of texts) for token classification. Can be pre-tokenized when
+ `is_split_into_words=True`.
+
+ Return:
+ A list or a list of list of `dict`: Each result comes as a list of dictionaries (one for each token in the
+ corresponding input, or each entity if this pipeline was instantiated with an aggregation_strategy) with
+ the following keys:
+
+ - **word** (`str`) -- The token/word classified. This is obtained by decoding the selected tokens. If you
+ want to have the exact string in the original sentence, use `start` and `end`.
+ - **score** (`float`) -- The corresponding probability for `entity`.
+ - **entity** (`str`) -- The entity predicted for that token/word (it is named *entity_group* when
+ *aggregation_strategy* is not `"none"`.
+ - **index** (`int`, only present when `aggregation_strategy="none"`) -- The index of the corresponding
+ token in the sentence.
+ - **start** (`int`, *optional*) -- The index of the start of the corresponding entity in the sentence. Only
+ exists if the offsets are available within the tokenizer
+ - **end** (`int`, *optional*) -- The index of the end of the corresponding entity in the sentence. Only
+ exists if the offsets are available within the tokenizer
+ """
+
+ _inputs, is_split_into_words, offset_mapping, delimiter = self._args_parser(inputs, **kwargs)
+ kwargs["is_split_into_words"] = is_split_into_words
+ kwargs["delimiter"] = delimiter
+ if is_split_into_words and not all(isinstance(input, list) for input in inputs):
+ return super().__call__([inputs], **kwargs)
+ if offset_mapping:
+ kwargs["offset_mapping"] = offset_mapping
+
+ return super().__call__(inputs, **kwargs)
+
+ def preprocess(self, sentence, offset_mapping=None, **preprocess_params):
+ tokenizer_params = preprocess_params.pop("tokenizer_params", {})
+ truncation = self.tokenizer.model_max_length and self.tokenizer.model_max_length > 0
+
+ word_to_chars_map = None
+ is_split_into_words = preprocess_params["is_split_into_words"]
+ if is_split_into_words:
+ delimiter = preprocess_params["delimiter"]
+ if not isinstance(sentence, list):
+ raise ValueError("When `is_split_into_words=True`, `sentence` must be a list of tokens.")
+ words = sentence
+ sentence = delimiter.join(words) # Recreate the sentence string for later display and slicing
+ # This map will allow to convert back word => char indices
+ word_to_chars_map = []
+ delimiter_len = len(delimiter)
+ char_offset = 0
+ for word in words:
+ word_to_chars_map.append((char_offset, char_offset + len(word)))
+ char_offset += len(word) + delimiter_len
+
+ # We use `words` as the actual input for the tokenizer
+ text_to_tokenize = words
+ tokenizer_params["is_split_into_words"] = True
+ else:
+ if not isinstance(sentence, str):
+ raise ValueError("When `is_split_into_words=False`, `sentence` must be an untokenized string.")
+ text_to_tokenize = sentence
+
+ inputs = self.tokenizer(
+ text_to_tokenize,
+ return_tensors="pt",
+ truncation=truncation,
+ return_special_tokens_mask=True,
+ return_offsets_mapping=self.tokenizer.is_fast,
+ **tokenizer_params,
+ )
+
+ if is_split_into_words and not self.tokenizer.is_fast:
+ raise ValueError("is_split_into_words=True is only supported with fast tokenizers.")
+
+ inputs.pop("overflow_to_sample_mapping", None)
+ num_chunks = len(inputs["input_ids"])
+
+ for i in range(num_chunks):
+ model_inputs = {k: v[i].unsqueeze(0) for k, v in inputs.items()}
+ if offset_mapping is not None:
+ model_inputs["offset_mapping"] = offset_mapping
+
+ model_inputs["sentence"] = sentence if i == 0 else None
+ model_inputs["is_last"] = i == num_chunks - 1
+ if word_to_chars_map is not None:
+ model_inputs["word_ids"] = inputs.word_ids(i)
+ model_inputs["word_to_chars_map"] = word_to_chars_map
+
+ yield model_inputs
+
+ def _forward(self, model_inputs):
+ # Forward
+ special_tokens_mask = model_inputs.pop("special_tokens_mask")
+ offset_mapping = model_inputs.pop("offset_mapping", None)
+ sentence = model_inputs.pop("sentence")
+ is_last = model_inputs.pop("is_last")
+ word_ids = model_inputs.pop("word_ids", None)
+ word_to_chars_map = model_inputs.pop("word_to_chars_map", None)
+
+ output = self.model(**model_inputs)
+ logits = output["logits"] if isinstance(output, dict) else output[0]
+
+ return {
+ "logits": logits,
+ "special_tokens_mask": special_tokens_mask,
+ "offset_mapping": offset_mapping,
+ "sentence": sentence,
+ "is_last": is_last,
+ "word_ids": word_ids,
+ "word_to_chars_map": word_to_chars_map,
+ **model_inputs,
+ }
+
+ def postprocess(self, all_outputs, aggregation_strategy=AggregationStrategy.NONE, ignore_labels=None):
+ if ignore_labels is None:
+ ignore_labels = ["O"]
+ all_entities = []
+
+ # Get map from the first output, it's the same for all chunks
+ word_to_chars_map = all_outputs[0].get("word_to_chars_map")
+
+ for model_outputs in all_outputs:
+ if model_outputs["logits"][0].dtype in (torch.bfloat16, torch.float16):
+ logits = model_outputs["logits"][0].to(torch.float32).numpy()
+ else:
+ logits = model_outputs["logits"][0].numpy()
+
+ sentence = all_outputs[0]["sentence"]
+ input_ids = model_outputs["input_ids"][0]
+ offset_mapping = (
+ model_outputs["offset_mapping"][0] if model_outputs["offset_mapping"] is not None else None
+ )
+ special_tokens_mask = model_outputs["special_tokens_mask"][0].numpy()
+ word_ids = model_outputs.get("word_ids")
+
+ maxes = np.max(logits, axis=-1, keepdims=True)
+ shifted_exp = np.exp(logits - maxes)
+ scores = shifted_exp / shifted_exp.sum(axis=-1, keepdims=True)
+
+ pre_entities = self.gather_pre_entities(
+ sentence,
+ input_ids,
+ scores,
+ offset_mapping,
+ special_tokens_mask,
+ aggregation_strategy,
+ word_ids=word_ids,
+ word_to_chars_map=word_to_chars_map,
+ )
+ grouped_entities = self.aggregate(pre_entities, aggregation_strategy)
+ # Filter anything that is in self.ignore_labels
+ entities = [
+ entity
+ for entity in grouped_entities
+ if entity.get("entity", None) not in ignore_labels
+ and entity.get("entity_group", None) not in ignore_labels
+ ]
+ all_entities.extend(entities)
+ num_chunks = len(all_outputs)
+ if num_chunks > 1:
+ all_entities = self.aggregate_overlapping_entities(all_entities)
+ return all_entities
+
+ def aggregate_overlapping_entities(self, entities):
+ if len(entities) == 0:
+ return entities
+ entities = sorted(entities, key=lambda x: x["start"])
+ aggregated_entities = []
+ previous_entity = entities[0]
+ for entity in entities:
+ if previous_entity["start"] <= entity["start"] < previous_entity["end"]:
+ current_length = entity["end"] - entity["start"]
+ previous_length = previous_entity["end"] - previous_entity["start"]
+ if (
+ current_length > previous_length
+ or current_length == previous_length
+ and entity["score"] > previous_entity["score"]
+ ):
+ previous_entity = entity
+ else:
+ aggregated_entities.append(previous_entity)
+ previous_entity = entity
+ aggregated_entities.append(previous_entity)
+ return aggregated_entities
+
+ def gather_pre_entities(
+ self,
+ sentence: str,
+ input_ids: np.ndarray,
+ scores: np.ndarray,
+ offset_mapping: list[tuple[int, int]] | None,
+ special_tokens_mask: np.ndarray,
+ aggregation_strategy: AggregationStrategy,
+ word_ids: list[int | None] | None = None,
+ word_to_chars_map: list[tuple[int, int]] | None = None,
+ ) -> list[dict]:
+ """Fuse various numpy arrays into dicts with all the information needed for aggregation"""
+ pre_entities = []
+ for idx, token_scores in enumerate(scores):
+ # Filter special_tokens
+ if special_tokens_mask[idx]:
+ continue
+
+ word = self.tokenizer.convert_ids_to_tokens(int(input_ids[idx]))
+ if offset_mapping is not None:
+ start_ind, end_ind = offset_mapping[idx]
+
+ # If the input is pre-tokenized, we need to rescale the offsets to the absolute sentence.
+ if word_ids is not None and word_to_chars_map is not None:
+ word_index = word_ids[idx]
+ if word_index is not None:
+ start_char, _ = word_to_chars_map[word_index]
+ start_ind += start_char
+ end_ind += start_char
+
+ if not isinstance(start_ind, int):
+ start_ind = start_ind.item()
+ end_ind = end_ind.item()
+ word_ref = sentence[start_ind:end_ind]
+ if getattr(self.tokenizer, "_tokenizer", None) and getattr(
+ self.tokenizer._tokenizer.model, "continuing_subword_prefix", None
+ ):
+ # This is a BPE, word aware tokenizer, there is a correct way
+ # to fuse tokens
+ is_subword = len(word) != len(word_ref)
+ else:
+ # This is a fallback heuristic. This will fail most likely on any kind of text + punctuation mixtures that will be considered "words". Non word aware models cannot do better than this unfortunately.
+ if aggregation_strategy in {
+ AggregationStrategy.FIRST,
+ AggregationStrategy.AVERAGE,
+ AggregationStrategy.MAX,
+ }:
+ warnings.warn(
+ "Tokenizer does not support real words, using fallback heuristic",
+ UserWarning,
+ )
+ is_subword = start_ind > 0 and " " not in sentence[start_ind - 1 : start_ind + 1]
+
+ if int(input_ids[idx]) == self.tokenizer.unk_token_id:
+ word = word_ref
+ is_subword = False
+ else:
+ start_ind = None
+ end_ind = None
+ is_subword = False
+
+ pre_entity = {
+ "word": word,
+ "scores": token_scores,
+ "start": start_ind,
+ "end": end_ind,
+ "index": idx,
+ "is_subword": is_subword,
+ }
+ pre_entities.append(pre_entity)
+ return pre_entities
+
+ def aggregate(self, pre_entities: list[dict], aggregation_strategy: AggregationStrategy) -> list[dict]:
+ if aggregation_strategy in {AggregationStrategy.NONE, AggregationStrategy.SIMPLE}:
+ entities = []
+ for pre_entity in pre_entities:
+ entity_idx = pre_entity["scores"].argmax()
+ score = pre_entity["scores"][entity_idx]
+ entity = {
+ "entity": self.model.config.id2label[entity_idx],
+ "score": score,
+ "index": pre_entity["index"],
+ "word": pre_entity["word"],
+ "start": pre_entity["start"],
+ "end": pre_entity["end"],
+ }
+ entities.append(entity)
+ else:
+ entities = self.aggregate_words(pre_entities, aggregation_strategy)
+
+ if aggregation_strategy == AggregationStrategy.NONE:
+ return entities
+ return self.group_entities(entities)
+
+ def aggregate_word(self, entities: list[dict], aggregation_strategy: AggregationStrategy) -> dict:
+ word = self.tokenizer.convert_tokens_to_string([entity["word"] for entity in entities])
+ if aggregation_strategy == AggregationStrategy.FIRST:
+ scores = entities[0]["scores"]
+ idx = scores.argmax()
+ score = scores[idx]
+ entity = self.model.config.id2label[idx]
+ elif aggregation_strategy == AggregationStrategy.MAX:
+ max_entity = max(entities, key=lambda entity: entity["scores"].max())
+ scores = max_entity["scores"]
+ idx = scores.argmax()
+ score = scores[idx]
+ entity = self.model.config.id2label[idx]
+ elif aggregation_strategy == AggregationStrategy.AVERAGE:
+ scores = np.stack([entity["scores"] for entity in entities])
+ average_scores = np.nanmean(scores, axis=0)
+ entity_idx = average_scores.argmax()
+ entity = self.model.config.id2label[entity_idx]
+ score = average_scores[entity_idx]
+ else:
+ raise ValueError("Invalid aggregation_strategy")
+ new_entity = {
+ "entity": entity,
+ "score": score,
+ "word": word,
+ "start": entities[0]["start"],
+ "end": entities[-1]["end"],
+ }
+ return new_entity
+
+ def aggregate_words(self, entities: list[dict], aggregation_strategy: AggregationStrategy) -> list[dict]:
+ """
+ Override tokens from a given word that disagree to force agreement on word boundaries.
+
+ Example: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as microsoft|
+ company| B-ENT I-ENT
+ """
+ if aggregation_strategy in {
+ AggregationStrategy.NONE,
+ AggregationStrategy.SIMPLE,
+ }:
+ raise ValueError("NONE and SIMPLE strategies are invalid for word aggregation")
+
+ word_entities = []
+ word_group = None
+ for entity in entities:
+ if word_group is None:
+ word_group = [entity]
+ elif entity["is_subword"]:
+ word_group.append(entity)
+ else:
+ word_entities.append(self.aggregate_word(word_group, aggregation_strategy))
+ word_group = [entity]
+ # Last item
+ if word_group is not None:
+ word_entities.append(self.aggregate_word(word_group, aggregation_strategy))
+ return word_entities
+
+ def group_sub_entities(self, entities: list[dict]) -> dict:
+ """
+ Group together the adjacent tokens with the same entity predicted.
+
+ Args:
+ entities (`dict`): The entities predicted by the pipeline.
+ """
+ # Get the first entity in the entity group
+ entity = entities[0]["entity"].split("-", 1)[-1]
+ scores = np.nanmean([entity["score"] for entity in entities])
+ tokens = [entity["word"] for entity in entities]
+
+ entity_group = {
+ "entity_group": entity,
+ "score": np.mean(scores),
+ "word": self.tokenizer.convert_tokens_to_string(tokens),
+ "start": entities[0]["start"],
+ "end": entities[-1]["end"],
+ }
+ return entity_group
+
+ def get_tag(self, entity_name: str) -> tuple[str, str]:
+ if entity_name.startswith("B-"):
+ bi = "B"
+ tag = entity_name[2:]
+ elif entity_name.startswith("I-"):
+ bi = "I"
+ tag = entity_name[2:]
+ else:
+ # It's not in B-, I- format
+ # Default to I- for continuation.
+ bi = "I"
+ tag = entity_name
+ return bi, tag
+
+ def group_entities(self, entities: list[dict]) -> list[dict]:
+ """
+ Find and group together the adjacent tokens with the same entity predicted.
+
+ Args:
+ entities (`dict`): The entities predicted by the pipeline.
+ """
+
+ entity_groups = []
+ entity_group_disagg = []
+
+ for entity in entities:
+ if not entity_group_disagg:
+ entity_group_disagg.append(entity)
+ continue
+
+ # If the current entity is similar and adjacent to the previous entity,
+ # append it to the disaggregated entity group
+ # The split is meant to account for the "B" and "I" prefixes
+ # Shouldn't merge if both entities are B-type
+ bi, tag = self.get_tag(entity["entity"])
+ last_bi, last_tag = self.get_tag(entity_group_disagg[-1]["entity"])
+
+ if tag == last_tag and bi != "B":
+ # Modify subword type to be previous_type
+ entity_group_disagg.append(entity)
+ else:
+ # If the current entity is different from the previous entity
+ # aggregate the disaggregated entity group
+ entity_groups.append(self.group_sub_entities(entity_group_disagg))
+ entity_group_disagg = [entity]
+ if entity_group_disagg:
+ # it's the last entity, add it to the entity groups
+ entity_groups.append(self.group_sub_entities(entity_group_disagg))
+
+ return entity_groups
+
+
+NerPipeline = TokenClassificationPipeline
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/video_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/video_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e2ff77cbe625707f1860064dc08cf22941bceeb
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/video_classification.py
@@ -0,0 +1,183 @@
+# 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 io import BytesIO
+from typing import Any, overload
+
+import httpx
+
+from ..utils import (
+ add_end_docstrings,
+ is_av_available,
+ is_torch_available,
+ logging,
+ requires_backends,
+)
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_av_available():
+ import av
+ import numpy as np
+
+
+if is_torch_available():
+ from ..models.auto.modeling_auto import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class VideoClassificationPipeline(Pipeline):
+ """
+ Video classification pipeline using any `AutoModelForVideoClassification`. This pipeline predicts the class of a
+ video.
+
+ This video classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"video-classification"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=video-classification).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = False
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ requires_backends(self, "av")
+ self.check_model_type(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES)
+
+ def _sanitize_parameters(self, top_k=None, num_frames=None, frame_sampling_rate=None, function_to_apply=None):
+ preprocess_params = {}
+ if frame_sampling_rate is not None:
+ preprocess_params["frame_sampling_rate"] = frame_sampling_rate
+ if num_frames is not None:
+ preprocess_params["num_frames"] = num_frames
+
+ postprocess_params = {}
+ if top_k is not None:
+ postprocess_params["top_k"] = top_k
+ if function_to_apply is not None:
+ if function_to_apply not in ["softmax", "sigmoid", "none"]:
+ raise ValueError(
+ f"Invalid value for `function_to_apply`: {function_to_apply}. "
+ "Valid options are ['softmax', 'sigmoid', 'none']"
+ )
+ postprocess_params["function_to_apply"] = function_to_apply
+ else:
+ postprocess_params["function_to_apply"] = "softmax"
+ return preprocess_params, {}, postprocess_params
+
+ @overload
+ def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(self, inputs: str | list[str] | None, **kwargs):
+ """
+ Assign labels to the video(s) passed as inputs.
+
+ Args:
+ inputs (`str`, `list[str]`):
+ The pipeline handles three types of videos:
+
+ - A string containing a http link pointing to a video
+ - A string containing a local path to a video
+
+ The pipeline accepts either a single video or a batch of videos, which must then be passed as a string.
+ Videos in a batch must all be in the same format: all as http links or all as local paths.
+ top_k (`int`, *optional*, defaults to 5):
+ The number of top labels that will be returned by the pipeline. If the provided number is higher than
+ the number of labels available in the model configuration, it will default to the number of labels.
+ num_frames (`int`, *optional*, defaults to `self.model.config.num_frames`):
+ The number of frames sampled from the video to run the classification on. If not provided, will default
+ to the number of frames specified in the model configuration.
+ frame_sampling_rate (`int`, *optional*, defaults to 1):
+ The sampling rate used to select frames from the video. If not provided, will default to 1, i.e. every
+ frame will be used.
+ function_to_apply(`str`, *optional*, defaults to "softmax"):
+ The function to apply to the model output. By default, the pipeline will apply the softmax function to
+ the output of the model. Valid options: ["softmax", "sigmoid", "none"]. Note that passing Python's
+ built-in `None` will default to "softmax", so you need to pass the string "none" to disable any
+ post-processing.
+
+ Return:
+ A list of dictionaries or a list of list of dictionaries containing result. If the input is a single video,
+ will return a list of `top_k` dictionaries, if the input is a list of several videos, will return a list of list of
+ `top_k` dictionaries corresponding to the videos.
+
+ The dictionaries contain the following keys:
+
+ - **label** (`str`) -- The label identified by the model.
+ - **score** (`int`) -- The score attributed by the model for that label.
+ """
+ if inputs is None:
+ raise ValueError("Cannot call the video-classification pipeline without an inputs argument!")
+ return super().__call__(inputs, **kwargs)
+
+ def preprocess(self, video, num_frames=None, frame_sampling_rate=1):
+ if num_frames is None:
+ num_frames = self.model.config.num_frames
+
+ if video.startswith("http://") or video.startswith("https://"):
+ video = BytesIO(httpx.get(video, follow_redirects=True).content)
+
+ container = av.open(video)
+
+ start_idx = 0
+ end_idx = num_frames * frame_sampling_rate - 1
+ indices = np.linspace(start_idx, end_idx, num=num_frames, dtype=np.int64)
+
+ video = read_video_pyav(container, indices)
+ video = list(video)
+
+ model_inputs = self.image_processor(video, return_tensors="pt")
+ model_inputs = model_inputs.to(self.dtype)
+ return model_inputs
+
+ def _forward(self, model_inputs):
+ model_outputs = self.model(**model_inputs)
+ return model_outputs
+
+ def postprocess(self, model_outputs, top_k=5, function_to_apply="softmax"):
+ if top_k > self.model.config.num_labels:
+ top_k = self.model.config.num_labels
+
+ if function_to_apply == "softmax":
+ probs = model_outputs.logits[0].softmax(-1)
+ elif function_to_apply == "sigmoid":
+ probs = model_outputs.logits[0].sigmoid()
+ else:
+ probs = model_outputs.logits[0]
+ scores, ids = probs.topk(top_k)
+
+ scores = scores.tolist()
+ ids = ids.tolist()
+ return [{"score": score, "label": self.model.config.id2label[_id]} for score, _id in zip(scores, ids)]
+
+
+def read_video_pyav(container, indices):
+ frames = []
+ container.seek(0)
+ start_index = indices[0]
+ end_index = indices[-1]
+ for i, frame in enumerate(container.decode(video=0)):
+ if i > end_index:
+ break
+ if i >= start_index and i in indices:
+ frames.append(frame)
+ return np.stack([x.to_ndarray(format="rgb24") for x in frames])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_audio_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_audio_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..03c1a8d1c1337bce8897451d72337ae9cfac2dc2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_audio_classification.py
@@ -0,0 +1,160 @@
+# 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.
+from collections import UserDict
+from typing import Any
+
+import httpx
+import numpy as np
+
+from ..utils import (
+ add_end_docstrings,
+ logging,
+)
+from .audio_classification import ffmpeg_read
+from .base import Pipeline, build_pipeline_init_args
+
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_feature_extractor=True, has_tokenizer=True))
+class ZeroShotAudioClassificationPipeline(Pipeline):
+ """
+ Zero shot audio classification pipeline using `ClapModel`. This pipeline predicts the class of an audio when you
+ provide an audio and a set of `candidate_labels`.
+
+
+
+ The default `hypothesis_template` is : `"This is a sound of {}."`. Make sure you update it for your usage.
+
+
+
+ Example:
+ ```python
+ >>> from transformers import pipeline
+ >>> from datasets import load_dataset
+
+ >>> dataset = load_dataset("ashraq/esc50")
+ >>> audio = next(iter(dataset["train"]["audio"]))["array"]
+ >>> classifier = pipeline(task="zero-shot-audio-classification", model="laion/clap-htsat-unfused")
+ >>> classifier(audio, candidate_labels=["Sound of a dog", "Sound of vacuum cleaner"])
+ [{'score': 0.9996, 'label': 'Sound of a dog'}, {'score': 0.0004, 'label': 'Sound of vacuum cleaner'}]
+ ```
+
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) This audio
+ classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"zero-shot-audio-classification"`. See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-audio-classification).
+ """
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = True
+ _load_tokenizer = True
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ def __call__(self, audios: np.ndarray | bytes | str | dict, **kwargs: Any) -> list[dict[str, Any]]:
+ """
+ Assign labels to the audio(s) passed as inputs.
+
+ Args:
+ audios (`str`, `list[str]`, `np.array` or `list[np.array]`):
+ The pipeline handles three types of inputs:
+ - A string containing a http link pointing to an audio
+ - A string containing a local path to an audio
+ - An audio loaded in numpy
+ candidate_labels (`list[str]`):
+ The candidate labels for this audio. They will be formatted using *hypothesis_template*.
+ hypothesis_template (`str`, *optional*, defaults to `"This is a sound of {}"`):
+ The format used in conjunction with *candidate_labels* to attempt the audio classification by
+ replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are
+ already formatted.
+ Return:
+ A list of dictionaries containing one entry per proposed label. Each dictionary contains the
+ following keys:
+ - **label** (`str`) -- One of the suggested *candidate_labels*.
+ - **score** (`float`) -- The score attributed by the model to that label. It is a value between
+ 0 and 1, computed as the `softmax` of `logits_per_audio`.
+ """
+ return super().__call__(audios, **kwargs)
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_params = {}
+ if "candidate_labels" in kwargs:
+ preprocess_params["candidate_labels"] = kwargs["candidate_labels"]
+ if "hypothesis_template" in kwargs:
+ preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
+
+ return preprocess_params, {}, {}
+
+ def preprocess(self, audio, candidate_labels=None, hypothesis_template="This is a sound of {}."):
+ if isinstance(audio, str):
+ if audio.startswith("http://") or audio.startswith("https://"):
+ # We need to actually check for a real protocol, otherwise it's impossible to use a local file
+ # like http_huggingface_co.png
+ audio = httpx.get(audio, follow_redirects=True).content
+ else:
+ with open(audio, "rb") as f:
+ audio = f.read()
+
+ if isinstance(audio, bytes):
+ audio = ffmpeg_read(audio, self.feature_extractor.sampling_rate)
+
+ if not isinstance(audio, np.ndarray):
+ raise TypeError("We expect a numpy ndarray as input")
+ if len(audio.shape) != 1:
+ raise ValueError("We expect a single channel audio input for ZeroShotAudioClassificationPipeline")
+
+ inputs = self.feature_extractor(
+ [audio], sampling_rate=self.feature_extractor.sampling_rate, return_tensors="pt"
+ )
+ inputs = inputs.to(self.dtype)
+ inputs["candidate_labels"] = candidate_labels
+ sequences = [hypothesis_template.format(x) for x in candidate_labels]
+ text_inputs = self.tokenizer(sequences, return_tensors="pt", padding=True)
+ inputs["text_inputs"] = [text_inputs]
+ return inputs
+
+ def _forward(self, model_inputs):
+ candidate_labels = model_inputs.pop("candidate_labels")
+ text_inputs = model_inputs.pop("text_inputs")
+ if isinstance(text_inputs[0], UserDict):
+ text_inputs = text_inputs[0]
+ else:
+ # Batching case.
+ text_inputs = text_inputs[0][0]
+
+ outputs = self.model(**text_inputs, **model_inputs)
+
+ model_outputs = {
+ "candidate_labels": candidate_labels,
+ "logits": outputs.logits_per_audio,
+ }
+ return model_outputs
+
+ def postprocess(self, model_outputs):
+ candidate_labels = model_outputs.pop("candidate_labels")
+ logits = model_outputs["logits"][0]
+
+ probs = logits.softmax(dim=0)
+ scores = probs.tolist()
+
+ result = [
+ {"score": score, "label": candidate_label}
+ for score, candidate_label in sorted(zip(scores, candidate_labels), key=lambda x: -x[0])
+ ]
+ return result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..d88772310de8606235e3e7384476b12723b2c7cd
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_classification.py
@@ -0,0 +1,261 @@
+import inspect
+
+import numpy as np
+
+from ..tokenization_python import TruncationStrategy
+from ..utils import add_end_docstrings, logging
+from .base import ArgumentHandler, ChunkPipeline, build_pipeline_init_args
+
+
+logger = logging.get_logger(__name__)
+
+
+class ZeroShotClassificationArgumentHandler(ArgumentHandler):
+ """
+ Handles arguments for zero-shot for text classification by turning each possible label into an NLI
+ premise/hypothesis pair.
+ """
+
+ def _parse_labels(self, labels):
+ if isinstance(labels, str):
+ labels = [label.strip() for label in labels.split(",") if label.strip()]
+ return labels
+
+ def __call__(self, sequences, labels, hypothesis_template):
+ if len(labels) == 0 or len(sequences) == 0:
+ raise ValueError("You must include at least one label and at least one sequence.")
+ if hypothesis_template.format(labels[0]) == hypothesis_template:
+ raise ValueError(
+ f'The provided hypothesis_template "{hypothesis_template}" was not able to be formatted with the target labels. '
+ "Make sure the passed template includes formatting syntax such as {} where the label should go."
+ )
+
+ if isinstance(sequences, str):
+ sequences = [sequences]
+
+ sequence_pairs = []
+ for sequence in sequences:
+ sequence_pairs.extend([[sequence, hypothesis_template.format(label)] for label in labels])
+
+ return sequence_pairs, sequences
+
+
+@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True))
+class ZeroShotClassificationPipeline(ChunkPipeline):
+ """
+ NLI-based zero-shot classification pipeline using a `ModelForSequenceClassification` trained on NLI (natural
+ language inference) tasks. Equivalent of `text-classification` pipelines, but these models don't require a
+ hardcoded number of potential classes, they can be chosen at runtime. It usually means it's slower but it is
+ **much** more flexible.
+
+ Any combination of sequences and labels can be passed and each combination will be posed as a premise/hypothesis
+ pair and passed to the pretrained model. Then, the logit for *entailment* is taken as the logit for the candidate
+ label being valid. Any NLI model can be used, but the id of the *entailment* label must be included in the model
+ config's :attr:*~transformers.PreTrainedConfig.label2id*.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> oracle = pipeline(model="facebook/bart-large-mnli")
+ >>> oracle(
+ ... "I have a problem with my iphone that needs to be resolved asap!!",
+ ... candidate_labels=["urgent", "not urgent", "phone", "tablet", "computer"],
+ ... )
+ {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['urgent', 'phone', 'computer', 'not urgent', 'tablet'], 'scores': [0.504, 0.479, 0.013, 0.003, 0.002]}
+
+ >>> oracle(
+ ... "I have a problem with my iphone that needs to be resolved asap!!",
+ ... candidate_labels=["english", "german"],
+ ... )
+ {'sequence': 'I have a problem with my iphone that needs to be resolved asap!!', 'labels': ['english', 'german'], 'scores': [0.814, 0.186]}
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This NLI pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"zero-shot-classification"`.
+
+ The models that this pipeline can use are models that have been fine-tuned on an NLI task. See the up-to-date list
+ of available models on [huggingface.co/models](https://huggingface.co/models?search=nli).
+ """
+
+ _load_processor = False
+ _load_image_processor = False
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ def __init__(self, args_parser=ZeroShotClassificationArgumentHandler(), **kwargs):
+ self._args_parser = args_parser
+ super().__init__(**kwargs)
+ if self.entailment_id == -1:
+ logger.warning(
+ "Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to "
+ "-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."
+ )
+
+ @property
+ def entailment_id(self):
+ for label, ind in self.model.config.label2id.items():
+ if label.lower().startswith("entail"):
+ return ind
+ return -1
+
+ def _parse_and_tokenize(
+ self, sequence_pairs, padding=True, add_special_tokens=True, truncation=TruncationStrategy.ONLY_FIRST, **kwargs
+ ):
+ """
+ Parse arguments and tokenize only_first so that hypothesis (label) is not truncated
+ """
+ return_tensors = "pt"
+ if self.tokenizer.pad_token is None:
+ # Override for tokenizers not supporting padding
+ logger.error(
+ "Tokenizer was not supporting padding necessary for zero-shot, attempting to use "
+ " `pad_token=eos_token`"
+ )
+ self.tokenizer.pad_token = self.tokenizer.eos_token
+ try:
+ inputs = self.tokenizer(
+ sequence_pairs,
+ add_special_tokens=add_special_tokens,
+ return_tensors=return_tensors,
+ padding=padding,
+ truncation=truncation,
+ )
+ except Exception as e:
+ if "too short" in str(e):
+ # tokenizers might yell that we want to truncate
+ # to a value that is not even reached by the input.
+ # In that case we don't want to truncate.
+ # It seems there's not a really better way to catch that
+ # exception.
+
+ inputs = self.tokenizer(
+ sequence_pairs,
+ add_special_tokens=add_special_tokens,
+ return_tensors=return_tensors,
+ padding=padding,
+ truncation=TruncationStrategy.DO_NOT_TRUNCATE,
+ )
+ else:
+ raise e
+
+ return inputs
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_params = {}
+ if "candidate_labels" in kwargs:
+ preprocess_params["candidate_labels"] = self._args_parser._parse_labels(kwargs["candidate_labels"])
+ if "hypothesis_template" in kwargs:
+ preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
+
+ postprocess_params = {}
+ if "multi_label" in kwargs:
+ postprocess_params["multi_label"] = kwargs["multi_label"]
+ return preprocess_params, {}, postprocess_params
+
+ def __call__(
+ self,
+ sequences: str | list[str],
+ *args,
+ **kwargs,
+ ):
+ """
+ Classify the sequence(s) given as inputs. See the [`ZeroShotClassificationPipeline`] documentation for more
+ information.
+
+ Args:
+ sequences (`str` or `list[str]`):
+ The sequence(s) to classify, will be truncated if the model input is too large.
+ candidate_labels (`str` or `list[str]`):
+ The set of possible class labels to classify each sequence into. Can be a single label, a string of
+ comma-separated labels, or a list of labels.
+ hypothesis_template (`str`, *optional*, defaults to `"This example is {}."`):
+ The template used to turn each label into an NLI-style hypothesis. This template must include a {} or
+ similar syntax for the candidate label to be inserted into the template. For example, the default
+ template is `"This example is {}."` With the candidate label `"sports"`, this would be fed into the
+ model like `" sequence to classify This example is sports . "`. The default template
+ works well in many cases, but it may be worthwhile to experiment with different templates depending on
+ the task setting.
+ multi_label (`bool`, *optional*, defaults to `False`):
+ Whether or not multiple candidate labels can be true. If `False`, the scores are normalized such that
+ the sum of the label likelihoods for each sequence is 1. If `True`, the labels are considered
+ independent and probabilities are normalized for each candidate by doing a softmax of the entailment
+ score vs. the contradiction score.
+
+ Return:
+ A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys:
+
+ - **sequence** (`str`) -- The sequence for which this is the output.
+ - **labels** (`list[str]`) -- The labels sorted by order of likelihood.
+ - **scores** (`list[float]`) -- The probabilities for each of the labels.
+ """
+ if len(args) == 0:
+ pass
+ elif len(args) == 1 and "candidate_labels" not in kwargs:
+ kwargs["candidate_labels"] = args[0]
+ else:
+ raise ValueError(f"Unable to understand extra arguments {args}")
+
+ return super().__call__(sequences, **kwargs)
+
+ def preprocess(self, inputs, candidate_labels=None, hypothesis_template="This example is {}."):
+ sequence_pairs, sequences = self._args_parser(inputs, candidate_labels, hypothesis_template)
+
+ for i, (candidate_label, sequence_pair) in enumerate(zip(candidate_labels, sequence_pairs)):
+ model_input = self._parse_and_tokenize([sequence_pair])
+
+ yield {
+ "candidate_label": candidate_label,
+ "sequence": sequences[0],
+ "is_last": i == len(candidate_labels) - 1,
+ **model_input,
+ }
+
+ def _forward(self, inputs):
+ candidate_label = inputs["candidate_label"]
+ sequence = inputs["sequence"]
+ model_inputs = {k: inputs[k] for k in self.tokenizer.model_input_names}
+ # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported
+ model_forward = self.model.forward
+ if "use_cache" in inspect.signature(model_forward).parameters:
+ model_inputs["use_cache"] = False
+ outputs = self.model(**model_inputs)
+
+ model_outputs = {
+ "candidate_label": candidate_label,
+ "sequence": sequence,
+ "is_last": inputs["is_last"],
+ **outputs,
+ }
+ return model_outputs
+
+ def postprocess(self, model_outputs, multi_label=False):
+ candidate_labels = [outputs["candidate_label"] for outputs in model_outputs]
+ sequences = [outputs["sequence"] for outputs in model_outputs]
+ logits = np.concatenate([output["logits"].float().numpy() for output in model_outputs])
+ N = logits.shape[0]
+ n = len(candidate_labels)
+ num_sequences = N // n
+ reshaped_outputs = logits.reshape((num_sequences, n, -1))
+
+ if multi_label or len(candidate_labels) == 1:
+ # softmax over the entailment vs. contradiction dim for each label independently
+ entailment_id = self.entailment_id
+ contradiction_id = -1 if entailment_id == 0 else 0
+ entail_contr_logits = reshaped_outputs[..., [contradiction_id, entailment_id]]
+ scores = np.exp(entail_contr_logits) / np.exp(entail_contr_logits).sum(-1, keepdims=True)
+ scores = scores[..., 1]
+ else:
+ # softmax the "entailment" logits over all candidate labels
+ entail_logits = reshaped_outputs[..., self.entailment_id]
+ scores = np.exp(entail_logits) / np.exp(entail_logits).sum(-1, keepdims=True)
+
+ top_inds = list(reversed(scores[0].argsort()))
+ return {
+ "sequence": sequences[0],
+ "labels": [candidate_labels[i] for i in top_inds],
+ "scores": scores[0, top_inds].tolist(),
+ }
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_image_classification.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_image_classification.py
new file mode 100644
index 0000000000000000000000000000000000000000..d129c5836538904b2259e14e23e25267f529165c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_image_classification.py
@@ -0,0 +1,195 @@
+from collections import UserDict
+from typing import Any, Union, overload
+
+from ..utils import (
+ add_end_docstrings,
+ is_torch_available,
+ is_vision_available,
+ logging,
+ requires_backends,
+)
+from .base import Pipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image
+
+if is_torch_available():
+ import torch
+
+ from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES
+
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class ZeroShotImageClassificationPipeline(Pipeline):
+ """
+ Zero shot image classification pipeline using `CLIPModel`. This pipeline predicts the class of an image when you
+ provide an image and a set of `candidate_labels`.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> classifier = pipeline(model="google/siglip-so400m-patch14-384")
+ >>> classifier(
+ ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
+ ... candidate_labels=["animals", "humans", "landscape"],
+ ... )
+ [{'score': 0.965, 'label': 'animals'}, {'score': 0.03, 'label': 'humans'}, {'score': 0.005, 'label': 'landscape'}]
+
+ >>> classifier(
+ ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
+ ... candidate_labels=["black and white", "photorealist", "painting"],
+ ... )
+ [{'score': 0.996, 'label': 'black and white'}, {'score': 0.003, 'label': 'photorealist'}, {'score': 0.0, 'label': 'painting'}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This image classification pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"zero-shot-image-classification"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-image-classification).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ requires_backends(self, "vision")
+ self.check_model_type(MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES)
+
+ @overload
+ def __call__(
+ self, image: Union[str, "Image.Image"], candidate_labels: list[str], **kwargs: Any
+ ) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(
+ self, image: list[str] | list["Image.Image"], candidate_labels: list[str], **kwargs: Any
+ ) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self,
+ image: Union[str, list[str], "Image.Image", list["Image.Image"]],
+ candidate_labels: list[str],
+ **kwargs: Any,
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Assign labels to the image(s) passed as inputs.
+
+ Args:
+ image (`str`, `list[str]`, `PIL.Image` or `list[PIL.Image]`):
+ The pipeline handles three types of images:
+
+ - A string containing a http link pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ candidate_labels (`list[str]`):
+ The candidate labels for this image. They will be formatted using *hypothesis_template*.
+
+ hypothesis_template (`str`, *optional*, defaults to `"This is a photo of {}"`):
+ The format used in conjunction with *candidate_labels* to attempt the image classification by
+ replacing the placeholder with the candidate_labels. Pass "{}" if *candidate_labels* are
+ already formatted.
+
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+ Return:
+ A list of dictionaries containing one entry per proposed label. Each dictionary contains the
+ following keys:
+ - **label** (`str`) -- One of the suggested *candidate_labels*.
+ - **score** (`float`) -- The score attributed by the model to that label. It is a value between
+ 0 and 1, computed as the `softmax` of `logits_per_image`.
+ """
+ # After deprecation of this is completed, remove the default `None` value for `image`
+ if "images" in kwargs:
+ image = kwargs.pop("images")
+ if image is None:
+ raise ValueError("Cannot call the zero-shot-image-classification pipeline without an images argument!")
+ return super().__call__(image, candidate_labels=candidate_labels, **kwargs)
+
+ def _sanitize_parameters(self, tokenizer_kwargs=None, **kwargs):
+ preprocess_params = {}
+ if "candidate_labels" in kwargs:
+ preprocess_params["candidate_labels"] = kwargs["candidate_labels"]
+ if "timeout" in kwargs:
+ preprocess_params["timeout"] = kwargs["timeout"]
+ if "hypothesis_template" in kwargs:
+ preprocess_params["hypothesis_template"] = kwargs["hypothesis_template"]
+
+ return preprocess_params, {}, {}
+
+ def preprocess(
+ self,
+ image,
+ candidate_labels=None,
+ hypothesis_template="This is a photo of {}.",
+ timeout=None,
+ tokenizer_kwargs=None,
+ ):
+ if tokenizer_kwargs is None:
+ tokenizer_kwargs = {}
+ image = load_image(image, timeout=timeout)
+ inputs = self.image_processor(images=[image], return_tensors="pt")
+ inputs = inputs.to(self.dtype)
+ inputs["candidate_labels"] = candidate_labels
+ sequences = [hypothesis_template.format(x) for x in candidate_labels]
+ tokenizer_default_kwargs = {"padding": True}
+ if "siglip" in self.model.config.model_type:
+ tokenizer_default_kwargs.update(padding="max_length", max_length=64, truncation=True)
+ tokenizer_default_kwargs.update(tokenizer_kwargs)
+ text_inputs = self.tokenizer(sequences, return_tensors="pt", **tokenizer_default_kwargs)
+ inputs["text_inputs"] = [text_inputs]
+ return inputs
+
+ def _forward(self, model_inputs):
+ candidate_labels = model_inputs.pop("candidate_labels")
+ text_inputs = model_inputs.pop("text_inputs")
+ if isinstance(text_inputs[0], UserDict):
+ text_inputs = text_inputs[0]
+ else:
+ # Batching case.
+ text_inputs = text_inputs[0][0]
+
+ outputs = self.model(**text_inputs, **model_inputs)
+
+ model_outputs = {
+ "candidate_labels": candidate_labels,
+ "logits": outputs.logits_per_image,
+ }
+ return model_outputs
+
+ def postprocess(self, model_outputs):
+ candidate_labels = model_outputs.pop("candidate_labels")
+ logits = model_outputs["logits"][0]
+ if "siglip" in self.model.config.model_type:
+ probs = torch.sigmoid(logits).squeeze(-1)
+ scores = probs.tolist()
+ if not isinstance(scores, list):
+ scores = [scores]
+ else:
+ probs = logits.softmax(dim=-1).squeeze(-1)
+ scores = probs.tolist()
+ if not isinstance(scores, list):
+ scores = [scores]
+
+ result = [
+ {"score": score, "label": candidate_label}
+ for score, candidate_label in sorted(zip(scores, candidate_labels), key=lambda x: -x[0])
+ ]
+ return result
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_object_detection.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_object_detection.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f353afd7499e100353bd450293fd174183a0e13
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/pipelines/zero_shot_object_detection.py
@@ -0,0 +1,242 @@
+from typing import Any, Union, overload
+
+from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends
+from .base import ChunkPipeline, build_pipeline_init_args
+
+
+if is_vision_available():
+ from PIL import Image
+
+ from ..image_utils import load_image, valid_images
+
+if is_torch_available():
+ import torch
+
+ from transformers.modeling_outputs import BaseModelOutput
+
+ from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES
+
+logger = logging.get_logger(__name__)
+
+
+@add_end_docstrings(build_pipeline_init_args(has_image_processor=True))
+class ZeroShotObjectDetectionPipeline(ChunkPipeline):
+ """
+ Zero shot object detection pipeline using `OwlViTForObjectDetection`. This pipeline predicts bounding boxes of
+ objects when you provide an image and a set of `candidate_labels`.
+
+ Example:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")
+ >>> detector(
+ ... "http://images.cocodataset.org/val2017/000000039769.jpg",
+ ... candidate_labels=["cat", "couch"],
+ ... )
+ [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]
+
+ >>> detector(
+ ... "https://huggingface.co/datasets/Narsil/image_dummy/raw/main/parrots.png",
+ ... candidate_labels=["head", "bird"],
+ ... )
+ [{'score': 0.119, 'label': 'bird', 'box': {'xmin': 71, 'ymin': 170, 'xmax': 410, 'ymax': 508}}]
+ ```
+
+ Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial)
+
+ This object detection pipeline can currently be loaded from [`pipeline`] using the following task identifier:
+ `"zero-shot-object-detection"`.
+
+ See the list of available models on
+ [huggingface.co/models](https://huggingface.co/models?filter=zero-shot-object-detection).
+ """
+
+ _load_processor = False
+ _load_image_processor = True
+ _load_feature_extractor = False
+ _load_tokenizer = True
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+
+ requires_backends(self, "vision")
+ self.check_model_type(MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES)
+
+ @overload
+ def __call__(
+ self, image: Union[str, "Image.Image"], candidate_labels: str | list[str], **kwargs: Any
+ ) -> list[dict[str, Any]]: ...
+
+ @overload
+ def __call__(self, image: list[dict[str, Any]], **kwargs: Any) -> list[list[dict[str, Any]]]: ...
+
+ def __call__(
+ self,
+ image: Union[str, "Image.Image", list[dict[str, Any]]],
+ candidate_labels: str | list[str] | None = None,
+ **kwargs: Any,
+ ) -> list[dict[str, Any]] | list[list[dict[str, Any]]]:
+ """
+ Detect objects (bounding boxes & classes) in the image(s) passed as inputs.
+
+ Args:
+ image (`str`, `PIL.Image` or `list[dict[str, Any]]`):
+ The pipeline handles three types of images:
+
+ - A string containing an http url pointing to an image
+ - A string containing a local path to an image
+ - An image loaded in PIL directly
+
+ You can use this parameter to send directly a list of images, or a dataset or a generator like so:
+
+ ```python
+ >>> from transformers import pipeline
+
+ >>> detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")
+ >>> detector(
+ ... [
+ ... {
+ ... "image": "http://images.cocodataset.org/val2017/000000039769.jpg",
+ ... "candidate_labels": ["cat", "couch"],
+ ... },
+ ... {
+ ... "image": "http://images.cocodataset.org/val2017/000000039769.jpg",
+ ... "candidate_labels": ["cat", "couch"],
+ ... },
+ ... ]
+ ... )
+ [[{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.25, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}], [{'score': 0.287, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}}, {'score': 0.254, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}}, {'score': 0.121, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]]
+ ```
+
+
+ candidate_labels (`str` or `list[str]` or `list[list[str]]`):
+ What the model should recognize in the image.
+
+ threshold (`float`, *optional*, defaults to 0.1):
+ The probability necessary to make a prediction.
+
+ top_k (`int`, *optional*, defaults to None):
+ The number of top predictions that will be returned by the pipeline. If the provided number is `None`
+ or higher than the number of predictions available, it will default to the number of predictions.
+
+ timeout (`float`, *optional*, defaults to None):
+ The maximum time in seconds to wait for fetching images from the web. If None, no timeout is set and
+ the call may block forever.
+
+
+ Return:
+ A list of lists containing prediction results, one list per input image. Each list contains dictionaries
+ with the following keys:
+
+ - **label** (`str`) -- Text query corresponding to the found object.
+ - **score** (`float`) -- Score corresponding to the object (between 0 and 1).
+ - **box** (`dict[str,int]`) -- Bounding box of the detected object in image's original size. It is a
+ dictionary with `x_min`, `x_max`, `y_min`, `y_max` keys.
+ """
+ if "text_queries" in kwargs:
+ candidate_labels = kwargs.pop("text_queries")
+
+ if isinstance(image, (str, Image.Image)):
+ inputs = {"image": image, "candidate_labels": candidate_labels}
+ elif isinstance(image, (list, tuple)) and valid_images(image):
+ return list(
+ super().__call__(
+ ({"image": img, "candidate_labels": labels} for img, labels in zip(image, candidate_labels)),
+ **kwargs,
+ )
+ )
+ else:
+ """
+ Supports the following format
+ - {"image": image, "candidate_labels": candidate_labels}
+ - [{"image": image, "candidate_labels": candidate_labels}]
+ - Generator and datasets
+ This is a common pattern in other multimodal pipelines, so we support it here as well.
+ """
+ inputs = image
+
+ results = super().__call__(inputs, **kwargs)
+ return results
+
+ def _sanitize_parameters(self, **kwargs):
+ preprocess_params = {}
+ if "timeout" in kwargs:
+ preprocess_params["timeout"] = kwargs["timeout"]
+ postprocess_params = {}
+ if "threshold" in kwargs:
+ postprocess_params["threshold"] = kwargs["threshold"]
+ if "top_k" in kwargs:
+ postprocess_params["top_k"] = kwargs["top_k"]
+ return preprocess_params, {}, postprocess_params
+
+ def preprocess(self, inputs, timeout=None):
+ image = load_image(inputs["image"], timeout=timeout)
+ candidate_labels = inputs["candidate_labels"]
+ if isinstance(candidate_labels, str):
+ candidate_labels = candidate_labels.split(",")
+
+ target_size = torch.tensor([[image.height, image.width]], dtype=torch.int32)
+ for i, candidate_label in enumerate(candidate_labels):
+ text_inputs = self.tokenizer(candidate_label, return_tensors="pt")
+ image_features = self.image_processor(image, return_tensors="pt")
+ image_features = image_features.to(self.dtype)
+ yield {
+ "is_last": i == len(candidate_labels) - 1,
+ "target_size": target_size,
+ "candidate_label": candidate_label,
+ **text_inputs,
+ **image_features,
+ }
+
+ def _forward(self, model_inputs):
+ target_size = model_inputs.pop("target_size")
+ candidate_label = model_inputs.pop("candidate_label")
+ is_last = model_inputs.pop("is_last")
+
+ outputs = self.model(**model_inputs)
+
+ model_outputs = {"target_size": target_size, "candidate_label": candidate_label, "is_last": is_last, **outputs}
+ return model_outputs
+
+ def postprocess(self, model_outputs, threshold=0.1, top_k=None):
+ results = []
+ for model_output in model_outputs:
+ label = model_output["candidate_label"]
+ model_output = BaseModelOutput(model_output)
+ outputs = self.image_processor.post_process_object_detection(
+ outputs=model_output, threshold=threshold, target_sizes=model_output["target_size"]
+ )[0]
+
+ for index in outputs["scores"].nonzero():
+ score = outputs["scores"][index].item()
+ box = self._get_bounding_box(outputs["boxes"][index][0])
+
+ result = {"score": score, "label": label, "box": box}
+ results.append(result)
+
+ results = sorted(results, key=lambda x: x["score"], reverse=True)
+ if top_k:
+ results = results[:top_k]
+
+ return results
+
+ def _get_bounding_box(self, box: "torch.Tensor") -> dict[str, int]:
+ """
+ Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... }
+
+ Args:
+ box (`torch.Tensor`): Tensor containing the coordinates in corners format.
+
+ Returns:
+ bbox (`dict[str, int]`): Dict containing the coordinates in corners format.
+ """
+ xmin, ymin, xmax, ymax = box.int().tolist()
+ bbox = {
+ "xmin": xmin,
+ "ymin": ymin,
+ "xmax": xmax,
+ "ymax": ymax,
+ }
+ return bbox
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7117bc2b5d8045380f582ac09338af3f3f3e3f61
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__init__.py
@@ -0,0 +1,16 @@
+# 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.
+from .auto import AutoHfQuantizer, AutoQuantizationConfig, register_quantization_config, register_quantizer
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..94ea654126f89b9c97428665d7cdbb9534feb56e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/auto.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/auto.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..ec8587e7de8b4f372f29ea9710330ead92a40bf7
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/auto.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/base.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/base.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..789ea984103002f8c6226d7b745332cc985ffe11
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/base.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_aqlm.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_aqlm.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..888e8a7a0a51e40d9f1e45d723d68673ffe221fd
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_aqlm.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_auto_round.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_auto_round.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a26348ec3aa87acfd068f7cd9d91de54726ec9eb
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_auto_round.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_awq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_awq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..735d6f0e214bb12f0aaecbf03039be6382a027da
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_awq.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bitnet.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bitnet.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..481abb8c39b4ec846fa68939903523f6dfda2fc3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bitnet.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_4bit.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_4bit.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..76101e36cacb3685687a9b33aad1b541cffbb653
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_4bit.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_8bit.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_8bit.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e11d5a387b9a2cc91d1767295f5232716360a759
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_bnb_8bit.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_compressed_tensors.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_compressed_tensors.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c70ff2c365629a1314a44a9f032eed17445d5516
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_compressed_tensors.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_eetq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_eetq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8768a1c204bfce1be76b3ab1e01fd621f3a7e4e8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_eetq.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fbgemm_fp8.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fbgemm_fp8.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5e1df94a3508fd39fe97a7350aa3ecd143eba10c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fbgemm_fp8.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_finegrained_fp8.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_finegrained_fp8.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..8a69e8252033f37d9d49bfdc57827540a229cb25
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_finegrained_fp8.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fouroversix.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fouroversix.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c694b90b8dbe1590f0e64db68f1840fee5dfb068
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fouroversix.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fp_quant.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fp_quant.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..2ada08ec1e12bdee8a6376d88f6f9a2ba6dda5f6
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_fp_quant.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_gptq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_gptq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa4d762af8883eca756840283bb303282253d8b5
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_gptq.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_higgs.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_higgs.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d338b1ca48e57860cab1f772b1e408f24736e1c8
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_higgs.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_hqq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_hqq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f0d4ac9c96d9fb38b580d56a9776c98d519afd3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_hqq.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_metal.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_metal.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..07c2c6f998bc152f8d2d5df529efe7435cbf280f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_metal.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_mxfp4.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_mxfp4.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e32d28383983be5259641aad666f45d3cb0d1a45
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_mxfp4.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quanto.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quanto.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..20ec396f6049ac738aed4746d62a98286967b381
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quanto.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quark.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quark.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..270ec286580829edc1be0465dc9b3e303fc07210
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_quark.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_sinq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_sinq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d6d6a097306de93c66678aeff7df849f06b9c211
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_sinq.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_spqr.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_spqr.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..3b45291bef06ca396c79beeffcc3b0d274ba577a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_spqr.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_torchao.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_torchao.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..cf82220d77b87121a610517304bf45757d8cb20d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_torchao.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_vptq.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_vptq.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..04b170ff6f7e3e796bc36e84a6d049c6d798ff50
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizer_vptq.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizers_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizers_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..084b78a1a326ba35e2def9eb8ff72d4bd3480276
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/__pycache__/quantizers_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/auto.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/auto.py
new file mode 100644
index 0000000000000000000000000000000000000000..a972c6f637bb23092426e42a04be3753c97f58b5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/auto.py
@@ -0,0 +1,354 @@
+# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
+# Modifications Copyright (C) 2025, Advanced Micro Devices, Inc. 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 warnings
+
+from ..models.auto.configuration_auto import AutoConfig
+from ..utils import logging
+from ..utils.quantization_config import (
+ AqlmConfig,
+ AutoRoundConfig,
+ AwqConfig,
+ BitNetQuantConfig,
+ BitsAndBytesConfig,
+ CompressedTensorsConfig,
+ EetqConfig,
+ FbgemmFp8Config,
+ FineGrainedFP8Config,
+ FourOverSixConfig,
+ FPQuantConfig,
+ GPTQConfig,
+ HiggsConfig,
+ HqqConfig,
+ MetalConfig,
+ Mxfp4Config,
+ QuantizationConfigMixin,
+ QuantizationMethod,
+ QuantoConfig,
+ QuarkConfig,
+ SinqConfig,
+ SpQRConfig,
+ TorchAoConfig,
+ VptqConfig,
+)
+from .base import HfQuantizer
+from .quantizer_aqlm import AqlmHfQuantizer
+from .quantizer_auto_round import AutoRoundQuantizer
+from .quantizer_awq import AwqQuantizer
+from .quantizer_bitnet import BitNetHfQuantizer
+from .quantizer_bnb_4bit import Bnb4BitHfQuantizer
+from .quantizer_bnb_8bit import Bnb8BitHfQuantizer
+from .quantizer_compressed_tensors import CompressedTensorsHfQuantizer
+from .quantizer_eetq import EetqHfQuantizer
+from .quantizer_fbgemm_fp8 import FbgemmFp8HfQuantizer
+from .quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer
+from .quantizer_fouroversix import FourOverSixHfQuantizer
+from .quantizer_fp_quant import FPQuantHfQuantizer
+from .quantizer_gptq import GptqHfQuantizer
+from .quantizer_higgs import HiggsHfQuantizer
+from .quantizer_hqq import HqqHfQuantizer
+from .quantizer_metal import MetalHfQuantizer
+from .quantizer_mxfp4 import Mxfp4HfQuantizer
+from .quantizer_quanto import QuantoHfQuantizer
+from .quantizer_quark import QuarkHfQuantizer
+from .quantizer_sinq import SinqHfQuantizer
+from .quantizer_spqr import SpQRHfQuantizer
+from .quantizer_torchao import TorchAoHfQuantizer
+from .quantizer_vptq import VptqHfQuantizer
+
+
+AUTO_QUANTIZER_MAPPING = {
+ "awq": AwqQuantizer,
+ "bitsandbytes_4bit": Bnb4BitHfQuantizer,
+ "bitsandbytes_8bit": Bnb8BitHfQuantizer,
+ "gptq": GptqHfQuantizer,
+ "aqlm": AqlmHfQuantizer,
+ "quanto": QuantoHfQuantizer,
+ "quark": QuarkHfQuantizer,
+ "fouroversix": FourOverSixHfQuantizer,
+ "fp_quant": FPQuantHfQuantizer,
+ "eetq": EetqHfQuantizer,
+ "higgs": HiggsHfQuantizer,
+ "hqq": HqqHfQuantizer,
+ "compressed-tensors": CompressedTensorsHfQuantizer,
+ "fbgemm_fp8": FbgemmFp8HfQuantizer,
+ "torchao": TorchAoHfQuantizer,
+ "bitnet": BitNetHfQuantizer,
+ "vptq": VptqHfQuantizer,
+ "spqr": SpQRHfQuantizer,
+ "fp8": FineGrainedFP8HfQuantizer,
+ "auto-round": AutoRoundQuantizer,
+ "mxfp4": Mxfp4HfQuantizer,
+ "metal": MetalHfQuantizer,
+ "sinq": SinqHfQuantizer,
+}
+
+AUTO_QUANTIZATION_CONFIG_MAPPING = {
+ "awq": AwqConfig,
+ "bitsandbytes_4bit": BitsAndBytesConfig,
+ "bitsandbytes_8bit": BitsAndBytesConfig,
+ "eetq": EetqConfig,
+ "gptq": GPTQConfig,
+ "aqlm": AqlmConfig,
+ "quanto": QuantoConfig,
+ "quark": QuarkConfig,
+ "fouroversix": FourOverSixConfig,
+ "fp_quant": FPQuantConfig,
+ "hqq": HqqConfig,
+ "compressed-tensors": CompressedTensorsConfig,
+ "fbgemm_fp8": FbgemmFp8Config,
+ "higgs": HiggsConfig,
+ "torchao": TorchAoConfig,
+ "bitnet": BitNetQuantConfig,
+ "vptq": VptqConfig,
+ "spqr": SpQRConfig,
+ "fp8": FineGrainedFP8Config,
+ "auto-round": AutoRoundConfig,
+ "mxfp4": Mxfp4Config,
+ "metal": MetalConfig,
+ "sinq": SinqConfig,
+}
+
+LOADING_ATTRIBUTES_CONFIG_TYPES = (
+ GPTQConfig,
+ AwqConfig,
+ AutoRoundConfig,
+ FbgemmFp8Config,
+ CompressedTensorsConfig,
+ Mxfp4Config,
+ MetalConfig,
+ FineGrainedFP8Config,
+)
+
+logger = logging.get_logger(__name__)
+
+
+class AutoQuantizationConfig:
+ """
+ The Auto-HF quantization config class that takes care of automatically dispatching to the correct
+ quantization config given a quantization config stored in a dictionary.
+ """
+
+ @classmethod
+ def from_dict(cls, quantization_config_dict: dict):
+ quant_method = quantization_config_dict.get("quant_method")
+ # We need a special care for bnb models to make sure everything is BC ..
+ if quantization_config_dict.get("load_in_8bit", False) or quantization_config_dict.get("load_in_4bit", False):
+ suffix = "_4bit" if quantization_config_dict.get("load_in_4bit", False) else "_8bit"
+ quant_method = QuantizationMethod.BITS_AND_BYTES + suffix
+ elif quant_method is None:
+ raise ValueError(
+ "The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized"
+ )
+
+ if quant_method not in AUTO_QUANTIZATION_CONFIG_MAPPING:
+ raise ValueError(
+ f"Unknown quantization type, got {quant_method} - supported types are:"
+ f" {list(AUTO_QUANTIZER_MAPPING.keys())}"
+ )
+
+ target_cls = AUTO_QUANTIZATION_CONFIG_MAPPING[quant_method]
+ return target_cls.from_dict(quantization_config_dict)
+
+ @classmethod
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
+ model_config = AutoConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
+ if getattr(model_config, "quantization_config", None) is None:
+ raise ValueError(
+ f"Did not found a `quantization_config` in {pretrained_model_name_or_path}. Make sure that the model is correctly quantized."
+ )
+ quantization_config_dict = model_config.quantization_config
+ quantization_config = cls.from_dict(quantization_config_dict)
+ # Update with potential kwargs that are passed through from_pretrained.
+ quantization_config.update(**kwargs)
+ return quantization_config
+
+
+class AutoHfQuantizer:
+ """
+ The Auto-HF quantizer class that takes care of automatically instantiating to the correct
+ `HfQuantizer` given the `QuantizationConfig`.
+ """
+
+ @classmethod
+ def from_config(cls, quantization_config: QuantizationConfigMixin | dict, **kwargs):
+ # Convert it to a QuantizationConfig if the q_config is a dict
+ if isinstance(quantization_config, dict):
+ quantization_config = AutoQuantizationConfig.from_dict(quantization_config)
+
+ quant_method = quantization_config.quant_method
+
+ # Again, we need a special care for bnb as we have a single quantization config
+ # class for both 4-bit and 8-bit quantization
+ if quant_method == QuantizationMethod.BITS_AND_BYTES:
+ if not isinstance(quantization_config, BitsAndBytesConfig):
+ raise TypeError(
+ "Found `quant_method=bitsandbytes` but `quantization_config` is not a `BitsAndBytesConfig`."
+ )
+ if quantization_config.load_in_8bit:
+ quant_method += "_8bit"
+ else:
+ quant_method += "_4bit"
+
+ if quant_method not in AUTO_QUANTIZER_MAPPING:
+ raise ValueError(
+ f"Unknown quantization type, got {quant_method} - supported types are:"
+ f" {list(AUTO_QUANTIZER_MAPPING.keys())}"
+ )
+
+ target_cls = AUTO_QUANTIZER_MAPPING[quant_method]
+ return target_cls(quantization_config, **kwargs)
+
+ @classmethod
+ def from_pretrained(cls, pretrained_model_name_or_path, **kwargs):
+ quantization_config = AutoQuantizationConfig.from_pretrained(pretrained_model_name_or_path, **kwargs)
+ return cls.from_config(quantization_config)
+
+ @classmethod
+ def merge_quantization_configs(
+ cls,
+ quantization_config: dict | QuantizationConfigMixin,
+ quantization_config_from_args: QuantizationConfigMixin | None,
+ ):
+ """
+ handles situations where both quantization_config from args and quantization_config from model config are present.
+ """
+ if quantization_config_from_args is not None:
+ warning_msg = (
+ "You passed `quantization_config` or equivalent parameters to `from_pretrained` but the model you're loading"
+ " already has a `quantization_config` attribute. The `quantization_config` from the model will be used."
+ )
+ else:
+ warning_msg = ""
+
+ if isinstance(quantization_config, dict):
+ # Convert the config based on the type of quantization_config_from_args (e.g., AutoRoundConfig), which takes priority before automatic configuration dispatch.
+ if isinstance(quantization_config_from_args, AutoRoundConfig):
+ quantization_config = AutoRoundConfig.from_dict(quantization_config)
+ else:
+ quantization_config = AutoQuantizationConfig.from_dict(quantization_config)
+
+ if (
+ quantization_config_from_args is not None
+ and quantization_config.__class__.__name__ != quantization_config_from_args.__class__.__name__
+ ):
+ raise ValueError(
+ f"The model is quantized with {quantization_config.__class__.__name__} but you are passing a {quantization_config_from_args.__class__.__name__} config. "
+ "Please make sure to pass the same quantization config class to `from_pretrained` with different loading attributes."
+ )
+
+ if isinstance(quantization_config, LOADING_ATTRIBUTES_CONFIG_TYPES) and isinstance(
+ quantization_config_from_args, LOADING_ATTRIBUTES_CONFIG_TYPES
+ ):
+ loading_attr_dict = quantization_config_from_args.get_loading_attributes()
+ for attr, val in loading_attr_dict.items():
+ setattr(quantization_config, attr, val)
+
+ if loading_attr_dict:
+ warning_msg += f"However, loading attributes (e.g. {list(loading_attr_dict.keys())}) will be overwritten with the one you passed to `from_pretrained`. The rest will be ignored."
+
+ if warning_msg != "" and not isinstance(quantization_config, (Mxfp4Config, MetalConfig, FineGrainedFP8Config)):
+ warnings.warn(warning_msg)
+ else:
+ # in the case of mxfp4, we don't want to print the warning message, bit confusing for users
+ logger.info(warning_msg)
+ return quantization_config
+
+ @staticmethod
+ def supports_quant_method(quantization_config_dict):
+ quant_method = quantization_config_dict.get("quant_method", None)
+ if quantization_config_dict.get("load_in_8bit", False) or quantization_config_dict.get("load_in_4bit", False):
+ suffix = "_4bit" if quantization_config_dict.get("load_in_4bit", False) else "_8bit"
+ quant_method = QuantizationMethod.BITS_AND_BYTES + suffix
+ elif quant_method is None:
+ raise ValueError(
+ "The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized"
+ )
+
+ if quant_method not in AUTO_QUANTIZATION_CONFIG_MAPPING:
+ logger.warning(
+ f"Unknown quantization type, got {quant_method} - supported types are:"
+ f" {list(AUTO_QUANTIZER_MAPPING.keys())}. Hence, we will skip the quantization. "
+ "To remove the warning, you can delete the quantization_config attribute in config.json"
+ )
+ return False
+ return True
+
+
+def register_quantization_config(method: str):
+ """Register a custom quantization configuration."""
+
+ def register_config_fn(cls):
+ if method in AUTO_QUANTIZATION_CONFIG_MAPPING:
+ raise ValueError(f"Config '{method}' already registered")
+
+ if not issubclass(cls, QuantizationConfigMixin):
+ raise TypeError("Config must extend QuantizationConfigMixin")
+
+ AUTO_QUANTIZATION_CONFIG_MAPPING[method] = cls
+ return cls
+
+ return register_config_fn
+
+
+def register_quantizer(name: str):
+ """Register a custom quantizer."""
+
+ def register_quantizer_fn(cls):
+ if name in AUTO_QUANTIZER_MAPPING:
+ raise ValueError(f"Quantizer '{name}' already registered")
+
+ if not issubclass(cls, HfQuantizer):
+ raise TypeError("Quantizer must extend HfQuantizer")
+
+ AUTO_QUANTIZER_MAPPING[name] = cls
+ return cls
+
+ return register_quantizer_fn
+
+
+def get_hf_quantizer(config, quantization_config, device_map, weights_only, user_agent):
+ pre_quantized = hasattr(config, "quantization_config")
+ if pre_quantized and not AutoHfQuantizer.supports_quant_method(config.quantization_config):
+ pre_quantized = False
+
+ if pre_quantized or quantization_config is not None:
+ if pre_quantized:
+ config.quantization_config = AutoHfQuantizer.merge_quantization_configs(
+ config.quantization_config, quantization_config
+ )
+ else:
+ config.quantization_config = quantization_config
+
+ hf_quantizer = AutoHfQuantizer.from_config(
+ config.quantization_config,
+ pre_quantized=pre_quantized,
+ )
+ else:
+ hf_quantizer = None
+
+ if hf_quantizer is not None:
+ hf_quantizer.validate_environment(
+ device_map=device_map,
+ weights_only=weights_only,
+ )
+ device_map = hf_quantizer.update_device_map(device_map)
+ config = hf_quantizer.update_tp_plan(config)
+ config = hf_quantizer.update_ep_plan(config)
+
+ # In order to ensure popular quantization methods are supported. Can be disable with `disable_telemetry`
+ if not getattr(hf_quantizer.quantization_config, "dequantize", False):
+ quant_method = hf_quantizer.quantization_config.quant_method
+ user_agent["quant"] = getattr(quant_method, "value", quant_method)
+ return hf_quantizer, config, device_map
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/base.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..fbebea2977bebfbcdea00fa2fd74e4cb0d689f16
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/base.py
@@ -0,0 +1,342 @@
+# 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.
+from abc import ABC, abstractmethod
+from typing import TYPE_CHECKING, Any
+
+from ..utils import is_torch_available, logging
+from ..utils.quantization_config import QuantizationConfigMixin, QuantizationMethod
+from .quantizers_utils import get_module_from_name
+
+
+if TYPE_CHECKING:
+ from torch.nn import ModuleList
+
+ from ..modeling_utils import PreTrainedModel
+
+if is_torch_available():
+ import torch
+
+ if not TYPE_CHECKING:
+ from torch.nn import ModuleList
+else:
+ ModuleList = str
+
+logger = logging.get_logger(__file__)
+
+
+def get_keys_to_not_convert(model) -> list:
+ r"""
+ Function to automatically detect keys to not convert for usage like quantization. For example for CausalLM modules
+ we may want to keep the lm_head in full precision for numerical stability reasons.
+ """
+ # remove tied weights
+ tied_keys = set()
+ if len(model.all_tied_weights_keys) > 0:
+ tied_keys = set(model.all_tied_weights_keys.values()) | set(model.all_tied_weights_keys.keys())
+
+ # remove last module
+ last_module_key = {list(model.named_parameters())[-1][0]}
+
+ # remove output emb
+ output_emb_module = model.get_output_embeddings()
+ output_emb_keys = {
+ name
+ for name, module in model.named_modules()
+ if output_emb_module is not None and id(module) == id(output_emb_module)
+ }
+ modules_to_not_convert = tied_keys | last_module_key | output_emb_keys
+
+ modules_to_not_convert = list({k.removesuffix(".weight") for k in modules_to_not_convert})
+
+ return list(modules_to_not_convert)
+
+
+def _assign_is_quantized(model):
+ from ..modeling_utils import PreTrainedModel
+
+ for module in model.modules():
+ if isinstance(module, PreTrainedModel):
+ module.config._is_quantized = True
+
+
+class HfQuantizer(ABC):
+ """
+ Abstract class of the HuggingFace quantizer. Supports for now quantizing HF transformers models for inference and/or quantization.
+ This class is used only for transformers.PreTrainedModel.from_pretrained and cannot be easily used outside the scope of that method
+ yet.
+
+ Attributes
+ quantization_config (`transformers.utils.quantization_config.QuantizationConfigMixin`):
+ The quantization config that defines the quantization parameters of your model that you want to quantize.
+ requires_calibration (`bool`):
+ Whether the quantization method requires to calibrate the model before using it.
+ """
+
+ requires_calibration = False
+
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
+ self.quantization_config = quantization_config
+ self.pre_quantized = kwargs.pop("pre_quantized", True)
+
+ if not self.pre_quantized and self.requires_calibration:
+ raise ValueError(
+ f"The quantization method {quantization_config.quant_method} does require the model to be pre-quantized."
+ f" You explicitly passed `pre_quantized=False` meaning your model weights are not quantized. Make sure to "
+ f"pass `pre_quantized=True` while knowing what you are doing."
+ )
+
+ def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
+ """
+ Some quantization methods require to explicitly set the dtype of the model to a
+ target dtype. You need to override this method in case you want to make sure that behavior is
+ preserved
+
+ Args:
+ dtype (`torch.dtype`):
+ The input dtype that is passed in `from_pretrained`
+ """
+ return dtype
+
+ def update_device_map(self, device_map: dict[str, Any] | None) -> dict[str, Any] | None:
+ """
+ Override this method if you want to pass a override the existing device map with a new
+ one. E.g. for bitsandbytes, since `accelerate` is a hard requirement, if no device_map is
+ passed, the device_map is set to `"auto"``
+
+ Args:
+ device_map (`Union[dict, str]`, *optional*):
+ The device_map that is passed through the `from_pretrained` method.
+ """
+ return device_map
+
+ def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float:
+ return param.element_size()
+
+ def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]:
+ """adjust max_memory argument for infer_auto_device_map() if extra memory is needed for quantization"""
+ return max_memory
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ """
+ Check whether a given param needs to be quantized.
+ """
+ return False
+
+ def validate_environment(self, *args, **kwargs):
+ """
+ This method is used to potentially check for potential conflicts with arguments that are
+ passed in `from_pretrained`. You need to define it for all future quantizers that are integrated with transformers.
+ If no explicit check are needed, simply return nothing.
+ """
+ return
+
+ def update_tp_plan(self, config):
+ "updates the tp plan for the scales"
+ return config
+
+ def update_ep_plan(self, config):
+ "updates the tp plan for the scales"
+ return config
+
+ def _process_model_before_weight_loading(self, model, **kwargs):
+ return model
+
+ def preprocess_model(self, model: "PreTrainedModel", dtype=None, **kwargs):
+ """
+ Setting model attributes and/or converting model before weights loading. At this point
+ the model should be initialized on the meta device so you can freely manipulate the skeleton
+ of the model in order to replace modules in-place. Make sure to override the abstract method `_process_model_before_weight_loading`.
+
+ Args:
+ model (`~transformers.PreTrainedModel`):
+ The model to quantize
+ kwargs (`dict`, *optional*):
+ The keyword arguments that are passed along `_process_model_before_weight_loading`.
+ """
+ setattr(model, "is_quantized", True)
+ setattr(model, "quantization_method", self.quantization_config.quant_method)
+ if self.pre_quantized:
+ self._convert_model_for_quantization(model)
+ self._process_model_before_weight_loading(model, **kwargs)
+
+ def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ return model
+
+ def postprocess_model(self, model: "PreTrainedModel", **kwargs):
+ """
+ Post-process the model post weights loading.
+ Make sure to override the abstract method `_process_model_after_weight_loading`.
+
+ Args:
+ model (`~transformers.PreTrainedModel`):
+ The model to quantize
+ kwargs (`dict`, *optional*):
+ The keyword arguments that are passed along `_process_model_after_weight_loading`.
+ """
+ model.config.quantization_config = self.quantization_config
+
+ if self.pre_quantized and getattr(self.quantization_config, "dequantize", False):
+ self.remove_quantization_config(model)
+ else:
+ _assign_is_quantized(model)
+
+ return self._process_model_after_weight_loading(model, **kwargs)
+
+ def remove_quantization_config(self, model):
+ """
+ Remove the quantization config from the model.
+ """
+ if hasattr(model, "hf_quantizer"):
+ del model.hf_quantizer
+ if hasattr(model.config, "quantization_config"):
+ del model.config.quantization_config
+ if hasattr(model, "quantization_method"):
+ del model.quantization_method
+ model.is_quantized = False
+
+ def dequantize(self, model, dtype=None):
+ """
+ Potentially dequantize the model to retrieve the original model, with some loss in accuracy / performance.
+ Note not all quantization schemes support this.
+ """
+ if dtype is None:
+ # using the same dtype we used to load the model. If we don't do that, we might have issues with modules we didn't quantize.
+ # or we need to upcast everything to the same dtype
+ dtype = model.config.dtype
+ model = self._dequantize(model, dtype=dtype)
+ self.remove_quantization_config(model)
+
+ return model
+
+ def _dequantize(self, model, dtype=None):
+ raise NotImplementedError(
+ f"{self.quantization_config.quant_method} has no implementation of `dequantize`, please raise an issue on GitHub."
+ )
+
+ def get_param_name(self, param_name: str) -> str:
+ """
+ Override this method if you want to adjust the `param_name`.
+ """
+ return param_name
+
+ @staticmethod
+ def get_modules_to_not_convert(
+ model: "PreTrainedModel",
+ skip_modules: list[str] | None = None,
+ keep_in_fp32_modules: list[str] | None = None,
+ add_default_skips: bool = False,
+ ):
+ if skip_modules is None or add_default_skips:
+ modules_to_not_convert = get_keys_to_not_convert(model)
+ else:
+ modules_to_not_convert = []
+
+ if skip_modules is not None:
+ modules_to_not_convert.extend(skip_modules)
+
+ if keep_in_fp32_modules is not None:
+ modules_to_not_convert.extend(keep_in_fp32_modules)
+
+ modules_to_not_convert = list(set(modules_to_not_convert))
+
+ return modules_to_not_convert
+
+ @property
+ def is_qat_trainable(self) -> bool:
+ """Flag indicating whether the quantized model can carry out quantization aware training"""
+ return False
+
+ @property
+ def is_compileable(self) -> bool:
+ """Flag indicating whether the quantized model can be compiled"""
+ return False
+
+ def get_state_dict_and_metadata(self, model):
+ """Get state dict and metadata. Useful when we need to modify a bit the state dict due to quantization"""
+ return None, {}
+
+ @abstractmethod
+ def is_serializable(self): ...
+
+ @property
+ @abstractmethod
+ def is_trainable(self): ...
+
+ def _convert_model_for_quantization(self, model):
+ for name, module in model.named_modules():
+ module_class_name = module.__class__.__name__
+ if module_class_name in MODULES_TO_PATCH_FOR_QUANTIZATION and (
+ self.quantization_config.quant_method
+ in MODULES_TO_PATCH_FOR_QUANTIZATION[module_class_name]["quantization_methods"]
+ ):
+ with torch.device("meta"):
+ parent_module, name = get_module_from_name(model, name)
+ parent_module._modules[name] = MODULES_TO_PATCH_FOR_QUANTIZATION[module_class_name]["module_name"](
+ model.config.get_text_config()
+ )
+
+ def get_quantize_ops(self):
+ raise NotImplementedError(
+ f"{self.quantization_config.quant_method} is not available yet and will be supported soon."
+ )
+
+ def get_weight_conversions(self):
+ return []
+
+ def update_weight_conversions(self, weight_conversions):
+ """Give the quantizer a chance to rewrite the weight conversion pipeline.
+
+ Loading runs ``renamings → converters → (dequant → merge → concat)``. Dequant
+ has to happen *before* any merge/concat op because those operations aren't
+ aware of per-block scales, so the per-expert (weight, scale) pairs need to be
+ collapsed into full-precision tensors first. Subclasses (e.g. the FP8
+ quantizer in ``dequantize=True`` mode) override this to inject a dequantize
+ op at the start of each model-provided :class:`WeightConverter` and attach the
+ matching scale source patterns. Default: no-op.
+ """
+ return weight_conversions + self.get_weight_conversions()
+
+
+class SequentialLlama4TextExperts(ModuleList):
+ """
+ A module that implements a compressed version of a list of expert modules.
+ This is specifically designed to work with Llama4TextExperts in MoE layers.
+ """
+
+ def __init__(self, config):
+ from transformers.models.llama4.modeling_llama4 import Llama4TextMLP
+
+ super().__init__([Llama4TextMLP(config) for _ in range(config.num_local_experts)])
+ self.num_experts = config.num_local_experts
+
+ def forward(
+ self,
+ hidden_states: "torch.Tensor",
+ ) -> "torch.Tensor":
+ hidden_states = hidden_states.reshape(self.num_experts, -1, hidden_states.shape[-1])
+ routed_out = torch.zeros_like(hidden_states)
+ for expert_idx in range(self.num_experts):
+ routed_out[expert_idx] = self[expert_idx](hidden_states[expert_idx])
+ return routed_out
+
+
+MODULES_TO_PATCH_FOR_QUANTIZATION = {
+ "Llama4TextExperts": {
+ "module_name": SequentialLlama4TextExperts,
+ "quantization_methods": [
+ QuantizationMethod.COMPRESSED_TENSORS,
+ QuantizationMethod.BITS_AND_BYTES,
+ ],
+ }
+}
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_aqlm.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_aqlm.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d0fd7939d88ad4a417b5f92772f04de7f4fbc95
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_aqlm.py
@@ -0,0 +1,75 @@
+# 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.
+from importlib import metadata
+from typing import TYPE_CHECKING
+
+from packaging import version
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import AqlmConfig
+
+from ..integrations import replace_with_aqlm_linear
+from ..utils import is_accelerate_available, is_aqlm_available, logging
+from ..utils.quantization_config import QuantizationConfigMixin
+
+
+logger = logging.get_logger(__name__)
+
+
+class AqlmHfQuantizer(HfQuantizer):
+ """
+ Quantizer of the AQLM method. Enables the loading of prequantized models.
+ """
+
+ requires_calibration = True
+ quantization_config: "AqlmConfig"
+
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_accelerate_available():
+ raise ImportError("Using `aqlm` quantization requires Accelerate: `pip install accelerate`")
+
+ if not is_aqlm_available():
+ raise ImportError("Using `aqlm` quantization requires AQLM: `pip install aqlm[gpu,cpu]`")
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ **kwargs,
+ ):
+ replace_with_aqlm_linear(
+ model,
+ modules_to_not_convert=self.quantization_config.linear_weights_not_to_quantize,
+ quantization_config=self.quantization_config,
+ )
+
+ @property
+ def is_trainable(self) -> bool:
+ aqlm_supports_training = version.parse(metadata.version("aqlm")) >= version.parse("1.0.2")
+ if aqlm_supports_training:
+ return True
+ else:
+ logger.warning(
+ f"Currently installed `aqlm` version ({metadata.version('aqlm')}) doesn't support training. If you wish to train a quantized model, please update `aqlm` with `pip install aqlm>=1.0.2`"
+ )
+ return False
+
+ def is_serializable(self):
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_auto_round.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_auto_round.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a52314013066b21fb90ed5646e101ec7d67cd09
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_auto_round.py
@@ -0,0 +1,71 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+
+from ..utils import is_auto_round_available, logging
+from ..utils.quantization_config import QuantizationConfigMixin
+
+
+logger = logging.get_logger(__name__)
+
+
+class AutoRoundQuantizer(HfQuantizer):
+ """
+ Quantizer of the AutoRound method. (https://huggingface.co/papers/2309.05516)
+ """
+
+ # AutoRound requires data calibration - we support only inference
+ requires_calibration = True
+
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ self.device_map = kwargs.get("device_map")
+ if not is_auto_round_available():
+ raise ImportError(
+ "Loading an AutoRound quantized model requires auto-round library (`pip install 'auto-round>=0.5'`)"
+ )
+
+ def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ if model.__class__.main_input_name != "input_ids":
+ logger.warning("AutoRound offers only limited support for models that are not strictly text-based.")
+ from auto_round.inference.convert_model import convert_hf_model, infer_target_device
+
+ if self.pre_quantized:
+ target_device = infer_target_device(self.device_map)
+ model, used_backends = convert_hf_model(model, target_device)
+ self.used_backends = used_backends
+
+ def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ if self.pre_quantized:
+ from auto_round.inference.convert_model import post_init
+
+ post_init(model, self.used_backends)
+ else:
+ raise ValueError("AutoRound only sports pre-quantized models.")
+
+ @property
+ def is_trainable(self) -> bool:
+ return False
+
+ def is_serializable(self):
+ ## for gptq/awq models, the quantization config will be changed
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_awq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_awq.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a574ef13f8ff88cb033f650cbb71ee087644cb5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_awq.py
@@ -0,0 +1,97 @@
+# 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.
+import importlib.metadata
+from typing import TYPE_CHECKING
+
+from packaging import version
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import AwqConfig
+
+from ..utils import is_accelerate_available, is_gptqmodel_available, is_torch_available, logging
+from ..utils.quantization_config import AwqBackend
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class AwqQuantizer(HfQuantizer):
+ """
+ 4-bit quantization for Activation-aware Weight Quantization(AWQ) (https://huggingface.co/papers/2306.00978)
+ """
+
+ # AWQ requires data calibration - we support only inference
+ requires_calibration = True
+ quantization_config: "AwqConfig"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, **kwargs):
+ if not is_gptqmodel_available():
+ raise ImportError(
+ "Loading an AWQ quantized model requires gptqmodel. Please install it with `pip install gptqmodel`"
+ )
+
+ if not is_accelerate_available():
+ raise ImportError("Loading an AWQ quantized model requires accelerate (`pip install accelerate`)")
+
+ def update_dtype(self, dtype):
+ if dtype == torch.bfloat16 and (torch.cuda.is_available() or torch.xpu.is_available()):
+ logger.warning(
+ "`torch.bfloat16` is not supported for AWQ CUDA/XPU kernels yet. Casting to `torch.float16`."
+ )
+ dtype = torch.float16
+ elif dtype != torch.float16 and (torch.cuda.is_available() or torch.xpu.is_available()):
+ logger.warning("We suggest you to set `dtype=torch.float16` for better efficiency on CUDA/XPU with AWQ.")
+ return dtype
+
+ def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ from ..integrations import replace_quantization_scales, replace_with_awq_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules, add_default_skips=True
+ )
+
+ model = replace_with_awq_linear(
+ model,
+ quantization_config=self.quantization_config,
+ modules_to_not_convert=self.modules_to_not_convert,
+ device_map=kwargs.get("device_map"),
+ )
+
+ model = replace_quantization_scales(model, model.config.model_type)
+
+ def _process_model_after_weight_loading(self, model, **kwargs):
+ from gptqmodel.utils.model import hf_gptqmodel_post_init
+
+ hf_gptqmodel_post_init(model, use_act_order=self.quantization_config.desc_act)
+
+ def is_serializable(self):
+ if self.quantization_config.backend in [AwqBackend.EXLLAMA_V1, AwqBackend.EXLLAMA_V2]:
+ logger.warning("You cannot save an AWQ model that uses Exllama backend!")
+ return False
+
+ return True
+
+ @property
+ def is_trainable(self):
+ return version.parse(importlib.metadata.version("gptqmodel")) >= version.parse("5.0.0")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bitnet.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bitnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec22976939eefcec251ad171f5c7a12331ff8e3e
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bitnet.py
@@ -0,0 +1,124 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import BitNetQuantConfig
+
+from ..utils import is_accelerate_available, is_torch_available, logging
+
+
+if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+
+
+class BitNetHfQuantizer(HfQuantizer):
+ """
+ 1.58-bit quantization from BitNet quantization method:
+ Before loading: it converts the linear layers into BitLinear layers during loading.
+
+ Check out the paper introducing this method: https://huggingface.co/papers/2402.17764
+ """
+
+ requires_calibration = True
+ quantization_config: "BitNetQuantConfig"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_accelerate_available():
+ raise ImportError("Loading a BitNet quantized model requires accelerate (`pip install accelerate`)")
+
+ if not torch.cuda.is_available():
+ logger.warning_once(
+ "You don't have a GPU available to load the model, the inference will be slow because of weight unpacking"
+ )
+ return
+
+ device_map = kwargs.get("device_map")
+ if device_map is None:
+ logger.warning_once(
+ "You have loaded a BitNet model on CPU and have a CUDA device available, make sure to set "
+ "your model on a GPU device in order to run your model."
+ )
+ elif isinstance(device_map, dict):
+ if len(device_map) > 1 and "cpu" in device_map.values() or "disk" in device_map.values():
+ raise ValueError(
+ "You are attempting to load a BitNet model with a device_map that contains a CPU or disk device."
+ "This is not supported. Please remove the CPU or disk device from the device_map."
+ )
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ **kwargs,
+ ):
+ from ..integrations import replace_with_bitnet_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+
+ model = replace_with_bitnet_linear(
+ model,
+ modules_to_not_convert=self.modules_to_not_convert,
+ quantization_config=self.quantization_config,
+ )
+
+ def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]:
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
+ return max_memory
+
+ def is_serializable(self):
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ return (
+ self.quantization_config.linear_class == "autobitlinear"
+ and self.quantization_config.quantization_mode == "online"
+ )
+
+ @property
+ def is_qat_trainable(self) -> bool:
+ """Flag indicating whether the quantized model can carry out quantization aware training"""
+ return (
+ self.quantization_config.linear_class == "autobitlinear"
+ and self.quantization_config.quantization_mode == "online"
+ )
+
+ def get_weight_conversions(self):
+ from ..core_model_loading import WeightConverter
+ from ..integrations.bitnet import BitNetDeserialize
+
+ if (
+ self.quantization_config.linear_class == "autobitlinear"
+ and self.quantization_config.quantization_mode == "offline"
+ ):
+ return [
+ WeightConverter(
+ source_patterns=["weight"],
+ target_patterns=["weight"],
+ operations=[BitNetDeserialize(self)],
+ )
+ ]
+ return []
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_4bit.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_4bit.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fd040bed10e9fce70473e667adb4513459163b4
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_4bit.py
@@ -0,0 +1,187 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import BitsAndBytesConfig
+
+from ..utils import (
+ ACCELERATE_MIN_VERSION,
+ BITSANDBYTES_MIN_VERSION,
+ is_accelerate_available,
+ is_bitsandbytes_available,
+ is_torch_available,
+ is_torch_hpu_available,
+ is_torch_npu_available,
+ is_torch_xpu_available,
+ logging,
+)
+
+
+if is_torch_available():
+ import torch
+
+ from ..core_model_loading import WeightConverter
+
+logger = logging.get_logger(__name__)
+
+
+class Bnb4BitHfQuantizer(HfQuantizer):
+ """
+ 4-bit quantization from bitsandbytes quantization method
+ """
+
+ requires_calibration = False
+ quantization_config: "BitsAndBytesConfig"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_accelerate_available():
+ raise ImportError(
+ f"Using `bitsandbytes` 4-bit quantization requires accelerate: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`"
+ )
+ if not is_bitsandbytes_available():
+ raise ImportError(
+ f"Using `bitsandbytes` 4-bit quantization requires bitsandbytes: `pip install -U bitsandbytes>={BITSANDBYTES_MIN_VERSION}`"
+ )
+
+ from ..integrations import validate_bnb_backend_availability
+
+ validate_bnb_backend_availability(raise_exception=True)
+
+ device_map = kwargs.get("device_map")
+ if not self.quantization_config.llm_int8_enable_fp32_cpu_offload and isinstance(device_map, dict):
+ values = set(device_map.values())
+ if values != {"cpu"} and ("cpu" in values or "disk" in values):
+ raise ValueError(
+ "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the "
+ "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules "
+ "in 32-bit, you need to set `llm_int8_enable_fp32_cpu_offload=True` and pass a custom `device_map` to "
+ "`from_pretrained`. Check "
+ "https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu "
+ "for more details. "
+ )
+
+ def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float:
+ "Return the element size (in bytes) for `param_name`."
+ if self.param_needs_quantization(model, param_name):
+ # 4 bit
+ return 0.5
+
+ return super().param_element_size(model, param_name, param)
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ import bitsandbytes as bnb
+
+ module, name = get_module_from_name(model, param_name)
+ return isinstance(module, bnb.nn.Linear4bit) and name != "bias"
+
+ def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]:
+ # need more space for buffers that are created during quantization
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
+ return max_memory
+
+ def update_device_map(self, device_map):
+ if device_map is None:
+ if torch.cuda.is_available():
+ device_map = {"": torch.cuda.current_device()}
+ elif is_torch_npu_available() and hasattr(torch, "npu"):
+ device_map = {"": f"npu:{torch.npu.current_device()}"}
+ elif is_torch_hpu_available() and hasattr(torch, "hpu"):
+ device_map = {"": f"hpu:{torch.hpu.current_device()}"}
+ elif is_torch_xpu_available():
+ device_map = {"": torch.xpu.current_device()}
+ else:
+ device_map = {"": "cpu"}
+ logger.info(
+ "The device_map was not initialized. "
+ f"Setting device_map to {device_map}. "
+ "If you want to use the model for inference, please set device_map ='auto' "
+ )
+ return device_map
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ device_map,
+ **kwargs,
+ ):
+ from ..integrations import replace_with_bnb_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.llm_int8_skip_modules, model._keep_in_fp32_modules
+ )
+
+ if self.quantization_config.llm_int8_enable_fp32_cpu_offload:
+ if isinstance(device_map, dict):
+ keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
+ self.modules_to_not_convert.extend(keys_on_cpu)
+
+ model = replace_with_bnb_linear(
+ model,
+ modules_to_not_convert=self.modules_to_not_convert,
+ quantization_config=self.quantization_config,
+ pre_quantized=self.pre_quantized,
+ )
+
+ def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ setattr(model, "is_loaded_in_4bit", True)
+ setattr(model, "is_4bit_serializable", self.is_serializable())
+ return model
+
+ def is_serializable(self):
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ return True
+
+ def _dequantize(self, model, dtype=None):
+ from ..integrations import dequantize_and_replace
+
+ model = dequantize_and_replace(model, quantization_config=self.quantization_config, dtype=dtype)
+ return model
+
+ def get_quantize_ops(self):
+ from ..integrations.bitsandbytes import Bnb4bitQuantize
+
+ return Bnb4bitQuantize(self)
+
+ def get_weight_conversions(self):
+ from ..integrations.bitsandbytes import Bnb4bitDeserialize
+
+ if self.pre_quantized:
+ return [
+ WeightConverter(
+ source_patterns=[
+ "weight.nested_absmax",
+ "weight.nested_quant_map",
+ "weight.quant_map",
+ "weight.absmax",
+ "weight.quant_state.bitsandbytes__nf4",
+ "weight.quant_state.bitsandbytes__fp4",
+ "weight",
+ ],
+ target_patterns="weight",
+ operations=[Bnb4bitDeserialize(self)],
+ )
+ ]
+ return []
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_8bit.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_8bit.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf3192bcd72a48a9e0d27cec1baaec19236f0a85
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_bnb_8bit.py
@@ -0,0 +1,178 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import BitsAndBytesConfig
+
+from ..utils import (
+ ACCELERATE_MIN_VERSION,
+ BITSANDBYTES_MIN_VERSION,
+ is_accelerate_available,
+ is_bitsandbytes_available,
+ is_torch_available,
+ is_torch_hpu_available,
+ is_torch_npu_available,
+ is_torch_xpu_available,
+ logging,
+)
+from .quantizers_utils import get_module_from_name
+
+
+if is_torch_available():
+ import torch
+
+ from ..core_model_loading import WeightConverter
+
+logger = logging.get_logger(__name__)
+
+
+class Bnb8BitHfQuantizer(HfQuantizer):
+ """
+ 8-bit quantization from bitsandbytes quantization method
+ """
+
+ requires_calibration = False
+ quantization_config: "BitsAndBytesConfig"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_accelerate_available():
+ raise ImportError(
+ f"Using `bitsandbytes` 8-bit quantization requires accelerate: `pip install 'accelerate>={ACCELERATE_MIN_VERSION}'`"
+ )
+ if not is_bitsandbytes_available():
+ raise ImportError(
+ f"Using `bitsandbytes` 8-bit quantization requires bitsandbytes: `pip install -U bitsandbytes>={BITSANDBYTES_MIN_VERSION}`"
+ )
+
+ from ..integrations import validate_bnb_backend_availability
+
+ validate_bnb_backend_availability(raise_exception=True)
+
+ device_map = kwargs.get("device_map")
+ if not self.quantization_config.llm_int8_enable_fp32_cpu_offload and isinstance(device_map, dict):
+ values = set(device_map.values())
+ if values != {"cpu"} and ("cpu" in values or "disk" in values):
+ raise ValueError(
+ "Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit the "
+ "quantized model. If you want to dispatch the model on the CPU or the disk while keeping these modules "
+ "in 32-bit, you need to set `llm_int8_enable_fp32_cpu_offload=True` and pass a custom `device_map` to "
+ "`from_pretrained`. Check "
+ "https://huggingface.co/docs/transformers/main/en/main_classes/quantization#offload-between-cpu-and-gpu "
+ "for more details. "
+ )
+
+ def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]:
+ # need more space for buffers that are created during quantization
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
+ return max_memory
+
+ def update_device_map(self, device_map):
+ if device_map is None:
+ if torch.cuda.is_available():
+ device_map = {"": torch.cuda.current_device()}
+ elif is_torch_npu_available() and hasattr(torch, "npu"):
+ device_map = {"": f"npu:{torch.npu.current_device()}"}
+ elif is_torch_hpu_available() and hasattr(torch, "hpu"):
+ device_map = {"": f"hpu:{torch.hpu.current_device()}"}
+ elif is_torch_xpu_available():
+ device_map = {"": torch.xpu.current_device()}
+ else:
+ device_map = {"": "cpu"}
+ logger.info(
+ "The device_map was not initialized. "
+ f"Setting device_map to {device_map}. "
+ "If you want to use the model for inference, please set device_map ='auto' "
+ )
+ return device_map
+
+ def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float:
+ "Return the element size (in bytes) for `param_name`."
+ if self.param_needs_quantization(model, param_name):
+ # 8-bit
+ return 1
+ return super().param_element_size(model, param_name, param)
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ import bitsandbytes as bnb
+
+ module, name = get_module_from_name(model, param_name)
+ return isinstance(module, bnb.nn.Linear8bitLt) and name != "bias"
+
+ def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ setattr(model, "is_loaded_in_8bit", True)
+ model.is_8bit_serializable = self.is_serializable()
+ return model
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ device_map,
+ **kwargs,
+ ):
+ from ..integrations import replace_with_bnb_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.llm_int8_skip_modules, model._keep_in_fp32_modules
+ )
+
+ if self.quantization_config.llm_int8_enable_fp32_cpu_offload:
+ if isinstance(device_map, dict):
+ keys_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]]
+ self.modules_to_not_convert.extend(keys_on_cpu)
+
+ model = replace_with_bnb_linear(
+ model,
+ modules_to_not_convert=self.modules_to_not_convert,
+ quantization_config=self.quantization_config,
+ pre_quantized=self.pre_quantized,
+ )
+
+ def is_serializable(self):
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ return True
+
+ def _dequantize(self, model, dtype=None):
+ from ..integrations import dequantize_and_replace
+
+ model = dequantize_and_replace(model, quantization_config=self.quantization_config, dtype=dtype)
+ return model
+
+ def get_quantize_ops(self):
+ from ..integrations.bitsandbytes import Bnb8bitQuantize
+
+ return Bnb8bitQuantize(self)
+
+ def get_weight_conversions(self):
+ from ..integrations.bitsandbytes import Bnb8bitDeserialize
+
+ if self.pre_quantized:
+ return [
+ WeightConverter(
+ source_patterns=["SCB", "weight_format", "weight"],
+ target_patterns="weight",
+ operations=[Bnb8bitDeserialize(self)],
+ )
+ ]
+ return []
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_compressed_tensors.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_compressed_tensors.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e1e4882beea28467043e85813757f764d175a97
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_compressed_tensors.py
@@ -0,0 +1,114 @@
+# 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.
+
+
+from ..utils import is_compressed_tensors_available, is_torch_available, logging
+from ..utils.quantization_config import CompressedTensorsConfig
+from .base import HfQuantizer
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class CompressedTensorsHfQuantizer(HfQuantizer):
+ """
+ Quantizer for the compressed_tensors package. Loads and restores models to
+ quantized state with compressed_tensors
+ """
+
+ requires_calibration = True
+ quantization_config: CompressedTensorsConfig
+
+ def __init__(self, quantization_config: CompressedTensorsConfig, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ if not is_compressed_tensors_available():
+ raise ImportError(
+ "Using `compressed_tensors` quantized models requires the compressed-tensors library: "
+ "`pip install compressed-tensors`"
+ )
+
+ # Call post_init here to ensure proper config setup when `run_compressed`
+ # is provided directly via CompressedTensorsConfig, and to avoid duplicate logging.
+
+ quantization_config.post_init()
+ from compressed_tensors.compressors import ModelCompressor
+
+ self.compressor = ModelCompressor.from_compression_config(quantization_config)
+ self.run_compressed = quantization_config.run_compressed
+ self.quantization_config = quantization_config
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_compressed_tensors_available():
+ raise ImportError(
+ "Using `compressed_tensors` quantized models requires the compressed-tensors library: "
+ "`pip install compressed-tensors`"
+ )
+
+ def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
+ if dtype != torch.float16:
+ logger.info("We suggest you to set `dtype=torch.float16` for better efficiency with compressed_tensors.")
+ return dtype
+
+ def _process_model_before_weight_loading(self, model, **kwargs):
+ from compressed_tensors.quantization import apply_quantization_config
+
+ ct_quantization_config = self.compressor.quantization_config
+
+ # Always initialize compressed wrappers to match the checkpoint
+ apply_quantization_config(model, ct_quantization_config, self.run_compressed)
+ if (
+ self.quantization_config.is_quantization_compressed
+ or self.quantization_config.is_sparsification_compressed
+ ):
+ self.compressor.compress_model(model=model)
+
+ def _process_model_after_weight_loading(self, model, **kwargs):
+ """Decompress loaded model if necessary - need for qat"""
+
+ if (self.quantization_config.is_quantization_compressed and not self.run_compressed) or (
+ self.quantization_config.is_sparsification_compressed
+ ):
+ self.compressor.decompress_model(model=model)
+
+ # NOTE: TP plan override for compressed tensors removed - unsupported styles were used.
+ # TODO: Implement proper TP support for compressed tensors quantization
+ def update_tp_plan(self, config):
+ additional_plan = {
+ "layers.*.feed_forward.experts.*.gate_proj.weight": "colwise",
+ "layers.*.feed_forward.experts.*.gate_proj.weight_scale": "colwise",
+ "layers.*.feed_forward.experts.*.up_proj.weight": "colwise",
+ "layers.*.feed_forward.experts.*.up_proj.weight_scale": "colwise",
+ "layers.*.feed_forward.experts.*.down_proj.weight": "rowwise",
+ }
+ if config.get_text_config() is not None and config.get_text_config().base_model_tp_plan is not None:
+ config.get_text_config().base_model_tp_plan.update(additional_plan)
+
+ return config
+
+ @property
+ def is_trainable(self):
+ return True
+
+ def is_qat_trainable(self) -> bool:
+ """Loaded Models can carry out quantization aware training"""
+ # models need to be decompressed carry out qat
+ return not self.run_compressed or not self.quantization_config.is_quantization_compressed
+
+ def is_serializable(self) -> bool:
+ """Models quantized using compressed tensors can be saved to disk"""
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_eetq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_eetq.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce1d350f3d96438663c6f065e94af95cc8d5fc57
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_eetq.py
@@ -0,0 +1,110 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import EetqConfig
+
+from ..utils import is_accelerate_available, is_kernels_available, is_torch_available, logging
+from .quantizers_utils import get_module_from_name
+
+
+if is_torch_available():
+ import torch
+
+
+logger = logging.get_logger(__name__)
+
+
+class EetqHfQuantizer(HfQuantizer):
+ """
+ 8-bit quantization from EETQ quantization method
+ """
+
+ requires_calibration = False
+ quantization_config: "EetqConfig"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_kernels_available():
+ raise ImportError("Loading an EETQ quantized model requires kernels (`pip install kernels`)")
+
+ if not is_accelerate_available():
+ raise ImportError("Loading an EETQ quantized model requires accelerate (`pip install accelerate`)")
+
+ if not torch.cuda.is_available():
+ raise RuntimeError("No GPU found. A GPU is needed for quantization.")
+
+ device_map = kwargs.get("device_map")
+ if device_map is None:
+ logger.warning_once(
+ "You have loaded an EETQ model on CPU and have a CUDA device available, make sure to set "
+ "your model on a GPU device in order to run your model."
+ )
+ elif isinstance(device_map, dict):
+ if len(device_map) > 1 and "cpu" in device_map.values() or "disk" in device_map.values():
+ raise ValueError(
+ "You are attempting to load an EETQ model with a device_map that contains a CPU or disk device."
+ " This is not supported. Please remove the CPU or disk device from the device_map."
+ )
+
+ def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
+ if dtype != torch.float16:
+ logger.info("We suggest you to set `dtype=torch.float16` for better efficiency with EETQ.")
+ return dtype
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ from ..integrations.eetq import EetqLinear
+
+ module, tensor_name = get_module_from_name(model, param_name)
+
+ if isinstance(module, EetqLinear):
+ if self.pre_quantized or tensor_name == "bias":
+ return False
+ else:
+ return True
+ return False
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ **kwargs,
+ ):
+ from ..integrations import replace_with_eetq_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+
+ model = replace_with_eetq_linear(
+ model, modules_to_not_convert=self.modules_to_not_convert, pre_quantized=self.pre_quantized
+ )
+
+ def is_serializable(self):
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ return True
+
+ def get_quantize_ops(self):
+ from ..integrations.eetq import EetqQuantize
+
+ return EetqQuantize(self)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fbgemm_fp8.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fbgemm_fp8.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cbc3cdcbe5f2413af19c4819692ba97a9178d98
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fbgemm_fp8.py
@@ -0,0 +1,207 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import FbgemmFp8Config
+
+from ..utils import (
+ is_accelerate_available,
+ is_fbgemm_gpu_available,
+ is_kernels_available,
+ is_torch_available,
+ is_torch_cuda_available,
+ is_torch_xpu_available,
+ logging,
+)
+from .quantizers_utils import get_module_from_name
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class FbgemmFp8HfQuantizer(HfQuantizer):
+ """
+ FP8 quantization using fbgemm kernels
+ """
+
+ requires_calibration = False
+ quantization_config: "FbgemmFp8Config"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_torch_cuda_available() and not is_torch_xpu_available():
+ raise ImportError("Using fbgemm fp8 quantization requires a GPU or XPU")
+ if is_torch_xpu_available() and not is_kernels_available():
+ raise ImportError("Using FP8 fbgemm on XPU requires kernels (`pip install kernels`)")
+ if is_torch_cuda_available() and not is_fbgemm_gpu_available():
+ raise ImportError(
+ "Loading an FP8 fbgemm quantized model on CUDA requires fbgemm-gpu library"
+ "Please install the latest version of fbgemm-gpu library by following : https://pytorch.org/FBGEMM/fbgemm_gpu-development/InstallationInstructions.html#fbgemm-gpu-install-libraries"
+ )
+ if not is_accelerate_available():
+ raise ImportError(
+ "Loading an FP8 quantized model requires accelerate (`pip install --upgrade accelerate`)"
+ )
+ if is_torch_cuda_available():
+ compute_capability = torch.cuda.get_device_capability()
+ major, _ = compute_capability
+ if major < 9:
+ raise ValueError(
+ "FP8 quantized models is only supported on GPUs with compute capability >= 9.0 (e.g H100)"
+ )
+
+ device_map = kwargs.get("device_map")
+ if device_map is None:
+ logger.warning_once(
+ "You have loaded an FP8 model on CPU and have a CUDA/XPU device available, make sure to set "
+ "your model on a GPU/XPU device in order to run your model. To remove this warning, pass device_map = 'cuda' or 'xpu' or 'auto'. "
+ )
+ elif isinstance(device_map, dict):
+ if not self.pre_quantized and ("cpu" in device_map.values() or "disk" in device_map.values()):
+ raise ValueError(
+ "You are attempting to load an FP8 model with a device_map that contains a CPU or disk device."
+ "This is not supported when the model is quantized on the fly. "
+ "Please use a quantized checkpoint or remove the CPU or disk device from the device_map."
+ )
+
+ def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
+ if dtype != torch.bfloat16:
+ logger.warning_once(
+ f"Setting dtype to {dtype}, but only bfloat16 is supported right now. Overwriting torch_dtype to bfloat16."
+ )
+ dtype = torch.bfloat16
+ return dtype
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ from ..integrations import FbgemmFp8Linear, FbgemmFp8Llama4TextExperts
+
+ module, tensor_name = get_module_from_name(model, param_name)
+
+ if isinstance(module, FbgemmFp8Linear):
+ if self.pre_quantized or tensor_name == "bias":
+ return False
+ else:
+ return True
+ if isinstance(module, FbgemmFp8Llama4TextExperts):
+ if self.pre_quantized or tensor_name == "bias":
+ return False
+ else:
+ return True
+ return False
+
+ def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float:
+ "Return the element size (in bytes) for `param_name`."
+ if self.param_needs_quantization(model, param_name):
+ # 8 bit, this is neeed as when `pre_quantized`` is False, we don't set the dtype of the FP8Linear in order to correctly load the weights
+ return 1
+ return super().param_element_size(model, param_name, param)
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ **kwargs,
+ ):
+ from ..integrations import replace_with_fbgemm_fp8_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+
+ model = replace_with_fbgemm_fp8_linear(
+ model,
+ modules_to_not_convert=self.modules_to_not_convert,
+ quantization_config=self.quantization_config,
+ pre_quantized=self.pre_quantized,
+ tp_plan=model._tp_plan,
+ )
+
+ def _process_model_after_weight_loading(self, model, **kwargs):
+ """
+ Force update the input scale upper bound after weight loading and device dispatch are complete.
+ This resolves issues where persistent buffers are zeroed out or overwritten during the loading process.
+ """
+ from ..integrations.fbgemm_fp8 import FbgemmFp8Linear, FbgemmFp8Llama4TextExperts
+
+ for m in model.modules():
+ if isinstance(m, (FbgemmFp8Linear, FbgemmFp8Llama4TextExperts)):
+ if hasattr(m, "input_scale_ub"):
+ # The model is now on the target device, so we can use fill_ directly.
+ m.input_scale_ub.fill_(self.quantization_config.activation_scale_ub)
+ return model
+
+ def update_tp_plan(self, config):
+ if "Llama4" in config.__class__.__name__:
+ text_plan = {
+ # We are using a different tp plan with local_colwise and local_rowwise for the attention because fbgemm operations cannot be parallelized
+ # With local_colwise and local_rowwise, all the operations are done locally, and we add a gather operation to gather the results instead of
+ # using dtensors
+ "layers.*.self_attn.q_proj.weight": "colwise",
+ "layers.*.self_attn.q_proj.weight_scale": "colwise",
+ "layers.*.self_attn.k_proj.weight": "colwise",
+ "layers.*.self_attn.k_proj.weight_scale": "colwise",
+ "layers.*.self_attn.v_proj.weight": "colwise",
+ "layers.*.self_attn.v_proj.weight_scale": "colwise",
+ "layers.*.self_attn.o_proj.weight": "rowwise",
+ # We keep the same sequence_parallel plan for layernorms
+ "layers.*.input_layernorm.weight": "sequence_parallel",
+ "layers.*.post_attention_layernorm.weight": "sequence_parallel",
+ "norm.weight": "sequence_parallel",
+ # We keep the same local_colwise and local_rowwise plan for the feed forward shared expert
+ # We also add scales for the shared expert, for local_colwise the scale is also local_colwise
+ # For local_rowwise the scale is replicated, so we don't need to add it
+ "layers.*.feed_forward.shared_expert.gate_proj.weight": "colwise",
+ "layers.*.feed_forward.shared_expert.gate_proj.weight_scale": "colwise",
+ "layers.*.feed_forward.shared_expert.up_proj.weight": "colwise",
+ "layers.*.feed_forward.shared_expert.up_proj.weight_scale": "colwise",
+ "layers.*.feed_forward.shared_expert.down_proj.weight": "rowwise",
+ "layers.*.feed_forward.experts.*.gate_proj.weight": "colwise",
+ "layers.*.feed_forward.experts.*.gate_proj.weight_scale": "colwise",
+ "layers.*.feed_forward.experts.*.up_proj.weight": "colwise",
+ "layers.*.feed_forward.experts.*.up_proj.weight_scale": "colwise",
+ "layers.*.feed_forward.experts.*.down_proj.weight": "rowwise",
+ # For Fused implementation we use local_packed_rowwise for the gate_up_proj, and the same for the packed scales
+ # We use local_colwise for the down_proj, and the scales are replicated so we don't add them
+ "layers.*.feed_forward.experts.gate_up_proj": "packed_rowwise",
+ "layers.*.feed_forward.experts.gate_up_proj_scale": "packed_rowwise",
+ "layers.*.feed_forward.experts.down_proj": "colwise",
+ }
+ if config.get_text_config() is not None:
+ config.get_text_config().base_model_tp_plan = text_plan
+ else:
+ config.base_model_tp_plan = text_plan
+ return config
+
+ return config
+
+ def is_serializable(self):
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ return False
+
+ def get_quantize_ops(self):
+ from ..integrations.fbgemm_fp8 import FbgemmFp8Quantize
+
+ return FbgemmFp8Quantize(self)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_finegrained_fp8.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_finegrained_fp8.py
new file mode 100644
index 0000000000000000000000000000000000000000..be10624d4842b189420de294cadf42660153a0f6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_finegrained_fp8.py
@@ -0,0 +1,226 @@
+from typing import TYPE_CHECKING
+
+from ..utils import is_accelerate_available, is_torch_available, is_torch_xpu_available, logging
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name
+
+
+if is_torch_available():
+ import torch
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import FineGrainedFP8Config
+
+logger = logging.get_logger(__name__)
+
+
+class FineGrainedFP8HfQuantizer(HfQuantizer):
+ """
+ FP8 quantization implementation supporting both standard and MoE models.
+ Supports both e4m3fn formats based on platform.
+ """
+
+ requires_calibration = False
+ quantization_config: "FineGrainedFP8Config"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_accelerate_available():
+ raise ImportError("Loading an FP8 quantized model requires accelerate (`pip install accelerate`)")
+
+ if self.quantization_config.dequantize:
+ return
+
+ if not torch.cuda.is_available() and not is_torch_xpu_available():
+ if self.pre_quantized:
+ logger.warning_once(
+ "Using FP8 quantized models requires a GPU or XPU, we will default to dequantizing the model to bf16 since no GPU or XPU is available"
+ )
+ self.quantization_config.dequantize = True
+ return
+ else:
+ raise RuntimeError("No GPU or XPU found. A GPU or XPU is needed for FP8 quantization.")
+
+ if torch.cuda.is_available():
+ compute_capability = torch.cuda.get_device_capability()
+ major, minor = compute_capability
+ if (major < 8) or (major == 8 and minor < 9):
+ logger.warning_once(
+ "FP8 quantized models is only supported on GPUs with compute capability >= 8.9 (e.g 4090/H100)"
+ f", actual = `{major}.{minor}`. We will default to dequantizing the model to bf16. Feel free "
+ f"to use a different quantization method like bitsandbytes or torchao"
+ )
+ self.quantization_config.dequantize = True
+ return
+
+ device_map = kwargs.get("device_map")
+ if device_map is None:
+ logger.warning_once(
+ "You have loaded an FP8 model on CPU and have a CUDA or XPU device available, make sure to set "
+ "your model on a GPU or XPU device in order to run your model. To remove this warning, "
+ "pass device_map = 'cuda' or 'xpu'. "
+ )
+ elif isinstance(device_map, dict):
+ if (
+ not self.pre_quantized
+ and len(device_map) > 1
+ and "cpu" in device_map.values()
+ or "disk" in device_map.values()
+ ):
+ raise ValueError(
+ "You are attempting to load an FP8 model with a device_map that contains a cpu/disk device."
+ "This is not supported when the model is quantized on the fly. "
+ "Please use a quantized checkpoint or remove the cpu/disk device from the device_map."
+ )
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ from ..integrations.finegrained_fp8 import FP8Experts, FP8Linear
+
+ module, tensor_name = get_module_from_name(model, param_name)
+ if isinstance(module, (FP8Linear, FP8Experts)):
+ if self.pre_quantized or tensor_name == "bias":
+ return False
+ else:
+ return True
+ return False
+
+ def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float:
+ "Return the element size (in bytes) for `param_name`."
+ if self.param_needs_quantization(model, param_name):
+ # 8 bit, this is neeed as when `pre_quantized`` is False, we don't set the dtype of the FP8Linear in order to correctly load the weights
+ return 1
+ return super().param_element_size(model, param_name, param)
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ **kwargs,
+ ):
+ from ..integrations.finegrained_fp8 import replace_with_fp8_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+
+ model = replace_with_fp8_linear(
+ model,
+ modules_to_not_convert=self.modules_to_not_convert,
+ quantization_config=self.quantization_config,
+ pre_quantized=self.pre_quantized,
+ )
+
+ def update_tp_plan(self, config):
+ if "Qwen3" in config.__class__.__name__:
+ text_plan = {
+ "layers.*.self_attn.q_proj.weight": "colwise",
+ "layers.*.self_attn.q_proj.weight_scale_inv": "colwise",
+ "layers.*.self_attn.k_proj.weight": "colwise",
+ "layers.*.self_attn.k_proj.weight_scale_inv": "colwise",
+ "layers.*.self_attn.v_proj.weight": "colwise",
+ "layers.*.self_attn.v_proj.weight_scale_inv": "colwise",
+ "layers.*.self_attn.o_proj.weight": "rowwise",
+ "layers.*.self_attn.o_proj.weight_scale_inv": "rowwise",
+ "layers.*.mlp.gate_proj.weight": "colwise",
+ "layers.*.mlp.gate_proj.weight_scale_inv": "colwise",
+ "layers.*.mlp.up_proj.weight": "colwise",
+ "layers.*.mlp.up_proj.weight_scale_inv": "colwise",
+ "layers.*.mlp.down_proj.weight": "rowwise",
+ "layers.*.mlp.down_proj.weight_scale_inv": "rowwise",
+ }
+
+ config.base_model_tp_plan = text_plan
+
+ return config
+
+ def is_serializable(self):
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ return False
+
+ @property
+ def is_compileable(self) -> bool:
+ return True
+
+ def get_quantize_ops(self):
+ from ..integrations.finegrained_fp8 import Fp8Quantize
+
+ return Fp8Quantize(self)
+
+ def get_weight_conversions(self):
+ from ..core_model_loading import WeightConverter
+ from ..integrations.finegrained_fp8 import Fp8Dequantize
+
+ if self.pre_quantized and self.quantization_config.dequantize:
+ return [
+ # either use the dollar sign, or permute the source patterns to start matching against the scales first
+ # We also collect the activation scales, they will not be used
+ WeightConverter(
+ source_patterns=["weight$", "weight_scale_inv", "activation_scale"],
+ target_patterns="weight",
+ operations=[Fp8Dequantize(self)],
+ )
+ ]
+ return []
+
+ def update_weight_conversions(self, weight_conversions):
+ """When loading with ``dequantize=True``, attach an :class:`Fp8Dequantize` op to
+ every existing :class:`WeightConverter` so that per-block scales are folded into
+ the weight *before* any later merge/concat ops collapse the per-expert structure.
+
+ For each model-supplied converter that has a ``.weight`` source, we:
+ 1. anchor the existing weight patterns with ``$`` so they don't accidentally
+ also match the ``.weight_scale_inv`` keys (the regex is searched, so the
+ unanchored prefix would match both, sending scales to the wrong bucket);
+ 2. add anchored ``*.weight_scale_inv`` sources next to each weight pattern so
+ the loader collects scale tensors alongside the weight tensors into the
+ *same* converter bucket (both keys rewrite to the same target);
+ 3. prepend a fresh :class:`Fp8Dequantize` op so dequant runs first, before
+ any merge/concat collapses the per-expert structure.
+
+ The generic ``weight$ + weight_scale_inv → weight`` converter from
+ :meth:`get_weight_conversions` is still appended at the end as a fallback for
+ plain ``nn.Linear`` weights with no model-specific converter.
+ """
+ if not (self.pre_quantized and self.quantization_config.dequantize):
+ return weight_conversions + self.get_weight_conversions()
+
+ from ..core_model_loading import WeightConverter, WeightRenaming
+ from ..integrations.finegrained_fp8 import Fp8Dequantize
+
+ # Some upstream FP8 checkpoints (e.g. DeepSeek-V4-Flash) ship per-block scales
+ # under a ``.scale`` suffix instead of HF's canonical ``.weight_scale_inv``.
+ # Prepending the rename here (instead of in each model's conversion_mapping)
+ # keeps the model-side mapping clean — the rename only kicks in when FP8 dequant
+ # is actually active, so a non-FP8 save / load round-trip doesn't see a stray
+ # rule that ``test_reverse_loading_mapping`` can't match.
+ scale_rename = WeightRenaming(source_patterns=r"^(.+)\.scale$", target_patterns=r"\1.weight_scale_inv")
+ weight_conversions = [scale_rename] + list(weight_conversions)
+
+ updated: list = []
+ for conv in weight_conversions:
+ # Only WeightConverter has ``.operations`` to extend with the dequant op;
+ # WeightRenaming (e.g. the ``scale_rename`` we prepended) just passes through.
+ if not isinstance(conv, WeightConverter):
+ updated.append(conv)
+ continue
+ weight_sources = [p for p in conv.source_patterns if p.endswith(".weight")]
+ if weight_sources:
+ anchored_weight = [p + "$" for p in weight_sources]
+ scale_sources = [p[: -len(".weight")] + ".weight_scale_inv$" for p in weight_sources]
+ other = [p for p in conv.source_patterns if not p.endswith(".weight")]
+ new_sources = anchored_weight + scale_sources + other
+ new_ops = [Fp8Dequantize(self)] + list(conv.operations)
+ conv = WeightConverter(
+ source_patterns=new_sources,
+ target_patterns=conv._original_target_patterns,
+ operations=new_ops,
+ )
+ updated.append(conv)
+ # Generic fallback for plain ``nn.Linear`` weights with no model-specific converter.
+ updated.extend(self.get_weight_conversions())
+ return updated
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fouroversix.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fouroversix.py
new file mode 100644
index 0000000000000000000000000000000000000000..79acb8cbb2161a9545229252270b53eaab99b9cf
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fouroversix.py
@@ -0,0 +1,123 @@
+from typing import TYPE_CHECKING
+
+from ..utils.import_utils import is_fouroversix_available
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import FourOverSixConfig
+
+from ..utils import (
+ is_torch_available,
+)
+
+
+if is_torch_available():
+ import torch
+
+
+class FourOverSixHfQuantizer(HfQuantizer):
+ """
+ FP4 quantization with fouroversix.
+ """
+
+ requires_calibration = False
+ quantization_config: "FourOverSixConfig"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_fouroversix_available():
+ raise ImportError(
+ "Using `fouroversix` requires fouroversix: `pip install fouroversix --no-build-isolation`"
+ )
+
+ def param_element_size(
+ self,
+ model: "PreTrainedModel",
+ param_name: str,
+ param: "torch.Tensor",
+ ) -> float:
+ from fouroversix import QuantizedModule
+
+ module, tensor_name = get_module_from_name(model, param_name)
+
+ if QuantizedModule.is_quantized_module_type(type(module)):
+ return module.get_element_size(tensor_name)
+
+ return super().param_element_size(model, param_name, param)
+
+ def param_needs_quantization(
+ self,
+ model: "PreTrainedModel",
+ param_name: str,
+ **kwargs,
+ ) -> bool:
+ from fouroversix import QuantizedModule
+
+ module, tensor_name = get_module_from_name(model, param_name)
+
+ return QuantizedModule.is_quantized_module_type(type(module)) and tensor_name in module.parameters_to_quantize
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ device_map,
+ **kwargs,
+ ):
+ from fouroversix import QuantizedModule, quantize_model
+
+ from ..integrations.fouroversix import adapt_fouroversix_config
+
+ quantize_model(
+ model,
+ adapt_fouroversix_config(self.quantization_config),
+ )
+
+ # If the model has already been quantized, we need to delete the weight tensor here so that
+ # it's not expected when parameters are loaded from the checkpoint.
+ if self.pre_quantized and not self.quantization_config.keep_master_weights:
+ for _, module in model.named_modules():
+ if QuantizedModule.is_quantized_module_type(type(module)):
+ for parameter_name in module.parameters_to_quantize:
+ delattr(module, parameter_name)
+
+ def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ return model
+
+ def is_serializable(self):
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ return self.quantization_config.keep_master_weights
+
+ def get_quantize_ops(self):
+ from ..integrations.fouroversix import FourOverSixQuantize
+
+ return FourOverSixQuantize(self)
+
+ def get_weight_conversions(self):
+ """
+ Return weight conversions for loading pre-quantized checkpoints of
+ other pre-quantized models (not fouroversix models). After first use,
+ the pre_quantized_model_config_type attribute is set to None to ensure
+ subsequent calls (e.g., during save_pretrained) return an empty list
+ since, by then, the model will be saved with our framework's format
+ so weight conversions are no longer needed.
+ """
+ from fouroversix import WeightConversions
+
+ # pre_quantized_model_config_type is only set if we are loading a
+ # pre-quantized model so it is not guaranteed to exist.
+ if hasattr(self.quantization_config, "pre_quantized_model_config_type"):
+ model_config_type = self.quantization_config.pre_quantized_model_config_type
+ weight_conversions = WeightConversions.get_weight_conversions(
+ model_config_type,
+ )
+ return weight_conversions
+
+ return []
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fp_quant.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fp_quant.py
new file mode 100644
index 0000000000000000000000000000000000000000..c367b957d206fed69a361f11bd42b8e429bda5e5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_fp_quant.py
@@ -0,0 +1,164 @@
+# 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.
+from typing import TYPE_CHECKING, Optional
+
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import FPQuantConfig
+
+from ..utils import is_fp_quant_available, is_qutlass_available, is_torch_available, is_torch_xpu_available, logging
+from ..utils.quantization_config import QuantizationConfigMixin
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class FPQuantHfQuantizer(HfQuantizer):
+ """
+ Quantizer for the FP-Quant method. Enables the loading of prequantized models and in-flight quantization of full-precision models.
+ """
+
+ requires_calibration = False
+ is_qat_trainable = True
+ quantization_config: "FPQuantConfig"
+
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, device_map, **kwargs):
+ if not torch.cuda.is_available() and not is_torch_xpu_available():
+ raise NotImplementedError(
+ "FPQuant quantization is only supported on GPU or Intel XPU. Please use a different quantizer."
+ )
+
+ if not is_qutlass_available() and not self.quantization_config.pseudoquantization:
+ raise ImportError(
+ "Using `fp_quant` with real quantization requires a **Blackwell GPU** and qutlass: `git clone https://github.com/IST-DASLab/qutlass.git && cd qutlass && pip install --no-build-isolation .`. You can use `FPQuantConfig(pseudoquantization=True, ...)` to use Triton-based pseudo-quantization. It doesn't provide any speedups but emulates the quantization behavior of the real quantization."
+ )
+
+ if (
+ self.quantization_config.pseudoquantization
+ and self.quantization_config.forward_dtype == "nvfp4"
+ and torch.cuda.is_available()
+ and torch.cuda.get_device_capability()[0] < 9
+ ):
+ raise ValueError(
+ "NVFP4 pseudoquantization requires a GPU with compute capability >= 9.0 (Hopper or newer) "
+ "because the Triton kernel uses the `fp8e4nv` type. Please use `forward_dtype='mxfp4'` instead, "
+ "or use a GPU with compute capability >= 9.0."
+ )
+
+ if self.quantization_config.pseudoquantization:
+ logger.warning(
+ "Using pseudo-quantization for FP-Quant. This doesn't provide any speedups but emulates the quantization behavior of the real quantization."
+ )
+
+ if not is_fp_quant_available():
+ raise ImportError("Using `fp_quant` quantization requires fp_quant: `pip install fp_quant`")
+
+ if device_map is None and not self.quantization_config.pseudoquantization:
+ raise ValueError(
+ "You are attempting to load a FPQuant model without setting device_map."
+ " Please set device_map comprised of 'cuda' devices."
+ )
+ elif isinstance(device_map, dict):
+ if (
+ not self.quantization_config.pseudoquantization
+ and len(device_map) > 1
+ and "cpu" in device_map.values()
+ or "disk" in device_map.values()
+ ):
+ raise ValueError(
+ "You are attempting to load a FPQuant model with a device_map that contains a CPU or disk device."
+ " This is not supported. Please remove the CPU or disk device from the device_map."
+ )
+
+ def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
+ if dtype != torch.bfloat16:
+ logger.warning_once(
+ f"Setting dtype to {dtype}, but only bfloat16 is supported right now. Overwriting torch_dtype to bfloat16."
+ )
+ dtype = torch.bfloat16
+ return dtype
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ from fp_quant import FPQuantLinear
+
+ module, tensor_name = get_module_from_name(model, param_name)
+ if isinstance(module, FPQuantLinear) and tensor_name in ["weight", "qweight", "dqweight"]:
+ # Only quantize weights of FPQuantLinear modules that are not already quantized
+ return True
+ else:
+ return False
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ **kwargs,
+ ):
+ from fp_quant import replace_with_fp_quant_linear
+
+ from ..integrations.fp_quant import adapt_fp_quant_config
+
+ replace_with_fp_quant_linear(
+ model,
+ fp_quant_linear_config=adapt_fp_quant_config(self.quantization_config),
+ )
+
+ @property
+ def is_trainable(self, model: Optional["PreTrainedModel"] = None):
+ trainable = self.quantization_config.store_master_weights
+ if not trainable:
+ logger.warning(
+ "You are attempting to train a model with FPQuant quantization. This is only supported when `store_master_weights=True`. Please set `store_master_weights=True` to train the model."
+ )
+ return trainable
+
+ def is_serializable(self):
+ return True
+
+ def get_quantize_ops(self):
+ from ..integrations.fp_quant import FpQuantQuantize
+
+ return FpQuantQuantize(self)
+
+ def get_weight_conversions(self):
+ from ..core_model_loading import WeightConverter
+ from ..integrations.fp_quant import FpQuantDeserialize
+
+ if self.pre_quantized:
+ if self.quantization_config.pseudoquantization:
+ return [
+ WeightConverter(
+ source_patterns=[".dqweight"],
+ target_patterns=".dqweight",
+ operations=[FpQuantDeserialize(self)],
+ ),
+ ]
+ else:
+ return [
+ WeightConverter(
+ source_patterns=[".qweight"],
+ target_patterns=".qweight",
+ operations=[FpQuantDeserialize(self)],
+ ),
+ ]
+ return []
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_gptq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_gptq.py
new file mode 100644
index 0000000000000000000000000000000000000000..f018704f494931d5c30f66d695d8ff96bacfc5d0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_gptq.py
@@ -0,0 +1,111 @@
+# 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.
+from importlib import metadata
+from typing import TYPE_CHECKING
+
+from packaging import version
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+
+from ..utils import is_gptqmodel_available, is_optimum_available, is_torch_available, logging
+from ..utils.quantization_config import GPTQConfig, QuantizationConfigMixin
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+MIN_GPTQ_VERSION = "1.4.3"
+MIN_OPTIMUM_VERSION = "1.24.0"
+
+
+class GptqHfQuantizer(HfQuantizer):
+ """
+ Quantizer of the GPTQ method - for GPTQ the quantizer support calibration of the model through
+ the GPT-QModel package (Python import name `gptqmodel`). Quantization is done under the hood for users if they
+ load a non-prequantized model.
+ """
+
+ requires_calibration = False
+ quantization_config: "GPTQConfig"
+
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ if not is_optimum_available():
+ raise ImportError("Loading a GPTQ quantized model requires optimum (`pip install optimum`)")
+ from optimum.gptq import GPTQQuantizer
+
+ self.optimum_quantizer = GPTQQuantizer.from_dict(self.quantization_config.to_dict_optimum())
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_optimum_available():
+ raise ImportError("Loading a GPTQ quantized model requires optimum (`pip install optimum`)")
+
+ gptq_supports_cpu = is_gptqmodel_available()
+ if not gptq_supports_cpu and not torch.cuda.is_available():
+ raise RuntimeError("GPU is required to quantize or run quantize model.")
+ elif not is_gptqmodel_available():
+ raise ImportError("Loading a GPTQ quantized model requires gptqmodel (`pip install gptqmodel`) library.")
+ elif is_gptqmodel_available() and (
+ version.parse(metadata.version("gptqmodel")) < version.parse(MIN_GPTQ_VERSION)
+ or version.parse(metadata.version("optimum")) < version.parse(MIN_OPTIMUM_VERSION)
+ ):
+ raise ImportError(
+ f"The gptqmodel version should be >= {MIN_GPTQ_VERSION}, optimum version should >= {MIN_OPTIMUM_VERSION}"
+ )
+
+ def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
+ if dtype != torch.float16:
+ logger.info("We suggest you to set `dtype=torch.float16` for better efficiency with GPTQ.")
+ return dtype
+
+ def update_device_map(self, device_map):
+ if device_map is None:
+ device_map = {"": torch.device("cpu")}
+ return device_map
+
+ def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ if model.__class__.main_input_name != "input_ids":
+ raise RuntimeError("We can only quantize pure text model.")
+
+ if self.pre_quantized:
+ # compat: latest optimum has gptqmodel refactor
+ if version.parse(metadata.version("optimum")) < version.parse(MIN_OPTIMUM_VERSION):
+ model = self.optimum_quantizer.convert_model(model)
+ else:
+ model = self.optimum_quantizer.convert_model(model, **kwargs)
+
+ def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ if self.pre_quantized:
+ model = self.optimum_quantizer.post_init_model(model)
+ else:
+ if self.quantization_config.tokenizer is None:
+ self.quantization_config.tokenizer = model.name_or_path
+
+ self.optimum_quantizer.quantize_model(model, self.quantization_config.tokenizer)
+ model.config.quantization_config = GPTQConfig.from_dict(self.optimum_quantizer.to_dict())
+
+ @property
+ def is_trainable(self) -> bool:
+ return True
+
+ def is_serializable(self):
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_higgs.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_higgs.py
new file mode 100644
index 0000000000000000000000000000000000000000..78d168aab59c2b097c17df6fcfb60483385eeeb0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_higgs.py
@@ -0,0 +1,178 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from ..utils.logging import tqdm
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import HiggsConfig
+
+from ..utils import is_accelerate_available, is_flute_available, is_hadamard_available, is_torch_available, logging
+from ..utils.quantization_config import QuantizationConfigMixin
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class HiggsHfQuantizer(HfQuantizer):
+ """
+ Quantizer of the HIGGS method. Enables the loading of prequantized models and in-flight quantization of full-precision models.
+ """
+
+ requires_calibration = False
+ quantization_config: "HiggsConfig"
+
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, device_map, **kwargs):
+ if not torch.cuda.is_available():
+ raise NotImplementedError("HIGGS quantization is only supported on GPU. Please use a different quantizer.")
+
+ if not is_accelerate_available():
+ raise ImportError("Using `higgs` quantization requires Accelerate: `pip install accelerate`")
+
+ if not is_flute_available():
+ raise ImportError("Using `higgs` quantization requires FLUTE: `pip install flute-kernel>=0.3.0`")
+
+ if not is_hadamard_available():
+ raise ImportError(
+ "Using `higgs` quantization requires fast_hadamard_transform: `pip install fast_hadamard_transform`"
+ )
+
+ if device_map is None:
+ raise ValueError(
+ "You are attempting to load a HIGGS model without setting device_map."
+ " Please set device_map comprised of 'cuda' devices."
+ )
+ elif isinstance(device_map, dict):
+ if "cpu" in device_map.values() or "disk" in device_map.values():
+ raise ValueError(
+ "You are attempting to load a HIGGS model with a device_map that contains a CPU or disk device."
+ " This is not supported. Please remove the CPU or disk device from the device_map."
+ )
+
+ def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
+ if dtype != torch.float16 and dtype != torch.bfloat16:
+ raise ValueError(
+ f"Invalid `dtype` {dtype}. HIGGS quantization only supports `dtype=torch.float16` or `dtype=torch.bfloat16`."
+ )
+
+ return dtype
+
+ # TODO: to remove
+ # Kept here in case we see some interest in adding support for it
+ # def create_quantized_param(
+ # self,
+ # model: "PreTrainedModel",
+ # param_value: "torch.Tensor",
+ # param_name: str,
+ # target_device: "torch.device",
+ # **kwargs,
+ # ):
+ # from ..integrations import quantize_with_higgs
+
+ # flute_dict = quantize_with_higgs(
+ # param_value.to(target_device),
+ # self.quantization_config.bits,
+ # self.quantization_config.p,
+ # self.quantization_config.group_size,
+ # self.quantization_config.hadamard_size,
+ # )
+ # del param_value
+
+ # module, _ = get_module_from_name(model, param_name)
+ # module_name = ".".join(param_name.split(".")[:-1])
+ # for key, value in flute_dict.items():
+ # if key in module._parameters:
+ # module._parameters[key] = torch.nn.Parameter(value, requires_grad=False)
+ # elif key in module._buffers:
+ # module._buffers[key] = torch.nn.Buffer(value)
+ # elif key == "tune_metadata":
+ # module.tune_metadata = value
+ # self.quantization_config.tune_metadata[module_name] = value.to_dict()
+ # else:
+ # raise ValueError(f"Unexpected key {key} in module {module}")
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ **kwargs,
+ ):
+ from ..integrations import replace_with_higgs_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+
+ replace_with_higgs_linear(
+ model,
+ quantization_config=self.quantization_config,
+ modules_to_not_convert=self.modules_to_not_convert,
+ )
+
+ def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ from flute.tune import TuneMetaData, maybe_tune_and_repack
+ from flute.utils import make_workspace_streamk
+
+ from ..integrations import HiggsLinear
+
+ flute_workspaces = {}
+ flute_modules = {name: module for name, module in model.named_modules() if isinstance(module, HiggsLinear)}
+ for name, module in tqdm(flute_modules.items(), desc="Repacking HIGGS modules", leave=False):
+ # Every HiggsLinear needs a "workspace": a buffer for the unpacking operation.
+ # This buffer needs to be on the same device as the weights, but can be reused across modules otherwise.
+ if module.weight.device not in flute_workspaces:
+ flute_workspaces[module.weight.device] = make_workspace_streamk(device=module.weight.device)
+ module.workspace = flute_workspaces[module.weight.device]
+
+ # FLUTE weights are packed in a way that is optimized for a specific number of SMs (GPU streaming multiprocessors).
+ # If the model is loaded on a different device than the one it was saved on, we need to repack the weights.
+ module.tune_metadata = TuneMetaData.from_dict(self.quantization_config.tune_metadata[name])
+ module.weight.data, module.tune_metadata = maybe_tune_and_repack(
+ weight=module.weight.data,
+ scales=module.scales.data,
+ metadata=module.tune_metadata,
+ )
+ self.quantization_config.tune_metadata[name] = module.tune_metadata.to_dict()
+
+ @property
+ def is_trainable(self) -> bool:
+ return False
+
+ def is_serializable(self):
+ return True
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ from ..integrations import HiggsLinear
+
+ module, tensor_name = get_module_from_name(model, param_name)
+ if isinstance(module, HiggsLinear) and tensor_name == "weight":
+ # Only quantize weights of HiggsLinear modules that are not already quantized
+ return True
+ else:
+ return False
+
+ def _dequantize(self, model):
+ from ..integrations import dequantize_higgs
+
+ model = dequantize_higgs(model)
+ return model
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_hqq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_hqq.py
new file mode 100644
index 0000000000000000000000000000000000000000..05dce3d996a0693a9db2349cbc5079f3aff52cd6
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_hqq.py
@@ -0,0 +1,264 @@
+# 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 ..integrations import prepare_for_hqq_linear
+from ..utils import is_hqq_available, is_torch_available, logging
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import HqqConfig
+
+
+if is_torch_available():
+ import torch
+
+if is_hqq_available():
+ from hqq.core.quantize import HQQLinear
+
+ # This is a compatibility hack. HQQ-quantized linear layers do not have a `weight` attribute,
+ # but some models attempt to access `weight.dtype` during the forward pass. To prevent runtime errors,
+ # we patch HQQLinear with a dummy `weight` property that returns an empty tensor with the correct dtype and device.
+ @property
+ def weight(self):
+ return torch.empty(0, dtype=self.compute_dtype, device=self.device)
+
+ HQQLinear.weight = weight
+
+logger = logging.get_logger(__name__)
+
+
+class HqqHfQuantizer(HfQuantizer):
+ """
+ HQQ quantizer base HF class.
+ nn.Linear modules are first tagged with quant_config in _process_model_before_weight_loading().
+ """
+
+ requires_calibration = False
+ quantization_config: "HqqConfig"
+
+ def __init__(self, quantization_config, **kwargs):
+ if not is_hqq_available():
+ raise ImportError(
+ "A valid HQQ version (>=0.2.1) is not available. Please follow the instructions to install it: `https://github.com/mobiusml/hqq/`."
+ )
+ super().__init__(quantization_config, **kwargs)
+ self.dtype = None
+ self.using_multi_gpu = False
+ # Keys that are serialized specifically by hqq
+ self.hqq_keys = HQQLinear(None, None).state_dict_keys() - {"bias"}
+
+ def validate_environment(self, *args, **kwargs):
+ if self.dtype is None:
+ if "dtype" in kwargs:
+ self.dtype = kwargs["dtype"]
+ else:
+ self.dtype = torch.float32
+ logger.info("Setting dtype to torch.float32 as the default value since it was not specified.")
+
+ device_map = kwargs.get("device_map")
+ if isinstance(device_map, dict):
+ if "cpu" in device_map.values() or "disk" in device_map.values():
+ raise ValueError(
+ "You are attempting to use an HQQ model with a device_map that contains a CPU or disk device."
+ " This is not supported. Please remove the CPU or disk device from the device_map."
+ )
+ else:
+ self.using_multi_gpu = len(set(device_map.values())) > 1
+
+ # TODO: to remove
+ # Kept here in case we see some interest in adding support for it
+ # # Adds missing keys for HQQLinear modules that are loaded but the model with initialized with torch.nn.Linear
+ # def update_expected_keys(
+ # self, model: "PreTrainedModel", expected_keys: list[str], loaded_keys: list[str]
+ # ) -> list[str]:
+ # if not self.pre_quantized:
+ # return expected_keys
+
+ # # Collects all quantizable (linear) layers
+ # def _find_hqq_quantizable_layers(model, layers):
+ # for name, module in model.named_children():
+ # if isinstance(module, (torch.nn.Linear)):
+ # layers.add(module.name)
+ # _find_hqq_quantizable_layers(module, layers)
+
+ # new_keys = set(expected_keys)
+
+ # # Name modules
+ # for name, module in model.named_modules():
+ # module.name = name
+
+ # # valid modules are Linear layers that have HQQLinear state_dict. We ignore skip_modules and any layers with Linear state_dict() params
+ # _valid_modules = set()
+ # _find_hqq_quantizable_layers(model, _valid_modules)
+
+ # # Remove skipped modules
+ # _skipped_modules = set()
+ # for _module in _valid_modules:
+ # for _skip_module in model.config.quantization_config["skip_modules"]:
+ # if _skip_module in _module:
+ # _skipped_modules.add(_module)
+ # _valid_modules -= _skipped_modules
+
+ # # Append new expected layers based on _ref_keys
+ # _ref_keys = HQQLinear(
+ # linear_layer=None,
+ # quant_config=None,
+ # compute_dtype=torch.float16,
+ # device="cpu",
+ # del_orig=False,
+ # ).state_dict_keys() - {"bias"}
+
+ # # Clean-up
+ # _rm_keys = set()
+ # for key in new_keys:
+ # if any(_module in key for _module in _valid_modules):
+ # _rm_keys.add(key)
+ # new_keys -= _rm_keys
+ # # At this point, new_keys contains all the keys of the layers that are NOT HQQLinear or torch.nn.Linear
+
+ # # Re-populate Linear/HQQLinear
+ # for _module in _valid_modules:
+ # if _module + ".weight" in loaded_keys:
+ # new_keys.add(_module + ".weight")
+ # else:
+ # new_keys.update({_module + "." + _ref_key for _ref_key in _ref_keys})
+ # if _module + ".bias" in loaded_keys:
+ # new_keys.add(_module + ".bias")
+
+ # return list(new_keys)
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ module, _ = get_module_from_name(model, param_name)
+ # Since we do not prepare the modules in advance, we need every param of the Linear layer to go through
+ # `create_quantized_param`, even when `self.is_quantized == True`
+ return isinstance(module, torch.nn.Linear)
+
+ # TODO: to remove
+ # def create_quantized_param(
+ # self,
+ # model: "PreTrainedModel",
+ # param_value: "torch.Tensor",
+ # param_name: str,
+ # target_device: "torch.device",
+ # **kwargs,
+ # ):
+ # module, tensor_name = get_module_from_name(model, param_name)
+ # module_name = param_name.rsplit(".", 1)[0]
+ # parent_module, node = get_module_from_name(model, module_name)
+
+ # quant_config = model.config.quantization_config["quant_config"]
+ # skip_modules = model.config.quantization_config["skip_modules"]
+
+ # # In this case we do not quantize this layer (it's explicitly skipped) -> simply load param
+ # if any(skip_module in module.name for skip_module in skip_modules):
+ # module.load_state_dict(
+ # {tensor_name: param_value.to(device=target_device, dtype=self.dtype)}, strict=False, assign=True
+ # )
+ # return
+
+ # # We need this hack as the model is not pre-prepared as an empty skeleton on meta device
+ # if self.pre_quantized:
+ # # Save them for later
+ # if not hasattr(self, "hqq_params"):
+ # self.hqq_params = defaultdict(dict)
+ # self.hqq_params[module_name].update({tensor_name: param_value})
+ # hqq_params = self.hqq_params[module_name]
+
+ # # If they are all present and saved, make it a HQQLinear layer! (we cannot do it param after param because
+ # # hqq does not support it...)
+ # if all(k in hqq_params for k in self.hqq_keys) and ("bias" in hqq_params or module.bias is None):
+ # hqq_layer = HQQLinear(
+ # linear_layer=None,
+ # quant_config=None,
+ # compute_dtype=self.dtype,
+ # device=target_device,
+ # del_orig=False,
+ # )
+ # hqq_layer.load_state_dict(hqq_params)
+
+ # if hqq_layer.bias is not None and isinstance(hqq_layer.bias, torch.Tensor):
+ # hqq_layer.bias = torch.nn.Parameter(hqq_layer.bias)
+ # if self.using_multi_gpu:
+ # hqq_layer = self._patch_layer_for_multigpu(hqq_layer)
+
+ # setattr(parent_module, node, hqq_layer)
+ # del self.hqq_params[module_name], module
+ # return
+
+ # # Load param in the module (without caring about device or dtype, it will be changed later)
+ # module.load_state_dict({tensor_name: param_value}, strict=False, assign=True)
+
+ # # If both the weight and bias have already been loaded, time to quantize!
+ # module_is_ready = module.weight.device.type != "meta" and (
+ # module.bias is None or module.bias.device.type != "meta"
+ # )
+
+ # if module_is_ready:
+ # module_tag = ".".join(module.name.split(".")[-2:])
+ # if "weight_quant_params" in quant_config:
+ # module_quant_config = quant_config
+ # elif module_tag in quant_config:
+ # module_quant_config = quant_config[module_tag]
+
+ # hqq_layer = HQQLinear(
+ # module,
+ # quant_config=module_quant_config,
+ # compute_dtype=self.dtype,
+ # device=target_device,
+ # del_orig=True,
+ # )
+
+ # if hqq_layer.bias is not None and isinstance(hqq_layer.bias, torch.Tensor):
+ # hqq_layer.bias = torch.nn.Parameter(hqq_layer.bias)
+
+ # if self.using_multi_gpu:
+ # hqq_layer = self._patch_layer_for_multigpu(hqq_layer)
+
+ # setattr(parent_module, node, hqq_layer)
+
+ def _patch_layer_for_multigpu(self, hqq_layer):
+ def forward_with_device(self, x):
+ out = torch.matmul(x.to(self.device), self.dequantize().t())
+ if self.bias is not None:
+ out += self.bias
+ return out
+
+ hqq_layer.forward = lambda x: forward_with_device(hqq_layer, x)
+ return hqq_layer
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ **kwargs,
+ ):
+ # Add the corresponding quant_config to each valid module. This allows us to do the actual nn.Linear -> HQQLinear conversion in create_quantized_param().
+ # prepare_for_hqq_linear() also sets the right quantization config inside the model (model.config.quantization_config) and the layers (hqq_layer.quant_config)
+ model = prepare_for_hqq_linear(model, quantization_config=self.quantization_config)
+
+ def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ setattr(model, "is_hqq_quantized", True)
+ setattr(model, "is_hqq_serializable", self.is_serializable())
+ return model
+
+ def is_serializable(self):
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_metal.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_metal.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3706ed7e2b44d7b30aad5715097bf6a0c5351f9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_metal.py
@@ -0,0 +1,130 @@
+# 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.
+from typing import TYPE_CHECKING, Any
+
+from ..utils import is_kernels_available, is_torch_available, logging
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name
+
+
+if is_torch_available():
+ import torch
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import MetalConfig
+
+logger = logging.get_logger(__name__)
+
+
+class MetalHfQuantizer(HfQuantizer):
+ """
+ Quantizer for Metal affine quantization on Apple Silicon (MPS) devices.
+
+ Uses the ``quantization-mlx`` Metal kernels from the Hub to pack weights into
+ low-bit (2/4/8) uint32 tensors with per-group scales and biases, and performs
+ fused dequant + matmul in the forward pass.
+ """
+
+ requires_calibration = False
+ quantization_config: "MetalConfig"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if self.quantization_config.dequantize:
+ return
+
+ if not torch.backends.mps.is_available():
+ if self.pre_quantized:
+ logger.warning_once(
+ "Metal quantization requires an Apple Silicon GPU (MPS), but none is available. "
+ "We will default to dequantizing the model to the original dtype."
+ )
+ self.quantization_config.dequantize = True
+ return
+ else:
+ raise RuntimeError("Metal quantization requires an Apple Silicon GPU (MPS). No MPS device found.")
+
+ if not is_kernels_available():
+ raise ImportError("Metal quantization requires kernels: `pip install kernels`")
+
+ device_map = kwargs.get("device_map")
+ if device_map is None:
+ logger.warning_once(
+ "You have loaded a Metal quantized model on CPU and have an MPS device available. "
+ "Set device_map='mps' to use the Metal kernels."
+ )
+ elif isinstance(device_map, dict):
+ if not self.pre_quantized and ("cpu" in device_map.values() or "disk" in device_map.values()):
+ raise ValueError(
+ "Metal quantization on the fly does not support CPU or disk in the device_map. "
+ "Please use a pre-quantized checkpoint or remove CPU/disk from device_map."
+ )
+
+ def update_device_map(self, device_map: dict[str, Any] | None) -> dict[str, Any] | None:
+ if device_map is None:
+ device_map = {"": "mps"}
+ return device_map
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ from ..integrations.metal_quantization import MetalLinear
+
+ module, tensor_name = get_module_from_name(model, param_name)
+ if isinstance(module, MetalLinear):
+ if self.pre_quantized or tensor_name != "weight":
+ return False
+ return True
+ return False
+
+ def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ from ..integrations.metal_quantization import replace_with_metal_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+
+ model = replace_with_metal_linear(
+ model,
+ modules_to_not_convert=self.modules_to_not_convert,
+ quantization_config=self.quantization_config,
+ pre_quantized=self.pre_quantized,
+ )
+
+ def is_serializable(self):
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ return False
+
+ def get_quantize_ops(self):
+ from ..integrations.metal_quantization import MetalQuantize
+
+ return MetalQuantize(self)
+
+ def get_weight_conversions(self):
+ from ..core_model_loading import WeightConverter
+ from ..integrations.metal_quantization import MetalDequantize
+
+ if self.pre_quantized and self.quantization_config.dequantize:
+ return [
+ WeightConverter(
+ source_patterns=["weight$", "scales", "qbiases"],
+ target_patterns="weight",
+ operations=[MetalDequantize(self)],
+ )
+ ]
+ return []
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_mxfp4.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_mxfp4.py
new file mode 100644
index 0000000000000000000000000000000000000000..7859a8ff739ad41674f0f0ad5c28bbcfe3639ab9
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_mxfp4.py
@@ -0,0 +1,315 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import Mxfp4Config
+
+from ..utils import (
+ is_accelerate_available,
+ is_kernels_available,
+ is_torch_available,
+ is_triton_available,
+ logging,
+)
+from .quantizers_utils import get_module_from_name
+
+
+if is_torch_available():
+ import torch
+
+ from ..core_model_loading import WeightConverter
+
+logger = logging.get_logger(__name__)
+triton_kernels_hub = None
+
+
+class Mxfp4HfQuantizer(HfQuantizer):
+ """
+ FP4 quantization using fbgemm kernels
+ """
+
+ requires_calibration = False
+ quantization_config: "Mxfp4Config"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+ self.triton_kernels_hub = None
+
+ def _lazy_import_kernels(self):
+ """Lazy import and initialize kernels only when needed"""
+ if self.triton_kernels_hub is None:
+ try:
+ from ..integrations.hub_kernels import get_kernel
+
+ self.triton_kernels_hub = get_kernel("kernels-community/gpt-oss-triton-kernels")
+ except ImportError:
+ raise ImportError("kernels package is required for MXFP4 quantization")
+ return self.triton_kernels_hub
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_torch_available():
+ raise ImportError(
+ "Using mxfp4 quantization requires torch"
+ "Please install the latest version of torch ( pip install --upgrade torch )"
+ )
+
+ if self.quantization_config.dequantize:
+ return
+
+ if not is_accelerate_available():
+ raise ImportError("Using mxfp4 requires Accelerate: `pip install accelerate`")
+
+ device = torch.accelerator.current_accelerator() or torch.device("cpu")
+ if device.type not in ["cuda", "xpu", "cpu"]:
+ if self.pre_quantized:
+ logger.warning_once(
+ f"Using MXFP4 quantized models requires model on cuda/xpu/cpu, but found {device}, we will default to dequantizing the model to bf16. To use mxfp4, please disable the current accelerator."
+ )
+ self.quantization_config.dequantize = True
+ return
+ else:
+ raise RuntimeError(
+ f"Quantizing a model using MXFP4 requires model on cuda/xpu/cpu, but found {device}. To use mxfp4, please disable the current accelerator."
+ )
+
+ if torch.xpu.is_available():
+ is_device_supported_mxfp4 = True
+ triton_available = is_triton_available("3.5.0")
+ kernels_installed = is_kernels_available()
+ elif torch.cuda.is_available():
+ compute_capability = torch.cuda.get_device_capability()
+ is_device_supported_mxfp4 = compute_capability >= (7, 5)
+ triton_available = is_triton_available("3.4.0")
+ kernels_installed = is_kernels_available()
+ elif device.type == "cpu":
+ is_device_supported_mxfp4 = True
+ triton_available = is_triton_available("3.5.0")
+ kernels_installed = is_kernels_available()
+ else:
+ is_device_supported_mxfp4 = False
+ triton_available = False
+ kernels_installed = False
+
+ if self.pre_quantized:
+ if not is_device_supported_mxfp4:
+ logger.warning_once(
+ "MXFP4 quantization is only supported on GPUs with compute capability >= 7.5 "
+ "(e.g T4, A100, L4, H100, or B200) or XPUs (e.g Intel® Data Center GPU Max Series). "
+ "We will default to dequantizing the model to bf16."
+ )
+ self.quantization_config.dequantize = True
+ return
+
+ if not triton_available:
+ logger.warning_once(
+ "MXFP4 quantization requires Triton: CUDA requires Triton >= 3.4.0, "
+ "XPU/CPU requires Triton >= 3.5.0. Please install triton: `pip install triton`. "
+ "We will default to dequantizing the model to bf16."
+ )
+ self.quantization_config.dequantize = True
+ return
+
+ if not kernels_installed:
+ logger.warning_once(
+ "MXFP4 quantization requires the `kernels` package: "
+ "`pip install kernels>=0.12.0`. "
+ "We will default to dequantizing the model to bf16."
+ )
+ self.quantization_config.dequantize = True
+ return
+ elif not is_device_supported_mxfp4:
+ raise ValueError(
+ "MXFP4 quantization is only supported on GPUs with compute capability >= 7.5 "
+ "(e.g T4, A100, L4, H100, or B200) or XPUs (e.g Intel® Data Center GPU Max Series) or CPU"
+ )
+ elif not triton_available:
+ raise ValueError(
+ "MXFP4 quantization requires Triton: CUDA requires Triton >= 3.4.0, "
+ "XPU/CPU requires Triton >= 3.5.0. Please install triton: `pip install triton`"
+ )
+ elif not kernels_installed:
+ raise ValueError("MXFP4 quantization requires the `kernels` package: `pip install kernels>=0.12.0`")
+
+ if not self.pre_quantized:
+ self._lazy_import_kernels()
+
+ device_map = kwargs.get("device_map")
+ if device_map is not None and isinstance(device_map, dict):
+ if not self.pre_quantized and "disk" in device_map.values():
+ raise ValueError(
+ "You are attempting to load an FP4 model with a device_map that contains a disk device."
+ "This is not supported when the model is quantized on the fly. "
+ "Please use a quantized checkpoint or remove the disk device from the device_map."
+ )
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ from ..integrations import Mxfp4GptOssExperts
+
+ module, tensor_name = get_module_from_name(model, param_name)
+ if isinstance(module, Mxfp4GptOssExperts):
+ if tensor_name in ["down_proj_bias", "gate_up_proj_bias"]:
+ return False
+ return True
+ return False
+
+ def _process_model_after_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ # clean cache due to triton ops
+ if torch.cuda.is_available():
+ torch.cuda.empty_cache()
+ elif torch.xpu.is_available():
+ torch.xpu.empty_cache()
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ use_kernels: bool = False,
+ **kwargs,
+ ):
+ from ..integrations import replace_with_mxfp4_linear
+
+ # if we are using kernels, we can't use the quantized model, since the forward pass is different and needs special handling
+ # only CPU kernels can work with pre-quantized models
+ device = torch.accelerator.current_accelerator() or torch.device("cpu")
+ if use_kernels and device.type not in ["cpu"]:
+ logger.warning_once(
+ "You are using full precision kernels, we will dequantize the model to bf16. "
+ "To use the quantized model with quantization kernels, please set use_kernels=False"
+ )
+ self.quantization_config.dequantize = True
+
+ if not use_kernels and device.type in ["cpu"]:
+ logger.warning_once(
+ "MXFP4 inference on CPU requires use_kernels=True, but use_kernels is disabled. "
+ "We will dequantize the model to bf16. To run MXFP4 natively on CPU, please set use_kernels=True."
+ )
+ self.quantization_config.dequantize = True
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+
+ model = replace_with_mxfp4_linear(
+ model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
+ )
+
+ def update_tp_plan(self, config):
+ if "GptOssConfig" in config.__class__.__name__:
+ if getattr(config, "base_model_tp_plan", None) is not None:
+ config.base_model_tp_plan.update(
+ {
+ "layers.*.mlp.experts.gate_up_proj_blocks": "grouped_gemm",
+ "layers.*.mlp.experts.gate_up_proj_scales": "grouped_gemm",
+ "layers.*.mlp.experts.down_proj_blocks": "grouped_gemm",
+ "layers.*.mlp.experts.down_proj_scales": "grouped_gemm",
+ }
+ )
+ return config
+
+ def update_ep_plan(self, config):
+ if "GptOssConfig" in config.__class__.__name__:
+ if getattr(config, "base_model_ep_plan", None) is not None:
+ config.base_model_ep_plan.update(
+ {
+ "layers.*.mlp.experts.gate_up_proj_blocks": "grouped_gemm",
+ "layers.*.mlp.experts.gate_up_proj_scales": "grouped_gemm",
+ "layers.*.mlp.experts.down_proj_blocks": "grouped_gemm",
+ "layers.*.mlp.experts.down_proj_scales": "grouped_gemm",
+ }
+ )
+ return config
+
+ def get_state_dict_and_metadata(self, model):
+ from ..integrations import Mxfp4GptOssExperts
+
+ state_dict = model.state_dict()
+ num_local_experts = getattr(model.config, "num_local_experts", 32)
+ hidden_size = getattr(model.config, "hidden_size", 2880)
+
+ for name, module in model.named_modules():
+ if not (
+ isinstance(module, Mxfp4GptOssExperts)
+ and hasattr(module, "gate_up_proj")
+ and hasattr(module, "down_proj")
+ ):
+ continue
+
+ for proj in ("gate_up_proj", "down_proj"):
+ triton_tensor = getattr(module, proj)
+ precision_config = getattr(module, f"{proj}_precision_config")
+
+ blocks = triton_tensor.storage.layout.unswizzle_data(triton_tensor.storage.data).transpose(-1, -2)
+ if proj == "gate_up_proj":
+ blocks = blocks.reshape(num_local_experts, -1, 90, 16)
+ else:
+ blocks = blocks.reshape(num_local_experts, hidden_size, 90, -1)
+
+ scales = precision_config.weight_scale.storage.layout.unswizzle_data(
+ precision_config.weight_scale.storage.data
+ ).transpose(-1, -2)
+
+ state_dict[f"{name}.{proj}_blocks"] = blocks
+ state_dict[f"{name}.{proj}_scales"] = scales
+
+ metadata = {}
+ return state_dict, metadata
+
+ def is_serializable(self):
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ logger.warning_once(
+ "MXFP4 quantization don't support training, please consider dequantizing the model first by passing quantization_config=Mxfp4Config(dequantize=True) to .from_pretrained()"
+ )
+ return False
+
+ def get_quantize_ops(self):
+ from ..integrations.mxfp4 import Mxfp4Quantize
+
+ return Mxfp4Quantize(self)
+
+ def get_weight_conversions(self):
+ from ..integrations.mxfp4 import Mxfp4Dequantize, Mxfp4Deserialize
+
+ if self.pre_quantized and self.quantization_config.dequantize:
+ return [
+ WeightConverter(
+ source_patterns=["down_proj_blocks", "down_proj_scales"],
+ target_patterns=r"down_proj$",
+ operations=[Mxfp4Dequantize(self)],
+ ),
+ WeightConverter(
+ source_patterns=["gate_up_proj_blocks", "gate_up_proj_scales"],
+ target_patterns=["gate_up_proj$"],
+ operations=[Mxfp4Dequantize(self)],
+ ),
+ ]
+
+ return [
+ WeightConverter(
+ source_patterns=["gate_up_proj_blocks", "gate_up_proj_scales"],
+ target_patterns=r"gate_up_proj$",
+ operations=[Mxfp4Deserialize(self)],
+ ),
+ WeightConverter(
+ source_patterns=["down_proj_blocks", "down_proj_scales"],
+ target_patterns=r"down_proj$",
+ operations=[Mxfp4Deserialize(self)],
+ ),
+ ]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quanto.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quanto.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b08ec271356b1c8236f48a6e6418d4afbbd5768
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quanto.py
@@ -0,0 +1,122 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+
+from ..utils import (
+ is_accelerate_available,
+ is_optimum_quanto_available,
+ is_torch_available,
+ logging,
+)
+from ..utils.quantization_config import QuantoConfig
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class QuantoHfQuantizer(HfQuantizer):
+ """
+ Quantizer for the quanto library
+ """
+
+ requires_calibration = False
+ quantization_config: "QuantoConfig"
+
+ def __init__(self, quantization_config: QuantoConfig, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+ map_to_param_size = {
+ "int8": 1,
+ "float8": 1,
+ "int4": 0.5,
+ "int2": 0.25,
+ }
+ self.quantized_param_size = map_to_param_size.get(self.quantization_config.weights, None)
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_optimum_quanto_available():
+ raise ImportError(
+ "Loading an optimum-quanto quantized model requires optimum-quanto library (`pip install optimum-quanto`)"
+ )
+ if not is_accelerate_available():
+ raise ImportError(
+ "Loading an optimum-quanto quantized model requires accelerate library (`pip install accelerate`)"
+ )
+ device_map = kwargs.get("device_map")
+ if isinstance(device_map, dict):
+ if len(device_map) > 1 and "cpu" in device_map.values() or "disk" in device_map.values():
+ raise ValueError(
+ "You are attempting to load an model with a device_map that contains a CPU or disk device."
+ "This is not supported with quanto when the model is quantized on the fly. "
+ "Please remove the CPU or disk device from the device_map."
+ )
+ if self.quantization_config.activations is not None:
+ raise ValueError(
+ "We don't support quantizing the activations with transformers library."
+ "Use quanto library for more complex use cases such as activations quantization, calibration and quantization aware training."
+ )
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ from optimum.quanto import QModuleMixin
+
+ module, tensor_name = get_module_from_name(model, param_name)
+ # We only quantize the weights and the bias is not quantized.
+ if isinstance(module, QModuleMixin) and "weight" in tensor_name:
+ # if the weights are quantized, don't need to recreate it again with `create_quantized_param`
+ return not module.frozen
+ else:
+ return False
+
+ def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]:
+ max_memory = {key: val * 0.90 for key, val in max_memory.items()}
+ return max_memory
+
+ def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float:
+ "Return the element size (in bytes) for `param_name`."
+ if self.param_needs_quantization(model, param_name) and self.quantized_param_size is not None:
+ return self.quantized_param_size
+
+ return super().param_element_size(model, param_name, param)
+
+ def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ from ..integrations import replace_with_quanto_layers
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+
+ model = replace_with_quanto_layers(
+ model, modules_to_not_convert=self.modules_to_not_convert, quantization_config=self.quantization_config
+ )
+
+ @property
+ def is_trainable(self) -> bool:
+ return True
+
+ def is_serializable(self):
+ return False
+
+ def get_quantize_ops(self):
+ from ..integrations.quanto import QuantoQuantize
+
+ return QuantoQuantize(self)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quark.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quark.py
new file mode 100644
index 0000000000000000000000000000000000000000..590159cce77cb765b6d3c53a439ee3d9eb60d45a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_quark.py
@@ -0,0 +1,104 @@
+# Copyright 2025 Advanced Micro Devices, 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.
+
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import QuarkConfig
+
+from ..utils import is_quark_available, logging
+
+
+logger = logging.get_logger(__name__)
+
+
+CHECKPOINT_KEYS = {
+ "weight_scale": "weight_quantizer.scale",
+ "bias_scale": "bias_quantizer.scale",
+ "input_scale": "input_quantizer.scale",
+ "output_scale": "output_quantizer.scale",
+ "weight_zero_point": "weight_quantizer.zero_point",
+ "bias_zero_point": "bias_quantizer.zero_point",
+ "input_zero_point": "input_quantizer.zero_point",
+ "output_zero_point": "output_quantizer.zero_point",
+}
+
+
+class QuarkHfQuantizer(HfQuantizer):
+ """
+ Quark quantizer (https://quark.docs.amd.com/latest/).
+ """
+
+ requires_calibration = True # On-the-fly quantization with quark is not supported for now.
+ quantization_config: "QuarkConfig"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ self.json_export_config = quantization_config.json_export_config
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_quark_available():
+ raise ImportError(
+ "Loading a Quark quantized model requires the `quark` library but it was not found in the environment. Please refer to https://quark.docs.amd.com/latest/install.html."
+ )
+
+ def _process_model_before_weight_loading(self, model: "PreTrainedModel", **kwargs):
+ from quark.torch.export.api import _map_to_quark
+
+ _map_to_quark(
+ model,
+ self.quantization_config.quant_config,
+ pack_method=self.json_export_config.pack_method,
+ custom_mode=self.quantization_config.custom_mode,
+ )
+
+ return model
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ return True
+
+ def is_serializable(self):
+ return False
+
+ @property
+ def is_trainable(self):
+ return False
+
+ def get_weight_conversions(self):
+ from ..core_model_loading import WeightConverter
+ from ..integrations.quark import QuarkDeserialize
+
+ # In Quark, quantization is managed through a QParamsLinear module, which holds
+ # separate quantizers for the weights, inputs, and biases (e.g. weight_quantizer
+ # input_quantizer, bias_quantizer, etc.).
+ #
+ # The checkpoint stores keys like `weight_scale`, `input_scale`, etc.
+ # but the model's state_dict() exposes `weight_quantizer.scale`, `input_quantizer.scale`, etc.
+ # We rename from checkpoint format to model format, and the QuarkDeserialize operation
+ # handles assigning values into the corresponding quantizer attributes.
+ converters = []
+ for source_key, target_key in CHECKPOINT_KEYS.items():
+ converters.append(
+ WeightConverter(
+ source_patterns=[source_key],
+ target_patterns=target_key,
+ operations=[QuarkDeserialize(self)],
+ )
+ )
+ return converters
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_sinq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_sinq.py
new file mode 100644
index 0000000000000000000000000000000000000000..d42d4cc8296d2e0fba5535075235cf13c99d63a1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_sinq.py
@@ -0,0 +1,262 @@
+# Copyright 2026 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 __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from ..utils import is_torch_available, logging
+from ..utils.quantization_config import SinqConfig
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name
+
+
+if is_torch_available():
+ import torch
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+
+logger = logging.get_logger(__name__)
+
+
+class SinqHfQuantizer(HfQuantizer):
+ """
+ HF v5 quantizer for SINQ.
+
+ Modes:
+ - method="sinq" (default):
+ * weight-only SINQ
+ * param-level ConversionOps (`SinqQuantize`) during load for pure language models
+ (each Linear.weight is turned into a SINQLinear module)
+ * module-level quantization after load for multimodal models
+ - method="asinq":
+ * A-SINQ (activation-aware) SINQ quantization
+ """
+
+ requires_parameters_quantization: bool = True
+ quantization_config: SinqConfig
+
+ def __init__(self, quantization_config: SinqConfig, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ self._normalized_device_str: str | None = None
+ self._do_param_level_sinq: bool = False
+
+ def is_serializable(self) -> bool:
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ return True
+
+ def update_device_map(self, device_map):
+ if device_map is None:
+ if torch.cuda.is_available():
+ device_map = {"": torch.cuda.current_device()}
+ else:
+ device_map = {"": "cpu"}
+ logger.info(
+ "The device_map was not initialized. "
+ f"Setting device_map to {device_map}. "
+ "If you want to use the model for inference, please set device_map='auto'"
+ )
+ return device_map
+
+ def update_dtype(self, dtype: torch.dtype) -> torch.dtype:
+ if dtype is None:
+ dtype = torch.bfloat16
+ self.dtype = dtype
+ return dtype
+
+ def validate_environment(self, *args, **kwargs) -> None:
+ from ..utils import is_sinq_available
+
+ if not is_sinq_available():
+ raise ImportError("The 'sinq' package is not installed. Please install it with: pip install sinq")
+
+ if not torch.cuda.is_available():
+ logger.warning(
+ "No CUDA device is available. Quantization and inference will run on the CPU. Please note that this will significantly slow down inference speed and increase quantization time."
+ )
+
+ device_map = kwargs.get("device_map")
+
+ if isinstance(device_map, dict):
+ device_map_values = set(device_map.values())
+ if len(device_map_values) > 1:
+ raise RuntimeError(
+ "SinqHfQuantizer: multi-GPU device_map detected, but SINQ currently supports only a single CUDA "
+ f"device. Got {sorted(device_map_values)}. Please use device_map=None."
+ )
+
+ if self.quantization_config.method == "asinq" and not self.pre_quantized:
+ raise ValueError(
+ "You are using `method='asinq'` in the quantization config. Right now the calibrated version of SINQ"
+ " is not supported in Hugging Face, please refer and use the official SINQ repository "
+ "`to quantize a model with this method. "
+ )
+
+ def _build_sinq_quant_dict(self, cfg: SinqConfig) -> dict:
+ """
+ Build the dict that SINQLinear expects as quant_config.
+ """
+ from sinq.sinqlinear_hf import sinq_base_quant_config as sinq_base_quant_config_fn
+
+ method = cfg.method
+ return sinq_base_quant_config_fn(
+ nbits=int(cfg.nbits),
+ group_size=int(cfg.group_size) if cfg.group_size is not None else None,
+ quant_zero=False,
+ quant_scale=False,
+ view_as_float=False,
+ axis=1,
+ tiling_mode=str(cfg.tiling_mode),
+ method=method,
+ )
+
+ def param_needs_quantization(self, model: PreTrainedModel, param_name: str, **kwargs) -> bool:
+ """
+ Called per-parameter to decide whether to run `SinqQuantize` on it.
+
+ - If `self.pre_quantized`, we do *not* quantize again (handled by SinqDeserialize instead).
+ - For method="asinq": return False (ASINQ is not supported in Hugging Face).
+ - For method="sinq": True only for SINQLinear.weight not in modules_to_not_convert.
+
+ Note: After _process_model_before_weight_loading(), the modules are already SINQLinear,
+ not nn.Linear. We check for SINQLinear modules that are not yet quantized (ready=False).
+ """
+ from sinq.sinqlinear_hf import SINQLinear
+
+ if self.pre_quantized:
+ return False
+
+ if self.quantization_config.method == "asinq":
+ return False
+
+ # SINQ param-level only if deemed safe
+ if not self._do_param_level_sinq:
+ return False
+
+ module, tensor_name = get_module_from_name(model, param_name)
+
+ if tensor_name != "weight":
+ return False
+
+ # Check if it's an unquantized SINQLinear
+ is_sinq = isinstance(module, SINQLinear)
+ is_ready = getattr(module, "ready", True)
+ result = is_sinq and not is_ready
+ return result
+
+ def get_quantize_ops(self):
+ """
+ Return the ConversionOps used for param-level quantization (Sinq).
+ The actual SINQLinear construction is in integrations/sinq.py.
+ """
+ from ..integrations.sinq import SinqQuantize
+
+ return SinqQuantize(self)
+
+ def get_weight_conversions(self):
+ """
+ If `pre_quantized=True`, interpret a checkpoint produced by SINQLinear.state_dict:
+
+ .W_q
+ .bias
+ .meta
+
+ via a WeightConverter + SinqDeserialize so that we reconstruct a SINQLinear
+ module instead of a plain nn.Linear.
+ """
+ from ..core_model_loading import WeightConverter
+
+ if self.pre_quantized:
+ from ..integrations.sinq import SinqDeserialize
+
+ return [
+ WeightConverter(
+ source_patterns=[
+ ".W_q",
+ ".meta",
+ ".bias",
+ ],
+ target_patterns=[".weight"],
+ operations=[SinqDeserialize(self)],
+ )
+ ]
+ return []
+
+ def _process_model_before_weight_loading(
+ self,
+ model: PreTrainedModel,
+ device_map,
+ keep_in_fp32_modules: list[str] | None = None,
+ **kwargs,
+ ):
+ """
+ Called on meta-initialized model, before loading any weights.
+
+ For SINQ, we replace nn.Linear modules with empty SINQLinear modules here.
+ The actual quantization happens later in SinqQuantize.convert() when weights are loaded.
+ """
+ from ..integrations.sinq import replace_with_sinq_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, (self.quantization_config.modules_to_not_convert or []), keep_in_fp32_modules
+ )
+
+ # Enable param-level quantization for SINQ method
+ self._do_param_level_sinq = self.quantization_config.method == "sinq" and not self.pre_quantized
+
+ sinq_quant_dict = None if self.pre_quantized else self._build_sinq_quant_dict(self.quantization_config)
+
+ # Extract device from device_map (guaranteed to be set by update_device_map)
+ if isinstance(device_map, dict):
+ first_device = next(iter(device_map.values()), 0)
+ if isinstance(first_device, int):
+ device_str = f"cuda:{first_device}"
+ else:
+ device_str = str(first_device)
+ else:
+ device_str = "cuda:0" if torch.cuda.is_available() else "cpu"
+
+ model = replace_with_sinq_linear(
+ model,
+ modules_to_not_convert=self.modules_to_not_convert,
+ quant_config=sinq_quant_dict,
+ compute_dtype=self.dtype,
+ device=device_str,
+ pre_quantized=self.pre_quantized,
+ )
+
+ def _process_model_after_weight_loading(
+ self,
+ model: PreTrainedModel,
+ **kwargs,
+ ):
+ """
+ Called after *all* weights have been loaded.
+
+ For SINQ:
+ 1. Move non-SINQLinear modules to GPU (embeddings, norms, lm_head, etc.)
+ - SINQLinear modules already have GemLite buffers on GPU
+ - We skip moving SINQLinear's W_q/meta to avoid memory duplication
+ 2. Patch HF save/load methods for SINQ serialization
+ """
+ from sinq.hf_io import patch_hf_pretrained_io
+
+ # Patch HF save/load methods for SINQ serialization
+ patch_hf_pretrained_io()
+
+ return model
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_spqr.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_spqr.py
new file mode 100644
index 0000000000000000000000000000000000000000..918b7c6a01b5e2717a600f21c2982088ef4694d3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_spqr.py
@@ -0,0 +1,81 @@
+# 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/lic enses/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 .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import SpQRConfig
+
+from ..integrations import replace_with_spqr_linear
+from ..utils import is_accelerate_available, is_spqr_available, is_torch_available, logging
+from ..utils.quantization_config import QuantizationConfigMixin
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class SpQRHfQuantizer(HfQuantizer):
+ """
+ Quantizer of the SpQR method. Enables the loading of prequantized models.
+ """
+
+ requires_calibration = True
+ quantization_config: "SpQRConfig"
+
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if not torch.cuda.is_available():
+ raise RuntimeError("GPU is required to run SpQR quantized model.")
+
+ if not is_accelerate_available():
+ raise ImportError("Using `spqr` quantization requires Accelerate: `pip install accelerate`")
+
+ if not is_spqr_available():
+ raise ImportError("Using `spqr` quantization requires SpQR: `pip install spqr_quant[gpu]`")
+
+ def update_dtype(self, dtype: "torch.dtype") -> "torch.dtype":
+ if dtype != torch.float16:
+ raise ValueError(
+ "You cannot use any type other than torch.float16 for SpQR. Please set it totorch.float16 explicitly."
+ )
+ return dtype
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ **kwargs,
+ ):
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+ replace_with_spqr_linear(
+ model,
+ quantization_config=self.quantization_config,
+ modules_to_not_convert=self.modules_to_not_convert,
+ )
+
+ @property
+ def is_trainable(self):
+ return False
+
+ def is_serializable(self):
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_torchao.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_torchao.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd117b08023b598c334d80c1140707de5717c93c
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_torchao.py
@@ -0,0 +1,196 @@
+# 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.
+import re
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+from .quantizers_utils import get_module_from_name, should_convert_module
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import TorchAoConfig
+
+from safetensors import safe_open
+
+from ..utils import is_torch_available, is_torchao_available, logging
+
+
+MIN_TORCH_VERSION = "2.5.0"
+
+
+if is_torch_available():
+ from ..core_model_loading import WeightConverter
+
+
+if is_torch_available():
+ import torch
+
+if is_torchao_available():
+ from torchao.prototype.safetensors.safetensors_support import (
+ flatten_tensor_state_dict,
+ )
+
+
+logger = logging.get_logger(__name__)
+
+
+def _fuzzy_match_size(config_name: str) -> str | None:
+ """
+ Extract the size digit from torchao config class names like "Int4WeightOnlyConfig", "Int8WeightOnlyConfig".
+ Returns the digit as a string if found, otherwise None.
+ """
+ match = re.search(r"(\d)weight", config_name.lower())
+ return match.group(1) if match else None
+
+
+class TorchAoHfQuantizer(HfQuantizer):
+ """
+ Quantizer for torchao: https://github.com/pytorch/ao/
+ """
+
+ requires_calibration = False
+ quantization_config: "TorchAoConfig"
+
+ def __init__(self, quantization_config, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ size_digit = _fuzzy_match_size(type(self.quantization_config.quant_type).__name__)
+ self.quantized_param_size = 0.5 if size_digit == "4" else 1
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_torchao_available():
+ raise ImportError("Loading an torchao quantized model requires torchao library (`pip install torchao`)")
+
+ device_map = kwargs.get("device_map")
+ self.offload_to_cpu = False
+ if isinstance(device_map, dict):
+ if ("disk" in device_map.values() or "cpu" in device_map.values()) and len(device_map) > 1:
+ self.offload_to_cpu = "cpu" in device_map.values()
+ if self.pre_quantized and "disk" in device_map.values():
+ raise ValueError(
+ "You are attempting to perform disk offload with a pre-quantized torchao model "
+ "This is not supported yet . Please remove the disk device from the device_map."
+ )
+
+ def get_state_dict_and_metadata(self, model):
+ """
+ We flatten the state dict of tensor subclasses so that it is compatible with the safetensors format.
+ """
+ return flatten_tensor_state_dict(model.state_dict())
+
+ def param_element_size(self, model: "PreTrainedModel", param_name: str, param: "torch.Tensor") -> float:
+ "Return the element size (in bytes) for `param_name`."
+ if self.param_needs_quantization(model, param_name) and self.quantized_param_size is not None:
+ return self.quantized_param_size
+
+ return super().param_element_size(model, param_name, param)
+
+ def adjust_max_memory(self, max_memory: dict[str, int | str]) -> dict[str, int | str]:
+ # need more space for the quantization parameters (e.g. scale). Tested with int4 wo and group size = 128
+ max_memory = {key: val * 0.9 for key, val in max_memory.items()}
+ return max_memory
+
+ def _process_model_before_weight_loading(self, model: "PreTrainedModel", checkpoint_files=None, **kwargs):
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+ if self.quantization_config.include_input_output_embeddings:
+ input_emb = model.get_input_embeddings()
+ input_emb_names = [name for name, module in model.named_modules() if id(module) == id(input_emb)]
+ output_emb = model.get_output_embeddings()
+ output_emb_names = [name for name, module in model.named_modules() if id(module) == id(output_emb)]
+ self.modules_to_not_convert = [
+ x for x in self.modules_to_not_convert if x not in input_emb_names + output_emb_names
+ ]
+ if checkpoint_files is not None:
+ # Torchao needs access to all metadata later
+ self.set_metadata(checkpoint_files)
+
+ def param_needs_quantization(self, model: "PreTrainedModel", param_name: str, **kwargs) -> bool:
+ # check if the param_name is not in self.modules_to_not_convert
+ if not should_convert_module(param_name, self.modules_to_not_convert):
+ return False
+
+ # we only quantize the weight of nn.Linear and nn.Embedding
+ module, tensor_name = get_module_from_name(model, param_name)
+ _QUANTIZABLE = [torch.nn.Linear]
+ if self.quantization_config.include_input_output_embeddings:
+ _QUANTIZABLE.append(torch.nn.Embedding)
+
+ from torchao.quantization import FqnToConfig, fqn_matches_fqn_config
+
+ if isinstance(self.quantization_config.quant_type, FqnToConfig):
+ module_fqn, _ = param_name.rsplit(".", 1)
+ if (
+ fqn_matches_fqn_config(module_fqn, self.quantization_config.quant_type)
+ or fqn_matches_fqn_config(param_name, self.quantization_config.quant_type)
+ or (
+ "_default" in self.quantization_config.quant_type.fqn_to_config
+ and isinstance(module, tuple(_QUANTIZABLE))
+ )
+ ):
+ return True
+
+ return isinstance(module, tuple(_QUANTIZABLE)) and tensor_name == "weight"
+
+ def is_serializable(self) -> bool:
+ return True
+
+ @property
+ def is_trainable(self) -> bool:
+ # Only 8-bit quantization (e.g. Int8WeightOnly, Int8DynamicActivationInt8Weight) supports training
+ return _fuzzy_match_size(type(self.quantization_config.quant_type).__name__) == "8"
+
+ @property
+ def is_compileable(self) -> bool:
+ return True
+
+ def set_metadata(self, checkpoint_files: list[str]):
+ if checkpoint_files[0].endswith(".safetensors"):
+ metadata = {}
+ for checkpoint in checkpoint_files:
+ with safe_open(checkpoint, framework="pt") as f:
+ metadata_ = f.metadata() or {}
+ metadata.update(metadata_)
+ # Save it
+ self.metadata = metadata
+
+ def get_quantize_ops(self):
+ from ..integrations.torchao import TorchAoQuantize
+
+ return TorchAoQuantize(self)
+
+ def get_weight_conversions(self):
+ from ..integrations.torchao import TorchAoDeserialize
+
+ if self.pre_quantized:
+ return [
+ WeightConverter(
+ # TODO: incr flexibility by generalizing the source patterns to match the format of "_weight_"
+ # note that the matching logic is greedy, so for ex, if _weight_scale is before _weight_scale_and_zero in this list, it will match _weight_scale always (this is incorrect)
+ # thus, the order of source_patterns is intentional
+ source_patterns=[
+ "_weight_qdata",
+ "_weight_scale_and_zero",
+ "_weight_per_tensor_scale",
+ "_weight_scale",
+ "_weight_zero_point",
+ "_weight_act_pre_scale",
+ ],
+ target_patterns="weight",
+ operations=[TorchAoDeserialize(self)],
+ ),
+ ]
+ return []
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_vptq.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_vptq.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d60559b09d36e7b401c24fa0bcbfcdc1106a165
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizer_vptq.py
@@ -0,0 +1,75 @@
+# 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.
+from typing import TYPE_CHECKING
+
+from .base import HfQuantizer
+
+
+if TYPE_CHECKING:
+ from ..modeling_utils import PreTrainedModel
+ from ..utils.quantization_config import VptqConfig
+
+from ..utils import is_accelerate_available, is_torch_available, is_vptq_available, logging
+from ..utils.quantization_config import QuantizationConfigMixin
+
+
+if is_torch_available():
+ import torch
+
+logger = logging.get_logger(__name__)
+
+
+class VptqHfQuantizer(HfQuantizer):
+ """
+ Quantizer of the VPTQ method. Enables the loading of prequantized models.
+ """
+
+ requires_calibration = True
+ quantization_config: "VptqConfig"
+
+ def __init__(self, quantization_config: QuantizationConfigMixin, **kwargs):
+ super().__init__(quantization_config, **kwargs)
+
+ def validate_environment(self, *args, **kwargs):
+ if not is_accelerate_available():
+ raise ImportError("Using `vptq` quantization requires Accelerate: `pip install accelerate`")
+
+ if not is_vptq_available():
+ raise ImportError("Using `vptq` quantization requires VPTQ>=0.0.4: `pip install -U vptq`")
+
+ if not torch.cuda.is_available():
+ raise RuntimeError("GPU is required to run VTPQ quantized model.")
+
+ def _process_model_before_weight_loading(
+ self,
+ model: "PreTrainedModel",
+ **kwargs,
+ ):
+ from ..integrations import replace_with_vptq_linear
+
+ self.modules_to_not_convert = self.get_modules_to_not_convert(
+ model, self.quantization_config.modules_to_not_convert, model._keep_in_fp32_modules
+ )
+ replace_with_vptq_linear(
+ model,
+ quantization_config=self.quantization_config,
+ modules_to_not_convert=self.modules_to_not_convert,
+ )
+
+ @property
+ def is_trainable(self) -> bool:
+ return False
+
+ def is_serializable(self):
+ return True
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizers_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizers_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e90e238ec4a6ed4a392b170c95d1c6895025a80
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/quantizers/quantizers_utils.py
@@ -0,0 +1,41 @@
+# 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.
+import re
+from typing import Any
+
+
+def get_module_from_name(module, tensor_name: str) -> tuple[Any, str]:
+ if "." in tensor_name:
+ module_name, tensor_name = tensor_name.rsplit(".", 1)
+ module = module.get_submodule(module_name)
+ return module, tensor_name
+
+
+def should_convert_module(full_name, patterns: list[str] | None = None):
+ if patterns is None:
+ return True
+
+ # We should avoid converting in the following situations:
+ # 1. The pattern appears as a prefix followed by a dot in `full_name`
+ # (e.g., "model.decoder.layer.11." matches "model.decoder.layer.11.attn.weight").
+ # 2. The pattern matches `full_name` exactly or via regex
+ # (e.g., "lm_head" matches "lm_head"; "model.decoder.layer.*" matches "model.decoder.layer.11.attn.weight").
+ # 3. `full_name` ends with the pattern
+ # (e.g., "fc1" matches "model.decoder.layers.23.fc1").
+
+ should_not_convert = any(
+ re.match(f"{key}\\.", full_name) or re.match(f"{key}", full_name) or full_name.endswith(key)
+ for key in patterns
+ )
+ return not should_not_convert
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__init__.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d12e0b277c1bc54bd030dfaefb1caef3b1727737
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__init__.py
@@ -0,0 +1,336 @@
+#!/usr/bin/env python
+
+# 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.
+
+from functools import lru_cache
+
+from packaging import version
+
+from .. import __version__
+from .auto_docstring import (
+ ClassAttrs,
+ ClassDocstring,
+ ImageProcessorArgs,
+ ModelArgs,
+ ModelOutputArgs,
+ auto_class_docstring,
+ auto_docstring,
+ get_args_doc_from_source,
+ parse_docstring,
+ set_min_indent,
+)
+from .chat_template_utils import DocstringParsingException, TypeHintParsingException, get_json_schema
+from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
+from .doc import (
+ add_code_sample_docstrings,
+ add_end_docstrings,
+ add_start_docstrings,
+ add_start_docstrings_to_model_forward,
+ copy_func,
+ replace_return_docstrings,
+)
+from .generic import (
+ ContextManagers,
+ ExplicitEnum,
+ ModelOutput,
+ PaddingStrategy,
+ TensorType,
+ TransformersKwargs,
+ _is_tensor_or_array_like,
+ can_return_loss,
+ can_return_tuple,
+ expand_dims,
+ filter_out_non_signature_kwargs,
+ find_labels,
+ flatten_dict,
+ is_numpy_array,
+ is_tensor,
+ is_timm_config_dict,
+ is_timm_local_checkpoint,
+ is_torch_device,
+ is_torch_dtype,
+ is_torch_tensor,
+ reshape,
+ safe_load_json_file,
+ squeeze,
+ strtobool,
+ tensor_size,
+ to_numpy,
+ to_py_obj,
+ torch_float,
+ torch_int,
+ transpose,
+)
+from .hub import (
+ CHAT_TEMPLATE_DIR,
+ CHAT_TEMPLATE_FILE,
+ CLOUDFRONT_DISTRIB_PREFIX,
+ HF_MODULES_CACHE,
+ LEGACY_PROCESSOR_CHAT_TEMPLATE_FILE,
+ S3_BUCKET_PREFIX,
+ TRANSFORMERS_DYNAMIC_MODULE_NAME,
+ EntryNotFoundError,
+ PushInProgress,
+ PushToHubMixin,
+ RepositoryNotFoundError,
+ RevisionNotFoundError,
+ cached_file,
+ define_sagemaker_information,
+ extract_commit_hash,
+ has_file,
+ http_user_agent,
+ list_repo_templates,
+ try_to_load_from_cache,
+)
+from .import_utils import (
+ ACCELERATE_MIN_VERSION,
+ BITSANDBYTES_MIN_VERSION,
+ ENV_VARS_TRUE_AND_AUTO_VALUES,
+ ENV_VARS_TRUE_VALUES,
+ GGUF_MIN_VERSION,
+ TRITON_MIN_VERSION,
+ XLA_FSDPV2_MIN_VERSION,
+ DummyObject,
+ OptionalDependencyNotAvailable,
+ _LazyModule,
+ check_torch_load_is_safe,
+ direct_transformers_import,
+ enable_tf32,
+ get_torch_version,
+ is_accelerate_available,
+ is_apex_available,
+ is_apollo_torch_available,
+ is_aqlm_available,
+ is_auto_round_available,
+ is_av_available,
+ is_bitsandbytes_available,
+ is_bs4_available,
+ is_coloredlogs_available,
+ is_compressed_tensors_available,
+ is_cuda_platform,
+ is_cv2_available,
+ is_cython_available,
+ is_datasets_available,
+ is_decord_available,
+ is_detectron2_available,
+ is_env_variable_false,
+ is_env_variable_true,
+ is_essentia_available,
+ is_faiss_available,
+ is_fbgemm_gpu_available,
+ is_flash_attn_2_available,
+ is_flash_attn_3_available,
+ is_flash_attn_4_available,
+ is_flash_attn_greater_or_equal,
+ is_flash_attn_greater_or_equal_2_10,
+ is_flute_available,
+ is_fouroversix_available,
+ is_fp_quant_available,
+ is_fsdp_available,
+ is_g2p_en_available,
+ is_galore_torch_available,
+ is_gguf_available,
+ is_gptqmodel_available,
+ is_grokadamw_available,
+ is_grouped_mm_available,
+ is_habana_gaudi1,
+ is_hadamard_available,
+ is_hqq_available,
+ is_huggingface_hub_greater_or_equal,
+ is_in_notebook,
+ is_ipython_available,
+ is_jinja_available,
+ is_jmespath_available,
+ is_jumanpp_available,
+ is_kenlm_available,
+ is_kernels_available,
+ is_levenshtein_available,
+ is_libcst_available,
+ is_librosa_available,
+ is_liger_kernel_available,
+ is_llm_awq_available,
+ is_lomo_available,
+ is_matplotlib_available,
+ is_mistral_common_available,
+ is_mlx_available,
+ is_multipart_available,
+ is_natten_available,
+ is_ninja_available,
+ is_nltk_available,
+ is_num2words_available,
+ is_numba_available,
+ is_onnx_available,
+ is_openai_available,
+ is_optimum_available,
+ is_optimum_quanto_available,
+ is_pandas_available,
+ is_peft_available,
+ is_phonemizer_available,
+ is_pretty_midi_available,
+ is_protobuf_available,
+ is_psutil_available,
+ is_py3nvml_available,
+ is_pyctcdecode_available,
+ is_pytesseract_available,
+ is_pytest_available,
+ is_pytest_order_available,
+ is_pytorch_quantization_available,
+ is_quanto_greater,
+ is_quark_available,
+ is_qutlass_available,
+ is_rich_available,
+ is_rjieba_available,
+ is_rocm_platform,
+ is_sacremoses_available,
+ is_sagemaker_dp_enabled,
+ is_sagemaker_mp_enabled,
+ is_schedulefree_available,
+ is_scipy_available,
+ is_sentencepiece_available,
+ is_seqio_available,
+ is_serve_available,
+ is_sinq_available,
+ is_sklearn_available,
+ is_soundfile_available,
+ is_spacy_available,
+ is_speech_available,
+ is_spqr_available,
+ is_sudachi_available,
+ is_sudachi_projection_available,
+ is_tiktoken_available,
+ is_timm_available,
+ is_tokenizers_available,
+ is_torch_accelerator_available,
+ is_torch_available,
+ is_torch_bf16_available_on_device,
+ is_torch_bf16_gpu_available,
+ is_torch_cuda_available,
+ is_torch_deterministic,
+ is_torch_flex_attn_available,
+ is_torch_fp16_available_on_device,
+ is_torch_fx_proxy,
+ is_torch_greater_or_equal,
+ is_torch_hpu_available,
+ is_torch_mlu_available,
+ is_torch_mps_available,
+ is_torch_musa_available,
+ is_torch_neuron_available,
+ is_torch_neuroncore_available,
+ is_torch_npu_available,
+ is_torch_optimi_available,
+ is_torch_tensorrt_fx_available,
+ is_torch_tf32_available,
+ is_torch_xla_available,
+ is_torch_xpu_available,
+ is_torchao_available,
+ is_torchaudio_available,
+ is_torchcodec_available,
+ is_torchdistx_available,
+ is_torchdynamo_compiling,
+ is_torchdynamo_exporting,
+ is_torchvision_available,
+ is_torchvision_v2_available,
+ is_tracing,
+ is_training_run_on_sagemaker,
+ is_triton_available,
+ is_uroman_available,
+ is_vision_available,
+ is_vptq_available,
+ is_xlstm_available,
+ is_yt_dlp_available,
+ requires_backends,
+ torch_compilable_check,
+ torch_only_method,
+)
+from .kernel_config import KernelConfig
+from .peft_utils import (
+ ADAPTER_CONFIG_NAME,
+ ADAPTER_SAFE_WEIGHTS_NAME,
+ ADAPTER_WEIGHTS_NAME,
+ check_peft_version,
+ find_adapter_config_file,
+)
+
+
+WEIGHTS_NAME = "pytorch_model.bin"
+WEIGHTS_INDEX_NAME = "pytorch_model.bin.index.json"
+SAFE_WEIGHTS_NAME = "model.safetensors"
+SAFE_WEIGHTS_INDEX_NAME = "model.safetensors.index.json"
+CONFIG_NAME = "config.json"
+FEATURE_EXTRACTOR_NAME = "preprocessor_config.json"
+IMAGE_PROCESSOR_NAME = "preprocessor_config.json"
+VIDEO_PROCESSOR_NAME = "video_preprocessor_config.json"
+AUDIO_TOKENIZER_NAME = "audio_tokenizer_config.json"
+PROCESSOR_NAME = "processor_config.json"
+GENERATION_CONFIG_NAME = "generation_config.json"
+MODEL_CARD_NAME = "modelcard.json"
+
+
+SENTENCEPIECE_UNDERLINE = "▁"
+SPIECE_UNDERLINE = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility
+
+MULTIPLE_CHOICE_DUMMY_INPUTS = [
+ [[0, 1, 0, 1], [1, 0, 0, 1]]
+] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too.
+DUMMY_INPUTS = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
+DUMMY_MASK = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]
+
+
+def check_min_version(min_version):
+ if version.parse(__version__) < version.parse(min_version):
+ if "dev" in min_version:
+ error_message = (
+ "This example requires a source install from HuggingFace Transformers (see "
+ "`https://huggingface.co/docs/transformers/installation#install-from-source`),"
+ )
+ else:
+ error_message = f"This example requires a minimum version of {min_version},"
+ error_message += f" but the version found is {__version__}.\n"
+ raise ImportError(
+ error_message
+ + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other "
+ "versions of HuggingFace Transformers."
+ )
+
+
+@lru_cache
+def get_available_devices() -> frozenset[str]:
+ """
+ Returns a frozenset of devices available for the current PyTorch installation.
+ """
+ devices = {"cpu"} # `cpu` is always supported as a device in PyTorch
+
+ if is_torch_cuda_available():
+ devices.add("cuda")
+
+ if is_torch_mps_available():
+ devices.add("mps")
+
+ if is_torch_xpu_available():
+ devices.add("xpu")
+
+ if is_torch_npu_available():
+ devices.add("npu")
+
+ if is_torch_hpu_available():
+ devices.add("hpu")
+
+ if is_torch_mlu_available():
+ devices.add("mlu")
+
+ if is_torch_musa_available():
+ devices.add("musa")
+
+ return frozenset(devices)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/__init__.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/__init__.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a34931ff9950aa3919f758f9839af17ac7c2d94a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/__init__.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/attention_visualizer.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/attention_visualizer.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..743cdb0622bcc88cf0bd4138eaf9ae17d8532694
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/attention_visualizer.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/backbone_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/backbone_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..26e3e211aaec0c52d3a3c1ddf813d92a1ffc70e0
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/backbone_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_parsing_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_parsing_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc932baa4a1254767bad98241a91a21e3b7b41f4
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_parsing_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_template_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_template_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..63960ef1b94d346b9e2fdae3f3a40a26bef54c22
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/chat_template_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/constants.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/constants.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..aa144e4cdaf51ddfae307f0f9629fa536a2d93f1
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/constants.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/deprecation.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/deprecation.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc0db77809c152594b70ff07281cd4f7a4a42465
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/deprecation.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/doc.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/doc.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..e126236fd04cd2d3404ecf3983ed3ec1e8ffd37c
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/doc.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_detectron2_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_detectron2_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..f12cea8b4329e1a5c90c81b07504a4b394097a91
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_detectron2_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a4abe96ec5214a7a17ab4733be927f1bb78beb59
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_mistral_common_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_mistral_common_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7a0053b10cb30af0530d803b7ef8b2b8b23b57aa
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_mistral_common_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_music_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_music_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a0acde2520c71f78b1d64e2520594af02b315402
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_music_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_pt_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_pt_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5845a2ccfb35e71efc993367667f65fd4867d751
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_pt_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_sentencepiece_and_tokenizers_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_sentencepiece_and_tokenizers_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..d4a3a51061b437c70aa6f7184cc00d10d0e8046a
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_sentencepiece_and_tokenizers_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_speech_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_speech_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fb7a124d7970e3a604e039f63dd538dd713ff2ca
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_speech_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_timm_and_torchvision_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_timm_and_torchvision_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..84397e88928e371cd1157bdd842fee5a3d92a05e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_timm_and_torchvision_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_tokenizers_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_tokenizers_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..946b6960231b4250c8c0c4ea666a2736842f5745
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_tokenizers_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchaudio_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchaudio_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..10db61078b0c7245acda6e959588948c472a6002
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchaudio_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchvision_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchvision_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..c17a1f3bc697d729683f77fdb3a4d4029e4cac1d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_torchvision_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_vision_objects.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_vision_objects.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..a8f411ffef3a0e8680ee5675a4deae25f1973d30
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/dummy_vision_objects.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/generic.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/generic.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..4513d76f10dbd08be718c3211b8241a3f6ced55f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/generic.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hp_naming.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hp_naming.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..fde57256239a73b62e43b2c3b2f5209c29a533d3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hp_naming.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hub.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hub.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..90d81e10055a7971eaeccd788fea1c8f9449a574
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/hub.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/kernel_config.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/kernel_config.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7e7914457339a35980c56db60ece260b2afe3ff3
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/kernel_config.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/loading_report.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/loading_report.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..143cb6304e89cbefb1e93f417682d6cf6bbadacd
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/loading_report.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/logging.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/logging.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..bed9f65033a47d5dd978113be883e0f105307435
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/logging.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/metrics.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/metrics.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..1cf67bc447e8d42e23f04a2e46ecd93d7874098e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/metrics.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/network_logging.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/network_logging.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..dc03f3187cdc0be7a596fe5670f1421e52b830ac
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/network_logging.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/notebook.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/notebook.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..85b17cc29e79e3a4eb84e8daf3e01b4c86319185
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/notebook.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/output_capturing.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/output_capturing.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7eff8ac640262c2c67bc75a89c83adedd5a19a1d
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/output_capturing.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/peft_utils.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/peft_utils.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..7fec42b1948795caeac5365a5ec0022cad29f82b
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/peft_utils.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/pytest_helpers.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/pytest_helpers.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..b6ea3d9110bbf8cd5f4678114eff5cb0fa107295
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/pytest_helpers.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..64966ca7cd9e744bc288f3a76b4b71e1ee8d1d06
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2_new.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2_new.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..395244f63f292033f14242def33eb8f5a3fa1b5e
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/sentencepiece_model_pb2_new.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/type_validators.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/type_validators.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..05b8d7f3c5c200cb96876ffc555ecafc222aaa3f
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/type_validators.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/versions.cpython-311.pyc b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/versions.cpython-311.pyc
new file mode 100644
index 0000000000000000000000000000000000000000..5f3249dfae1ed2c62215e435a6380e1e7fee0705
Binary files /dev/null and b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/__pycache__/versions.cpython-311.pyc differ
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/attention_visualizer.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/attention_visualizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f9b9699101269cabdf84d9e79f8c91e10ff772a
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/attention_visualizer.py
@@ -0,0 +1,255 @@
+# Copyright 2025 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 io
+
+import httpx
+from PIL import Image
+
+from ..masking_utils import create_causal_mask
+from ..models.auto.auto_factory import _get_model_class
+from ..models.auto.configuration_auto import AutoConfig
+from ..models.auto.modeling_auto import MODEL_FOR_PRETRAINING_MAPPING, MODEL_MAPPING
+from ..models.auto.processing_auto import PROCESSOR_MAPPING_NAMES, AutoProcessor
+from ..models.auto.tokenization_auto import AutoTokenizer
+from .import_utils import is_torch_available
+
+
+if is_torch_available():
+ import torch
+ import torch.nn as nn
+
+# Print the matrix with words as row labels
+GREEN = "\033[92m"
+YELLOW = "\033[93m"
+RESET = "\033[0m"
+BLACK_SQUARE = "■"
+WHITE_SQUARE = "⬚"
+
+
+def generate_attention_matrix_from_mask(
+ words, mask, img_token="", sliding_window=None, token_type_ids=None, image_seq_length=None
+):
+ """
+ Generates an attention matrix from a given attention mask.
+
+ Optionally applies a sliding window mask (e.g., for Gemma2/3) and
+ marks regions where image tokens occur based on the specified `img_token`.
+ """
+ mask = mask.int()
+ if mask.ndim == 3:
+ mask = mask[0, :, :]
+ if mask.ndim == 4:
+ mask = mask[0, 0, :, :]
+
+ n = len(words)
+ max_word_length = max(len(repr(word)) for word in words)
+ first_img_idx = 0
+ output = []
+
+ for i, k in enumerate(words):
+ if k == img_token and not first_img_idx:
+ first_img_idx = i
+ mask[i, i] = 2 # Mark yellow regions
+ if first_img_idx > 0 and (k != img_token or i == n - 1):
+ if i == n - 1:
+ i += 1
+ mask[first_img_idx:i, first_img_idx:i] = 2 # Mark yellow regions
+ first_img_idx = 0
+
+ # Generate sliding window mask (size = 4), excluding img_token
+ sliding_window_mask = None
+ if sliding_window is not None:
+ sliding_window_mask = [[1 if (0 <= i - j < sliding_window) else 0 for j in range(n)] for i in range(n)]
+
+ row_dummy = " ".join(
+ f"{YELLOW}{BLACK_SQUARE}{RESET}"
+ if mask[0, j]
+ else f"{GREEN}{BLACK_SQUARE}{RESET}"
+ if j == 0
+ else BLACK_SQUARE
+ if mask[0, j]
+ else WHITE_SQUARE
+ for j in range(n)
+ )
+
+ if token_type_ids is not None:
+ is_special = token_type_ids == 1
+ token_type_buckets = torch.where(
+ (token_type_ids.cumsum(-1) % 5 + is_special).bool(), token_type_ids.cumsum(-1), 0
+ )
+ boundaries = torch.arange(0, image_seq_length + 1, image_seq_length)
+ token_type_buckets = torch.bucketize(token_type_buckets, boundaries=boundaries)
+
+ # Print headers
+ legend = f"{GREEN}{BLACK_SQUARE}{RESET}: i == j (diagonal) {YELLOW}{BLACK_SQUARE}{RESET}: token_type_ids"
+ output.append(" " + legend)
+ f_string = " " * (max_word_length + 5) + "Attention Matrix".ljust(len(row_dummy) // 2)
+ if sliding_window is not None:
+ f_string += "Sliding Window Mask"
+ output.append(f_string)
+
+ vertical_header = []
+ for idx, word in enumerate(words):
+ if mask[idx, idx] == 2:
+ vertical_header.append([f"{YELLOW}{k}{RESET}" for k in list(str(idx).rjust(len(str(n))))])
+ else:
+ vertical_header.append(list(str(idx).rjust(len(str(n)))))
+
+ vertical_header = list(map(list, zip(*vertical_header))) # Transpose
+
+ for row in vertical_header:
+ output.append(
+ (max_word_length + 5) * " " + " ".join(row) + " | " + " ".join(row)
+ if sliding_window is not None
+ else ""
+ )
+ for i, word in enumerate(words):
+ word_repr = repr(word).ljust(max_word_length)
+ colored_word = f"{YELLOW}{word_repr}{RESET}" if img_token in word else word_repr
+ row_display = " ".join(
+ f"{YELLOW}{BLACK_SQUARE}{RESET}"
+ if img_token in words[j] and mask[i, j] and img_token in word
+ else f"{GREEN}{BLACK_SQUARE}{RESET}"
+ if i == j
+ else BLACK_SQUARE
+ if mask[i, j]
+ else WHITE_SQUARE
+ for j in range(n)
+ )
+ sliding_window_row = ""
+ if sliding_window is not None:
+ sliding_window_row = " ".join(
+ f"{YELLOW}{BLACK_SQUARE}{RESET}"
+ if img_token in words[j] and img_token in word and token_type_buckets[0, i] == token_type_buckets[0, j]
+ else f"{GREEN}{BLACK_SQUARE}{RESET}"
+ if i == j
+ else BLACK_SQUARE
+ if sliding_window_mask[i][j]
+ else WHITE_SQUARE
+ for j in range(n)
+ )
+
+ output.append(f"{colored_word}: {str(i).rjust(2)} {row_display} | {sliding_window_row}")
+
+ return "\n".join(output)
+
+
+class AttentionMaskVisualizer:
+ def __init__(self, model_name: str):
+ config = AutoConfig.from_pretrained(model_name)
+ self.image_token = ""
+ if hasattr(config.get_text_config(), "sliding_window"):
+ self.sliding_window = getattr(config.get_text_config(), "sliding_window", None)
+ try:
+ mapped_cls = _get_model_class(config, MODEL_MAPPING)
+ except Exception:
+ mapped_cls = _get_model_class(config, MODEL_FOR_PRETRAINING_MAPPING)
+
+ if mapped_cls is None:
+ raise ValueError(f"Model name {model_name} is not supported for attention visualization")
+ self.mapped_cls = mapped_cls
+
+ class _ModelWrapper(mapped_cls, nn.Module):
+ def __init__(self, config, model_name):
+ nn.Module.__init__(self)
+ self.dummy_module = nn.Linear(1, 1)
+ self.config = config
+
+ self.model = _ModelWrapper(config, model_name)
+ self.model.to(config.dtype)
+ self.repo_id = model_name
+ self.config = config
+
+ def __call__(self, input_sentence: str, suffix=""):
+ self.visualize_attention_mask(input_sentence, suffix=suffix)
+
+ def visualize_attention_mask(self, input_sentence: str, suffix=""):
+ model = self.model
+ kwargs = {}
+ image_seq_length = None
+ if self.config.model_type in PROCESSOR_MAPPING_NAMES:
+ img = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg?download=true"
+ img = Image.open(io.BytesIO(httpx.get(img, follow_redirects=True).content))
+ image_seq_length = 5
+ processor = AutoProcessor.from_pretrained(self.repo_id, image_seq_length=image_seq_length)
+ if hasattr(processor, "image_token"):
+ image_token = processor.image_token
+ else:
+ image_token = processor.tokenizer.convert_ids_to_tokens([processor.image_token_id])[0]
+
+ if image_token:
+ input_sentence = input_sentence.replace("", image_token)
+
+ inputs = processor(images=img, text=input_sentence, suffix=suffix, return_tensors="pt")
+
+ self.image_token = processor.tokenizer.convert_ids_to_tokens([processor.image_token_id])[0]
+
+ attention_mask = inputs["attention_mask"]
+ if "token_type_ids" in inputs: # TODO inspect signature of update causal mask
+ kwargs["token_type_ids"] = inputs["token_type_ids"]
+ tokens = processor.tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
+ else:
+ tokenizer = AutoTokenizer.from_pretrained(self.repo_id)
+ if tokenizer is None:
+ raise ValueError(f"Could not load tokenizer for {self.repo_id}")
+ tokens = tokenizer.tokenize(input_sentence)
+ attention_mask = tokenizer(input_sentence, return_tensors="pt")["attention_mask"]
+ if attention_mask is None:
+ raise ValueError(f"Model type {self.config.model_type} does not support attention visualization")
+
+ model.config._attn_implementation = "eager"
+ model.train()
+
+ batch_size, seq_length = attention_mask.shape
+ inputs_embeds = torch.zeros((batch_size, seq_length, model.config.hidden_size), dtype=self.model.dtype)
+
+ causal_mask = create_causal_mask(
+ config=model.config,
+ inputs_embeds=inputs_embeds,
+ attention_mask=attention_mask,
+ past_key_values=None,
+ )
+
+ if causal_mask is None:
+ # attention_mask must be a tensor here
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(1).expand(batch_size, 1, seq_length, seq_length)
+ elif isinstance(causal_mask, torch.Tensor):
+ attention_mask = ~causal_mask.to(dtype=torch.bool)
+ else:
+ attention_mask = ~causal_mask
+
+ top_bottom_border = "##" * (
+ len(f"Attention visualization for {self.config.model_type} | {self.mapped_cls}") + 4
+ ) # Box width adjusted to text length
+ side_border = "##"
+ print(f"\n{top_bottom_border}")
+ print(
+ "##"
+ + f" Attention visualization for \033[1m{self.config.model_type}:{self.repo_id}\033[0m {self.mapped_cls.__name__}".center(
+ len(top_bottom_border)
+ )
+ + " "
+ + side_border,
+ )
+ print(f"{top_bottom_border}")
+ f_string = generate_attention_matrix_from_mask(
+ tokens,
+ attention_mask,
+ img_token=self.image_token,
+ sliding_window=getattr(self.config, "sliding_window", None),
+ token_type_ids=kwargs.get("token_type_ids"),
+ image_seq_length=image_seq_length,
+ )
+ print(f_string)
+ print(f"{top_bottom_border}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/auto_docstring.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/auto_docstring.py
new file mode 100644
index 0000000000000000000000000000000000000000..419579891e35530a2bface37fe7f7ecfedad1e91
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/auto_docstring.py
@@ -0,0 +1,4515 @@
+# Copyright 2025 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 __future__ import annotations
+
+import inspect
+import os
+from collections.abc import Mapping
+from functools import lru_cache
+from pathlib import Path
+from types import UnionType
+from typing import ClassVar, Union, get_args, get_origin
+
+import regex as re
+import typing_extensions
+
+from .doc import (
+ MODELS_TO_PIPELINE,
+ PIPELINE_TASKS_TO_SAMPLE_DOCSTRINGS,
+ PT_SAMPLE_DOCSTRINGS,
+)
+from .generic import ModelOutput
+
+
+PATH_TO_TRANSFORMERS = Path("src").resolve() / "transformers"
+
+
+AUTODOC_FILES = [
+ "configuration_*.py",
+ "modeling_*.py",
+ "tokenization_*.py",
+ "processing_*.py",
+ "image_processing_pil_*.py",
+ "image_processing_*.py",
+ "feature_extractor_*.py",
+]
+
+PLACEHOLDER_TO_AUTO_MODULE = {
+ "image_processor_class": ("image_processing_auto", "IMAGE_PROCESSOR_MAPPING_NAMES"),
+ "tokenizer_class": ("tokenization_auto", "TOKENIZER_MAPPING_NAMES"),
+ "video_processor_class": ("video_processing_auto", "VIDEO_PROCESSOR_MAPPING_NAMES"),
+ "feature_extractor_class": ("feature_extraction_auto", "FEATURE_EXTRACTOR_MAPPING_NAMES"),
+ "processor_class": ("processing_auto", "PROCESSOR_MAPPING_NAMES"),
+ "config_class": ("configuration_auto", "CONFIG_MAPPING_NAMES"),
+ "model_class": ("modeling_auto", "MODEL_MAPPING_NAMES"),
+}
+
+UNROLL_KWARGS_METHODS = {
+ "preprocess",
+ "__call__",
+}
+
+UNROLL_KWARGS_CLASSES = {
+ "BaseImageProcessor",
+ "ProcessorMixin",
+}
+BASIC_KWARGS_TYPES = ["TextKwargs", "ImagesKwargs", "VideosKwargs", "AudioKwargs"]
+
+# Short indicator added to unrolled kwargs to distinguish them from regular args
+KWARGS_INDICATOR = ", *kwargs*"
+
+HARDCODED_CONFIG_FOR_MODELS = {
+ "openai": "OpenAIGPTConfig",
+ "x-clip": "XCLIPConfig",
+ "kosmos2": "Kosmos2Config",
+ "kosmos2-5": "Kosmos2_5Config",
+ "donut": "DonutSwinConfig",
+ "esmfold": "EsmConfig",
+ "parakeet": "ParakeetCTCConfig",
+ "privacy-filter": "OpenAIPrivacyFilterConfig",
+ "lasr": "LasrCTCConfig",
+ "wav2vec2-with-lm": "Wav2Vec2Config",
+}
+
+_re_checkpoint = re.compile(r"\[(.+?)\]\((https://huggingface\.co/.+?)\)")
+
+# Pre-compiled patterns used repeatedly at runtime. Compiling once here avoids
+# repeated compilation overhead (and cache lookups) on every decorator call.
+_re_example_or_return = re.compile(r"(?m)^([ \t]*)(?=Example|Return|```)")
+_re_return = re.compile(r"(?m)^([ \t]*)(?=Return)")
+_re_example = re.compile(r"(?m)^([ \t]*)(?=Example|```)")
+_re_args_section = re.compile(r"(?:Args:)(\n.*)?(\n)?$", re.DOTALL)
+_re_shape = re.compile(r"(of shape\s*(?:`.*?`|\(.*?\)))")
+_re_default = re.compile(r"(defaults to \s*[^)]*)")
+_re_param = re.compile(
+ r"^\s{0,0}(\w+)\s*\(\s*([^, \)]*)(\s*.*?)\s*\)\s*:\s*((?:(?!\n^\s{0,0}\w+\s*\().)*)",
+ re.DOTALL | re.MULTILINE,
+)
+_re_forward_ref = re.compile(r"ForwardRef\('([\w.]+)'\)")
+_re_optional = re.compile(r"Optional\[(.*?)\]")
+_re_placeholders = re.compile(r"{(.*?)}")
+_re_model_task = None # built lazily because PT_SAMPLE_DOCSTRINGS isn't available yet
+
+
+class ImageProcessorArgs:
+ images = {
+ "description": """
+ 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`.
+ """,
+ "shape": None,
+ }
+
+ videos = {
+ "description": """
+ Video to preprocess. Expects a single or batch of videos with pixel values ranging from 0 to 255. If
+ passing in videos with pixel values between 0 and 1, set `do_rescale=False`.
+ """,
+ "shape": None,
+ }
+
+ do_resize = {
+ "description": """
+ Whether to resize the image.
+ """,
+ "shape": None,
+ }
+
+ size = {
+ "description": """
+ Describes the maximum input dimensions to the model.
+ """,
+ "shape": None,
+ }
+
+ size_divisor = {
+ "description": """
+ The size by which to make sure both the height and width can be divided.
+ """,
+ "shape": None,
+ }
+
+ default_to_square = {
+ "description": """
+ Whether to default to a square image when resizing, if size is an int.
+ """,
+ "shape": None,
+ }
+
+ resample = {
+ "description": """
+ 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`.
+ """,
+ "shape": None,
+ }
+
+ do_center_crop = {
+ "description": """
+ Whether to center crop the image.
+ """,
+ "shape": None,
+ }
+
+ crop_size = {
+ "description": """
+ Size of the output image after applying `center_crop`.
+ """,
+ "shape": None,
+ }
+
+ do_pad = {
+ "description": """
+ Whether to pad the image. Padding is done either to the largest size in the batch
+ or to a fixed square size per image. The exact padding strategy depends on the model.
+ """,
+ "shape": None,
+ }
+
+ pad_size = {
+ "description": """
+ The size in `{"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. Applied only when `do_pad=True.`
+ """,
+ "shape": None,
+ }
+
+ do_rescale = {
+ "description": """
+ Whether to rescale the image.
+ """,
+ "shape": None,
+ }
+
+ rescale_factor = {
+ "description": """
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
+ """,
+ "shape": None,
+ }
+
+ do_normalize = {
+ "description": """
+ Whether to normalize the image.
+ """,
+ "shape": None,
+ }
+
+ image_mean = {
+ "description": """
+ Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.
+ """,
+ "shape": None,
+ }
+
+ image_std = {
+ "description": """
+ Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to
+ `True`.
+ """,
+ "shape": None,
+ }
+
+ do_convert_rgb = {
+ "description": """
+ Whether to convert the image to RGB.
+ """,
+ "shape": None,
+ }
+
+ return_tensors = {
+ "description": """
+ Returns stacked tensors if set to `'pt'`, otherwise returns a list of tensors.
+ """,
+ "shape": None,
+ }
+
+ data_format = {
+ "description": """
+ Only `ChannelDimension.FIRST` is supported. Added for compatibility with slow processors.
+ """,
+ "shape": None,
+ }
+
+ input_data_format = {
+ "description": """
+ 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.
+ """,
+ "shape": None,
+ }
+
+ device = {
+ "description": """
+ The device to process the images on. If unset, the device is inferred from the input images.
+ """,
+ "shape": None,
+ }
+
+ disable_grouping = {
+ "description": """
+ Whether to disable grouping of images by size to process them individually and not in batches.
+ If None, will be set to True if the images are on CPU, and False otherwise. This choice is based on
+ empirical observations, as detailed here: https://github.com/huggingface/transformers/pull/38157
+ """,
+ "shape": None,
+ }
+
+ image_seq_length = {
+ "description": """
+ The number of image tokens to be used for each image in the input.
+ Added for backward compatibility but this should be set as a processor attribute in future models.
+ """,
+ "shape": None,
+ }
+
+ # Used for the **kwargs summary line when unrolling typed kwargs (key: "__kwargs__")
+ __kwargs__ = {
+ "description": """
+ Additional image preprocessing options. Model-specific kwargs are listed above; see the TypedDict class
+ for the complete list of supported arguments.
+ """,
+ "shape": None,
+ }
+
+
+class ProcessorArgs:
+ # __init__ arguments
+ image_processor = {
+ "description": """
+ The image processor is a required input.
+ """,
+ "type": "{image_processor_class}",
+ }
+
+ tokenizer = {
+ "description": """
+ The tokenizer is a required input.
+ """,
+ "type": "{tokenizer_class}",
+ }
+
+ video_processor = {
+ "description": """
+ The video processor is a required input.
+ """,
+ "type": "{video_processor_class}",
+ }
+
+ audio_processor = {
+ "description": """
+ The audio processor is a required input.
+ """,
+ "type": "{audio_processor_class}",
+ }
+
+ feature_extractor = {
+ "description": """
+ The feature extractor is a required input.
+ """,
+ "type": "{feature_extractor_class}",
+ }
+
+ chat_template = {
+ "description": """
+ A Jinja template to convert lists of messages in a chat into a tokenizable string.
+ """,
+ "type": "str",
+ }
+
+ # __call__ arguments
+ text = {
+ "description": """
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
+ (pretokenized string). If you pass a pretokenized input, set `is_split_into_words=True` to avoid ambiguity with batched inputs.
+ """,
+ }
+
+ audio = {
+ "description": """
+ The audio or batch of audios to be prepared. Each audio can be a NumPy array or PyTorch tensor.
+ In case of a NumPy array/PyTorch tensor, each audio should be of shape (C, T), where C is a number of channels,
+ and T is the sample length of the audio.
+ """,
+ }
+
+ audios = {
+ "description": """
+ The audio or batch of audios to be prepared. Each audio can be a NumPy array or PyTorch tensor.
+ In case of a NumPy array/PyTorch tensor, each audio should be of shape (C, T), where C is a number of channels,
+ and T is the sample length of the audio.
+ """,
+ }
+
+ return_tensors = {
+ "description": """
+ If set, will return tensors of a particular framework. Acceptable values are:
+
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
+ - `'np'`: Return NumPy `np.ndarray` objects.
+ """,
+ "shape": None,
+ }
+
+ # Standard tokenizer arguments
+ add_special_tokens = {
+ "description": """
+ Whether or not to add special tokens when encoding the sequences. This will use the underlying
+ [`PretrainedTokenizerBase.build_inputs_with_special_tokens`] function, which defines which tokens are
+ automatically added to the input ids. This is useful if you want to add `bos` or `eos` tokens
+ automatically.
+ """,
+ "type": "bool",
+ }
+
+ padding = {
+ "description": """
+ 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 is 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).
+ """,
+ "type": "bool, str or [`~utils.PaddingStrategy`]",
+ }
+
+ truncation = {
+ "description": """
+ Activates and controls truncation. Accepts the following values:
+
+ - `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).
+ """,
+ "type": "bool, str or [`~tokenization_utils_base.TruncationStrategy`]",
+ }
+
+ max_length = {
+ "description": """
+ 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.
+ """,
+ "type": "int",
+ }
+
+ stride = {
+ "description": """
+ 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.
+ """,
+ "type": "int",
+ }
+
+ pad_to_multiple_of = {
+ "description": """
+ If set will pad the sequence to a multiple of the provided value. Requires `padding` to be activated.
+ This is especially useful to enable using Tensor Cores on NVIDIA hardware with compute capability
+ `>= 7.5` (Volta).
+ """,
+ "type": "int",
+ }
+
+ return_token_type_ids = {
+ "description": """
+ Whether to return token type IDs. If left to the default, will return the token type IDs according to
+ the specific tokenizer's default, defined by the `return_outputs` attribute.
+
+ [What are token type IDs?](../glossary#token-type-ids)
+ """,
+ "type": "bool",
+ }
+
+ return_attention_mask = {
+ "description": """
+ Whether to return the attention mask. If left to the default, will return the attention mask according
+ to the specific tokenizer's default, defined by the `return_outputs` attribute.
+
+ [What are attention masks?](../glossary#attention-mask)
+ """,
+ "type": "bool",
+ }
+
+ return_overflowing_tokens = {
+ "description": """
+ Whether or not to return overflowing token sequences. If a pair of sequences of input ids (or a batch
+ of pairs) is provided with `truncation_strategy = longest_first` or `True`, an error is raised instead
+ of returning overflowing tokens.
+ """,
+ "type": "bool",
+ }
+
+ return_special_tokens_mask = {
+ "description": """
+ Whether or not to return special tokens mask information.
+ """,
+ "type": "bool",
+ }
+
+ return_offsets_mapping = {
+ "description": """
+ Whether or not to return `(char_start, char_end)` for each token.
+
+ This is only available on fast tokenizers inheriting from [`PreTrainedTokenizerFast`], if using
+ Python's tokenizer, this method will raise `NotImplementedError`.
+ """,
+ "type": "bool",
+ }
+
+ return_length = {
+ "description": """
+ Whether or not to return the lengths of the encoded inputs.
+ """,
+ "type": "bool",
+ }
+
+ verbose = {
+ "description": """
+ Whether or not to print more information and warnings.
+ """,
+ "type": "bool",
+ }
+
+ text_pair = {
+ "description": """
+ Optional second sequence to be encoded. This can be a string, a list of strings (tokenized string using
+ the `tokenize` method) or a list of integers (tokenized string ids using the `convert_tokens_to_ids`
+ method).
+ """,
+ "type": "str, list[str] or list[int]",
+ }
+
+ text_target = {
+ "description": """
+ The sequence or batch of sequences to be encoded as target texts. Each sequence can be a string or a
+ list of strings (pretokenized string). If you pass pretokenized input, set `is_split_into_words=True`
+ to avoid ambiguity with batched inputs.
+ """,
+ "type": "str, list[str] or list[list[str]]",
+ }
+
+ text_pair_target = {
+ "description": """
+ The sequence or batch of sequences to be encoded as target texts. Each sequence can be a string or a
+ list of strings (pretokenized string). If you pass pretokenized input, set `is_split_into_words=True`
+ to avoid ambiguity with batched inputs.
+ """,
+ "type": "str, list[str] or list[list[str]]",
+ }
+
+ is_split_into_words = {
+ "description": """
+ 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.
+ """,
+ "type": "bool",
+ }
+
+ boxes = {
+ "description": """
+ Word-level bounding boxes. Each bounding box should be normalized to be on a 0-1000 scale.
+ """,
+ "type": "list[list[int]] or list[list[list[int]]]",
+ }
+
+ word_labels = {
+ "description": """
+ Word-level integer labels (for token classification tasks such as FUNSD, CORD).
+ """,
+ "type": "list[int] or list[list[int]]",
+ }
+
+ # Used for the **kwargs summary line when unrolling typed kwargs (key: "__kwargs__")
+ __kwargs__ = {
+ "description": """
+ Additional processing options for each modality (text, images, videos, audio). Model-specific parameters
+ are listed above; see the TypedDict class for the complete list of supported arguments.
+ """,
+ "shape": None,
+ }
+
+
+class ConfigArgs:
+ output_hidden_states = {
+ "description": """
+ Whether or not the model should return all hidden-states.
+ """,
+ }
+
+ chunk_size_feed_forward = {
+ "description": """
+ The `dtype` of the weights. This attribute can be used to initialize the model to a non-default `dtype`
+ (which is normally `float32`) and thus allow for optimal storage allocation. For example, if the saved
+ model is `float16`, ideally we want to load it back using the minimal amount of memory needed to load
+ `float16` weights.
+ """,
+ }
+
+ dtype = {
+ "description": """
+ The chunk size of all feed forward layers in the residual attention blocks. A chunk size of `0` means that
+ the feed forward layer is not chunked. A chunk size of n means that the feed forward layer processes `n` <
+ sequence_length embeddings at a time. For more information on feed forward chunking, see [How does Feed
+ Forward Chunking work?](../glossary.html#feed-forward-chunking).
+ """,
+ }
+
+ id2label = {
+ "description": """
+ A map from index (for instance prediction index, or target index) to label.
+ """,
+ }
+
+ label2id = {
+ "description": """
+ A map from label to index for the model.
+ """,
+ }
+
+ problem_type = {
+ "description": """
+ Problem type for `XxxForSequenceClassification` models. Can be one of `"regression"`,
+ `"single_label_classification"` or `"multi_label_classification"`.
+ """,
+ }
+
+ tokenizer_class = {
+ "description": """
+ The class name of model's tokenizer.
+ """,
+ }
+
+ vocab_size = {
+ "description": """
+ Vocabulary size of the model. Defines the number of different tokens that can be represented by the `input_ids`.
+ """,
+ }
+
+ hidden_size = {
+ "description": """
+ Dimension of the hidden representations.
+ """,
+ }
+
+ intermediate_size = {
+ "description": """
+ Dimension of the MLP representations.
+ """,
+ }
+
+ head_dim = {
+ "description": """
+ The attention head dimension. If None, it will default to hidden_size // num_attention_heads
+ """
+ }
+
+ num_hidden_layers = {
+ "description": """
+ Number of hidden layers in the Transformer decoder.
+ """,
+ }
+
+ num_attention_heads = {
+ "description": """
+ Number of attention heads for each attention layer in the Transformer decoder.
+ """,
+ }
+
+ num_key_value_heads = {
+ "description": """
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
+ `num_key_value_heads=num_attention_heads`, 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). If it is not specified, will default to
+ `num_attention_heads`.
+ """,
+ }
+ hidden_act = {
+ "description": """
+ The non-linear activation function (function or string) in the decoder. For example, `"gelu"`,
+ `"relu"`, `"silu"`, etc.
+ """,
+ }
+
+ max_position_embeddings = {
+ "description": """
+ The maximum sequence length that this model might ever be used with.
+ """,
+ }
+
+ initializer_range = {
+ "description": """
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
+ """,
+ }
+
+ rms_norm_eps = {
+ "description": """
+ The epsilon used by the rms normalization layers.
+ """,
+ }
+
+ use_cache = {
+ "description": """
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
+ relevant if `config.is_decoder=True` or when the model is a decoder-only generative model.
+ """,
+ }
+
+ rope_parameters = {
+ "description": """
+ Dictionary containing the configuration parameters for the RoPE embeddings. The dictionary should contain
+ a value for `rope_theta` and optionally parameters used for scaling in case you want to use RoPE
+ with longer `max_position_embeddings`.
+ """,
+ }
+
+ attention_bias = {
+ "description": """
+ Whether to use a bias in the query, key, value and output projection layers during self-attention.
+ """,
+ }
+
+ mlp_bias = {
+ "description": """
+ Whether to use a bias in up_proj, down_proj and gate_proj layers in the MLP layers.
+ """,
+ }
+
+ attention_dropout = {
+ "description": """
+ The dropout ratio for the attention probabilities.
+ """,
+ }
+
+ pretraining_tp = {
+ "description": """
+ Experimental feature. Tensor parallelism rank used during pretraining. Please refer to [this
+ document](https://huggingface.co/docs/transformers/main/perf_train_gpu_many#tensor-parallelism) to
+ understand more about it. This value is necessary to ensure exact reproducibility of the pretraining
+ results. Please refer to [this issue](https://github.com/pytorch/pytorch/issues/76232).
+ """,
+ }
+
+ pad_token_id = {
+ "description": """
+ Token id used for padding in the vocabulary.
+ """,
+ }
+
+ eos_token_id = {
+ "description": """
+ Token id used for end-of-stream in the vocabulary.
+ """,
+ }
+
+ bos_token_id = {
+ "description": """
+ Token id used for beginning-of-stream in the vocabulary.
+ """,
+ }
+
+ sep_token_id = {
+ "description": """
+ Token id used for separator in the vocabulary.
+ """,
+ }
+
+ cls_token_id = {
+ "description": """
+ Token id used for CLS in the vocabulary.
+ """,
+ }
+
+ tie_word_embeddings = {
+ "description": """
+ Whether to tie weight embeddings according to model's `tied_weights_keys` mapping.
+ """,
+ }
+
+ d_model = {
+ "description": """
+ Size of the encoder layers and the pooler layer.
+ """,
+ }
+
+ d_kv = {
+ "description": """
+ Size of the key, query, value projections per attention head. The `inner_dim` of the projection layer will
+ be defined as `num_heads * d_kv`.
+ """,
+ }
+
+ num_decoder_layers = {
+ "description": """
+ Number of hidden layers in the Transformer decoder. Will use the same value as `num_layers` if not set.
+ """,
+ }
+
+ num_encoder_layers = {
+ "description": """
+ Number of hidden layers in the Transformer encoder. Will use the same value as `num_layers` if not set.
+ """,
+ }
+
+ dropout_rate = {
+ "description": """
+ The ratio for all dropout layers.
+ """,
+ }
+
+ classifier_dropout = {
+ "description": """
+ The dropout ratio for classifier.
+ """,
+ }
+
+ layer_norm_eps = {
+ "description": """
+ The epsilon used by the layer normalization layers.
+ """,
+ }
+
+ initializer_factor = {
+ "description": """
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
+ testing).
+ """,
+ }
+
+ encoder_attention_heads = {
+ "description": """
+ Number of attention heads for each attention layer in the Transformer encoder.
+ """,
+ }
+
+ decoder_attention_heads = {
+ "description": """
+ Number of attention heads for each attention layer in the Transformer decoder.
+ """,
+ }
+
+ decoder_ffn_dim = {
+ "description": """
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
+ """,
+ }
+
+ encoder_ffn_dim = {
+ "description": """
+ Dimensionality of the "intermediate" (often named feed-forward) layer in encoder.
+ """,
+ }
+
+ activation_dropout = {
+ "description": """
+ The dropout ratio for activations inside the fully connected layer.
+ """,
+ }
+
+ encoder_layerdrop = {
+ "description": """
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
+ for more details.
+ """,
+ }
+
+ decoder_layerdrop = {
+ "description": """
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556)
+ for more details.
+ """,
+ }
+
+ scale_embedding = {
+ "description": """
+ Whether to scale embeddings by dividing by sqrt(d_model).
+ """,
+ }
+
+ forced_eos_token_id = {
+ "description": """
+ The id of the token to force as the last generated token when `max_length` is reached. Usually set to
+ `eos_token_id`.
+ """,
+ }
+
+ moe_intermediate_size = {
+ "description": """
+ Intermediate size of the routed expert MLPs.
+ """,
+ }
+
+ num_experts = {
+ "description": """
+ Number of routed experts in MoE layers.
+
+ """,
+ }
+
+ num_experts_per_tok = {
+ "description": """
+ Number of experts to route each token to. This is the top-k value for the token-choice routing.
+ """,
+ }
+
+ num_shared_experts = {
+ "description": """
+ Number of shared experts that are always activated for all tokens.
+ """,
+ }
+
+ layer_types = {
+ "description": """
+ A list that explicitly maps each layer index with its layer type. If not provided, it will be automatically
+ generated based on config values.
+ """,
+ }
+
+ norm_topk_prob = {
+ "description": """
+ Whether to normalize the weights of the routed experts.
+
+ """,
+ }
+
+ topk_group = {
+ "description": """
+ Number of selected groups for each token (for each token, ensuring the selected experts is only within `topk_group` groups).
+ """,
+ }
+
+ qk_rope_head_dim = {
+ "description": """
+ Dimension of the query/key heads that use rotary position embeddings.
+ """,
+ }
+
+ v_head_dim = {
+ "description": """
+ Dimension of the value heads.
+ """,
+ }
+
+ qk_nope_head_dim = {
+ "description": """
+ Dimension of the query/key heads that don't use rotary position embeddings.
+ """,
+ }
+
+ kv_lora_rank = {
+ "description": """
+ Rank of the LoRA matrices for key and value projections.
+ """,
+ }
+
+ q_lora_rank = {
+ "description": """
+ Rank of the LoRA matrices for query projections.
+ """,
+ }
+
+ routed_scaling_factor = {
+ "description": """
+ Scaling factor or routed experts.
+ """,
+ }
+
+ n_routed_experts = {
+ "description": """
+ Number of routed experts.
+ """,
+ }
+
+ n_shared_experts = {
+ "description": """
+ Number of shared experts.
+ """,
+ }
+
+ vision_config = {
+ "description": """
+ The config object or dictionary of the vision backbone.
+ """,
+ }
+
+ text_config = {
+ "description": """
+ The config object or dictionary of the text backbone.
+ """,
+ }
+
+ projector_hidden_act = {
+ "description": """
+ The activation function used by the multimodal projector.
+ """,
+ }
+
+ vision_feature_select_strategy = {
+ "description": """
+ The feature selection strategy used to select the vision feature from the vision backbone.
+ """,
+ }
+
+ vision_feature_layer = {
+ "description": """
+ The index of the layer to select the vision feature. If multiple indices are provided,
+ the vision feature of the corresponding indices will be concatenated to form the
+ vision features.
+ """,
+ }
+
+ multimodal_projector_bias = {
+ "description": """
+ Whether to use bias in the multimodal projector.
+ """,
+ }
+
+ image_token_id = {
+ "description": """
+ The image token index used as a placeholder for input images.
+ """,
+ }
+
+ video_token_id = {
+ "description": """
+ The video token index used as a placeholder for input videos.
+ """,
+ }
+
+ audio_token_id = {
+ "description": """
+ The audio token index used as a placeholder for input audio.
+ """,
+ }
+
+ image_seq_length = {
+ "description": """
+ Sequence length of one image embedding.
+ """,
+ }
+
+ video_seq_length = {
+ "description": """
+ Sequence length of one video embedding.
+ """,
+ }
+
+ add_cross_attention = {
+ "description": """
+ Whether cross-attention layers should be added to the model.
+ """,
+ }
+
+ is_decoder = {
+ "description": """
+ Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
+ """,
+ }
+
+ sliding_window = {
+ "description": """
+ Sliding window attention window size. If `None`, no sliding window is applied.
+ """,
+ }
+
+ use_sliding_window = {
+ "description": """
+ Whether to use sliding window attention.
+ """,
+ }
+
+ shared_expert_intermediate_size = {
+ "description": """
+ Intermediate size of the shared expert MLPs.
+ """,
+ }
+
+ decoder_sparse_step = {
+ "description": """
+ The frequency of adding a sparse MoE layer. The default is 1, which means all decoder layers are sparse MoE.
+ """,
+ }
+
+ output_router_logits = {
+ "description": """
+ Whether or not the router logits should be returned by the model. Enabling this will also allow the model
+ to output the auxiliary loss, including load balancing loss and router z-loss.
+ """,
+ }
+
+ router_aux_loss_coef = {
+ "description": """
+ Auxiliary load balancing loss coefficient. Used to penalize uneven expert routing in MoE models.
+ """,
+ }
+
+ out_indices = {
+ "description": """
+ Indices of the intermediate hidden states (feature maps) to return from the backbone. Each index
+ corresponds to one stage of the model.
+ """,
+ }
+
+ out_features = {
+ "description": """
+ Names of the intermediate hidden states (feature maps) to return from the backbone. One of `"stem"`,
+ `"stage1"`, `"stage2"`, etc.
+ """,
+ }
+
+ image_size = {
+ "description": """
+ The size (resolution) of each image.
+ """,
+ }
+
+ patch_size = {
+ "description": """
+ The size (resolution) of each patch.
+ """,
+ }
+
+ num_channels = {
+ "description": """
+ The number of input channels.
+ """,
+ }
+
+ num_mel_bins = {
+ "description": """
+ Number of mel features used per input frame. Should correspond to the value used in the
+ `AutoFeatureExtractor` class.
+ """,
+ }
+
+ sampling_rate = {
+ "description": """
+ The sampling rate at which the audio files should be digitalized expressed in hertz (Hz).
+ """,
+ }
+
+ hidden_dropout = {
+ "description": """
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ """,
+ }
+
+ mlp_ratio = {
+ "description": """
+ Ratio of the MLP hidden dim to the embedding dim.
+ """,
+ }
+
+ qkv_bias = {
+ "description": """
+ Whether to add a bias to the queries, keys and values.
+ """,
+ }
+
+ n_embd = {
+ "description": """
+ Dimensionality of the embeddings and hidden states.
+ """,
+ }
+
+ resid_pdrop = {
+ "description": """
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
+ """,
+ }
+
+ embd_pdrop = {
+ "description": """
+ The dropout ratio for the embeddings.
+ """,
+ }
+
+ clip_qkv = {
+ "description": """
+ If not `None`, cap the absolute value of the query, key, and value tensors to this value.
+ """,
+ }
+
+ type_vocab_size = {
+ "description": """
+ The vocabulary size of the `token_type_ids`.
+ """,
+ }
+
+ audio_config = {
+ "description": """
+ The config object or dictionary of the audio backbone.
+ """,
+ }
+
+ layerdrop = {
+ "description": """
+ The LayerDrop probability. See the [LayerDrop paper](see https://huggingface.co/papers/1909.11556) for
+ more details.
+ """,
+ }
+
+ expert_capacity = {
+ "description": """
+ The number of tokens that each expert can process. If `None`, `expert_capacity` will be set to
+ `(sequence_length / num_experts) * capacity_factor`.
+ """,
+ }
+
+ decoder_start_token_id = {
+ "description": """
+ If an encoder-decoder model starts decoding with a different token than `bos`, the id of that token.
+ """,
+ }
+
+ is_encoder_decoder = {
+ "description": """
+ Whether the model is used as an encoder/decoder or not.
+ """,
+ }
+
+ num_codebooks = {
+ "description": """
+ The number of parallel codebooks used by the model.
+ """,
+ }
+
+ codebook_dim = {
+ "description": """
+ Dimensionality of each codebook embedding vector.
+ """,
+ }
+
+ hidden_sizes = {
+ "description": """
+ Dimensionality (hidden size) at each stage of the model.
+ """,
+ }
+
+ depths = {
+ "description": """
+ Depth of each layer in the Transformer.
+ """,
+ }
+
+ patch_sizes = {
+ "description": """
+ Patch size at each stage of the model.
+ """,
+ }
+
+ strides = {
+ "description": """
+ Stride at each stage of the model.
+ """,
+ }
+
+ router_jitter_noise = {
+ "description": """
+ Amount of noise to add to the router logits during training for better load balancing.
+ """,
+ }
+
+ num_local_experts = {
+ "description": """
+ Number of local experts on each device. `num_experts` should be divisible by `num_local_experts`.
+ """,
+ }
+
+ qk_layernorm = {
+ "description": """
+ Whether to use query-key normalization in the attention.
+ """,
+ }
+
+ backbone_config = {
+ "description": """
+ The configuration of the backbone model.
+ """,
+ }
+
+ no_object_weight = {
+ "description": """
+ Relative classification weight of the no-object class in the object detection loss.
+ """,
+ }
+
+ class_weight = {
+ "description": """
+ Relative weight of the classification error in the Hungarian matching cost.
+ """,
+ }
+
+ mask_weight = {
+ "description": """
+ Relative weight of the focal loss in the panoptic segmentation loss.
+ """,
+ }
+
+ dice_weight = {
+ "description": """
+ Relative weight of the dice loss in the panoptic segmentation loss.
+ """,
+ }
+
+ class_cost = {
+ "description": """
+ Relative weight of the classification error in the Hungarian matching cost.
+ """,
+ }
+
+ bbox_cost = {
+ "description": """
+ Relative weight of the L1 bounding box error in the Hungarian matching cost.
+ """,
+ }
+
+ giou_cost = {
+ "description": """
+ Relative weight of the generalized IoU loss in the Hungarian matching cost.
+ """,
+ }
+
+ focal_alpha = {
+ "description": """
+ Alpha parameter in the focal loss.
+ """,
+ }
+
+ mask_loss_coefficient = {
+ "description": """
+ Relative weight of the focal loss in the panoptic segmentation loss.
+ """,
+ }
+
+ giou_loss_coefficient = {
+ "description": """
+ Relative weight of the generalized IoU loss in the panoptic segmentation loss.
+ """,
+ }
+
+ bbox_loss_coefficient = {
+ "description": """
+ Relative weight of the L1 bounding box loss in the panoptic segmentation loss.
+ """,
+ }
+
+ cls_loss_coefficient = {
+ "description": """
+ Relative weight of the classification loss in the panoptic segmentation loss.
+ """,
+ }
+
+ dice_loss_coefficient = {
+ "description": """
+ Relative weight of the dice loss in the panoptic segmentation loss.
+ """,
+ }
+
+ semantic_loss_ignore_index = {
+ "description": """
+ The index that is ignored by the loss function of the semantic segmentation model.
+ """,
+ }
+
+ projection_dim = {
+ "description": """
+ Dimensionality of text and vision projection layers.
+ """,
+ }
+
+ logit_scale_init_value = {
+ "description": """
+ The initial value of the *logit_scale* parameter.
+ """,
+ }
+
+ num_dense_layers = {
+ "description": """
+ Number of initial dense layers before MoE layers begin. Layers with index < num_dense_layers will use
+ standard dense MLPs instead of MoE.
+ """,
+ }
+
+ drop_path_rate = {
+ "description": """
+ Drop path rate for the patch fusion.
+ """,
+ }
+
+ vq_config = {
+ "description": """
+ Configuration dict of the vector quantize module.
+ """,
+ }
+
+ num_embeddings = {
+ "description": """
+ Number of codebook embeddings.
+ """,
+ }
+
+ double_latent = {
+ "description": """
+ Whether to use double z channels.
+ """,
+ }
+
+ latent_channels = {
+ "description": """
+ Number of channels for the latent space.
+ """,
+ }
+
+ qformer_config = {
+ "description": """
+ Configuration dict of the Q-Former module.
+ """,
+ }
+
+ conv_kernel_size = {
+ "description": """
+ The size of the convolutional kernel.
+ """,
+ }
+
+ output_stride = {
+ "description": """
+ The ratio between the spatial resolution of the input and output feature maps.
+ """,
+ }
+
+ depth_multiplier = {
+ "description": """
+ Shrinks or expands the number of channels in each layer. This is sometimes also called "alpha" or "width multiplier".
+ """,
+ }
+
+ use_absolute_position_embeddings = {
+ "description": """
+ Whether to use absolute position embeddings.
+ """,
+ }
+
+ use_relative_position_bias = {
+ "description": """
+ Whether to use relative position bias in the self-attention layers.
+ """,
+ }
+
+ layer_scale_init_value = {
+ "description": """
+ Scale to use in the self-attention layers. 0.1 for base, 1e-6 for large. Set 0 to disable layer scale.
+ """,
+ }
+
+ vlm_config = {
+ "description": """
+ The config object or dictionary of the vision-language backbone.
+ """,
+ }
+
+ init_xavier_std = {
+ "description": """
+ The scaling factor used for the Xavier initialization of the cross-attention weights.
+ """,
+ }
+
+ auxiliary_loss = {
+ "description": """
+ Whether auxiliary decoding losses (losses at each decoder layer) are to be used.
+ """,
+ }
+
+ encoder_config = {
+ "description": """
+ The config object or dictionary of the encoder backbone.
+ """,
+ }
+
+ decoder_config = {
+ "description": """
+ The config object or dictionary of the decoder backbone.
+ """,
+ }
+
+ embedding_multiplier = {
+ "description": """
+ Scaling factor applied to the word embeddings. Used to scale the embeddings relative to the hidden size.
+ """,
+ }
+
+ logits_scaling = {
+ "description": """
+ Scaling factor applied to the output logits before computing the probability distribution.
+ """,
+ }
+
+ residual_multiplier = {
+ "description": """
+ Scaling factor applied to the residual connections.
+ """,
+ }
+
+ attention_multiplier = {
+ "description": """
+ Scaling factor applied to the attention weights.
+ """,
+ }
+
+ classifier_activation = {
+ "description": """
+ The activation function for the classification head.
+ """,
+ }
+
+ return_dict = {
+ "description": """
+ Whether to return a `ModelOutput` (dataclass) instead of a plain tuple.
+ """,
+ }
+
+ router_z_loss_coef = {
+ "description": """
+ Coefficient for the router z-loss, which penalizes large router logits to improve training stability.
+ """,
+ }
+
+ final_logit_softcapping = {
+ "description": """
+ Soft-capping value applied to the final logits before computing the probability distribution. Logits are
+ scaled by `tanh(logit / cap) * cap`.
+ """,
+ }
+
+ cross_attention_hidden_size = {
+ "description": """
+ Hidden size of the encoder outputs projected into the cross-attention key/value space of the decoder. Used
+ when the encoder and decoder have different hidden sizes.
+ """,
+ }
+
+ input_dim = {
+ "description": """
+ Dimensionality of the input acoustic features (e.g., number of mel-filterbank channels).
+ """,
+ }
+
+ use_auxiliary_loss = {
+ "description": """
+ Whether to calculate loss using intermediate predictions from transformer decoder.
+ """,
+ }
+
+ batch_norm_eps = {
+ "description": """
+ The epsilon used by the batch normalization layers.
+ """,
+ }
+
+ max_window_layers = {
+ "description": """
+ The number of layers using full attention. The first `max_window_layers` layers will use full attention, while any
+ additional layer afterwards will use SWA (Sliding Window Attention).
+ """,
+ }
+
+ ctc_loss_reduction = {
+ "description": """
+ Specifies the reduction to apply to the output of `torch.nn.CTCLoss`. Only relevant when training.
+ """,
+ }
+
+ mask_feature_prob = {
+ "description": """
+ Percentage (between 0 and 1) of all feature vectors along the feature axis which will be masked. The
+ masking procedure generates `mask_feature_prob*len(feature_axis)/mask_time_length` independent masks over
+ the axis. If reasoning from the probability of each feature vector to be chosen as the start of the vector
+ span to be masked, *mask_feature_prob* should be `prob_vector_start*mask_feature_length`. Note that overlap
+ may decrease the actual percentage of masked vectors. This is only relevant if `apply_spec_augment` is
+ `True`.
+ """,
+ }
+
+ eos_coefficient = {
+ "description": """
+ Relative classification weight of the 'no-object' class in the object detection loss.
+ """,
+ }
+
+ num_labels = {
+ "description": """
+ Number of labels to use in the last layer added to the model, typically for a classification task.
+ """,
+ }
+
+ depth = {
+ "description": """
+ Number of Transformer layers in the vision encoder.
+ """,
+ }
+
+ temporal_patch_size = {
+ "description": """
+ Temporal patch size used in the 3D patch embedding for video inputs.
+ """,
+ }
+
+ spatial_merge_size = {
+ "description": """
+ The size of the spatial merge window used to reduce the number of visual tokens by merging neighboring patches.
+ """,
+ }
+
+ vision_start_token_id = {
+ "description": """
+ Token ID that marks the start of a visual segment in the multimodal input sequence.
+ """,
+ }
+
+ vision_end_token_id = {
+ "description": """
+ Token ID that marks the end of a visual segment in the multimodal input sequence.
+ """,
+ }
+
+ mamba_n_heads = {
+ "description": """
+ The number of mamba heads used in the v2 implementation.
+ """,
+ }
+
+ mamba_d_head = {
+ "description": """
+ Head embedding dimension size
+ """,
+ }
+
+ mamba_n_groups = {
+ "description": """
+ The number of the mamba groups used in the v2 implementation.
+ """,
+ }
+
+ mamba_d_conv = {
+ "description": """
+ The size of the mamba convolution kernel
+ """,
+ }
+
+ mamba_expand = {
+ "description": """
+ Expanding factor (relative to hidden_size) used to determine the mamba intermediate size
+ """,
+ }
+
+ mamba_chunk_size = {
+ "description": """
+ The chunks in which to break the sequence when doing prefill/training
+ """,
+ }
+
+ mamba_conv_bias = {
+ "description": """
+ Flag indicating whether or not to use bias in the convolution layer of the mamba mixer block.
+ """,
+ }
+
+ mamba_proj_bias = {
+ "description": """
+ Flag indicating whether or not to use bias in the input and output projections (["in_proj", "out_proj"]) of the mamba mixer block
+ """,
+ }
+
+ time_step_min = {
+ "description": """
+ Minimum `time_step` used to bound `dt_proj.bias`.
+ """,
+ }
+
+ time_step_max = {
+ "description": """
+ Maximum `time_step` used to bound `dt_proj.bias`.
+ """,
+ }
+
+ time_step_limit = {
+ "description": """
+ Accepted range of time step values for clamping.
+ """,
+ }
+
+ expand_ratio = {
+ "description": """
+ Expand ratio to set the output dimensions for the expansion
+ """,
+ }
+
+ state_size = {
+ "description": """
+ Size of the SSM state (latent state dimension) in the Mamba layers.
+ """,
+ }
+
+ time_step_rank = {
+ "description": """
+ Rank of the delta (time step) projection. Can be `"auto"` to set it automatically.
+ """,
+ }
+
+ time_step_floor = {
+ "description": """
+ Minimum allowed value for the discrete time step delta after softplus activation.
+ """,
+ }
+
+ time_step_scale = {
+ "description": """
+ Scale applied to the time step delta before discretization.
+ """,
+ }
+
+ time_step_init_scheme = {
+ "description": """
+ Initialization scheme for the time step delta. Can be `"random"` or `"uniform"`.
+ """,
+ }
+
+ mamba_d_ssm = {
+ "description": """
+ Inner state size of the SSM (state-space model) in the Mamba layers of FalconH1.
+ """,
+ }
+
+ mamba_norm_before_gate = {
+ "description": """
+ Whether to apply normalization before the gating mechanism in the Mamba mixer.
+ """,
+ }
+
+ mamba_rms_norm = {
+ "description": """
+ Whether to use RMS normalization in the Mamba layers (as opposed to standard LayerNorm).
+ """,
+ }
+
+ mamba_d_state = state_size
+ mamba_num_heads = mamba_n_heads
+ mamba_head_dim = mamba_d_head
+ num_input_channels = num_channels
+ audio_channels = num_channels
+ input_channels = num_channels
+ in_channels = num_channels
+ in_chans = num_channels
+ scale_attn_weights = scale_embedding
+ attention_probs_dropout_prob = attention_dropout
+ attn_pdrop = attention_dropout
+ attn_dropout = attention_dropout
+ dropout = dropout_rate
+ resid_dropout = resid_pdrop
+ residual_dropout = resid_pdrop
+ emb_pdrop = embd_pdrop
+ embed_dropout = embd_pdrop
+ embedding_dropout = embd_pdrop
+ hidden_dropout_prob = hidden_dropout
+ hidden_dropout_rate = hidden_dropout
+ classifier_dropout_prob = classifier_dropout
+ classifier_dropout_rate = classifier_dropout
+ dropout_prob = dropout
+ dropout_p = dropout
+ decoder_attention_dropout = attention_dropout
+ decoder_dropout = dropout
+ encoder_dropout = dropout
+
+ route_scale = routed_scaling_factor
+ activation_function = hidden_act
+ hidden_dim = hidden_size
+ num_decoder_attention_heads = decoder_attention_heads
+ num_encoder_attention_heads = encoder_attention_heads
+ decoder_num_heads = decoder_attention_heads
+ decoder_num_attention_heads = decoder_attention_heads
+ encoder_num_heads = encoder_attention_heads
+ encoder_num_attention_heads = encoder_attention_heads
+ encoder_layers = num_encoder_layers
+ decoder_layers = num_decoder_layers
+ decoder_num_layers = num_decoder_layers
+ encoder_num_layers = num_encoder_layers
+ d_ff = intermediate_size
+ dim_ff = intermediate_size
+ n_inner = intermediate_size
+ decoder_intermediate_size = intermediate_size
+ num_kv_heads = num_key_value_heads
+ num_layers = num_hidden_layers
+ n_layers = num_hidden_layers
+ n_layer = num_hidden_layers
+ layers = num_layers
+ encoder_num_hidden_layers = encoder_layers
+ decoder_num_hidden_layers = decoder_layers
+ num_heads = num_attention_heads
+ n_heads = num_attention_heads
+ n_head = num_attention_heads
+ hidden_activation = hidden_act
+ activation = hidden_act
+ mlp_hidden_act = hidden_act
+ d_head = head_dim
+ d_inner = intermediate_size
+ dim_head = head_dim
+ ffn_dim = intermediate_size
+ attention_heads = num_attention_heads
+ n_positions = max_position_embeddings
+ init_std = initializer_range
+ initializer_std = initializer_range
+ projector_bias = multimodal_projector_bias
+ image_token_index = image_token_id
+ video_token_index = video_token_id
+ audio_token_index = audio_token_id
+ embedding_size = n_embd
+ embed_dim = n_embd
+ projection_hidden_act = projector_hidden_act
+ layer_norm_epsilon = layer_norm_eps
+ rms_norm = rms_norm_eps
+ norm_eps = layer_norm_eps
+ eps = layer_norm_eps
+ norm_epsilon = layer_norm_eps
+ qk_layernorms = qk_layernorm
+ use_qk_norm = qk_layernorm
+ use_qkv_bias = qkv_bias
+
+ decoder_hidden_act = hidden_act
+ decoder_hidden_dim = hidden_size
+ decoder_hidden_size = hidden_size
+ encoder_hidden_dim = hidden_size
+ encoder_hidden_size = hidden_size
+ layer_scale_initial_scale = layer_scale_init_value
+ multi_modal_projector_bias = projector_bias
+ projector_hidden_size = projection_dim
+ projection_size = projection_dim
+ kernel_size = conv_kernel_size
+ conv_kernel = conv_kernel_size
+ use_absolute_embeddings = use_absolute_position_embeddings
+ use_abs_pos = use_absolute_position_embeddings
+ use_rel_pos = use_relative_position_bias
+ aux_loss_coef = router_aux_loss_coef
+ embedding_dimension = embed_dim
+ embedding_dim = embed_dim
+ emb_dim = embed_dim
+ n_codebooks = num_codebooks
+ codebook_size = num_codebooks
+ layers_block_type = layer_types
+ sample_rate = sampling_rate
+ text_vocab_size = vocab_size
+
+
+class ModelArgs:
+ labels = {
+ "description": """
+ 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]`.
+ """,
+ "shape": "of shape `(batch_size, sequence_length)`",
+ }
+
+ num_logits_to_keep = {
+ "description": """
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
+ """,
+ "shape": None,
+ }
+
+ input_ids = {
+ "description": """
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.
+
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
+ [`PreTrainedTokenizer.__call__`] for details.
+
+ [What are input IDs?](../glossary#input-ids)
+ """,
+ "shape": "of shape `(batch_size, sequence_length)`",
+ }
+
+ input_values = {
+ "description": """
+ Float values of input raw speech waveform. Values can be obtained by loading a `.flac` or `.wav` audio file
+ into an array of type `list[float]`, a `numpy.ndarray` or a `torch.Tensor`, *e.g.* via the torchcodec library
+ (`pip install torchcodec`) or the soundfile library (`pip install soundfile`).
+ To prepare the array into `input_values`, the [`AutoProcessor`] should be used for padding and conversion
+ into a tensor of type `torch.FloatTensor`. See [`{processor_class}.__call__`] for details.
+ """,
+ "shape": "of shape `(batch_size, sequence_length)`",
+ }
+
+ attention_mask = {
+ "description": """
+ 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)
+ """,
+ "shape": "of shape `(batch_size, sequence_length)`",
+ }
+
+ decoder_attention_mask = {
+ "description": """
+ Mask to avoid performing attention on certain token indices. By default, a causal mask will be used, to
+ make sure the model can only look at previous inputs in order to predict the future.
+ """,
+ "shape": "of shape `(batch_size, target_sequence_length)`",
+ }
+
+ encoder_hidden_states = {
+ "description": """
+ 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.
+ """,
+ "shape": "of shape `(batch_size, sequence_length, hidden_size)`",
+ }
+
+ encoder_attention_mask = {
+ "description": """
+ 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**.
+ """,
+ "shape": "of shape `(batch_size, sequence_length)`",
+ }
+
+ token_type_ids = {
+ "description": """
+ 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)
+ """,
+ "shape": "of shape `(batch_size, sequence_length)`",
+ }
+
+ mm_token_type_ids = {
+ "description": """
+ Indices of input sequence tokens matching each modality. For example text (0), image (1), video (2).
+ Multimodal token type ids can be obtained using [`AutoProcessor`]. See [`ProcessorMixin.__call__`] for details.
+
+ """,
+ "shape": "of shape `(batch_size, sequence_length)`",
+ }
+
+ position_ids = {
+ "description": """
+ 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)
+ """,
+ "shape": "of shape `(batch_size, sequence_length)`",
+ }
+
+ past_key_values = {
+ "description": """
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
+
+ Only [`~cache_utils.Cache`] instance is allowed as input, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+ If no `past_key_values` are passed, [`~cache_utils.DynamicCache`] will be initialized by default.
+
+ The model will output the same cache format that is fed as input.
+
+ If `past_key_values` are used, the user is expected to input only unprocessed `input_ids` (those that don't
+ have their past key value states given to this model) of shape `(batch_size, unprocessed_length)` instead of all `input_ids`
+ of shape `(batch_size, sequence_length)`.
+ """,
+ "shape": None,
+ }
+
+ inputs_embeds = {
+ "description": """
+ 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.
+ """,
+ "shape": "of shape `(batch_size, sequence_length, hidden_size)`",
+ }
+
+ decoder_input_ids = {
+ "description": """
+ 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)
+ """,
+ "shape": "of shape `(batch_size, target_sequence_length)`",
+ }
+
+ decoder_inputs_embeds = {
+ "description": """
+ 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.
+
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
+ of `inputs_embeds`.
+ """,
+ "shape": "of shape `(batch_size, target_sequence_length, hidden_size)`",
+ }
+
+ use_cache = {
+ "description": """
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
+ `past_key_values`).
+ """,
+ "shape": None,
+ }
+
+ output_attentions = {
+ "description": """
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
+ tensors for more detail.
+ """,
+ "shape": None,
+ }
+
+ output_hidden_states = {
+ "description": """
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
+ more detail.
+ """,
+ "shape": None,
+ }
+
+ return_dict = {
+ "description": """
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
+ """,
+ "shape": None,
+ }
+
+ hidden_states = {
+ "description": """ input to the layer of shape `(batch, seq_len, embed_dim)""",
+ "shape": None,
+ }
+
+ interpolate_pos_encoding = {
+ "description": """
+ Whether to interpolate the pre-trained position encodings.
+ """,
+ "shape": None,
+ }
+
+ position_embeddings = {
+ "description": """
+ 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.
+ """,
+ "shape": None,
+ }
+
+ config = {
+ "description": """
+ 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.
+ """,
+ "shape": None,
+ }
+
+ start_positions = {
+ "description": """
+ 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.
+ """,
+ "shape": "of shape `(batch_size,)`",
+ }
+
+ end_positions = {
+ "description": """
+ 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.
+ """,
+ "shape": "of shape `(batch_size,)`",
+ }
+
+ encoder_outputs = {
+ "description": """
+ 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.
+ """,
+ "shape": None,
+ }
+
+ output_router_logits = {
+ "description": """
+ Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
+ should not be returned during inference.
+ """,
+ "shape": None,
+ }
+
+ logits_to_keep = {
+ "description": """
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
+ """,
+ "shape": None,
+ }
+
+ pixel_values = {
+ "description": """
+ The tensors corresponding to the input images. Pixel values can be obtained using
+ [`{image_processor_class}`]. See [`{image_processor_class}.__call__`] for details ([`{processor_class}`] uses
+ [`{image_processor_class}`] for processing images).
+ """,
+ "shape": "of shape `(batch_size, num_channels, image_size, image_size)`",
+ }
+
+ pixel_values_videos = {
+ "description": """
+ The tensors corresponding to the input video. Pixel values for videos can be obtained using
+ [`{video_processor_class}`]. See [`{video_processor_class}.__call__`] for details ([`{processor_class}`] uses
+ [`{video_processor_class}`] for processing videos).
+ """,
+ "shape": "of shape `(batch_size, num_frames, num_channels, frame_size, frame_size)`",
+ }
+
+ vision_feature_layer = {
+ "description": """
+ The index of the layer to select the vision feature. If multiple indices are provided,
+ the vision feature of the corresponding indices will be concatenated to form the
+ vision features.
+ """,
+ "shape": None,
+ }
+
+ vision_feature_select_strategy = {
+ "description": """
+ The feature selection strategy used to select the vision feature from the vision backbone.
+ Can be one of `"default"` or `"full"`.
+ """,
+ "shape": None,
+ }
+
+ image_sizes = {
+ "description": """
+ The sizes of the images in the batch, being (height, width) for each image.
+ """,
+ "shape": "of shape `(batch_size, 2)`",
+ }
+
+ pixel_mask = {
+ "description": """
+ 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)
+ """,
+ "shape": "of shape `(batch_size, height, width)`",
+ }
+
+ input_features = {
+ "description": """
+ The tensors corresponding to the input audio features. Audio features can be obtained using
+ [`{feature_extractor_class}`]. See [`{feature_extractor_class}.__call__`] for details ([`{processor_class}`] uses
+ [`{feature_extractor_class}`] for processing audios).
+ """,
+ "shape": "of shape `(batch_size, sequence_length, feature_dim)`",
+ }
+
+
+class ModelOutputArgs:
+ last_hidden_state = {
+ "description": """
+ Sequence of hidden-states at the output of the last layer of the model.
+ """,
+ "shape": "of shape `(batch_size, sequence_length, hidden_size)`",
+ }
+
+ past_key_values = {
+ "description": """
+ It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
+
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if
+ `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`
+ input) to speed up sequential decoding.
+ """,
+ "shape": None,
+ "additional_info": "returned when `use_cache=True` is passed or when `config.use_cache=True`",
+ }
+
+ hidden_states = {
+ "description": """
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
+ 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 optional initial embedding outputs.
+ """,
+ "shape": None,
+ "additional_info": "returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`",
+ }
+
+ attentions = {
+ "description": """
+ 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.
+ """,
+ "shape": None,
+ "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`",
+ }
+
+ pooler_output = {
+ "description": """
+ Last layer hidden-state after a pooling operation on the spatial dimensions.
+ """,
+ "shape": "of shape `(batch_size, hidden_size)`",
+ }
+
+ cross_attentions = {
+ "description": """
+ 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.
+ """,
+ "shape": None,
+ "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`",
+ }
+
+ decoder_hidden_states = {
+ "description": """
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
+
+ Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
+ """,
+ "shape": None,
+ "additional_info": "returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`",
+ }
+
+ decoder_attentions = {
+ "description": """
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
+ self-attention heads.
+ """,
+ "shape": None,
+ "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`",
+ }
+
+ encoder_last_hidden_state = {
+ "description": """
+ Sequence of hidden-states at the output of the last layer of the encoder of the model.
+ """,
+ "shape": "of shape `(batch_size, sequence_length, hidden_size)`",
+ }
+
+ encoder_hidden_states = {
+ "description": """
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
+ 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.
+ """,
+ "shape": None,
+ "additional_info": "returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`",
+ }
+
+ encoder_attentions = {
+ "description": """
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
+ sequence_length)`.
+
+ Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
+ self-attention heads.
+ """,
+ "shape": None,
+ "additional_info": "returned when `output_attentions=True` is passed or when `config.output_attentions=True`",
+ }
+
+ router_logits = {
+ "description": """
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
+
+ Router logits of the model, useful to compute the auxiliary loss for Mixture of Experts models.
+ """,
+ "shape": None,
+ "additional_info": "returned when `output_router_logits=True` is passed or when `config.add_router_probs=True`",
+ }
+
+ router_probs = {
+ "description": """
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, sequence_length, num_experts)`.
+
+ Raw router probabilities that are computed by MoE routers, these terms are used to compute the auxiliary
+ loss and the z_loss for Mixture of Experts models.
+ """,
+ "shape": None,
+ "additional_info": "returned when `output_router_probs=True` and `config.add_router_probs=True` is passed or when `config.output_router_probs=True`",
+ }
+
+ z_loss = {
+ "description": """
+ z_loss for the sparse modules.
+ """,
+ "shape": None,
+ "additional_info": "returned when `labels` is provided",
+ }
+
+ aux_loss = {
+ "description": """
+ aux_loss for the sparse modules.
+ """,
+ "shape": None,
+ "additional_info": "returned when `labels` is provided",
+ }
+
+ start_logits = {
+ "description": """
+ Span-start scores (before SoftMax).
+ """,
+ "shape": "of shape `(batch_size, sequence_length)`",
+ }
+
+ end_logits = {
+ "description": """
+ Span-end scores (before SoftMax).
+ """,
+ "shape": "of shape `(batch_size, sequence_length)`",
+ }
+
+ feature_maps = {
+ "description": """
+ Feature maps of the stages.
+ """,
+ "shape": "of shape `(batch_size, num_channels, height, width)`",
+ }
+
+ reconstruction = {
+ "description": """
+ Reconstructed / completed images.
+ """,
+ "shape": "of shape `(batch_size, num_channels, height, width)`",
+ }
+
+ spectrogram = {
+ "description": """
+ The predicted spectrogram.
+ """,
+ "shape": "of shape `(batch_size, sequence_length, num_bins)`",
+ }
+
+ predicted_depth = {
+ "description": """
+ Predicted depth for each pixel.
+ """,
+ "shape": "of shape `(batch_size, height, width)`",
+ }
+
+ sequences = {
+ "description": """
+ Sampled values from the chosen distribution.
+ """,
+ "shape": "of shape `(batch_size, num_samples, prediction_length)` or `(batch_size, num_samples, prediction_length, input_size)`",
+ }
+
+ params = {
+ "description": """
+ Parameters of the chosen distribution.
+ """,
+ "shape": "of shape `(batch_size, num_samples, num_params)`",
+ }
+
+ loc = {
+ "description": """
+ Shift values of each time series' context window which is used to give the model inputs of the same
+ magnitude and then used to shift back to the original magnitude.
+ """,
+ "shape": "of shape `(batch_size,)` or `(batch_size, input_size)`",
+ }
+
+ scale = {
+ "description": """
+ Scaling values of each time series' context window which is used to give the model inputs of the same
+ magnitude and then used to rescale back to the original magnitude.
+ """,
+ "shape": "of shape `(batch_size,)` or `(batch_size, input_size)`",
+ }
+
+ static_features = {
+ "description": """
+ Static features of each time series' in a batch which are copied to the covariates at inference time.
+ """,
+ "shape": "of shape `(batch_size, feature size)`",
+ }
+
+ embeddings = {
+ "description": """
+ Utterance embeddings used for vector similarity-based retrieval.
+ """,
+ "shape": "of shape `(batch_size, config.xvector_output_dim)`",
+ }
+
+ extract_features = {
+ "description": """
+ Sequence of extracted feature vectors of the last convolutional layer of the model.
+ """,
+ "shape": "of shape `(batch_size, sequence_length, conv_dim[-1])`",
+ }
+
+ projection_state = {
+ "description": """
+ Text embeddings before the projection layer, used to mimic the last hidden state of the teacher encoder.
+ """,
+ "shape": "of shape `(batch_size,config.project_dim)`",
+ }
+
+ image_hidden_states = {
+ "description": """
+ Image hidden states of the model produced by the vision encoder and after projecting the last hidden state.
+ """,
+ "shape": "of shape `(batch_size, num_images, sequence_length, hidden_size)`",
+ }
+
+ video_hidden_states = {
+ "description": """
+ Video hidden states of the model produced by the vision encoder and after projecting the last hidden state.
+ """,
+ "shape": "of shape `(batch_size * num_frames, num_images, sequence_length, hidden_size)`",
+ }
+
+
+class ClassDocstring:
+ Config = r"""
+ This is the configuration class to store the configuration of a {model_base_class}. It is used to instantiate a {model_name}
+ 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 [{model_checkpoint}](https://huggingface.co/{model_checkpoint})
+
+ Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
+ documentation from [`PreTrainedConfig`] for more information.
+ """
+
+ PreTrainedModel = 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.
+ """
+
+ Model = r"""
+ The bare {model_name} Model outputting raw hidden-states without any specific head on top.
+ """
+
+ ForPreTraining = r"""
+ The {model_name} Model with a specified pretraining head on top.
+ """
+
+ Decoder = r"""
+ The bare {model_name} Decoder outputting raw hidden-states without any specific head on top.
+ """
+
+ TextModel = r"""
+ The bare {model_name} Text Model outputting raw hidden-states without any specific head on to.
+ """
+
+ ForSequenceClassification = r"""
+ The {model_name} Model with a sequence classification/regression head on top e.g. for GLUE tasks.
+ """
+
+ ForQuestionAnswering = r"""
+ The {model_name} transformer 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`).
+ """
+
+ ForMultipleChoice = r"""
+ The {model_name} 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.
+ """
+
+ ForMaskedLM = r"""
+ The {model_name} Model with a `language modeling` head on top."
+ """
+
+ ForTokenClassification = r"""
+ The {model_name} transformer 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.
+ """
+
+ ForConditionalGeneration = r"""
+ The {model_name} Model for token generation conditioned on other modalities (e.g. image-text-to-text generation).
+ """
+
+ ForCausalLM = r"""
+ The {model_name} Model for causal language modeling.
+ """
+
+ Backbone = r"""
+ The {model_name} backbone.
+ """
+
+ ForImageClassification = r"""
+ The {model_name} Model with an image classification head on top e.g. for ImageNet.
+ """
+ ForSemanticSegmentation = r"""
+ The {model_name} Model with a semantic segmentation head on top e.g. for ADE20K, CityScapes.
+ """
+ ForAudioClassification = r"""
+ The {model_name} Model with an audio classification head on top (a linear layer on top of the pooled
+ output).
+ """
+
+ ForAudioFrameClassification = r"""
+ The {model_name} Model with a frame classification head on top for tasks like Speaker Diarization.
+ """
+
+ ForPrediction = r"""
+ The {model_name} Model with a distribution head on top for time-series forecasting.
+ """
+
+ WithProjection = r"""
+ The {model_name} Model with a projection layer on top (a linear layer on top of the pooled output).
+ """
+
+
+class ClassAttrs:
+ # fmt: off
+ base_model_prefix = r"""
+ A string indicating the attribute associated to the base model in derived classes of the same architecture adding modules on top of the base model.
+ """
+ supports_gradient_checkpointing = r"""
+ Whether the model supports gradient checkpointing or not. Gradient checkpointing is a memory-saving technique that trades compute for memory, by storing only a subset of activations (checkpoints) and recomputing the activations that are not stored during the backward pass.
+ """
+ _no_split_modules = r"""
+ Layers of modules that should not be split across devices should be added to `_no_split_modules`. This can be useful for modules that contains skip connections or other operations that are not compatible with splitting the module across devices. Setting this attribute will enable the use of `device_map="auto"` in the `from_pretrained` method.
+ """
+ _skip_keys_device_placement = r"""
+ A list of keys to ignore when moving inputs or outputs between devices when using the `accelerate` library.
+ """
+ _supports_flash_attn = r"""
+ Whether the model's attention implementation supports FlashAttention.
+ """
+ _supports_sdpa = r"""
+ Whether the model's attention implementation supports SDPA (Scaled Dot Product Attention).
+ """
+ _supports_flex_attn = r"""
+ Whether the model's attention implementation supports FlexAttention.
+ """
+ _can_compile_fullgraph = r"""
+ Whether the model can `torch.compile` fullgraph without graph breaks. Models will auto-compile if this flag is set to `True`
+ in inference, if a compilable cache is used.
+ """
+ _supports_attention_backend = r"""
+ Whether the model supports attention interface functions. This flag signal that the model can be used as an efficient backend in TGI and vLLM.
+ """
+ _tied_weights_keys = r"""
+ A list of `state_dict` keys that are potentially tied to another key in the state_dict.
+ """
+ # fmt: on
+
+
+ARGS_TO_IGNORE = {"self", "kwargs", "args", "deprecated_arguments"}
+ARGS_TO_RENAME = {"_out_features": "out_features", "_out_indices": "out_indices"}
+
+
+def get_indent_level(func):
+ # Use this instead of `inspect.getsource(func)` as getsource can be very slow
+ return (len(func.__qualname__.split(".")) - 1) * 4
+
+
+def equalize_indent(docstring: str, indent_level: int) -> str:
+ """
+ Adjust the indentation of a docstring to match the specified indent level.
+ """
+ prefix = " " * indent_level
+ # Uses splitlines() (no keepends) to match previous behaviour that dropped
+ # any trailing newline via the old splitlines() + "\n".join() + textwrap.indent path.
+ return "\n".join(prefix + line.lstrip() if line.strip() else "" for line in docstring.splitlines())
+
+
+def set_min_indent(docstring: str, indent_level: int) -> str:
+ """
+ Adjust the indentation of a docstring to match the specified indent level.
+ """
+ # Equivalent to textwrap.dedent + textwrap.indent but avoids the two regex
+ # passes that textwrap uses internally (one per call in dedent, one in indent).
+ lines = docstring.split("\n")
+ min_indent = min(
+ (len(line) - len(line.lstrip()) for line in lines if line.strip()),
+ default=0,
+ )
+ prefix = " " * indent_level
+ return "\n".join(prefix + line[min_indent:] if line.strip() else "" for line in lines)
+
+
+def parse_shape(docstring):
+ match = _re_shape.search(docstring)
+ if match:
+ return " " + match.group(1)
+ return None
+
+
+def parse_default(docstring):
+ match = _re_default.search(docstring)
+ if match:
+ return " " + match.group(1)
+ return None
+
+
+def parse_docstring(docstring, max_indent_level=0, return_intro=False):
+ """
+ Parse the docstring to extract the Args section and return it as a dictionary.
+ The docstring is expected to be in the format:
+ Args:
+ arg1 (type):
+ Description of arg1.
+ arg2 (type):
+ Description of arg2.
+
+ # This function will also return the remaining part of the docstring after the Args section.
+ Returns:/Example:
+ ...
+ """
+ match = _re_example_or_return.search(docstring)
+ if match:
+ remainder_docstring = docstring[match.start() :]
+ docstring = docstring[: match.start()]
+ else:
+ remainder_docstring = ""
+
+ args_match = _re_args_section.search(docstring)
+ # still try to find args description in the docstring, if args are not preceded by "Args:"
+ docstring_intro = None
+ if args_match:
+ docstring_intro = docstring[: args_match.start()]
+ if docstring_intro.split("\n")[-1].strip() == '"""':
+ docstring_intro = "\n".join(docstring_intro.split("\n")[:-1])
+ if docstring_intro.split("\n")[0].strip() == 'r"""' or docstring_intro.split("\n")[0].strip() == '"""':
+ docstring_intro = "\n".join(docstring_intro.split("\n")[1:])
+ if docstring_intro.strip() == "":
+ docstring_intro = None
+ args_section = args_match.group(1).lstrip("\n") if args_match else docstring
+ if args_section.split("\n")[-1].strip() == '"""':
+ args_section = "\n".join(args_section.split("\n")[:-1])
+ if args_section.split("\n")[0].strip() == 'r"""' or args_section.split("\n")[0].strip() == '"""':
+ args_section = "\n".join(args_section.split("\n")[1:])
+ args_section = set_min_indent(args_section, 0)
+ params = {}
+ if args_section:
+ # Use the pre-compiled pattern (max_indent_level is always 0 at all call
+ # sites; if a non-zero value is ever needed, compile a fresh pattern).
+ if max_indent_level == 0:
+ param_pattern = _re_param
+ else:
+ param_pattern = re.compile(
+ # |--- Group 1 ---|| Group 2 ||- Group 3 -||---------- Group 4 ----------|
+ rf"^\s{{0,{max_indent_level}}}(\w+)\s*\(\s*([^, \)]*)(\s*.*?)\s*\)\s*:\s*((?:(?!\n^\s{{0,{max_indent_level}}}\w+\s*\().)*)",
+ re.DOTALL | re.MULTILINE,
+ )
+ for match in param_pattern.finditer(args_section):
+ param_name = match.group(1)
+ param_type = match.group(2)
+ additional_info = match.group(3)
+ optional = "optional" in additional_info
+ shape = parse_shape(additional_info)
+ default = parse_default(additional_info)
+ param_description = match.group(4).strip()
+ # indent the first line of param_description to 4 spaces:
+ param_description = " " * 4 + param_description
+ param_description = f"\n{param_description}"
+ params[param_name] = {
+ "type": param_type,
+ "description": param_description,
+ "optional": optional,
+ "shape": shape,
+ "default": default,
+ "additional_info": additional_info,
+ }
+
+ if params and remainder_docstring:
+ remainder_docstring = "\n" + remainder_docstring
+
+ remainder_docstring = set_min_indent(remainder_docstring, 0)
+
+ if return_intro:
+ return params, remainder_docstring, docstring_intro
+ return params, remainder_docstring
+
+
+def contains_type(type_hint, target_type) -> tuple[bool, object | None]:
+ """
+ Check if a "nested" type hint contains a specific target type,
+ return the first-level type containing the target_type if found.
+ """
+ args = get_args(type_hint)
+ if args == ():
+ try:
+ return issubclass(type_hint, target_type), type_hint
+ except Exception:
+ return issubclass(type(type_hint), target_type), type_hint
+ found_type_tuple = [contains_type(arg, target_type)[0] for arg in args]
+ found_type = any(found_type_tuple)
+ if found_type:
+ type_hint = args[found_type_tuple.index(True)]
+ return found_type, type_hint
+
+
+def get_model_name(obj):
+ """
+ Get the model name from the file path of the object.
+ """
+
+ path = inspect.getsourcefile(obj)
+ if path is None:
+ return None
+ if path.split(os.path.sep)[-3] != "models":
+ return None
+ file_name = path.split(os.path.sep)[-1]
+ model_name_lowercase_from_folder = path.split(os.path.sep)[-2]
+ model_name_lowercase_from_file = None
+ for file_type in AUTODOC_FILES:
+ start = file_type.split("*")[0]
+ end = file_type.split("*")[-1] if "*" in file_type else ""
+ if file_name.startswith(start) and file_name.endswith(end):
+ model_name_lowercase_from_file = file_name[len(start) : -len(end)]
+ break
+ if model_name_lowercase_from_file and model_name_lowercase_from_folder != model_name_lowercase_from_file:
+ from transformers.models.auto.configuration_auto import SPECIAL_MODEL_TYPE_TO_MODULE_NAME
+
+ if (
+ model_name_lowercase_from_file in SPECIAL_MODEL_TYPE_TO_MODULE_NAME
+ or model_name_lowercase_from_file.replace("_", "-") in SPECIAL_MODEL_TYPE_TO_MODULE_NAME
+ ):
+ return model_name_lowercase_from_file
+ return model_name_lowercase_from_folder
+ return model_name_lowercase_from_folder
+
+
+def generate_processor_intro(cls) -> str:
+ """
+ Generate the intro docstring for a processor class based on its attributes.
+
+ Args:
+ cls: Processor class to generate intro for
+
+ Returns:
+ str: Generated intro text
+ """
+ class_name = cls.__name__
+
+ # Get attributes and their corresponding class names
+ attributes = cls.get_attributes()
+ if not attributes:
+ return ""
+
+ # Build list of component names and their classes
+ components = []
+ component_classes = []
+
+ for attr in attributes:
+ # Get the class name for this attribute
+ class_attr = f"{attr}_class"
+ # Format attribute name for display
+ attr_display = attr.replace("_", " ")
+ components.append(attr_display)
+ component_classes.append(f"[`{{{class_attr}}}`]")
+ if not components:
+ return ""
+
+ # Generate the intro text
+ if len(components) == 1:
+ components_text = f"a {components[0]}"
+ classes_text = component_classes[0]
+ classes_text_short = component_classes[0].replace("[`", "[`~")
+ elif len(components) == 2:
+ components_text = f"a {components[0]} and a {components[1]}"
+ classes_text = f"{component_classes[0]} and {component_classes[1]}"
+ classes_text_short = (
+ f"{component_classes[0].replace('[`', '[`~')} and {component_classes[1].replace('[`', '[`~')}"
+ )
+ else:
+ components_text = ", ".join(f"a {c}" for c in components[:-1]) + f", and a {components[-1]}"
+ classes_text = ", ".join(component_classes[:-1]) + f", and {component_classes[-1]}"
+ classes_short = [c.replace("[`", "[`~") for c in component_classes]
+ classes_text_short = ", ".join(classes_short[:-1]) + f", and {classes_short[-1]}"
+
+ intro = f"""Constructs a {class_name} which wraps {components_text} into a single processor.
+
+[`{class_name}`] offers all the functionalities of {classes_text}. See the
+{classes_text_short} for more information.
+"""
+
+ return intro
+
+
+def get_placeholders_dict(placeholders: set[str], model_name: str) -> Mapping[str, str | None]:
+ """
+ Get the dictionary of placeholders for the given model name.
+ """
+ # import here to avoid circular import
+ from transformers.models import auto as auto_module
+
+ placeholders_dict = {}
+ for placeholder in placeholders:
+ # Infer placeholders from the model name and the auto modules
+ if placeholder in PLACEHOLDER_TO_AUTO_MODULE:
+ try:
+ place_holder_value = getattr(
+ getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE[placeholder][0]),
+ PLACEHOLDER_TO_AUTO_MODULE[placeholder][1],
+ ).get(model_name, None)
+ except ImportError:
+ # In case a library is not installed, we don't want to fail the docstring generation
+ place_holder_value = None
+ if place_holder_value is not None:
+ if isinstance(place_holder_value, list | tuple):
+ place_holder_value = (
+ place_holder_value[-1] if place_holder_value[-1] is not None else place_holder_value[0]
+ )
+ placeholders_dict[placeholder] = place_holder_value if place_holder_value is not None else placeholder
+ else:
+ placeholders_dict[placeholder] = placeholder
+
+ return placeholders_dict
+
+
+def format_args_docstring(docstring: str, model_name: str) -> str:
+ """
+ Replaces placeholders such as {image_processor_class} in the docstring with the actual values,
+ deducted from the model name and the auto modules.
+ """
+ # first check if there are any placeholders in the docstring, if not return it as is
+ placeholders = set(_re_placeholders.findall(docstring))
+ if not placeholders:
+ return docstring
+
+ # get the placeholders dictionary for the given model name
+ placeholders_dict = get_placeholders_dict(placeholders, model_name)
+ # replace the placeholders in the docstring with the values from the placeholders_dict
+ for placeholder, value in placeholders_dict.items():
+ if isinstance(value, dict) and placeholder == "image_processor_class":
+ value = value.get("torchvision", value.get("pil", None))
+ if placeholder is not None:
+ docstring = docstring.replace(f"{{{placeholder}}}", value)
+ return docstring
+
+
+def get_args_doc_from_source(args_classes: object | list[object]) -> dict:
+ if isinstance(args_classes, list | tuple):
+ return _merge_args_dicts(tuple(args_classes))
+ return args_classes.__dict__
+
+
+@lru_cache(maxsize=16)
+def _merge_args_dicts(args_classes_tuple: tuple) -> dict:
+ """Cached merger of args-doc dicts. The input classes are static so caching is safe."""
+ result = {}
+ for cls in args_classes_tuple:
+ result.update(cls.__dict__)
+ return result
+
+
+def get_checkpoint_from_config_class(config_class):
+ checkpoint = None
+
+ # source code of `config_class`
+ # config_source = inspect.getsource(config_class)
+ config_source = config_class.__doc__
+ if not config_source:
+ return None
+
+ checkpoints = _re_checkpoint.findall(config_source)
+ # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link.
+ # For example, `('google-bert/bert-base-uncased', 'https://huggingface.co/google-bert/bert-base-uncased')`
+ for ckpt_name, ckpt_link in checkpoints:
+ # allow the link to end with `/`
+ ckpt_link = ckpt_link.removesuffix("/")
+
+ # verify the checkpoint name corresponds to the checkpoint link
+ ckpt_link_from_name = f"https://huggingface.co/{ckpt_name}"
+ if ckpt_link == ckpt_link_from_name:
+ checkpoint = ckpt_name
+ break
+
+ return checkpoint
+
+
+def add_intro_docstring(func, class_name, indent_level=0):
+ intro_docstring = ""
+ if func.__name__ == "forward":
+ intro_docstring = rf"""The [`{class_name}`] forward method, overrides the `__call__` special method.
+
+
+
+ Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`]
+ instance afterwards instead of this since the former takes care of running the pre and post processing steps while
+ the latter silently ignores them.
+
+
+
+ """
+ intro_docstring = equalize_indent(intro_docstring, indent_level + 4)
+
+ return intro_docstring
+
+
+def _get_model_info(func, parent_class):
+ """
+ Extract model information from a function or its parent class.
+
+ Args:
+ func (`function`): The function to extract information from
+ parent_class (`class`): Optional parent class of the function
+ """
+ # import here to avoid circular import
+ from transformers.models import auto as auto_module
+
+ # Get model name from either parent class or function
+ if parent_class is not None:
+ model_name_lowercase = get_model_name(parent_class)
+ else:
+ model_name_lowercase = get_model_name(func)
+
+ # Normalize model name if needed
+ if model_name_lowercase and model_name_lowercase not in getattr(
+ getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["config_class"][0]),
+ PLACEHOLDER_TO_AUTO_MODULE["config_class"][1],
+ ):
+ model_name_lowercase = model_name_lowercase.replace("_", "-")
+
+ # Get class name from function's qualified name
+ class_name = func.__qualname__.split(".")[0]
+
+ # Get config class for the model
+ if model_name_lowercase is None:
+ config_class = None
+ else:
+ try:
+ config_class = getattr(
+ getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["config_class"][0]),
+ PLACEHOLDER_TO_AUTO_MODULE["config_class"][1],
+ )[model_name_lowercase]
+ except KeyError:
+ if model_name_lowercase in HARDCODED_CONFIG_FOR_MODELS:
+ config_class = HARDCODED_CONFIG_FOR_MODELS[model_name_lowercase]
+ else:
+ config_class = "ModelConfig"
+ print(
+ f"[ERROR] Config not found for {model_name_lowercase}. You can manually add it to HARDCODED_CONFIG_FOR_MODELS in utils/auto_docstring.py"
+ )
+ return model_name_lowercase, class_name, config_class
+
+
+def _format_type_annotation_recursive(type_hint):
+ """
+ Recursively format a type annotation object as a string, preserving generic type arguments.
+
+ This is an internal helper used by process_type_annotation for the type object path.
+
+ Args:
+ type_hint: A type annotation object
+
+ Returns:
+ str: Formatted type string
+ """
+ # Handle special cases
+ if type_hint is type(...) or type_hint is Ellipsis:
+ return "..."
+ # Note: NoneType handling is done later to preserve "NoneType" in Union[] but "None" in | syntax
+
+ # Check if this is a generic type (e.g., list[str], dict[str, int])
+ origin = get_origin(type_hint)
+ args = get_args(type_hint)
+
+ if origin is not None and args:
+ # This is a generic type - format it with its arguments
+ # Get the origin type name
+ if hasattr(origin, "__module__") and hasattr(origin, "__name__"):
+ # Clean up module name - need to handle both 'typing.' prefix and just 'typing'
+ module_name = origin.__module__
+ if module_name in ("typing", "types", "builtins"):
+ module_name = ""
+ else:
+ module_name = (
+ module_name.replace("transformers.", "~")
+ .replace("typing.", "")
+ .replace("types.", "")
+ .replace("builtins.", "")
+ )
+
+ if module_name:
+ origin_str = f"{module_name}.{origin.__name__}"
+ else:
+ origin_str = origin.__name__
+ else:
+ origin_str = str(origin)
+
+ # Handle special origin types
+ if origin_str == "UnionType":
+ # Python 3.13's X | Y syntax - format it nicely
+ arg_strs = [_format_type_annotation_recursive(arg) for arg in args]
+ return " | ".join(arg_strs)
+
+ # Special handling for Annotated[Union[...], ...] and Annotated[UnionType[...], ...]
+ # Check if first arg is a Union/UnionType and format it specially
+ if origin_str == "Annotated" and args:
+ first_arg_origin = get_origin(args[0])
+ # Check if it's a UnionType (modern | syntax) or Union (old Union[] syntax)
+ if first_arg_origin is UnionType:
+ # Modern union type - format as X | Y | Z (with None not NoneType)
+ union_args = get_args(args[0])
+ union_strs = []
+ for arg in union_args:
+ if arg is type(None):
+ union_strs.append("None") # Modern syntax uses "None"
+ else:
+ union_strs.append(_format_type_annotation_recursive(arg))
+ formatted_union = " | ".join(union_strs)
+ # Include the rest of the Annotated metadata
+ remaining_args = [_format_type_annotation_recursive(arg) for arg in args[1:]]
+ all_args = [formatted_union] + remaining_args
+ return f"{origin_str}[{', '.join(all_args)}]"
+ elif first_arg_origin is Union:
+ # Old-style Union - format as Union[X, Y, Z]
+ union_args = get_args(args[0])
+ union_strs = [_format_type_annotation_recursive(arg) for arg in union_args]
+ formatted_union = f"Union[{', '.join(union_strs)}]"
+ # Include the rest of the Annotated metadata
+ remaining_args = [_format_type_annotation_recursive(arg) for arg in args[1:]]
+ all_args = [formatted_union] + remaining_args
+ return f"{origin_str}[{', '.join(all_args)}]"
+
+ # Recursively format the generic arguments
+ arg_strs = [_format_type_annotation_recursive(arg) for arg in args]
+ return f"{origin_str}[{', '.join(arg_strs)}]"
+ elif hasattr(type_hint, "__module__") and hasattr(type_hint, "__name__"):
+ # Simple type with module and name
+ # Clean up module name - need to handle both 'typing.' prefix and just 'typing'
+ module_name = type_hint.__module__
+ if module_name in ("typing", "types", "builtins"):
+ module_name = ""
+ else:
+ module_name = (
+ module_name.replace("transformers.", "~")
+ .replace("typing.", "")
+ .replace("types.", "")
+ .replace("builtins.", "")
+ )
+
+ if module_name:
+ type_name = f"{module_name}.{type_hint.__name__}"
+ else:
+ type_name = type_hint.__name__
+
+ return type_name
+ else:
+ # Fallback to string representation
+ type_str = str(type_hint)
+ # Clean up ForwardRef
+ if "ForwardRef" in type_str:
+ type_str = _re_forward_ref.sub(r"\1", type_str)
+ # Clean up module prefixes
+ type_str = type_str.replace("typing.", "").replace("types.", "")
+ return type_str
+
+
+def process_type_annotation(type_input, param_name: str | None = None) -> tuple[str, bool]:
+ """
+ Unified function to process and format a parameter's type annotation.
+
+ This function intelligently handles both type objects (from inspect.Parameter.annotation)
+ and string representations of types. It will:
+ - Use type introspection when given a type object (preserves generic arguments)
+ - Parse string representations when that's all that's available
+ - Always return a formatted type string and optional flag
+
+ Handles various type representations including:
+ - Type objects with generics (e.g., list[str], Optional[int])
+ - Union types (both Union[X, Y] and X | Y syntax)
+ - Modern union syntax with | (e.g., "bool | None")
+ - Complex typing constructs (Union, Optional, Annotated, etc.)
+ - Generic types with brackets
+ - Class type strings
+ - Simple types and module paths
+
+ Args:
+ type_input: Either a type annotation object or a string representation of a type
+ param_name (`str | None`): The parameter name (used for legacy module path handling)
+
+ Returns:
+ tuple[str, bool]: (formatted_type_string, is_optional)
+ """
+ optional = False
+
+ # Path 1: Type object (best approach - preserves generic type information)
+ if not isinstance(type_input, str):
+ # Handle None type
+ if type_input is None or type_input is type(None):
+ return "None", True
+
+ # Handle Union types and modern UnionType (X | Y)
+ if get_origin(type_input) is Union or get_origin(type_input) is UnionType:
+ subtypes = get_args(type_input)
+ out_str = []
+ for subtype in subtypes:
+ if subtype is type(None):
+ optional = True
+ continue
+ formatted_type = _format_type_annotation_recursive(subtype)
+ out_str.append(formatted_type)
+
+ if not out_str:
+ return "", optional
+ elif len(out_str) == 1:
+ return out_str[0], optional
+ else:
+ return f"Union[{', '.join(out_str)}]", optional
+
+ # Single type (not a Union)
+ formatted_type = _format_type_annotation_recursive(type_input)
+ return formatted_type, optional
+
+ # Path 2: String representation (fallback when we only have strings)
+ param_type = type_input
+
+ # Handle Union types with | syntax
+ if " | " in param_type:
+ # Modern union syntax (e.g., "bool | None")
+ parts = [p.strip() for p in param_type.split(" | ")]
+ if "None" in parts:
+ optional = True
+ parts = [p for p in parts if p != "None"]
+ param_type = " | ".join(parts) if parts else ""
+ # Clean up module prefixes including typing
+ param_type = "".join(param_type.split("typing.")).replace("transformers.", "~").replace("builtins.", "")
+
+ elif "typing" in param_type or "Union[" in param_type or "Optional[" in param_type or "[" in param_type:
+ # Complex typing construct or generic type - clean up typing module references
+ param_type = "".join(param_type.split("typing.")).replace("transformers.", "~")
+
+ elif "" - should NOT append param_name
+ param_type = (
+ param_type.replace("transformers.", "~").replace("builtins.", "").replace("", "")
+ )
+
+ else:
+ # Simple type or module path - only append param_name if it looks like a module path
+ # This is legacy behavior for backwards compatibility
+ if param_name and "." in param_type and not param_type.split(".")[-1][0].isupper():
+ # Looks like a module path ending with an attribute
+ param_type = f"{param_type.replace('transformers.', '~').replace('builtins', '')}.{param_name}"
+ else:
+ # Simple type name, don't append param_name
+ param_type = param_type.replace("transformers.", "~").replace("builtins.", "")
+
+ # Clean up ForwardRef
+ if "ForwardRef" in param_type:
+ param_type = _re_forward_ref.sub(r"\1", param_type)
+
+ # Handle Optional wrapper
+ if "Optional" in param_type:
+ param_type = _re_optional.sub(r"\1", param_type)
+ optional = True
+
+ return param_type, optional
+
+
+def _process_parameter_type(param):
+ """
+ Process and format a parameter's type annotation from an inspect.Parameter object.
+
+ Args:
+ param (`inspect.Parameter`): The parameter from the function signature
+
+ Returns:
+ tuple[str, bool]: (formatted_type_string, is_optional)
+ """
+ if param.annotation == inspect.Parameter.empty:
+ return "", False
+
+ # Use the unified function to process the type annotation
+ formatted_type, optional = process_type_annotation(param.annotation)
+
+ # Check if parameter has a default value (makes it optional)
+ if param.default is not inspect.Parameter.empty:
+ optional = True
+
+ return formatted_type, optional
+
+
+def _get_parameter_info(param_name, documented_params, source_args_dict, param_type, optional):
+ """
+ Get parameter documentation details from the appropriate source.
+ Tensor shape, optional status and description are taken from the custom docstring in priority if available.
+ Type is taken from the function signature first, then from the custom docstring if missing from the signature
+
+ Args:
+ param_name (`str`): Name of the parameter
+ documented_params (`dict`): Dictionary of documented parameters (manually specified in the docstring)
+ source_args_dict (`dict`): Default source args dictionary to use if not in documented_params
+ param_type (`str`): Current parameter type (may be updated)
+ optional (`bool`): Whether the parameter is optional (may be updated)
+ """
+ description = None
+ shape = None
+ shape_string = ""
+ is_documented = True
+ additional_info = None
+ optional_string = r", *optional*" if optional else ""
+
+ if param_name in documented_params:
+ # Parameter is documented in the function's docstring
+ if (
+ param_type == ""
+ and documented_params[param_name].get("type", None) is not None
+ or documented_params[param_name]["additional_info"]
+ ):
+ param_type = documented_params[param_name]["type"]
+ optional = documented_params[param_name]["optional"]
+ shape = documented_params[param_name].get("shape", None)
+ shape_string = shape if shape else ""
+ additional_info = documented_params[param_name]["additional_info"] or ""
+ description = f"{documented_params[param_name]['description']}\n"
+ elif param_name in source_args_dict:
+ # Parameter is documented in ModelArgs or ImageProcessorArgs
+ param_type = source_args_dict[param_name].get("type", param_type)
+ shape = source_args_dict[param_name].get("shape", None)
+ shape_string = " " + shape if shape else ""
+ description = source_args_dict[param_name]["description"]
+ additional_info = source_args_dict[param_name].get("additional_info", None)
+ if additional_info:
+ additional_info = shape_string + optional_string + ", " + additional_info
+ else:
+ # Parameter is not documented
+ is_documented = False
+
+ return param_type, optional_string, shape_string, additional_info, description, is_documented
+
+
+def _process_regular_parameters(
+ sig,
+ func,
+ class_name,
+ documented_params,
+ indent_level,
+ undocumented_parameters,
+ source_args_dict,
+ parent_class,
+ allowed_params=None,
+):
+ """
+ Process all regular parameters (not kwargs parameters) from the function signature.
+
+ Args:
+ sig (`inspect.Signature`): Function signature
+ func (`function`): Function the parameters belong to
+ class_name (`str`): Name of the class
+ documented_params (`dict`): Dictionary of parameters that are already documented
+ indent_level (`int`): Indentation level
+ undocumented_parameters (`list`): List to append undocumented parameters to
+ """
+ docstring = ""
+ # Check if this is a processor by inspecting class hierarchy
+ is_processor = _is_processor_class(func, parent_class)
+
+ # Use appropriate args source based on whether it's a processor or not
+ if source_args_dict is None:
+ if is_processor:
+ source_args_dict = get_args_doc_from_source([ModelArgs, ImageProcessorArgs, ProcessorArgs])
+ else:
+ source_args_dict = get_args_doc_from_source([ModelArgs, ImageProcessorArgs])
+
+ missing_args = {}
+
+ for param_name, param in sig.parameters.items():
+ # Skip parameters that should be ignored
+ if (
+ param_name in ARGS_TO_IGNORE
+ or param_name.startswith("_") # Private/internal params (e.g. ClassVar-backed fields in configs)
+ or param.kind == inspect.Parameter.VAR_POSITIONAL
+ or param.kind == inspect.Parameter.VAR_KEYWORD
+ ):
+ continue
+ # When a filter is active (e.g. config classes: only own annotations), skip inherited params
+ if allowed_params is not None and param_name not in allowed_params:
+ continue
+
+ # When a filter is active (e.g. config classes: only own annotations), skip inherited params
+ if allowed_params is not None and param_name not in allowed_params:
+ continue
+
+ param_name = ARGS_TO_RENAME.get(param_name, param_name)
+
+ # Process parameter type and optional status
+ param_type, optional = _process_parameter_type(param)
+
+ # Check for default value
+ param_default = ""
+ if param.default != inspect._empty and param.default is not None:
+ param_default = f", defaults to `{str(param.default)}`"
+
+ param_type, optional_string, shape_string, additional_info, description, is_documented = _get_parameter_info(
+ param_name, documented_params, source_args_dict, param_type, optional
+ )
+
+ if is_documented:
+ if param_name == "config":
+ if param_type == "":
+ param_type = f"[`{class_name}`]"
+ else:
+ param_type = f"[`{param_type.split('.')[-1]}`]"
+ # elif param_type == "" and False: # TODO: Enforce typing for all parameters
+ # print(f"[ERROR] {param_name} for {func.__qualname__} in file {func.__code__.co_filename} has no type")
+ param_type = param_type if "`" in param_type else f"`{param_type}`"
+ # Format the parameter docstring
+ if additional_info:
+ param_docstring = f"{param_name} ({param_type}{additional_info}):{description}"
+ else:
+ param_docstring = (
+ f"{param_name} ({param_type}{shape_string}{optional_string}{param_default}):{description}"
+ )
+ docstring += set_min_indent(
+ param_docstring,
+ indent_level + 8,
+ )
+ else:
+ missing_args[param_name] = {
+ "type": param_type if param_type else "",
+ "optional": optional,
+ "shape": shape_string,
+ "description": description if description else "\n ",
+ "default": param_default,
+ }
+ # Try to get the correct source file; for classes decorated with @strict (huggingface_hub),
+ # func.__code__.co_filename points to the wrapper in huggingface_hub, not the config file.
+ try:
+ if parent_class is not None:
+ _source_file = inspect.getsourcefile(parent_class) or func.__code__.co_filename
+ else:
+ _source_file = inspect.getsourcefile(inspect.unwrap(func)) or func.__code__.co_filename
+ except (TypeError, OSError):
+ _source_file = func.__code__.co_filename
+ undocumented_parameters.append(
+ f"[ERROR] `{param_name}` is part of {func.__qualname__}'s signature, but not documented. Make sure to add it to the docstring of the function in {_source_file}."
+ )
+
+ return docstring, missing_args
+
+
+def find_sig_line(lines, line_end):
+ parenthesis_count = 0
+ sig_line_end = line_end
+ found_sig = False
+ while not found_sig:
+ for char in lines[sig_line_end]:
+ if char == "(":
+ parenthesis_count += 1
+ elif char == ")":
+ parenthesis_count -= 1
+ if parenthesis_count == 0:
+ found_sig = True
+ break
+ sig_line_end += 1
+ return sig_line_end
+
+
+def _is_image_processor_class(func, parent_class):
+ """
+ Check if a function belongs to a ProcessorMixin class.
+
+ Uses two methods:
+ 1. Check parent_class inheritance (if provided)
+ 2. Check if the source file is named processing_*.py (multimodal processors)
+ vs image_processing_*.py, video_processing_*.py, etc. (single-modality processors)
+
+ Args:
+ func: The function to check
+ parent_class: Optional parent class (if available)
+
+ Returns:
+ bool: True if this is a multimodal processor (inherits from ProcessorMixin), False otherwise
+ """
+ # First, check if parent_class is provided and use it
+ if parent_class is not None:
+ return "BaseImageProcessor" in parent_class.__name__ or any(
+ "BaseImageProcessor" in base.__name__ for base in parent_class.__mro__
+ )
+
+ # If parent_class is None, check the filename
+ # Multimodal processors are in files named "processing_*.py"
+ # Single-modality processors are in "image_processing_*.py", "video_processing_*.py", etc.
+ try:
+ source_file = inspect.getsourcefile(func)
+ except TypeError:
+ return False
+ if not source_file:
+ return False
+
+ # Exception for DummyProcessorForTest
+ if func.__qualname__.split(".")[0] == "DummyForTestImageProcessorFast":
+ return True
+
+ filename = os.path.basename(source_file)
+
+ # Multimodal processors are implemented in processing_*.py modules
+ # (single-modality processors use image_processing_*, video_processing_*, etc.)self.
+ return filename.startswith("image_processing_") and filename.endswith(".py")
+
+
+def _is_processor_class(func, parent_class):
+ """
+ Check if a function belongs to a ProcessorMixin class.
+
+ Uses two methods:
+ 1. Check parent_class inheritance (if provided)
+ 2. Check if the source file is named processing_*.py (multimodal processors)
+ vs image_processing_*.py, video_processing_*.py, etc. (single-modality processors)
+
+ Args:
+ func: The function to check
+ parent_class: Optional parent class (if available)
+
+ Returns:
+ bool: True if this is a multimodal processor (inherits from ProcessorMixin), False otherwise
+ """
+ # First, check if parent_class is provided and use it
+ if parent_class is not None:
+ return "ProcessorMixin" in parent_class.__name__ or any(
+ "ProcessorMixin" in base.__name__ for base in parent_class.__mro__
+ )
+
+ # If parent_class is None, check the filename
+ # Multimodal processors are in files named "processing_*.py"
+ # Single-modality processors are in "image_processing_*.py", "video_processing_*.py", etc.
+ try:
+ source_file = inspect.getsourcefile(func)
+ except TypeError:
+ return False
+ if not source_file:
+ return False
+
+ # Exception for DummyProcessorForTest
+ if func.__qualname__.split(".")[0] == "DummyProcessorForTest":
+ return True
+
+ filename = os.path.basename(source_file)
+
+ # Multimodal processors are implemented in processing_*.py modules
+ # (single-modality processors use image_processing_*, video_processing_*, etc.)self.
+ return filename.startswith("processing_") and filename.endswith(".py")
+
+
+# Python < 3.12 fallback: naming heuristics when __orig_bases__ is not set (cpython#103699).
+# Order matters: check ImageProcessorKwargs before ProcessorKwargs.
+_BASIC_KWARGS_NAMES = frozenset({"ImagesKwargs", "ProcessingKwargs", "TextKwargs", "VideosKwargs", "AudioKwargs"})
+_BASIC_KWARGS_CLASSES = None # Lazy-loaded name -> class mapping
+
+
+def _get_base_kwargs_class_from_name(cls_name: str) -> str | None:
+ """Map kwargs class name to base using naming conventions. Returns base class name or None."""
+ if cls_name in _BASIC_KWARGS_NAMES:
+ return cls_name
+ if "ImageProcessorKwargs" in cls_name or cls_name.endswith("ImagesKwargs"):
+ return "ImagesKwargs"
+ if "ProcessorKwargs" in cls_name:
+ return "ProcessingKwargs"
+ if "VideoProcessorKwargs" in cls_name or cls_name.endswith("VideosKwargs"):
+ return "VideosKwargs"
+ if "AudioProcessorKwargs" in cls_name or cls_name.endswith("AudioKwargs"):
+ return "AudioKwargs"
+ if "TextKwargs" in cls_name:
+ return "TextKwargs"
+ return None
+
+
+def _get_base_kwargs_class(cls):
+ """
+ Get the root/base TypedDict class by walking the inheritance chain.
+ For model-specific kwargs like ComplexProcessingKwargs(ProcessingKwargs), returns ProcessingKwargs.
+ For model-specific kwargs like DummyImageProcessorKwargs(ImagesKwargs), returns ImagesKwargs.
+
+ Compatibility: On Python < 3.12, non-generic TypedDict subclasses do not have __orig_bases__ set
+ (cpython#103699). We fall back to naming heuristics (e.g. *ImageProcessorKwargs -> ImagesKwargs).
+ """
+ current = cls
+ while True:
+ bases = typing_extensions.get_original_bases(current)
+ parent = None
+ for base in bases:
+ if isinstance(base, type) and base not in (dict, object):
+ if getattr(base, "__name__", "") == "TypedDict" and getattr(base, "__module__", "") == "typing":
+ continue
+ parent = base
+ break
+ if parent is None:
+ # Python < 3.12 fallback: use naming heuristics
+ base_name = _get_base_kwargs_class_from_name(current.__name__)
+ if base_name is not None:
+ global _BASIC_KWARGS_CLASSES
+ if _BASIC_KWARGS_CLASSES is None:
+ from transformers.processing_utils import (
+ AudioKwargs,
+ ImagesKwargs,
+ ProcessingKwargs,
+ TextKwargs,
+ VideosKwargs,
+ )
+
+ _BASIC_KWARGS_CLASSES = {
+ "ImagesKwargs": ImagesKwargs,
+ "ProcessingKwargs": ProcessingKwargs,
+ "TextKwargs": TextKwargs,
+ "VideosKwargs": VideosKwargs,
+ "AudioKwargs": AudioKwargs,
+ }
+ parent = _BASIC_KWARGS_CLASSES[base_name]
+ if parent is None or parent == current:
+ return current
+ current = parent
+
+
+def _process_kwargs_parameters(sig, func, parent_class, documented_kwargs, indent_level, undocumented_parameters):
+ """
+ Process **kwargs parameters if needed.
+
+ Args:
+ sig (`inspect.Signature`): Function signature
+ func (`function`): Function the parameters belong to
+ parent_class (`class`): Parent class of the function
+ documented_kwargs (`dict`): Dictionary of kwargs that are already documented
+ indent_level (`int`): Indentation level
+ undocumented_parameters (`list`): List to append undocumented parameters to
+
+ Returns:
+ tuple[str, str]: (kwargs docstring, kwargs summary line to add after return_tensors)
+ """
+ docstring = ""
+ kwargs_summary = ""
+ # Check if we need to add typed kwargs description to the docstring
+ unroll_kwargs = func.__name__ in UNROLL_KWARGS_METHODS
+ if not unroll_kwargs and parent_class is not None:
+ # Check if the function has a parent class with unroll kwargs
+ unroll_kwargs = any(
+ any(unroll_kwargs_class in base.__name__ for base in parent_class.__mro__)
+ for unroll_kwargs_class in UNROLL_KWARGS_CLASSES
+ )
+ if not unroll_kwargs:
+ return docstring, kwargs_summary
+
+ # Check if this is a processor by inspecting class hierarchy
+ is_processor = _is_processor_class(func, parent_class)
+ is_image_processor = _is_image_processor_class(func, parent_class)
+
+ # Use appropriate args source based on whether it's a processor or not
+ if is_processor:
+ source_args_dict = get_args_doc_from_source([ImageProcessorArgs, ProcessorArgs])
+ elif is_image_processor:
+ source_args_dict = get_args_doc_from_source(ImageProcessorArgs)
+ else:
+ raise ValueError(
+ f"Unrolling kwargs is not supported for {func.__name__} of {parent_class.__name__ if parent_class else 'None'} class"
+ )
+
+ # get all unpackable "kwargs" parameters
+ kwargs_parameters = [
+ kwargs_param
+ for _, kwargs_param in sig.parameters.items()
+ if kwargs_param.kind == inspect.Parameter.VAR_KEYWORD
+ ]
+ for kwarg_param in kwargs_parameters:
+ # If kwargs not typed, skip
+ if kwarg_param.annotation == inspect.Parameter.empty:
+ continue
+
+ if not hasattr(kwarg_param.annotation, "__args__") or not hasattr(
+ kwarg_param.annotation.__args__[0], "__name__"
+ ):
+ continue
+
+ if kwarg_param.annotation.__args__[0].__name__ not in BASIC_KWARGS_TYPES:
+ # Extract documentation for kwargs
+ kwargs_documentation = kwarg_param.annotation.__args__[0].__doc__
+ if kwargs_documentation is not None:
+ documented_kwargs = parse_docstring(kwargs_documentation)[0]
+ # Process each kwarg parameter
+ for param_name, param_type_annotation in kwarg_param.annotation.__args__[0].__annotations__.items():
+ # Handle nested kwargs structures for processors
+
+ if is_processor and param_name.endswith("_kwargs"):
+ # Check if this is a basic kwargs type that should be skipped
+ # Basic kwargs types are generic containers that shouldn't be documented as individual params
+
+ # Get the actual type (unwrap Optional if needed)
+ actual_type = param_type_annotation
+ type_name = getattr(param_type_annotation, "__name__", None)
+ if type_name is None and hasattr(param_type_annotation, "__origin__"):
+ # Handle Optional[Type] or Union cases
+ args = getattr(param_type_annotation, "__args__", ())
+ for arg in args:
+ if arg is not type(None):
+ actual_type = arg
+ type_name = getattr(arg, "__name__", None)
+ break
+
+ # Skip only if it's one of the basic kwargs types
+ if type_name in BASIC_KWARGS_TYPES:
+ continue
+
+ # Otherwise, unroll the custom typed kwargs
+ # Get the nested TypedDict's annotations
+ if hasattr(actual_type, "__annotations__"):
+ nested_kwargs_doc = getattr(actual_type, "__doc__", None)
+ documented_nested_kwargs = {}
+ if nested_kwargs_doc:
+ documented_nested_kwargs = parse_docstring(nested_kwargs_doc)[0]
+
+ # Only process fields that are documented in the custom kwargs class's own docstring
+ # This prevents showing too many inherited parameters
+ if not documented_nested_kwargs:
+ # No documentation in the custom kwargs class, skip unrolling
+ continue
+
+ # Process each field in the custom typed kwargs
+ for nested_param_name, nested_param_type in actual_type.__annotations__.items():
+ # Only document parameters that are explicitly documented in the TypedDict's docstring
+ if nested_param_name not in documented_nested_kwargs:
+ continue
+ nested_param_type_str, nested_optional = process_type_annotation(
+ nested_param_type, nested_param_name
+ )
+
+ # Check for default value
+ nested_param_default = ""
+ if parent_class is not None:
+ nested_param_default = str(getattr(parent_class, nested_param_name, ""))
+ nested_param_default = (
+ f", defaults to `{nested_param_default}`" if nested_param_default != "" else ""
+ )
+
+ # Only use the TypedDict's own docstring, not source_args_dict
+ # This prevents pulling in too many inherited parameters
+ (
+ nested_param_type_str,
+ nested_optional_string,
+ nested_shape_string,
+ nested_additional_info,
+ nested_description,
+ nested_is_documented,
+ ) = _get_parameter_info(
+ nested_param_name,
+ documented_nested_kwargs,
+ {}, # Empty dict - only use TypedDict's own docstring
+ nested_param_type_str,
+ nested_optional,
+ )
+
+ # nested_is_documented should always be True here since we filter for it above
+ # Check if type is missing
+ if nested_param_type_str == "":
+ print(
+ f"🚨 {nested_param_name} for {type_name} in file {func.__code__.co_filename} has no type"
+ )
+ nested_param_type_str = (
+ nested_param_type_str if "`" in nested_param_type_str else f"`{nested_param_type_str}`"
+ )
+ # Format the parameter docstring (KWARGS_INDICATOR distinguishes from regular args)
+ if nested_additional_info:
+ docstring += set_min_indent(
+ f"{nested_param_name} ({nested_param_type_str}{KWARGS_INDICATOR}{nested_additional_info}):{nested_description}",
+ indent_level + 8,
+ )
+ else:
+ docstring += set_min_indent(
+ f"{nested_param_name} ({nested_param_type_str}{KWARGS_INDICATOR}{nested_shape_string}{nested_optional_string}{nested_param_default}):{nested_description}",
+ indent_level + 8,
+ )
+
+ # Skip processing the _kwargs parameter itself since we've processed its contents
+ continue
+ else:
+ # If we can't get annotations, skip this parameter
+ continue
+
+ if documented_kwargs and param_name not in documented_kwargs:
+ continue
+ param_type, optional = process_type_annotation(param_type_annotation, param_name)
+
+ # Check for default value
+ param_default = ""
+ if parent_class is not None:
+ param_default = str(getattr(parent_class, param_name, ""))
+ param_default = f", defaults to `{param_default}`" if param_default != "" else ""
+
+ param_type, optional_string, shape_string, additional_info, description, is_documented = (
+ _get_parameter_info(param_name, documented_kwargs, source_args_dict, param_type, optional)
+ )
+
+ if is_documented:
+ # Check if type is missing
+ if param_type == "":
+ print(
+ f"[ERROR] {param_name} for {kwarg_param.annotation.__args__[0].__qualname__} in file {func.__code__.co_filename} has no type"
+ )
+ param_type = param_type if "`" in param_type else f"`{param_type}`"
+ # Format the parameter docstring (KWARGS_INDICATOR distinguishes from regular args)
+ if additional_info:
+ docstring += set_min_indent(
+ f"{param_name} ({param_type}{KWARGS_INDICATOR}{additional_info}):{description}",
+ indent_level + 8,
+ )
+ else:
+ docstring += set_min_indent(
+ f"{param_name} ({param_type}{KWARGS_INDICATOR}{shape_string}{optional_string}{param_default}):{description}",
+ indent_level + 8,
+ )
+ else:
+ undocumented_parameters.append(
+ f"[ERROR] `{param_name}` is part of {kwarg_param.annotation.__args__[0].__qualname__}, but not documented. Make sure to add it to the docstring of the function in {func.__code__.co_filename}."
+ )
+
+ # Build **kwargs summary line (added after return_tensors in _process_parameters_section)
+ kwargs_annot_cls = kwarg_param.annotation.__args__[0]
+ kwargs_type_name = _get_base_kwargs_class(kwargs_annot_cls).__name__
+ kwargs_info = source_args_dict.get("__kwargs__", {})
+ kwargs_description = kwargs_info.get(
+ "description",
+ "Additional keyword arguments. Model-specific parameters are listed above.",
+ )
+ kwargs_summary = set_min_indent(
+ f"**kwargs ([`{kwargs_type_name}`], *optional*):{kwargs_description}",
+ indent_level + 8,
+ )
+
+ return docstring, kwargs_summary
+
+
+def _add_return_tensors_to_docstring(func, parent_class, docstring, indent_level):
+ """
+ Add return_tensors parameter documentation for processor __call__ methods if not already present.
+
+ Args:
+ func (`function`): Function being processed
+ parent_class (`class`): Parent class of the function
+ docstring (`str`): Current docstring being built
+ indent_level (`int`): Indentation level
+
+ Returns:
+ str: Updated docstring with return_tensors if applicable
+ """
+ # Check if this is a processor __call__ method or an image processor preprocess method
+ is_processor_call = False
+ is_image_processor_preprocess = False
+ if func.__name__ == "__call__":
+ # Check if this is a processor by inspecting class hierarchy
+ is_processor_call = _is_processor_class(func, parent_class)
+
+ if func.__name__ == "preprocess":
+ is_image_processor_preprocess = _is_image_processor_class(func, parent_class)
+
+ # If it's a processor __call__ method or an image processor preprocess method and return_tensors is not already documented
+ if (is_processor_call or is_image_processor_preprocess) and "return_tensors" not in docstring:
+ # Get the return_tensors documentation from ImageProcessorArgs
+ source_args_dict = (
+ get_args_doc_from_source(ProcessorArgs)
+ if is_processor_call
+ else get_args_doc_from_source(ImageProcessorArgs)
+ )
+ return_tensors_info = source_args_dict["return_tensors"]
+ param_type = return_tensors_info.get("type", "`str` or [`~utils.TensorType`]")
+ description = return_tensors_info["description"]
+
+ # Format the parameter type
+ param_type = param_type if "`" in param_type else f"`{param_type}`"
+
+ # Format the parameter docstring
+ param_docstring = f"return_tensors ({param_type}, *optional*):{description}"
+ docstring += set_min_indent(param_docstring, indent_level + 8)
+
+ return docstring
+
+
+def _process_parameters_section(
+ func_documentation,
+ sig,
+ func,
+ class_name,
+ model_name_lowercase,
+ parent_class,
+ indent_level,
+ source_args_dict,
+ allowed_params,
+):
+ """
+ Process the parameters section of the docstring.
+
+ Args:
+ func_documentation (`str`): Existing function documentation (manually specified in the docstring)
+ sig (`inspect.Signature`): Function signature
+ func (`function`): Function the parameters belong to
+ class_name (`str`): Name of the class the function belongs to
+ model_name_lowercase (`str`): Lowercase model name
+ parent_class (`class`): Parent class of the function (if any)
+ indent_level (`int`): Indentation level
+ """
+ # Start Args section — constant string, min_indent is always 0, so skip set_min_indent
+ docstring = " " * (indent_level + 4) + "Args:\n"
+ undocumented_parameters = []
+ documented_params = {}
+ documented_kwargs = {}
+
+ # Parse existing docstring if available
+ if func_documentation is not None:
+ documented_params, func_documentation = parse_docstring(func_documentation)
+
+ # Process regular parameters
+ param_docstring, missing_args = _process_regular_parameters(
+ sig,
+ func,
+ class_name,
+ documented_params,
+ indent_level,
+ undocumented_parameters,
+ source_args_dict,
+ parent_class,
+ allowed_params,
+ )
+ docstring += param_docstring
+
+ # Process **kwargs parameters if needed
+ kwargs_docstring, kwargs_summary = _process_kwargs_parameters(
+ sig, func, parent_class, documented_kwargs, indent_level, undocumented_parameters
+ )
+ docstring += kwargs_docstring
+
+ # Add return_tensors for processor __call__ methods if not already present
+ docstring = _add_return_tensors_to_docstring(func, parent_class, docstring, indent_level)
+
+ # Add **kwargs summary line after return_tensors
+ docstring += kwargs_summary
+
+ # Report undocumented parameters
+ if len(undocumented_parameters) > 0:
+ print("\n".join(undocumented_parameters))
+
+ return docstring
+
+
+def _prepare_return_docstring(output_type, config_class, add_intro=True):
+ """
+ Prepare the return docstring from a ModelOutput class.
+
+ This is a robust replacement for the old _prepare_output_docstrings from doc.py,
+ using the same parsing and formatting methods as the rest of auto_docstring.
+
+ Args:
+ output_type: The ModelOutput class to generate documentation for
+ config_class (`str`): Config class for the model
+ add_intro (`bool`): Whether to add the introduction text
+
+ Returns:
+ str: Formatted return docstring
+ """
+ output_docstring = output_type.__doc__
+
+ # If the class has no docstring, try to use the parent class's docstring
+ if output_docstring is None and hasattr(output_type, "__mro__"):
+ for base in output_type.__mro__[1:]: # Skip the class itself
+ if base.__doc__ is not None:
+ output_docstring = base.__doc__
+ break
+
+ if output_docstring is None:
+ if add_intro:
+ raise ValueError(
+ f"No docstring found for `{output_type.__name__}` or its parent classes. "
+ "Make sure the ModelOutput class or one of its parents has a docstring."
+ )
+ return ""
+
+ # Parse the output class docstring to extract parameters
+ documented_params, _ = parse_docstring(output_docstring)
+
+ if not documented_params and add_intro:
+ raise ValueError(
+ f"No `Args` or `Parameters` section is found in the docstring of `{output_type.__name__}`. "
+ "Make sure it has a docstring and contains either `Args` or `Parameters`."
+ )
+
+ # Build the return section
+ full_output_type, _ = process_type_annotation(output_type)
+ if add_intro:
+ # Import here to avoid circular import
+ from .doc import PT_RETURN_INTRODUCTION
+
+ intro = PT_RETURN_INTRODUCTION.format(full_output_type=full_output_type, config_class=config_class)
+ else:
+ intro = f"Returns:\n `{full_output_type}`"
+ if documented_params:
+ intro += ":\n"
+ else:
+ intro += "\n"
+
+ # Build the parameters section
+ params_text = ""
+ if documented_params:
+ for param_name, param_info in documented_params.items():
+ param_type = param_info.get("type", "")
+ param_description = param_info.get("description", "").strip()
+ additional_info = param_info.get("additional_info", "")
+
+ # Handle types with unbalanced backticks due to nested parentheses
+ # The parse_docstring function splits types like `tuple(torch.FloatTensor)` incorrectly
+ # so we need to reconstruct the complete type by grabbing the closing part from additional_info
+ if param_type.startswith("`") and not param_type.endswith("`"):
+ # Find the closing backtick in additional_info
+ closing_backtick_idx = additional_info.find("`")
+ if closing_backtick_idx != -1:
+ # Grab everything up to and including the closing backtick
+ param_type += additional_info[: closing_backtick_idx + 1]
+ # Remove that part from additional_info
+ additional_info = additional_info[closing_backtick_idx + 1 :]
+
+ # Strip backticks from type to add them back consistently
+ param_type = param_type.strip("`")
+
+ # Use process_type_annotation to ensure consistent type formatting
+ # This applies the same formatting rules as the rest of auto_docstring
+ if param_type:
+ param_type, _ = process_type_annotation(param_type)
+
+ # Build the parameter line
+ if additional_info:
+ # additional_info contains shape and optional status
+ param_line = f"- **{param_name}** (`{param_type}`{additional_info}) -- {param_description}"
+ else:
+ param_line = f"- **{param_name}** (`{param_type}`) -- {param_description}"
+
+ # Handle multi-line descriptions:
+ # Split the description to handle continuations with proper indentation
+ lines = param_line.split("\n")
+ formatted_lines = []
+ for i, line in enumerate(lines):
+ if i == 0:
+ # First line gets no extra indent (just the bullet point)
+ formatted_lines.append(line)
+ else:
+ # Continuation lines: strip existing indentation and add 2 spaces (relative to the bullet)
+ formatted_lines.append(" " + line.lstrip())
+
+ param_text = "\n".join(formatted_lines)
+
+ # Indent everything to 4 spaces and append with newline
+ param_text_indented = set_min_indent(param_text, 4)
+ params_text += param_text_indented + "\n"
+
+ result = intro + params_text
+
+ return result
+
+
+def _process_returns_section(func_documentation, sig, config_class, indent_level):
+ """
+ Process the returns section of the docstring.
+
+ Args:
+ func_documentation (`str`): Existing function documentation (manually specified in the docstring)
+ sig (`inspect.Signature`): Function signature
+ config_class (`str`): Config class for the model
+ indent_level (`int`): Indentation level
+ """
+ return_docstring = ""
+
+ # Extract returns section from existing docstring if available
+ if func_documentation is not None and (match_start := _re_return.search(func_documentation)) is not None:
+ match_end = _re_example.search(func_documentation)
+ if match_end:
+ return_docstring = func_documentation[match_start.start() : match_end.start()]
+ func_documentation = func_documentation[match_end.start() :]
+ else:
+ return_docstring = func_documentation[match_start.start() :]
+ func_documentation = ""
+ return_docstring = set_min_indent(return_docstring, indent_level + 4)
+ # Otherwise, generate return docstring from return annotation if available
+ elif sig.return_annotation is not None and sig.return_annotation != inspect._empty:
+ add_intro, return_annotation = contains_type(sig.return_annotation, ModelOutput)
+ return_docstring = _prepare_return_docstring(return_annotation, config_class, add_intro=add_intro)
+ # PT_RETURN_INTRODUCTION already starts with \n, so only add blank line if it doesn't start with one
+ if not return_docstring.startswith("\n"):
+ return_docstring = "\n" + return_docstring
+ return_docstring = set_min_indent(return_docstring, indent_level + 4)
+
+ return return_docstring, func_documentation
+
+
+def _process_example_section(
+ func_documentation, func, parent_class, class_name, model_name_lowercase, config_class, checkpoint, indent_level
+):
+ """
+ Process the example section of the docstring.
+
+ Args:
+ func_documentation (`str`): Existing function documentation (manually specified in the docstring)
+ func (`function`): Function being processed
+ parent_class (`class`): Parent class of the function
+ class_name (`str`): Name of the class
+ model_name_lowercase (`str`): Lowercase model name
+ config_class (`str`): Config class for the model
+ checkpoint: Checkpoint to use in examples
+ indent_level (`int`): Indentation level
+ """
+ # Import here to avoid circular import
+ from transformers.models import auto as auto_module
+
+ example_docstring = ""
+
+ # Use existing example section if available (with or without an "Example:" header)
+ if func_documentation is not None and (match := _re_example.search(func_documentation)):
+ example_docstring = func_documentation[match.start() :]
+ example_docstring = "\n" + set_min_indent(example_docstring, indent_level + 4)
+ # Skip examples for processors
+ elif _is_processor_class(func, parent_class):
+ # Processors don't get auto-generated examples
+ return example_docstring
+ # No examples for __init__ methods or if the class is not a model
+ elif parent_class is None and model_name_lowercase is not None:
+ global _re_model_task
+ if _re_model_task is None:
+ _re_model_task = re.compile(rf"({'|'.join(PT_SAMPLE_DOCSTRINGS.keys())})")
+ model_task = _re_model_task.search(class_name)
+ CONFIG_MAPPING = auto_module.configuration_auto.CONFIG_MAPPING
+
+ # Get checkpoint example
+ if (checkpoint_example := checkpoint) is None:
+ try:
+ checkpoint_example = get_checkpoint_from_config_class(CONFIG_MAPPING[model_name_lowercase])
+ except KeyError:
+ # For models with inconsistent lowercase model name
+ if model_name_lowercase in HARDCODED_CONFIG_FOR_MODELS:
+ CONFIG_MAPPING_NAMES = auto_module.configuration_auto.CONFIG_MAPPING_NAMES
+ config_class_name = HARDCODED_CONFIG_FOR_MODELS[model_name_lowercase]
+ if config_class_name in CONFIG_MAPPING_NAMES.values():
+ model_name_for_auto_config = [
+ k for k, v in CONFIG_MAPPING_NAMES.items() if v == config_class_name
+ ][0]
+ if model_name_for_auto_config in CONFIG_MAPPING:
+ checkpoint_example = get_checkpoint_from_config_class(
+ CONFIG_MAPPING[model_name_for_auto_config]
+ )
+
+ # Add example based on model task
+ if model_task is not None:
+ if checkpoint_example is not None:
+ example_annotation = ""
+ task = model_task.group()
+ example_annotation = PT_SAMPLE_DOCSTRINGS[task].format(
+ model_class=class_name,
+ checkpoint=checkpoint_example,
+ expected_output="...",
+ expected_loss="...",
+ qa_target_start_index=14,
+ qa_target_end_index=15,
+ mask="",
+ )
+ example_docstring = set_min_indent(example_annotation, indent_level + 4)
+ else:
+ print(
+ f"[ERROR] No checkpoint found for {class_name}.{func.__name__}. Please add a `checkpoint` arg to `auto_docstring` or add one in {config_class}'s docstring"
+ )
+ else:
+ # Check if the model is in a pipeline to get an example
+ for name_model_list_for_task in MODELS_TO_PIPELINE:
+ try:
+ model_list_for_task = getattr(auto_module.modeling_auto, name_model_list_for_task)
+ except (ImportError, AttributeError):
+ continue
+ if class_name in model_list_for_task.values():
+ pipeline_name = MODELS_TO_PIPELINE[name_model_list_for_task]
+ example_annotation = PIPELINE_TASKS_TO_SAMPLE_DOCSTRINGS[pipeline_name].format(
+ model_class=class_name,
+ checkpoint=checkpoint_example,
+ expected_output="...",
+ expected_loss="...",
+ qa_target_start_index=14,
+ qa_target_end_index=15,
+ )
+ example_docstring = set_min_indent(example_annotation, indent_level + 4)
+ break
+
+ return example_docstring
+
+
+def auto_method_docstring(
+ func,
+ parent_class=None,
+ custom_intro=None,
+ custom_args=None,
+ checkpoint=None,
+ source_args_dict=None,
+ allowed_params=None,
+):
+ """
+ Wrapper that automatically generates docstring.
+ """
+
+ # Use inspect to retrieve the method's signature
+ sig = inspect.signature(func)
+ indent_level = get_indent_level(func) if not parent_class else get_indent_level(parent_class)
+
+ # Get model information
+ model_name_lowercase, class_name, config_class = _get_model_info(func, parent_class)
+ func_documentation = func.__doc__
+
+ if custom_args is not None and func_documentation is not None:
+ func_documentation = "\n" + set_min_indent(custom_args.strip("\n"), 0) + "\n" + func_documentation
+ elif custom_args is not None:
+ func_documentation = "\n" + set_min_indent(custom_args.strip("\n"), 0)
+
+ # Add intro to the docstring before args description if needed
+ if custom_intro is not None:
+ docstring = set_min_indent(custom_intro, indent_level + 4)
+ if not docstring.strip().endswith("\n"):
+ docstring += "\n"
+ else:
+ docstring = add_intro_docstring(func, class_name=class_name, indent_level=indent_level)
+
+ # Process Parameters section
+ docstring += _process_parameters_section(
+ func_documentation,
+ sig,
+ func,
+ class_name,
+ model_name_lowercase,
+ parent_class,
+ indent_level,
+ source_args_dict,
+ allowed_params,
+ )
+
+ # Process Returns section
+ return_docstring, func_documentation = _process_returns_section(
+ func_documentation, sig, config_class, indent_level
+ )
+ docstring += return_docstring
+
+ # Process Example section
+ example_docstring = _process_example_section(
+ func_documentation,
+ func,
+ parent_class,
+ class_name,
+ model_name_lowercase,
+ config_class,
+ checkpoint,
+ indent_level,
+ )
+ docstring += example_docstring
+
+ # Format the docstring with the placeholders
+ docstring = format_args_docstring(docstring, model_name_lowercase)
+
+ # Assign the dynamically generated docstring to the wrapper function
+ func.__doc__ = docstring
+ return func
+
+
+def auto_class_docstring(cls, custom_intro=None, custom_args=None, checkpoint=None):
+ """
+ Wrapper that automatically generates a docstring for classes based on their attributes and methods.
+ """
+ # import here to avoid circular import
+ from transformers.models import auto as auto_module
+
+ is_dataclass = False
+ is_processor = False
+ is_config = False
+ is_image_processor = False
+ docstring_init = ""
+ docstring_args = ""
+ if "PreTrainedModel" in (x.__name__ for x in cls.__mro__):
+ docstring_init = auto_method_docstring(
+ cls.__init__, parent_class=cls, custom_args=custom_args, checkpoint=checkpoint
+ ).__doc__.replace("Args:", "Parameters:")
+ elif "ProcessorMixin" in (x.__name__ for x in cls.__mro__):
+ is_processor = True
+ docstring_init = auto_method_docstring(
+ cls.__init__,
+ parent_class=cls,
+ custom_args=custom_args,
+ checkpoint=checkpoint,
+ source_args_dict=get_args_doc_from_source([ModelArgs, ImageProcessorArgs, ProcessorArgs]),
+ ).__doc__.replace("Args:", "Parameters:")
+ elif "ModelOutput" in (x.__name__ for x in cls.__mro__):
+ # We have a data class
+ is_dataclass = True
+ doc_class = cls.__doc__
+ if custom_args is None and doc_class:
+ custom_args = doc_class
+ docstring_args = auto_method_docstring(
+ cls.__init__,
+ parent_class=cls,
+ custom_args=custom_args,
+ checkpoint=checkpoint,
+ source_args_dict=get_args_doc_from_source(ModelOutputArgs),
+ ).__doc__
+ elif any("BaseImageProcessor" in x.__name__ for x in cls.__mro__):
+ is_image_processor = True
+ docstring_init = auto_method_docstring(
+ cls.__init__,
+ parent_class=cls,
+ custom_args=custom_args,
+ checkpoint=checkpoint,
+ source_args_dict=get_args_doc_from_source(ImageProcessorArgs),
+ ).__doc__
+ elif "PreTrainedConfig" in (x.__name__ for x in cls.__mro__):
+ is_config = True
+ doc_class = cls.__doc__
+ if custom_args is None and doc_class:
+ custom_args = doc_class
+
+ # Collect all non-ClassVar annotations from the class and its ancestors up to
+ # (but not including) PreTrainedConfig. This allows inherited params from intermediate
+ # config base classes to be documented, while naturally excluding PreTrainedConfig-specific
+ # quasi-ClassVar params (e.g. `transformers_version`, `architectures`).
+ own_config_params = set()
+ for ancestor in cls.__mro__:
+ if ancestor.__name__ == "PreTrainedConfig":
+ break
+ own_config_params |= {
+ k for k, v in getattr(ancestor, "__annotations__", {}).items() if get_origin(v) is not ClassVar
+ }
+ allowed_params = own_config_params if own_config_params else None
+ docstring_init = auto_method_docstring(
+ cls.__init__,
+ parent_class=cls,
+ custom_args=custom_args,
+ checkpoint=checkpoint,
+ source_args_dict=get_args_doc_from_source([ConfigArgs]),
+ allowed_params=allowed_params,
+ ).__doc__
+
+ indent_level = get_indent_level(cls)
+ model_name_lowercase = get_model_name(cls)
+ model_name_title = " ".join([k.title() for k in model_name_lowercase.split("_")]) if model_name_lowercase else None
+ model_base_class = f"{model_name_title.title()}Model" if model_name_title is not None else None
+ if model_name_lowercase is not None:
+ try:
+ model_base_class = getattr(
+ getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["model_class"][0]),
+ PLACEHOLDER_TO_AUTO_MODULE["model_class"][1],
+ )[model_name_lowercase]
+ except KeyError:
+ pass
+ except ImportError:
+ # In some environments, certain model classes might not be available. In that case, we can skip this part.
+ pass
+
+ if model_name_lowercase and model_name_lowercase not in getattr(
+ getattr(auto_module, PLACEHOLDER_TO_AUTO_MODULE["config_class"][0]),
+ PLACEHOLDER_TO_AUTO_MODULE["config_class"][1],
+ ):
+ model_name_lowercase = model_name_lowercase.replace("_", "-")
+
+ name = re.findall(rf"({'|'.join(ClassDocstring.__dict__.keys())})$", cls.__name__)
+
+ if name == [] and custom_intro is None and not is_dataclass and not is_processor and not is_image_processor:
+ raise ValueError(
+ f"`{cls.__name__}` is not registered in the auto doc. Here are the available classes: {ClassDocstring.__dict__.keys()}.\n"
+ "Add a `custom_intro` to the decorator if you want to use `auto_docstring` on a class not registered in the auto doc."
+ )
+ if name != [] or custom_intro is not None or is_config or is_dataclass or is_processor or is_image_processor:
+ name = name[0] if name else None
+ formatting_kwargs = {"model_name": model_name_title}
+ if name == "Config":
+ formatting_kwargs.update({"model_base_class": model_base_class, "model_checkpoint": checkpoint})
+ if custom_intro is not None:
+ pre_block = equalize_indent(custom_intro, indent_level)
+ if not pre_block.endswith("\n"):
+ pre_block += "\n"
+ elif is_processor:
+ # Generate processor intro dynamically
+ pre_block = generate_processor_intro(cls)
+ if pre_block:
+ pre_block = equalize_indent(pre_block, indent_level)
+ pre_block = format_args_docstring(pre_block, model_name_lowercase)
+ elif is_image_processor:
+ pre_block = r"Constructs a {image_processor_class} image processor."
+ if pre_block:
+ pre_block = equalize_indent(pre_block, indent_level)
+ pre_block = format_args_docstring(pre_block, model_name_lowercase)
+ elif model_name_title is None or name is None:
+ pre_block = ""
+ else:
+ pre_block = getattr(ClassDocstring, name).format(**formatting_kwargs)
+ # Start building the docstring
+ docstring = set_min_indent(f"{pre_block}", indent_level) if len(pre_block) else ""
+ if name != "PreTrainedModel" and "PreTrainedModel" in (x.__name__ for x in cls.__mro__):
+ docstring += set_min_indent(f"{ClassDocstring.PreTrainedModel}", indent_level)
+ # Add the __init__ docstring
+ if docstring_init:
+ docstring += set_min_indent(f"\n{docstring_init}", indent_level)
+ elif is_dataclass or is_config:
+ # No init function, we have a data class
+ docstring += docstring_args if docstring_args else "\nArgs:\n"
+ source_args_dict = get_args_doc_from_source(ModelOutputArgs)
+ doc_class = cls.__doc__ if cls.__doc__ else ""
+ documented_kwargs = parse_docstring(doc_class)[0]
+ for param_name, param_type_annotation in cls.__annotations__.items():
+ param_type, optional = process_type_annotation(param_type_annotation, param_name)
+
+ # Check for default value
+ param_default = ""
+ param_default = str(getattr(cls, param_name, ""))
+ param_default = f", defaults to `{param_default}`" if param_default != "" else ""
+
+ param_type, optional_string, shape_string, additional_info, description, is_documented = (
+ _get_parameter_info(param_name, documented_kwargs, source_args_dict, param_type, optional)
+ )
+
+ if is_documented:
+ # Check if type is missing
+ if param_type == "":
+ print(
+ f"[ERROR] {param_name} for {cls.__qualname__} in file {cls.__code__.co_filename} has no type"
+ )
+ param_type = param_type if "`" in param_type else f"`{param_type}`"
+ # Format the parameter docstring
+ if additional_info:
+ docstring += set_min_indent(
+ f"{param_name} ({param_type}{additional_info}):{description}",
+ indent_level + 8,
+ )
+ else:
+ docstring += set_min_indent(
+ f"{param_name} ({param_type}{shape_string}{optional_string}{param_default}):{description}",
+ indent_level + 8,
+ )
+ # TODO (Yoni): Add support for Attributes section in docs
+
+ else:
+ print(
+ f"You used `@auto_class_docstring` decorator on `{cls.__name__}` but this class is not part of the AutoMappings. Remove the decorator"
+ )
+ # Assign the dynamically generated docstring to the wrapper class
+ cls.__doc__ = docstring
+
+ return cls
+
+
+def auto_docstring(obj=None, *, custom_intro=None, custom_args=None, checkpoint=None):
+ r"""
+ Automatically generates comprehensive docstrings for model classes and methods in the Transformers library.
+
+ This decorator reduces boilerplate by automatically including standard argument descriptions while allowing
+ overrides to add new or custom arguments. It inspects function signatures, retrieves predefined docstrings
+ for common arguments (like `input_ids`, `attention_mask`, etc.), and generates complete documentation
+ including examples and return value descriptions.
+
+ For complete documentation and examples, read this [guide](https://huggingface.co/docs/transformers/auto_docstring).
+
+ Examples of usage:
+
+ Basic usage (no parameters):
+ ```python
+ @auto_docstring
+ class MyAwesomeModel(PreTrainedModel):
+ def __init__(self, config, custom_parameter: int = 10):
+ r'''
+ custom_parameter (`int`, *optional*, defaults to 10):
+ Description of the custom parameter for MyAwesomeModel.
+ '''
+ super().__init__(config)
+ self.custom_parameter = custom_parameter
+ ```
+
+ Using `custom_intro` with a class:
+ ```python
+ @auto_docstring(
+ custom_intro="This model implements a novel attention mechanism for improved performance."
+ )
+ class MySpecialModel(PreTrainedModel):
+ def __init__(self, config, attention_type: str = "standard"):
+ r'''
+ attention_type (`str`, *optional*, defaults to "standard"):
+ Type of attention mechanism to use.
+ '''
+ super().__init__(config)
+ ```
+
+ Using `custom_intro` with a method, and specify custom arguments and example directly in the docstring:
+ ```python
+ @auto_docstring(
+ custom_intro="Performs forward pass with enhanced attention computation."
+ )
+ def forward(
+ self,
+ input_ids: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ):
+ r'''
+ custom_parameter (`int`, *optional*, defaults to 10):
+ Description of the custom parameter for MyAwesomeModel.
+
+ Example:
+
+ ```python
+ >>> model = MyAwesomeModel(config)
+ >>> model.forward(input_ids=torch.tensor([1, 2, 3]), attention_mask=torch.tensor([1, 1, 1]))
+ ```
+ '''
+ ```
+
+ Using `custom_args` to define reusable arguments:
+ ```python
+ VISION_ARGS = r'''
+ pixel_values (`torch.FloatTensor`, *optional*):
+ Pixel values of the input images.
+ image_features (`torch.FloatTensor`, *optional*):
+ Pre-computed image features for efficient processing.
+ '''
+
+ @auto_docstring(custom_args=VISION_ARGS)
+ def encode_images(self, pixel_values=None, image_features=None):
+ # ... method implementation
+ ```
+
+ Combining `custom_intro` and `custom_args`:
+ ```python
+ MULTIMODAL_ARGS = r'''
+ vision_features (`torch.FloatTensor`, *optional*):
+ Pre-extracted vision features from the vision encoder.
+ fusion_strategy (`str`, *optional*, defaults to "concat"):
+ Strategy for fusing text and vision modalities.
+ '''
+
+ @auto_docstring(
+ custom_intro="Processes multimodal inputs combining text and vision.",
+ custom_args=MULTIMODAL_ARGS
+ )
+ def forward(
+ self,
+ input_ids,
+ attention_mask=None,
+ vision_features=None,
+ fusion_strategy="concat"
+ ):
+ # ... multimodal processing
+ ```
+
+ Using with ModelOutput classes:
+ ```python
+ @dataclass
+ @auto_docstring(
+ custom_intro="Custom model outputs with additional fields."
+ )
+ class MyModelOutput(ImageClassifierOutput):
+ r'''
+ loss (`torch.FloatTensor`, *optional*):
+ The loss of the model.
+ custom_field (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*):
+ A custom output field specific to this model.
+ '''
+
+ # Standard fields like hidden_states, logits, attentions etc. can be automatically documented
+ # However, given that the loss docstring is often different per model, you should document it above
+ loss: Optional[torch.FloatTensor] = None
+ logits: Optional[torch.FloatTensor] = None
+ hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
+ attentions: Optional[tuple[torch.FloatTensor, ...]] = None
+ custom_field: Optional[torch.FloatTensor] = None
+ ```
+
+ Args:
+ custom_intro (`str`, *optional*):
+ Custom introduction text to add to the docstring. This replaces the default
+ introduction text generated by the decorator before the Args section. Use this to describe what
+ makes your model or method special.
+ custom_args (`str`, *optional*):
+ Custom argument documentation in docstring format. This allows you to define
+ argument descriptions once and reuse them across multiple methods. The format should follow the
+ standard docstring convention: `arg_name (`type`, *optional*, defaults to `value`): Description.`
+ checkpoint (`str`, *optional*):
+ Checkpoint name to use in examples within the docstring. This is typically
+ automatically inferred from the model configuration class, but can be overridden if needed for
+ custom examples.
+
+ Note:
+ - Standard arguments (`input_ids`, `attention_mask`, `pixel_values`, etc.) are automatically documented
+ from predefined descriptions and should not be redefined unless their behavior differs in your model.
+ - New or custom arguments should be documented in the method's docstring using the `r''' '''` block
+ or passed via the `custom_args` parameter.
+ - For model classes, the decorator derives parameter descriptions from the `__init__` method's signature
+ and docstring.
+ - Return value documentation is automatically generated for methods that return ModelOutput subclasses.
+ """
+
+ def auto_docstring_decorator(obj):
+ if len(obj.__qualname__.split(".")) > 1:
+ return auto_method_docstring(
+ obj, custom_args=custom_args, custom_intro=custom_intro, checkpoint=checkpoint
+ )
+ else:
+ return auto_class_docstring(obj, custom_args=custom_args, custom_intro=custom_intro, checkpoint=checkpoint)
+
+ if obj:
+ return auto_docstring_decorator(obj)
+
+ return auto_docstring_decorator
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/backbone_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/backbone_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2947b9a5a953228549e52e7b53af0588d3d4fb7b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/backbone_utils.py
@@ -0,0 +1,19 @@
+import warnings
+
+from ..backbone_utils import BackboneConfigMixin, BackboneMixin
+
+
+class BackboneConfigMixin(BackboneConfigMixin):
+ warnings.warn(
+ "Importing `BackboneConfigMixin` from `utils/backbone_utils.py` is deprecated and will be removed in "
+ "Transformers v5.10. Import as `from transformers.backbone_utils import BackboneConfigMixin` instead.",
+ FutureWarning,
+ )
+
+
+class BackboneMixin(BackboneMixin):
+ warnings.warn(
+ "Importing `BackboneMixin` from `utils/backbone_utils.py` is deprecated and will be removed in "
+ "Transformers v5.10. Import as `from transformers.backbone_utils import BackboneMixin` instead.",
+ FutureWarning,
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_parsing_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_parsing_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..44983cb33a25e613c1c40476b8b7f5251d0c947f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_parsing_utils.py
@@ -0,0 +1,305 @@
+# Copyright 2026 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 __future__ import annotations
+
+import json
+import re
+
+from transformers.utils import is_jmespath_available
+
+
+if is_jmespath_available():
+ import jmespath
+else:
+ jmespath = None
+
+
+def _gemma4_json_to_json(text: str) -> str:
+ """Convert Gemma4 tool call format (unquoted keys, ``<|"|>`` string delimiters) to valid JSON."""
+ strings = []
+
+ def _capture(m):
+ strings.append(m.group(1))
+ return f"\x00{len(strings) - 1}\x00"
+
+ # Grab the inside of gemma-quotes and store them for later
+ text = re.sub(r'<\|"\|>(.*?)<\|"\|>', _capture, text, flags=re.DOTALL)
+ # Add quotes to the bare keys elsewhere
+ text = re.sub(r"(?<=[{,])(\w+):", r'"\1":', text)
+
+ # Put the inside of the quotes back afterwards
+ for i, s in enumerate(strings):
+ text = text.replace(f"\x00{i}\x00", json.dumps(s))
+
+ return text
+
+
+def _parse_re_match(node_match: re.Match) -> dict | str:
+ # If the regex has named groups, return a dict of those groups
+ if node_match.groupdict():
+ return {key: val for key, val in node_match.groupdict().items() if val is not None}
+ # Otherwise the regex must have exactly one unnamed group, and we return that
+ else:
+ groups = list(node_match.groups())
+ if len(groups) > 1:
+ raise ValueError(f"Regex has multiple unnamed groups!\nGroups: {groups}\n")
+ elif len(groups) == 0:
+ raise ValueError(f"Regex has no capture groups:\n\n{node_match.group(0)}")
+ return groups[0]
+
+
+def recursive_parse(
+ node_content: str | list | dict,
+ node_schema: dict,
+):
+ """
+ This function takes content and a JSON schema which includes
+ regex extractors, and recursively parses the content. The output
+ should be a data structure matching the schema.
+
+ Args:
+ node_content: The content corresponding to this node. Usually a string, but can be something else
+ if the parent node has multiple capture groups or named groups. In that case,
+ we generally pass the capture groups straight through to the children of this node
+ and don't do any parsing at this level.
+ node_schema: The schema node controlling the parsing.
+
+ Returns:
+ The parsed data structure for the current node.
+ """
+
+ # If the schema has a const, we just return that value and do absolutely nothing else
+ if "const" in node_schema:
+ return node_schema["const"]
+
+ # If the node content is None, we return None. EZ.
+ if node_content is None:
+ return None
+
+ # If not, we have to do a little parsing. First, set some vars and do basic validation
+ node_type = node_schema.get("type")
+ has_regex = (
+ "x-regex" in node_schema
+ or "x-regex-iterator" in node_schema
+ or "x-regex-key-value" in node_schema
+ or "x-regex-substitutions" in node_schema
+ )
+ if has_regex and not isinstance(node_content, str):
+ raise TypeError(
+ "Schema node got a non-string input, but has a regex for parsing or substitution.\n"
+ f"Input: {node_content}\n"
+ f"Schema: {node_schema}"
+ )
+
+ node_subs = node_schema.get("x-regex-substitutions", [])
+ for node_sub in node_subs:
+ node_content = re.sub(node_sub[0], node_sub[1], node_content, flags=re.DOTALL)
+ node_regex = node_schema.get("x-regex")
+ node_regex_iterator = node_schema.get("x-regex-iterator")
+ node_regex_to_dict = node_schema.get("x-regex-key-value")
+ if node_regex is not None:
+ node_match = re.search(node_regex, node_content, flags=re.DOTALL)
+ if not node_match:
+ return None
+ node_content = _parse_re_match(node_match)
+ if node_regex_iterator is not None:
+ if node_type != "array":
+ raise TypeError(f"Schema node with type {node_type} cannot use x-regex-iterator.\nSchema: {node_schema}")
+ # Note that this can be applied after a standard node-regex search
+ node_content = [
+ _parse_re_match(node_match)
+ for node_match in re.finditer(node_regex_iterator, node_content, flags=re.DOTALL)
+ ]
+ if not node_content:
+ return None
+ if node_regex_to_dict is not None:
+ if node_type != "object":
+ raise TypeError(f"Schema node with type {node_type} cannot use x-regex-key-value.\nSchema: {node_schema}")
+ # Note that this can be applied after a standard node-regex search
+ output_content = {}
+ for node_match in re.finditer(node_regex_to_dict, node_content, flags=re.DOTALL):
+ match_groups = _parse_re_match(node_match)
+ if not isinstance(match_groups, dict) or "key" not in match_groups or "value" not in match_groups:
+ raise ValueError(
+ f"Regex for x-regex-key-value must have named groups 'key' and 'value'.\n"
+ f"Match groups: {match_groups}\n"
+ f"Schema: {node_schema}"
+ )
+ output_content[match_groups["key"]] = match_groups["value"]
+ node_content = output_content
+ if not node_content:
+ return None
+
+ # Next, if the node has a parser, apply it. We do this after regexes so that the regex can extract
+ # a substring to parse, if needed.
+ if "x-parser" in node_schema:
+ parser = node_schema["x-parser"]
+ if parser == "gemma4-tool-call":
+ if not isinstance(node_content, str):
+ raise TypeError(
+ f"Node has Gemma4 tool call parser but got non-string input: {node_content}\nSchema: {node_schema}"
+ )
+ node_content = _gemma4_json_to_json(node_content)
+ parser = "json" # fall through to the JSON parser below - don't add an elif!
+ if parser == "json":
+ if not isinstance(node_content, str):
+ raise TypeError(
+ f"Node has JSON parser but got non-string input: {node_content}\nSchema: {node_schema}"
+ )
+ parser_args = node_schema.get("x-parser-args", {})
+ transform = parser_args.get("transform")
+ allow_non_json = parser_args.get("allow_non_json", False)
+ try:
+ parsed_json = json.loads(node_content)
+ except json.JSONDecodeError as e:
+ if allow_non_json:
+ parsed_json = node_content
+ else:
+ raise ValueError(
+ f"Node has JSON parser but could not parse its contents as JSON. You can use the `allow_non_json` parser arg for nodes which may contain JSON or string content.\n\nContent: {node_content}\n\nError: {e}"
+ )
+ if transform is not None:
+ if jmespath is None:
+ raise ImportError(
+ "Chat response schema includes a jmespath transformation, but jmespath is not installed. You can install it with `pip install jmespath`."
+ )
+ parsed_json = jmespath.search(parser_args["transform"], parsed_json)
+ node_content = parsed_json
+ else:
+ raise ValueError(f"Unknown parser {parser} for schema node: {node_schema}")
+
+ # Finally, handle parsed content based on schema type and recurse if required
+ if node_type == "object":
+ parsed_schema = {}
+ if isinstance(node_content, str):
+ # This means we don't have a regex at this level, so all of our child nodes need to parse the whole
+ # string themselves to extract their value.
+ if "properties" not in node_schema:
+ raise ValueError(
+ f"Object node received string content but has no regex or parser to handle it.\n"
+ f"Content: {node_content}\n"
+ f"Schema: {node_schema}"
+ )
+ for key, child_node in node_schema["properties"].items():
+ child_node_content = recursive_parse(node_content, node_schema["properties"][key])
+ if child_node_content is not None:
+ parsed_schema[key] = child_node_content
+ elif isinstance(node_content, dict):
+ for key, child_node in node_schema.get("properties", {}).items():
+ if "const" in child_node:
+ parsed_schema[key] = child_node["const"]
+ elif key in node_content:
+ parsed_schema[key] = recursive_parse(node_content[key], child_node)
+ elif "default" in child_node:
+ parsed_schema[key] = child_node["default"]
+ additional_schema = node_schema.get("additionalProperties", True)
+ # We want to check only for False values; {} is "falsy" but should pass through
+ if additional_schema is not False:
+ additional_schema = additional_schema if isinstance(additional_schema, dict) else {}
+ for key, value in node_content.items():
+ if key not in node_schema.get("properties", {}):
+ parsed_schema[key] = recursive_parse(value, additional_schema)
+ else:
+ raise TypeError(f"Expected a dict or str for schema node with type object, got {node_content}")
+ required = node_schema.get("required", [])
+ missing = [key for key in required if key not in parsed_schema]
+ if missing:
+ input_preview = repr(node_content[:500]) if isinstance(node_content, str) else repr(node_content)
+ raise ValueError(
+ f"Required fields {missing} are missing from parsed output.\n"
+ f"Parsed: {parsed_schema}\n"
+ f"Input: {input_preview}"
+ )
+ return parsed_schema
+ elif node_type == "array":
+ if not node_content:
+ return []
+ parsed_schema = []
+ if "items" in node_schema:
+ if not isinstance(node_content, list):
+ raise TypeError(f"Expected a list or regex for schema node with type array, got {node_content}")
+ for item in node_content:
+ parsed_schema.append(recursive_parse(item, node_schema["items"]))
+ return parsed_schema
+ elif "prefixItems" in node_schema:
+ if not isinstance(node_content, list):
+ if len(node_schema["prefixItems"]) == 1:
+ # If there's only one prefix item, this is a single item array, we can just wrap the string
+ node_content = [node_content]
+ else:
+ raise TypeError(f"Expected a list or regex for schema node with type array, got {node_content}")
+ if len(node_content) != len(node_schema["prefixItems"]):
+ raise ValueError(
+ f"Array node has {len(node_content)} items, but schema only has "
+ f"{len(node_schema['prefixItems'])} prefixItems defined.\n"
+ f"Content: {node_content}\n"
+ f"Schema: {node_schema}"
+ )
+ for item, item_schema in zip(node_content, node_schema["prefixItems"]):
+ parsed_schema.append(recursive_parse(item, item_schema))
+ return parsed_schema
+ else:
+ raise ValueError(f"Array node has no items or prefixItems schema defined.\nSchema: {node_schema}")
+ elif node_type in ("string", "integer", "number", "boolean"):
+ if node_type == "integer":
+ if isinstance(node_content, int):
+ return node_content
+ if not isinstance(node_content, str):
+ raise TypeError(
+ f"Expected a string or int for schema node with type integer, got {type(node_content).__name__}: {node_content}"
+ )
+ try:
+ return int(node_content)
+ except ValueError:
+ raise ValueError(
+ f"Schema node has type 'integer', but the parsed string content is not a valid integer: {node_content!r}"
+ )
+ elif node_type == "number":
+ if isinstance(node_content, (int, float)):
+ return float(node_content)
+ if not isinstance(node_content, str):
+ raise TypeError(
+ f"Expected a string or number for schema node with type number, got {type(node_content).__name__}: {node_content}"
+ )
+ try:
+ return float(node_content)
+ except ValueError:
+ raise ValueError(
+ f"Schema node has type 'number', but the parsed string content is not a valid number: {node_content!r}"
+ )
+ elif node_type == "boolean":
+ if isinstance(node_content, bool):
+ return node_content
+ if not isinstance(node_content, str):
+ raise TypeError(
+ f"Expected a string or bool for schema node with type boolean, got {type(node_content).__name__}: {node_content}"
+ )
+ if node_content.lower() in ("true", "1"):
+ return True
+ elif node_content.lower() in ("false", "0"):
+ return False
+ else:
+ raise ValueError(f"Invalid boolean value: {node_content}")
+ else:
+ # String type
+ if not isinstance(node_content, str):
+ raise TypeError(
+ f"Expected a string for schema node with type string, got {type(node_content).__name__}: {node_content}"
+ )
+ return node_content
+ elif node_type is None or node_type == "any":
+ return node_content # Don't touch it
+ else:
+ raise TypeError(f"Unsupported schema type {node_type} for node: {node_content}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_template_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_template_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b23e2fa881d302e60f12528788d50d8ad2d50a1
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/chat_template_utils.py
@@ -0,0 +1,622 @@
+# 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.
+
+import inspect
+import json
+import re
+import types
+from collections.abc import Callable
+from contextlib import contextmanager
+from copy import deepcopy
+from datetime import datetime
+from functools import lru_cache
+from inspect import isfunction
+from typing import Any, Literal, Union, get_args, get_origin, get_type_hints, no_type_check
+
+from packaging import version
+
+from . import logging
+from .import_utils import is_jinja_available, is_torch_available, is_vision_available
+
+
+logger = logging.get_logger(__name__)
+
+if is_jinja_available():
+ import jinja2
+ import jinja2.exceptions
+ import jinja2.ext
+ import jinja2.meta
+ import jinja2.nodes
+ import jinja2.runtime
+ from jinja2.ext import Extension
+ from jinja2.sandbox import ImmutableSandboxedEnvironment
+else:
+ jinja2 = None
+
+if is_vision_available():
+ from PIL.Image import Image
+
+ChatType = list[dict[str, Any]]
+
+
+BASIC_TYPES = (int, float, str, bool, Any, type(None), ...)
+# Extracts the initial segment of the docstring, containing the function description
+description_re = re.compile(r"^(.*?)[\n\s]*(Args:|Returns:|Raises:|\Z)", re.DOTALL)
+# Extracts the Args: block from the docstring
+args_re = re.compile(r"\n\s*Args:\n\s*(.*?)[\n\s]*(Returns:|Raises:|\Z)", re.DOTALL)
+# Splits the Args: block into individual arguments
+args_split_re = re.compile(
+ r"""
+(?:^|\n) # Match the start of the args block, or a newline
+\s*(\w+):\s* # Capture the argument name and strip spacing
+(.*?)\s* # Capture the argument description, which can span multiple lines, and strip trailing spacing
+(?=\n\s*\w+:|\Z) # Stop when you hit the next argument or the end of the block
+""",
+ re.DOTALL | re.VERBOSE,
+)
+# Extracts the Returns: block from the docstring, if present. Note that most chat templates ignore the return type/doc!
+returns_re = re.compile(r"\n\s*Returns:\n\s*(.*?)[\n\s]*(Raises:|\Z)", re.DOTALL)
+
+
+class TypeHintParsingException(Exception):
+ """Exception raised for errors in parsing type hints to generate JSON schemas"""
+
+
+class DocstringParsingException(Exception):
+ """Exception raised for errors in parsing docstrings to generate JSON schemas"""
+
+
+def _get_json_schema_type(param_type: type) -> dict[str, str]:
+ type_mapping = {
+ int: {"type": "integer"},
+ float: {"type": "number"},
+ str: {"type": "string"},
+ bool: {"type": "boolean"},
+ type(None): {"type": "null"},
+ Any: {},
+ }
+ if is_vision_available():
+ type_mapping[Image] = {"type": "image"}
+ if is_torch_available():
+ import torch
+
+ type_mapping[torch.Tensor] = {"type": "audio"}
+ return type_mapping.get(param_type, {"type": "object"})
+
+
+def _parse_type_hint(hint: str) -> dict:
+ origin = get_origin(hint)
+ args = get_args(hint)
+
+ if origin is None:
+ try:
+ return _get_json_schema_type(hint)
+ except KeyError:
+ raise TypeHintParsingException(
+ "Couldn't parse this type hint, likely due to a custom class or object: ", hint
+ )
+
+ elif origin is Union or (hasattr(types, "UnionType") and origin is types.UnionType):
+ # Recurse into each of the subtypes in the Union, except None, which is handled separately at the end
+ subtypes = [_parse_type_hint(t) for t in args if t is not type(None)]
+ if len(subtypes) == 1:
+ # A single non-null type can be expressed directly
+ return_dict = subtypes[0]
+ elif all("type" in subtype and isinstance(subtype["type"], str) for subtype in subtypes):
+ # A union of basic types can be expressed as a list in the schema
+ return_dict = {"type": sorted([subtype["type"] for subtype in subtypes])}
+ else:
+ # A union of more complex types requires "anyOf"
+ return_dict = {"anyOf": subtypes}
+ if type(None) in args:
+ return_dict["nullable"] = True
+ return return_dict
+
+ elif origin is Literal and len(args) > 0:
+ LITERAL_TYPES = (int, float, str, bool, type(None))
+ args_types = []
+ for arg in args:
+ if type(arg) not in LITERAL_TYPES:
+ raise TypeHintParsingException("Only the valid python literals can be listed in typing.Literal.")
+ arg_type = _get_json_schema_type(type(arg)).get("type")
+ if arg_type is not None and arg_type not in args_types:
+ args_types.append(arg_type)
+ return {
+ "type": args_types.pop() if len(args_types) == 1 else list(args_types),
+ "enum": list(args),
+ }
+
+ elif origin is list:
+ if not args:
+ return {"type": "array"}
+ else:
+ # Lists can only have a single type argument, so recurse into it
+ return {"type": "array", "items": _parse_type_hint(args[0])}
+
+ elif origin is tuple:
+ if not args:
+ return {"type": "array"}
+ if len(args) == 1:
+ raise TypeHintParsingException(
+ f"The type hint {str(hint).replace('typing.', '')} is a Tuple with a single element, which "
+ "we do not automatically convert to JSON schema as it is rarely necessary. If this input can contain "
+ "more than one element, we recommend "
+ "using a list[] type instead, or if it really is a single element, remove the tuple[] wrapper and just "
+ "pass the element directly."
+ )
+ if ... in args:
+ raise TypeHintParsingException(
+ "Conversion of '...' is not supported in Tuple type hints. "
+ "Use list[] types for variable-length"
+ " inputs instead."
+ )
+ return {"type": "array", "prefixItems": [_parse_type_hint(t) for t in args]}
+
+ elif origin is dict:
+ # The JSON equivalent to a dict is 'object', which mandates that all keys are strings
+ # However, we can specify the type of the dict values with "additionalProperties"
+ out = {"type": "object"}
+ if len(args) == 2:
+ out["additionalProperties"] = _parse_type_hint(args[1])
+ return out
+
+ raise TypeHintParsingException("Couldn't parse this type hint, likely due to a custom class or object: ", hint)
+
+
+def _convert_type_hints_to_json_schema(func: Callable) -> dict:
+ type_hints = get_type_hints(func)
+ signature = inspect.signature(func)
+ func_name = getattr(func, "__name__", "operation")
+ # For methods, we need to ignore the first "self" or "cls" parameter. Here we assume that if the first parameter
+ # is named "self" or "cls" and has no type hint, it is an implicit receiver argument.
+ first_param_name = next(iter(signature.parameters), None)
+ if (
+ first_param_name in {"self", "cls"}
+ and signature.parameters[first_param_name].annotation == inspect.Parameter.empty
+ ):
+ implicit_arg_name = first_param_name
+ else:
+ implicit_arg_name = None
+ required = []
+ for param_name, param in signature.parameters.items():
+ if param_name == implicit_arg_name:
+ continue
+ if param.annotation == inspect.Parameter.empty:
+ raise TypeHintParsingException(f"Argument {param.name} is missing a type hint in function {func_name}")
+ if param.default == inspect.Parameter.empty:
+ required.append(param_name)
+
+ properties = {}
+ for param_name, param_type in type_hints.items():
+ if param_name == implicit_arg_name:
+ continue
+ properties[param_name] = _parse_type_hint(param_type)
+
+ schema = {"type": "object", "properties": properties}
+ if required:
+ schema["required"] = required
+
+ return schema
+
+
+def parse_google_format_docstring(docstring: str) -> tuple[str | None, dict | None, str | None]:
+ """
+ Parses a Google-style docstring to extract the function description,
+ argument descriptions, and return description.
+
+ Args:
+ docstring (str): The docstring to parse.
+
+ Returns:
+ The function description, arguments, and return description.
+ """
+
+ # Extract the sections
+ description_match = description_re.search(docstring)
+ args_match = args_re.search(docstring)
+ returns_match = returns_re.search(docstring)
+
+ # Clean and store the sections
+ description = description_match.group(1).strip() if description_match else None
+ docstring_args = args_match.group(1).strip() if args_match else None
+ returns = returns_match.group(1).strip() if returns_match else None
+
+ # Parsing the arguments into a dictionary
+ if docstring_args is not None:
+ docstring_args = "\n".join([line for line in docstring_args.split("\n") if line.strip()]) # Remove blank lines
+ matches = args_split_re.findall(docstring_args)
+ args_dict = {match[0]: re.sub(r"\s*\n+\s*", " ", match[1].strip()) for match in matches}
+ else:
+ args_dict = {}
+
+ return description, args_dict, returns
+
+
+def get_json_schema(func: Callable) -> dict:
+ """
+ This function generates a JSON schema for a given function, based on its docstring and type hints. This is
+ mostly used for passing lists of tools to a chat template. The JSON schema contains the name and description of
+ the function, as well as the names, types and descriptions for each of its arguments. `get_json_schema()` requires
+ that the function has a docstring, and that each argument has a description in the docstring, in the standard
+ Google docstring format shown below. It also requires that all user-facing arguments have valid Python type hints.
+ When passing methods, implicit receiver arguments (`self` or `cls`) are ignored.
+
+ Although it is not required, a `Returns` block can also be added, which will be included in the schema. This is
+ optional because most chat templates ignore the return value of the function.
+
+ Args:
+ func: The function to generate a JSON schema for.
+
+ Returns:
+ A dictionary containing the JSON schema for the function.
+
+ Examples:
+ ```python
+ >>> def multiply(x: float, y: float):
+ >>> '''
+ >>> A function that multiplies two numbers
+ >>>
+ >>> Args:
+ >>> x: The first number to multiply
+ >>> y: The second number to multiply
+ >>> '''
+ >>> return x * y
+ >>>
+ >>> print(get_json_schema(multiply))
+ {
+ "name": "multiply",
+ "description": "A function that multiplies two numbers",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "x": {"type": "number", "description": "The first number to multiply"},
+ "y": {"type": "number", "description": "The second number to multiply"}
+ },
+ "required": ["x", "y"]
+ }
+ }
+ ```
+
+ The general use for these schemas is that they are used to generate tool descriptions for chat templates that
+ support them, like so:
+
+ ```python
+ >>> from transformers import AutoTokenizer
+ >>> from transformers.utils import get_json_schema
+ >>>
+ >>> def multiply(x: float, y: float):
+ >>> '''
+ >>> A function that multiplies two numbers
+ >>>
+ >>> Args:
+ >>> x: The first number to multiply
+ >>> y: The second number to multiply
+ >>> return x * y
+ >>> '''
+ >>>
+ >>> multiply_schema = get_json_schema(multiply)
+ >>> tokenizer = AutoTokenizer.from_pretrained("CohereForAI/c4ai-command-r-v01")
+ >>> messages = [{"role": "user", "content": "What is 179 x 4571?"}]
+ >>> formatted_chat = tokenizer.apply_chat_template(
+ >>> messages,
+ >>> tools=[multiply_schema],
+ >>> chat_template="tool_use",
+ >>> return_dict=True,
+ >>> return_tensors="pt",
+ >>> add_generation_prompt=True
+ >>> )
+ >>> # The formatted chat can now be passed to model.generate()
+ ```
+
+ Each argument description can also have an optional `(choices: ...)` block at the end, such as
+ `(choices: ["tea", "coffee"])`, which will be parsed into an `enum` field in the schema. Note that this will
+ only be parsed correctly if it is at the end of the line:
+
+ ```python
+ >>> def drink_beverage(beverage: str):
+ >>> '''
+ >>> A function that drinks a beverage
+ >>>
+ >>> Args:
+ >>> beverage: The beverage to drink (choices: ["tea", "coffee"])
+ >>> '''
+ >>> pass
+ >>>
+ >>> print(get_json_schema(drink_beverage))
+ ```
+ {
+ 'name': 'drink_beverage',
+ 'description': 'A function that drinks a beverage',
+ 'parameters': {
+ 'type': 'object',
+ 'properties': {
+ 'beverage': {
+ 'type': 'string',
+ 'enum': ['tea', 'coffee'],
+ 'description': 'The beverage to drink'
+ }
+ },
+ 'required': ['beverage']
+ }
+ }
+ """
+ doc = inspect.getdoc(func)
+ func_name = getattr(func, "__name__", "operation")
+
+ if not doc:
+ raise DocstringParsingException(f"Cannot generate JSON schema for {func_name} because it has no docstring!")
+ doc = doc.strip()
+ main_doc, param_descriptions, return_doc = parse_google_format_docstring(doc)
+
+ json_schema = _convert_type_hints_to_json_schema(func)
+ if (return_dict := json_schema["properties"].pop("return", None)) is not None:
+ if return_doc is not None: # We allow a missing return docstring since most templates ignore it
+ return_dict["description"] = return_doc
+ for arg, schema in json_schema["properties"].items():
+ if arg not in param_descriptions:
+ raise DocstringParsingException(
+ f"Cannot generate JSON schema for {func_name} because the docstring has no description for the argument '{arg}'"
+ )
+ desc = param_descriptions[arg]
+ enum_choices = re.search(r"\(choices:\s*(.*?)\)\s*$", desc, flags=re.IGNORECASE)
+ if enum_choices:
+ schema["enum"] = [c.strip() for c in json.loads(enum_choices.group(1))]
+ desc = enum_choices.string[: enum_choices.start()].strip()
+ schema["description"] = desc
+
+ output = {"name": func_name, "description": main_doc, "parameters": json_schema}
+ if return_dict is not None:
+ output["return"] = return_dict
+ return {"type": "function", "function": output}
+
+
+@lru_cache
+@no_type_check
+def _get_template_variables(chat_template: str | None) -> frozenset[str]:
+ """Return the set of undeclared variables referenced by a chat template.
+
+ Uses ``jinja2.meta.find_undeclared_variables`` so that callers can
+ automatically distinguish template-level kwargs from processor kwargs
+ without maintaining a manual allowlist. Needed only to support BC as we
+ allowed all `kwargs` to be merged into one in the past
+ """
+ if chat_template is None:
+ return frozenset()
+ compiled = _compile_jinja_template(chat_template)
+ ast = compiled.environment.parse(chat_template)
+ return frozenset(jinja2.meta.find_undeclared_variables(ast))
+
+
+def _render_with_assistant_indices(
+ compiled_template, messages, tools, documents, add_generation_prompt, **template_kwargs
+):
+ rendered_blocks = []
+ generation_indices = []
+ with compiled_template.environment.activate_tracker(rendered_blocks, generation_indices):
+ for block in compiled_template.generate(
+ messages=messages,
+ tools=tools,
+ documents=documents,
+ add_generation_prompt=add_generation_prompt,
+ **template_kwargs,
+ ):
+ rendered_blocks.append(block)
+ rendered_chat = "".join(rendered_blocks)
+ return rendered_chat, generation_indices
+
+
+@lru_cache
+def _compile_jinja_template(chat_template):
+ return _cached_compile_jinja_template(chat_template)
+
+
+@no_type_check
+def _cached_compile_jinja_template(chat_template):
+ if not is_jinja_available():
+ raise ImportError(
+ "apply_chat_template requires jinja2 to be installed. Please install it using `pip install jinja2`."
+ )
+
+ class AssistantTracker(Extension):
+ # This extension is used to track the indices of assistant-generated tokens in the rendered chat
+ tags = {"generation"}
+
+ def __init__(self, environment: ImmutableSandboxedEnvironment):
+ # The class is only initiated by jinja.
+ super().__init__(environment)
+ environment.extend(activate_tracker=self.activate_tracker)
+ self._rendered_blocks = None
+ self._generation_indices = None
+
+ def parse(self, parser: jinja2.parser.Parser) -> jinja2.nodes.CallBlock:
+ lineno = next(parser.stream).lineno
+ body = parser.parse_statements(["name:endgeneration"], drop_needle=True)
+ return jinja2.nodes.CallBlock(self.call_method("_generation_support"), [], [], body).set_lineno(lineno)
+
+ @jinja2.pass_eval_context
+ def _generation_support(self, context: jinja2.nodes.EvalContext, caller: jinja2.runtime.Macro) -> str:
+ rv = caller()
+ if self.is_active():
+ # Only track generation indices if the tracker is active
+ start_index = len("".join(self._rendered_blocks))
+ end_index = start_index + len(rv)
+ self._generation_indices.append((start_index, end_index))
+ return rv
+
+ def is_active(self) -> bool:
+ return self._rendered_blocks is not None or self._generation_indices is not None
+
+ @contextmanager
+ def activate_tracker(self, rendered_blocks: list[int], generation_indices: list[int]):
+ try:
+ if self.is_active():
+ raise ValueError("AssistantTracker should not be reused before closed")
+ self._rendered_blocks = rendered_blocks
+ self._generation_indices = generation_indices
+
+ yield
+ finally:
+ self._rendered_blocks = None
+ self._generation_indices = None
+
+ if version.parse(jinja2.__version__) < version.parse("3.1.0"):
+ raise ImportError(
+ f"apply_chat_template requires jinja2>=3.1.0 to be installed. Your version is {jinja2.__version__}."
+ )
+
+ def raise_exception(message):
+ raise jinja2.exceptions.TemplateError(message)
+
+ def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
+ # We override the built-in tojson filter because Jinja's default filter escapes HTML characters
+ # We also expose some options like custom indents and separators
+ return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators, sort_keys=sort_keys)
+
+ def strftime_now(format):
+ return datetime.now().strftime(format)
+
+ jinja_env = ImmutableSandboxedEnvironment(
+ trim_blocks=True, lstrip_blocks=True, extensions=[AssistantTracker, jinja2.ext.loopcontrols]
+ )
+ jinja_env.filters["tojson"] = tojson
+ jinja_env.globals["raise_exception"] = raise_exception
+ jinja_env.globals["strftime_now"] = strftime_now
+ return jinja_env.from_string(chat_template)
+
+
+def render_jinja_template(
+ conversations: list[ChatType],
+ tools: list[dict | Callable] | None = None,
+ documents: ChatType | None = None,
+ chat_template: str | None = None,
+ return_assistant_tokens_mask: bool = False,
+ continue_final_message: bool = False,
+ add_generation_prompt: bool = False,
+ **kwargs,
+) -> str:
+ if return_assistant_tokens_mask and not re.search(r"\{\%-?\s*generation\s*-?\%\}", chat_template):
+ logger.warning_once(
+ "return_assistant_tokens_mask==True but chat template does not contain `{% generation %}` keyword."
+ )
+
+ # Compilation function uses a cache to avoid recompiling the same template
+ compiled_template = _compile_jinja_template(chat_template)
+
+ # We accept either JSON schemas or functions for tools. If we get functions, we convert them to schemas
+ if tools is not None:
+ tool_schemas = []
+ for tool in tools:
+ if isinstance(tool, dict):
+ tool_schemas.append(tool)
+ elif isfunction(tool) or inspect.ismethod(tool):
+ tool_schemas.append(get_json_schema(tool))
+ else:
+ raise ValueError(
+ "Tools should either be a JSON schema, or a callable function with type hints "
+ "and a docstring suitable for auto-conversion to a schema."
+ )
+ else:
+ tool_schemas = None
+
+ if documents is not None:
+ for document in documents:
+ if not isinstance(document, dict):
+ raise TypeError("Documents should be a list of dicts with 'title' and 'text' keys!")
+
+ rendered = []
+ all_generation_indices = []
+ continue_final_message_tag = "CONTINUE_FINAL_MESSAGE_TAG "
+ for chat in conversations:
+ if hasattr(chat, "messages"):
+ # Indicates it's a Conversation object
+ chat = chat.messages
+ if continue_final_message:
+ chat = deepcopy(chat)
+ final_message = chat[-1].get("content")
+ if final_message is None:
+ raise ValueError("continue_final_message is set but the final message has no content to continue!")
+ elif isinstance(final_message, (list, tuple)):
+ for content_block in reversed(final_message):
+ if "text" in content_block:
+ # Pick the last text block in the message (the first one we hit while iterating in reverse)
+ final_message = content_block["text"]
+ content_block["text"] = content_block["text"] + continue_final_message_tag
+ break
+ else:
+ raise ValueError(
+ "continue_final_message is set but we could not find any text to continue in the final message!"
+ )
+ else:
+ chat[-1]["content"] = chat[-1]["content"] + continue_final_message_tag
+ if return_assistant_tokens_mask:
+ rendered_chat, generation_indices = _render_with_assistant_indices(
+ compiled_template=compiled_template,
+ messages=chat,
+ tools=tool_schemas,
+ documents=documents,
+ add_generation_prompt=add_generation_prompt,
+ **kwargs,
+ )
+ all_generation_indices.append(generation_indices)
+ else:
+ rendered_chat = compiled_template.render(
+ messages=chat,
+ tools=tool_schemas,
+ documents=documents,
+ add_generation_prompt=add_generation_prompt,
+ **kwargs,
+ )
+ if continue_final_message:
+ if (final_message.strip() not in rendered_chat) or (
+ continue_final_message_tag.strip() not in rendered_chat
+ ):
+ raise ValueError(
+ "continue_final_message is set but the final message does not appear in the chat after "
+ "applying the chat template! This can happen if the chat template deletes portions of "
+ "the final message. Please verify the chat template and final message in your chat to "
+ "ensure they are compatible."
+ )
+ tag_loc = rendered_chat.rindex(continue_final_message_tag.strip())
+ if rendered_chat[tag_loc : tag_loc + len(continue_final_message_tag)] == continue_final_message_tag:
+ # The template preserves spacing, so things are simple
+ rendered_chat = rendered_chat[:tag_loc]
+ else:
+ # The message has trailing spacing that was trimmed, so we must be more cautious
+ rendered_chat = rendered_chat[:tag_loc].rstrip()
+ rendered.append(rendered_chat)
+
+ return rendered, all_generation_indices
+
+
+def is_valid_message(message):
+ """
+ Check that input is a valid message in a chat, namely a dict with "role" and "content" keys.
+ """
+ if not isinstance(message, dict):
+ return False
+ if not ("role" in message and "content" in message):
+ return False
+ return True
+
+
+class Chat:
+ """This class is intended to just be used internally for pipelines and not exposed to users. We convert chats
+ to this format because the rest of the pipeline code tends to assume that lists of messages are
+ actually a batch of samples rather than messages in the same conversation."""
+
+ def __init__(self, messages: dict):
+ for message in messages:
+ if not is_valid_message(message):
+ raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.")
+ self.messages = messages
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/constants.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..fefd1b4601da04e073ff2880099ccaf87d0b1666
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/constants.py
@@ -0,0 +1,6 @@
+IMAGENET_DEFAULT_MEAN = [0.485, 0.456, 0.406]
+IMAGENET_DEFAULT_STD = [0.229, 0.224, 0.225]
+IMAGENET_STANDARD_MEAN = [0.5, 0.5, 0.5]
+IMAGENET_STANDARD_STD = [0.5, 0.5, 0.5]
+OPENAI_CLIP_MEAN = [0.48145466, 0.4578275, 0.40821073]
+OPENAI_CLIP_STD = [0.26862954, 0.26130258, 0.27577711]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/deprecation.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/deprecation.py
new file mode 100644
index 0000000000000000000000000000000000000000..db0e67325d7811d41d1ca90f49813ed0fb803f0f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/deprecation.py
@@ -0,0 +1,175 @@
+# 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.
+import inspect
+import warnings
+from functools import wraps
+
+import packaging.version
+
+from .. import __version__
+from . import ExplicitEnum, is_torch_available, is_torchdynamo_compiling
+
+
+# This is needed in case we deprecate a kwarg of a function/method being compiled
+if is_torch_available():
+ import torch # noqa: F401
+
+
+class Action(ExplicitEnum):
+ NONE = "none"
+ NOTIFY = "notify"
+ NOTIFY_ALWAYS = "notify_always"
+ RAISE = "raise"
+
+
+def deprecate_kwarg(
+ old_name: str,
+ version: str,
+ new_name: str | None = None,
+ warn_if_greater_or_equal_version: bool = False,
+ raise_if_greater_or_equal_version: bool = False,
+ raise_if_both_names: bool = False,
+ additional_message: str | None = None,
+):
+ """
+ Function or method decorator to notify users about deprecated keyword arguments, replacing them with a new name if specified.
+ Note that is decorator is `torch.compile`-safe, i.e. it will not cause graph breaks (but no warning will be displayed if compiling).
+
+ This decorator allows you to:
+ - Notify users when a keyword argument is deprecated.
+ - Automatically replace deprecated keyword arguments with new ones.
+ - Raise an error if deprecated arguments are used, depending on the specified conditions.
+
+ By default, the decorator notifies the user about the deprecated argument while the `transformers.__version__` < specified `version`
+ in the decorator. To keep notifications with any version `warn_if_greater_or_equal_version=True` can be set.
+
+ Parameters:
+ old_name (`str`):
+ Name of the deprecated keyword argument.
+ version (`str`):
+ The version in which the keyword argument was (or will be) deprecated.
+ new_name (`Optional[str]`, *optional*):
+ The new name for the deprecated keyword argument. If specified, the deprecated keyword argument will be replaced with this new name.
+ warn_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`):
+ Whether to show warning if current `transformers` version is greater or equal to the deprecated version.
+ raise_if_greater_or_equal_version (`bool`, *optional*, defaults to `False`):
+ Whether to raise `ValueError` if current `transformers` version is greater or equal to the deprecated version.
+ raise_if_both_names (`bool`, *optional*, defaults to `False`):
+ Whether to raise `ValueError` if both deprecated and new keyword arguments are set.
+ additional_message (`Optional[str]`, *optional*):
+ An additional message to append to the default deprecation message.
+
+ Raises:
+ ValueError:
+ If raise_if_greater_or_equal_version is True and the current version is greater than or equal to the deprecated version, or if raise_if_both_names is True and both old and new keyword arguments are provided.
+
+ Returns:
+ Callable:
+ A wrapped function that handles the deprecated keyword arguments according to the specified parameters.
+
+ Example usage with renaming argument:
+
+ ```python
+ @deprecate_kwarg("reduce_labels", new_name="do_reduce_labels", version="6.0.0")
+ def my_function(do_reduce_labels):
+ print(do_reduce_labels)
+
+ my_function(reduce_labels=True) # Will show a deprecation warning and use do_reduce_labels=True
+ ```
+
+ Example usage without renaming argument:
+
+ ```python
+ @deprecate_kwarg("max_size", version="6.0.0")
+ def my_function(max_size):
+ print(max_size)
+
+ my_function(max_size=1333) # Will show a deprecation warning
+ ```
+
+ """
+
+ deprecated_version = packaging.version.parse(version)
+ current_version = packaging.version.parse(__version__)
+ is_greater_or_equal_version = current_version >= deprecated_version
+
+ if is_greater_or_equal_version:
+ version_message = f"and removed starting from version {version}"
+ else:
+ version_message = f"and will be removed in version {version}"
+
+ def wrapper(func):
+ # Required for better warning message
+ sig = inspect.signature(func)
+ function_named_args = set(sig.parameters.keys())
+ is_instance_method = "self" in function_named_args
+ is_class_method = "cls" in function_named_args
+
+ @wraps(func)
+ def wrapped_func(*args, **kwargs):
+ # Get class + function name (just for better warning message)
+ func_name = func.__name__
+ if is_instance_method:
+ func_name = f"{args[0].__class__.__name__}.{func_name}"
+ elif is_class_method:
+ func_name = f"{args[0].__name__}.{func_name}"
+
+ minimum_action = Action.NONE
+ message = None
+
+ # deprecated kwarg and its new version are set for function call -> replace it with new name
+ if old_name in kwargs and new_name in kwargs:
+ minimum_action = Action.RAISE if raise_if_both_names else Action.NOTIFY_ALWAYS
+ message = f"Both `{old_name}` and `{new_name}` are set for `{func_name}`. Using `{new_name}={kwargs[new_name]}` and ignoring deprecated `{old_name}={kwargs[old_name]}`."
+ kwargs.pop(old_name)
+
+ # only deprecated kwarg is set for function call -> replace it with new name
+ elif old_name in kwargs and new_name is not None and new_name not in kwargs:
+ minimum_action = Action.NOTIFY
+ message = f"`{old_name}` is deprecated {version_message} for `{func_name}`. Use `{new_name}` instead."
+ kwargs[new_name] = kwargs.pop(old_name)
+
+ # deprecated kwarg is not set for function call and new name is not specified -> just notify
+ elif old_name in kwargs:
+ minimum_action = Action.NOTIFY
+ message = f"`{old_name}` is deprecated {version_message} for `{func_name}`."
+
+ if message is not None and additional_message is not None:
+ message = f"{message} {additional_message}"
+
+ # update minimum_action if argument is ALREADY deprecated (current version >= deprecated version)
+ if is_greater_or_equal_version:
+ # change to (NOTIFY, NOTIFY_ALWAYS) -> RAISE if specified
+ # in case we want to raise error for already deprecated arguments
+ if raise_if_greater_or_equal_version and minimum_action != Action.NONE:
+ minimum_action = Action.RAISE
+
+ # change to NOTIFY -> NONE if specified (NOTIFY_ALWAYS can't be changed to NONE)
+ # in case we want to ignore notifications for already deprecated arguments
+ elif not warn_if_greater_or_equal_version and minimum_action == Action.NOTIFY:
+ minimum_action = Action.NONE
+
+ # raise error or notify user
+ if minimum_action == Action.RAISE:
+ raise ValueError(message)
+ # If we are compiling, we do not raise the warning as it would break compilation
+ elif minimum_action in (Action.NOTIFY, Action.NOTIFY_ALWAYS) and not is_torchdynamo_compiling():
+ # DeprecationWarning is ignored by default, so we use FutureWarning instead
+ warnings.warn(message, FutureWarning, stacklevel=2)
+
+ return func(*args, **kwargs)
+
+ return wrapped_func
+
+ return wrapper
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/doc.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/doc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ae111f11d19cc020544aab7dcb2fed875d6c04ab
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/doc.py
@@ -0,0 +1,1091 @@
+# 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.
+"""
+Doc utilities: Utilities related to documentation
+"""
+
+import functools
+import inspect
+import re
+import textwrap
+import types
+from collections import OrderedDict
+from typing import cast
+
+
+def get_docstring_indentation_level(func):
+ """Return the indentation level of the start of the docstring of a class or function (or method)."""
+ # We assume classes are always defined in the global scope
+ if inspect.isclass(func):
+ return 4
+ source = inspect.getsource(func)
+ first_line = source.splitlines()[0]
+ function_def_level = len(first_line) - len(first_line.lstrip())
+ return 4 + function_def_level
+
+
+def add_start_docstrings(*docstr):
+ def docstring_decorator(fn):
+ fn.__doc__ = "".join(docstr) + (fn.__doc__ if fn.__doc__ is not None else "")
+ return fn
+
+ return docstring_decorator
+
+
+def add_start_docstrings_to_model_forward(*docstr):
+ def docstring_decorator(fn):
+ class_name = f"[`{fn.__qualname__.split('.')[0]}`]"
+ intro = rf""" The {class_name} forward method, overrides the `__call__` special method.
+
+
+
+ Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`]
+ instance afterwards instead of this since the former takes care of running the pre and post processing steps while
+ the latter silently ignores them.
+
+
+"""
+
+ correct_indentation = get_docstring_indentation_level(fn)
+ current_doc = fn.__doc__ if fn.__doc__ is not None else ""
+ try:
+ first_non_empty = next(line for line in current_doc.splitlines() if line.strip() != "")
+ doc_indentation = len(first_non_empty) - len(first_non_empty.lstrip())
+ except StopIteration:
+ doc_indentation = correct_indentation
+
+ docs = docstr
+ # In this case, the correct indentation level (class method, 2 Python levels) was respected, and we should
+ # correctly reindent everything. Otherwise, the doc uses a single indentation level
+ if doc_indentation == 4 + correct_indentation:
+ docs = [textwrap.indent(textwrap.dedent(doc), " " * correct_indentation) for doc in docstr]
+ intro = textwrap.indent(textwrap.dedent(intro), " " * correct_indentation)
+
+ docstring = "".join(docs) + current_doc
+ fn.__doc__ = intro + docstring
+ return fn
+
+ return docstring_decorator
+
+
+def add_end_docstrings(*docstr):
+ def docstring_decorator(fn):
+ fn.__doc__ = (fn.__doc__ if fn.__doc__ is not None else "") + "".join(docstr)
+ return fn
+
+ return docstring_decorator
+
+
+PT_RETURN_INTRODUCTION = r"""
+ Returns:
+ [`{full_output_type}`] or `tuple(torch.FloatTensor)`: A [`{full_output_type}`] or a tuple of
+ `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various
+ elements depending on the configuration ([`{config_class}`]) and inputs.
+
+"""
+
+
+def _get_indent(t):
+ """Returns the indentation in the first line of t"""
+ search = re.search(r"^(\s*)\S", t)
+ return "" if search is None else search.groups()[0]
+
+
+def _convert_output_args_doc(output_args_doc):
+ """Convert output_args_doc to display properly."""
+ # Split output_arg_doc in blocks argument/description
+ indent = _get_indent(output_args_doc)
+ blocks = []
+ current_block = ""
+ for line in output_args_doc.split("\n"):
+ # If the indent is the same as the beginning, the line is the name of new arg.
+ if _get_indent(line) == indent:
+ if len(current_block) > 0:
+ blocks.append(current_block[:-1])
+ current_block = f"{line}\n"
+ else:
+ # Otherwise it's part of the description of the current arg.
+ # We need to remove 2 spaces to the indentation.
+ current_block += f"{line[2:]}\n"
+ blocks.append(current_block[:-1])
+
+ # Format each block for proper rendering
+ for i in range(len(blocks)):
+ blocks[i] = re.sub(r"^(\s+)(\S+)(\s+)", r"\1- **\2**\3", blocks[i])
+ blocks[i] = re.sub(r":\s*\n\s*(\S)", r" -- \1", blocks[i])
+
+ return "\n".join(blocks)
+
+
+def _prepare_output_docstrings(output_type, config_class, min_indent=None, add_intro=True):
+ """
+ Prepares the return part of the docstring using `output_type`.
+ """
+ output_docstring = output_type.__doc__
+ params_docstring = None
+ if output_docstring is not None:
+ # Remove the head of the docstring to keep the list of args only
+ lines = output_docstring.split("\n")
+ i = 0
+ while i < len(lines) and re.search(r"^\s*(Args|Parameters):\s*$", lines[i]) is None:
+ i += 1
+ if i < len(lines):
+ params_docstring = "\n".join(lines[(i + 1) :])
+ params_docstring = _convert_output_args_doc(params_docstring)
+ elif add_intro:
+ raise ValueError(
+ f"No `Args` or `Parameters` section is found in the docstring of `{output_type.__name__}`. Make sure it has "
+ "docstring and contain either `Args` or `Parameters`."
+ )
+
+ # Add the return introduction
+ if add_intro:
+ full_output_type = f"{output_type.__module__}.{output_type.__name__}"
+ intro = PT_RETURN_INTRODUCTION.format(full_output_type=full_output_type, config_class=config_class)
+ else:
+ full_output_type = str(output_type)
+ intro = f"\nReturns:\n `{full_output_type}`"
+ if params_docstring is not None:
+ intro += ":\n"
+
+ result = intro
+ if params_docstring is not None:
+ result += params_docstring
+
+ # Apply minimum indent if necessary
+ if min_indent is not None:
+ lines = result.split("\n")
+ # Find the indent of the first nonempty line
+ i = 0
+ while len(lines[i]) == 0:
+ i += 1
+ indent = len(_get_indent(lines[i]))
+ # If too small, add indentation to all nonempty lines
+ if indent < min_indent:
+ to_add = " " * (min_indent - indent)
+ lines = [(f"{to_add}{line}" if len(line) > 0 else line) for line in lines]
+ result = "\n".join(lines)
+
+ return result
+
+
+FAKE_MODEL_DISCLAIMER = """
+
+
+ This example uses a random model as the real ones are all very big. To get proper results, you should use
+ {real_checkpoint} instead of {fake_checkpoint}. If you get out-of-memory when loading that checkpoint, you can try
+ adding `device_map="auto"` in the `from_pretrained` call.
+
+
+"""
+
+
+PT_TOKEN_CLASSIFICATION_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, {model_class}
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> inputs = tokenizer(
+ ... "HuggingFace is a company based in Paris and New York", add_special_tokens=False, return_tensors="pt"
+ ... )
+
+ >>> with torch.no_grad():
+ ... logits = model(**inputs).logits
+
+ >>> predicted_token_class_ids = logits.argmax(-1)
+
+ >>> # Note that tokens are classified rather then input words which means that
+ >>> # there might be more predicted token classes than words.
+ >>> # Multiple token classes might account for the same word
+ >>> predicted_tokens_classes = [model.config.id2label[t.item()] for t in predicted_token_class_ids[0]]
+ >>> predicted_tokens_classes
+ {expected_output}
+
+ >>> labels = predicted_token_class_ids
+ >>> loss = model(**inputs, labels=labels).loss
+ >>> round(loss.item(), 2)
+ {expected_loss}
+ ```
+"""
+
+PT_QUESTION_ANSWERING_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, {model_class}
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet"
+
+ >>> inputs = tokenizer(question, text, return_tensors="pt")
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> answer_start_index = outputs.start_logits.argmax()
+ >>> answer_end_index = outputs.end_logits.argmax()
+
+ >>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1]
+ >>> tokenizer.decode(predict_answer_tokens, skip_special_tokens=True)
+ {expected_output}
+
+ >>> # target is "nice puppet"
+ >>> target_start_index = torch.tensor([{qa_target_start_index}])
+ >>> target_end_index = torch.tensor([{qa_target_end_index}])
+
+ >>> outputs = model(**inputs, start_positions=target_start_index, end_positions=target_end_index)
+ >>> loss = outputs.loss
+ >>> round(loss.item(), 2)
+ {expected_loss}
+ ```
+"""
+
+PT_SEQUENCE_CLASSIFICATION_SAMPLE = r"""
+ Example of single-label classification:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, {model_class}
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... logits = model(**inputs).logits
+
+ >>> predicted_class_id = logits.argmax().item()
+ >>> model.config.id2label[predicted_class_id]
+ {expected_output}
+
+ >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
+ >>> num_labels = len(model.config.id2label)
+ >>> model = {model_class}.from_pretrained("{checkpoint}", num_labels=num_labels)
+
+ >>> labels = torch.tensor([1])
+ >>> loss = model(**inputs, labels=labels).loss
+ >>> round(loss.item(), 2)
+ {expected_loss}
+ ```
+
+ Example of multi-label classification:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, {model_class}
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}", problem_type="multi_label_classification")
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... logits = model(**inputs).logits
+
+ >>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]
+
+ >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`
+ >>> num_labels = len(model.config.id2label)
+ >>> model = {model_class}.from_pretrained(
+ ... "{checkpoint}", num_labels=num_labels, problem_type="multi_label_classification"
+ ... )
+
+ >>> labels = torch.sum(
+ ... torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1
+ ... ).to(torch.float)
+ >>> loss = model(**inputs, labels=labels).loss
+ ```
+"""
+
+PT_MASKED_LM_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, {model_class}
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> inputs = tokenizer("The capital of France is {mask}.", return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... logits = model(**inputs).logits
+
+ >>> # retrieve index of {mask}
+ >>> mask_token_index = (inputs.input_ids == tokenizer.mask_token_id)[0].nonzero(as_tuple=True)[0]
+
+ >>> predicted_token_id = logits[0, mask_token_index].argmax(axis=-1)
+ >>> tokenizer.decode(predicted_token_id)
+ {expected_output}
+
+ >>> labels = tokenizer("The capital of France is Paris.", return_tensors="pt")["input_ids"]
+ >>> # mask labels of non-{mask} tokens
+ >>> labels = torch.where(inputs.input_ids == tokenizer.mask_token_id, labels, -100)
+
+ >>> outputs = model(**inputs, labels=labels)
+ >>> round(outputs.loss.item(), 2)
+ {expected_loss}
+ ```
+"""
+
+PT_BASE_MODEL_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, {model_class}
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs)
+
+ >>> last_hidden_states = outputs.last_hidden_state
+ ```
+"""
+
+PT_MULTIPLE_CHOICE_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoTokenizer, {model_class}
+ >>> import torch
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
+ >>> choice0 = "It is eaten with a fork and a knife."
+ >>> choice1 = "It is eaten while held in the hand."
+ >>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1
+
+ >>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="pt", padding=True)
+ >>> outputs = model(**{{k: v.unsqueeze(0) for k, v in encoding.items()}}, labels=labels) # batch size is 1
+
+ >>> # the linear classifier still needs to be trained
+ >>> loss = outputs.loss
+ >>> logits = outputs.logits
+ ```
+"""
+
+PT_CAUSAL_LM_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> import torch
+ >>> from transformers import AutoTokenizer, {model_class}
+
+ >>> tokenizer = AutoTokenizer.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
+ >>> outputs = model(**inputs, labels=inputs["input_ids"])
+ >>> loss = outputs.loss
+ >>> logits = outputs.logits
+ ```
+"""
+
+PT_SPEECH_BASE_MODEL_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoProcessor, {model_class}
+ >>> import torch
+ >>> from datasets import load_dataset
+
+ >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
+ >>> dataset = dataset.sort("id")
+ >>> sampling_rate = dataset.features["audio"].sampling_rate
+
+ >>> processor = AutoProcessor.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> # audio file is decoded on the fly
+ >>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> last_hidden_states = outputs.last_hidden_state
+ >>> list(last_hidden_states.shape)
+ {expected_output}
+ ```
+"""
+
+PT_SPEECH_CTC_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoProcessor, {model_class}
+ >>> from datasets import load_dataset
+ >>> import torch
+
+ >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
+ >>> dataset = dataset.sort("id")
+ >>> sampling_rate = dataset.features["audio"].sampling_rate
+
+ >>> processor = AutoProcessor.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> # audio file is decoded on the fly
+ >>> inputs = processor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
+ >>> with torch.no_grad():
+ ... logits = model(**inputs).logits
+ >>> predicted_ids = torch.argmax(logits, dim=-1)
+
+ >>> # transcribe speech
+ >>> transcription = processor.batch_decode(predicted_ids)
+ >>> transcription[0]
+ {expected_output}
+
+ >>> inputs["labels"] = processor(text=dataset[0]["text"], return_tensors="pt").input_ids
+
+ >>> # compute loss
+ >>> loss = model(**inputs).loss
+ >>> round(loss.item(), 2)
+ {expected_loss}
+ ```
+"""
+
+PT_SPEECH_SEQ_CLASS_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoFeatureExtractor, {model_class}
+ >>> from datasets import load_dataset
+ >>> import torch
+
+ >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
+ >>> dataset = dataset.sort("id")
+ >>> sampling_rate = dataset.features["audio"].sampling_rate
+
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> # audio file is decoded on the fly
+ >>> inputs = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=sampling_rate, return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... logits = model(**inputs).logits
+
+ >>> predicted_class_ids = torch.argmax(logits, dim=-1).item()
+ >>> predicted_label = model.config.id2label[predicted_class_ids]
+ >>> predicted_label
+ {expected_output}
+
+ >>> # compute loss - target_label is e.g. "down"
+ >>> target_label = model.config.id2label[0]
+ >>> inputs["labels"] = torch.tensor([model.config.label2id[target_label]])
+ >>> loss = model(**inputs).loss
+ >>> round(loss.item(), 2)
+ {expected_loss}
+ ```
+"""
+
+
+PT_SPEECH_FRAME_CLASS_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoFeatureExtractor, {model_class}
+ >>> from datasets import load_dataset
+ >>> import torch
+
+ >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
+ >>> dataset = dataset.sort("id")
+ >>> sampling_rate = dataset.features["audio"].sampling_rate
+
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> # audio file is decoded on the fly
+ >>> inputs = feature_extractor(dataset[0]["audio"]["array"], return_tensors="pt", sampling_rate=sampling_rate)
+ >>> with torch.no_grad():
+ ... logits = model(**inputs).logits
+
+ >>> probabilities = torch.sigmoid(logits[0])
+ >>> # labels is a one-hot array of shape (num_frames, num_speakers)
+ >>> labels = (probabilities > 0.5).long()
+ >>> labels[0].tolist()
+ {expected_output}
+ ```
+"""
+
+
+PT_SPEECH_XVECTOR_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoFeatureExtractor, {model_class}
+ >>> from datasets import load_dataset
+ >>> import torch
+
+ >>> dataset = load_dataset("hf-internal-testing/librispeech_asr_demo", "clean", split="validation")
+ >>> dataset = dataset.sort("id")
+ >>> sampling_rate = dataset.features["audio"].sampling_rate
+
+ >>> feature_extractor = AutoFeatureExtractor.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> # audio file is decoded on the fly
+ >>> inputs = feature_extractor(
+ ... [d["array"] for d in dataset[:2]["audio"]], sampling_rate=sampling_rate, return_tensors="pt", padding=True
+ ... )
+ >>> with torch.no_grad():
+ ... embeddings = model(**inputs).embeddings
+
+ >>> embeddings = torch.nn.functional.normalize(embeddings, dim=-1).cpu()
+
+ >>> # the resulting embeddings can be used for cosine similarity-based retrieval
+ >>> cosine_sim = torch.nn.CosineSimilarity(dim=-1)
+ >>> similarity = cosine_sim(embeddings[0], embeddings[1])
+ >>> threshold = 0.7 # the optimal threshold is dataset-dependent
+ >>> if similarity < threshold:
+ ... print("Speakers are not the same!")
+ >>> round(similarity.item(), 2)
+ {expected_output}
+ ```
+"""
+
+PT_VISION_BASE_MODEL_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, {model_class}
+ >>> import torch
+ >>> from datasets import load_dataset
+
+ >>> dataset = load_dataset("huggingface/cats-image")
+ >>> image = dataset["test"]["image"][0]
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> inputs = image_processor(image, return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> last_hidden_states = outputs.last_hidden_state
+ >>> list(last_hidden_states.shape)
+ {expected_output}
+ ```
+"""
+
+PT_VISION_SEQ_CLASS_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, {model_class}
+ >>> import torch
+ >>> from datasets import load_dataset
+
+ >>> dataset = load_dataset("huggingface/cats-image")
+ >>> image = dataset["test"]["image"][0]
+
+ >>> image_processor = AutoImageProcessor.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> inputs = image_processor(image, return_tensors="pt")
+
+ >>> with torch.no_grad():
+ ... logits = model(**inputs).logits
+
+ >>> # model predicts one of the 1000 ImageNet classes
+ >>> predicted_label = logits.argmax(-1).item()
+ >>> print(model.config.id2label[predicted_label])
+ {expected_output}
+ ```
+"""
+
+
+PT_SAMPLE_DOCSTRINGS = {
+ "SequenceClassification": PT_SEQUENCE_CLASSIFICATION_SAMPLE,
+ "QuestionAnswering": PT_QUESTION_ANSWERING_SAMPLE,
+ "TokenClassification": PT_TOKEN_CLASSIFICATION_SAMPLE,
+ "MultipleChoice": PT_MULTIPLE_CHOICE_SAMPLE,
+ "MaskedLM": PT_MASKED_LM_SAMPLE,
+ "LMHead": PT_CAUSAL_LM_SAMPLE,
+ "BaseModel": PT_BASE_MODEL_SAMPLE,
+ "SpeechBaseModel": PT_SPEECH_BASE_MODEL_SAMPLE,
+ "CTC": PT_SPEECH_CTC_SAMPLE,
+ "AudioClassification": PT_SPEECH_SEQ_CLASS_SAMPLE,
+ "AudioFrameClassification": PT_SPEECH_FRAME_CLASS_SAMPLE,
+ "AudioXVector": PT_SPEECH_XVECTOR_SAMPLE,
+ "VisionBaseModel": PT_VISION_BASE_MODEL_SAMPLE,
+ "ImageClassification": PT_VISION_SEQ_CLASS_SAMPLE,
+}
+
+
+TEXT_TO_AUDIO_SPECTROGRAM_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoProcessor, {model_class}, SpeechT5HifiGan
+
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> processor = AutoProcessor.from_pretrained("{checkpoint}")
+ >>> vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
+ >>> inputs = processor(text="Hello, my dog is cute", return_tensors="pt")
+
+ >>> # generate speech
+ >>> speech = model.generate(inputs["input_ids"], speaker_embeddings=speaker_embeddings, vocoder=vocoder)
+ ```
+"""
+
+
+TEXT_TO_AUDIO_WAVEFORM_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoProcessor, {model_class}
+
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> processor = AutoProcessor.from_pretrained("{checkpoint}")
+ >>> inputs = processor(text="Hello, my dog is cute", return_tensors="pt")
+
+ >>> # generate speech
+ >>> speech = model(inputs["input_ids"])
+ ```
+"""
+
+
+AUDIO_FRAME_CLASSIFICATION_SAMPLE = PT_SPEECH_FRAME_CLASS_SAMPLE
+
+
+AUDIO_XVECTOR_SAMPLE = PT_SPEECH_XVECTOR_SAMPLE
+
+
+DEPTH_ESTIMATION_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from transformers import AutoImageProcessor, {model_class}
+ >>> import torch
+ >>> from PIL import Image
+ >>> import httpx
+ >>> from io import BytesIO
+
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
+ >>> with httpx.stream("GET", url) as response:
+ ... image = Image.open(BytesIO(response.read())).convert("RGB")
+
+ >>> processor = AutoImageProcessor.from_pretrained("{checkpoint}")
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+
+ >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+ >>> model.to(device)
+
+ >>> # prepare image for the model
+ >>> inputs = processor(images=image, return_tensors="pt").to(device)
+
+ >>> with torch.no_grad():
+ ... outputs = model(**inputs)
+
+ >>> # interpolate to original size
+ >>> post_processed_output = processor.post_process_depth_estimation(
+ ... outputs, [(image.height, image.width)],
+ ... )
+ >>> predicted_depth = post_processed_output[0]["predicted_depth"]
+ ```
+"""
+
+
+VIDEO_CLASSIFICATION_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+ZERO_SHOT_OBJECT_DETECTION_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+IMAGE_TO_IMAGE_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+IMAGE_FEATURE_EXTRACTION_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+DOCUMENT_QUESTION_ANSWERING_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+NEXT_SENTENCE_PREDICTION_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+MULTIPLE_CHOICE_SAMPLE = PT_MULTIPLE_CHOICE_SAMPLE
+
+
+PRETRAINING_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+MASK_GENERATION_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+VISUAL_QUESTION_ANSWERING_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+TEXT_GENERATION_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+IMAGE_CLASSIFICATION_SAMPLE = PT_VISION_SEQ_CLASS_SAMPLE
+
+
+IMAGE_SEGMENTATION_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+FILL_MASK_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+OBJECT_DETECTION_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+QUESTION_ANSWERING_SAMPLE = PT_QUESTION_ANSWERING_SAMPLE
+
+
+TEXT_CLASSIFICATION_SAMPLE = PT_SEQUENCE_CLASSIFICATION_SAMPLE
+
+
+TABLE_QUESTION_ANSWERING_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+TOKEN_CLASSIFICATION_SAMPLE = PT_TOKEN_CLASSIFICATION_SAMPLE
+
+
+AUDIO_CLASSIFICATION_SAMPLE = PT_SPEECH_SEQ_CLASS_SAMPLE
+
+
+AUTOMATIC_SPEECH_RECOGNITION_SAMPLE = PT_SPEECH_CTC_SAMPLE
+
+
+ZERO_SHOT_IMAGE_CLASSIFICATION_SAMPLE = r"""
+ Example:
+
+ ```python
+ ```
+"""
+
+
+IMAGE_TEXT_TO_TEXT_GENERATION_SAMPLE = r"""
+ Example:
+
+ ```python
+ >>> from PIL import Image
+ >>> from transformers import AutoProcessor, {model_class}
+
+ >>> model = {model_class}.from_pretrained("{checkpoint}")
+ >>> processor = AutoProcessor.from_pretrained("{checkpoint}")
+
+ >>> messages = [
+ ... {{
+ ... "role": "user", "content": [
+ ... {{"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"}},
+ ... {{"type": "text", "text": "Where is the cat standing?"}},
+ ... ]
+ ... }},
+ ... ]
+
+ >>> inputs = processor.apply_chat_template(
+ ... messages,
+ ... tokenize=True,
+ ... return_dict=True,
+ ... return_tensors="pt",
+ ... add_generation_prompt=True
+ ... )
+ >>> # Generate
+ >>> generate_ids = model.generate(**inputs)
+ >>> processor.batch_decode(generate_ids, skip_special_tokens=True)[0]
+ ```
+"""
+
+
+PIPELINE_TASKS_TO_SAMPLE_DOCSTRINGS = OrderedDict(
+ [
+ ("text-to-audio-spectrogram", TEXT_TO_AUDIO_SPECTROGRAM_SAMPLE),
+ ("text-to-audio-waveform", TEXT_TO_AUDIO_WAVEFORM_SAMPLE),
+ ("automatic-speech-recognition", AUTOMATIC_SPEECH_RECOGNITION_SAMPLE),
+ ("audio-frame-classification", AUDIO_FRAME_CLASSIFICATION_SAMPLE),
+ ("audio-classification", AUDIO_CLASSIFICATION_SAMPLE),
+ ("audio-xvector", AUDIO_XVECTOR_SAMPLE),
+ ("image-text-to-text", IMAGE_TEXT_TO_TEXT_GENERATION_SAMPLE),
+ ("depth-estimation", DEPTH_ESTIMATION_SAMPLE),
+ ("video-classification", VIDEO_CLASSIFICATION_SAMPLE),
+ ("zero-shot-image-classification", ZERO_SHOT_IMAGE_CLASSIFICATION_SAMPLE),
+ ("image-classification", IMAGE_CLASSIFICATION_SAMPLE),
+ ("zero-shot-object-detection", ZERO_SHOT_OBJECT_DETECTION_SAMPLE),
+ ("object-detection", OBJECT_DETECTION_SAMPLE),
+ ("image-segmentation", IMAGE_SEGMENTATION_SAMPLE),
+ ("image-feature-extraction", IMAGE_FEATURE_EXTRACTION_SAMPLE),
+ ("text-generation", TEXT_GENERATION_SAMPLE),
+ ("table-question-answering", TABLE_QUESTION_ANSWERING_SAMPLE),
+ ("document-question-answering", DOCUMENT_QUESTION_ANSWERING_SAMPLE),
+ ("next-sentence-prediction", NEXT_SENTENCE_PREDICTION_SAMPLE),
+ ("multiple-choice", MULTIPLE_CHOICE_SAMPLE),
+ ("text-classification", TEXT_CLASSIFICATION_SAMPLE),
+ ("token-classification", TOKEN_CLASSIFICATION_SAMPLE),
+ ("fill-mask", FILL_MASK_SAMPLE),
+ ("mask-generation", MASK_GENERATION_SAMPLE),
+ ("pretraining", PRETRAINING_SAMPLE),
+ ]
+)
+
+# Ordered dict to look for more specialized model mappings first
+# before falling back to the more generic ones.
+MODELS_TO_PIPELINE = OrderedDict(
+ [
+ # Audio
+ ("MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES", "text-to-audio-spectrogram"),
+ ("MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES", "text-to-audio-waveform"),
+ ("MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES", "automatic-speech-recognition"),
+ ("MODEL_FOR_CTC_MAPPING_NAMES", "automatic-speech-recognition"),
+ ("MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES", "audio-frame-classification"),
+ ("MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES", "audio-classification"),
+ ("MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES", "audio-xvector"),
+ # Vision
+ ("MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES", "image-text-to-text"),
+ ("MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES", "depth-estimation"),
+ ("MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES", "video-classification"),
+ ("MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES", "zero-shot-image-classification"),
+ ("MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES", "image-classification"),
+ ("MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES", "zero-shot-object-detection"),
+ ("MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES", "object-detection"),
+ ("MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES", "image-segmentation"),
+ ("MODEL_FOR_IMAGE_MAPPING_NAMES", "image-feature-extraction"),
+ # Text/tokens
+ ("MODEL_FOR_CAUSAL_LM_MAPPING_NAMES", "text-generation"),
+ ("MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES", "table-question-answering"),
+ ("MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES", "document-question-answering"),
+ ("MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES", "next-sentence-prediction"),
+ ("MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES", "multiple-choice"),
+ ("MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES", "text-classification"),
+ ("MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES", "token-classification"),
+ ("MODEL_FOR_MASKED_LM_MAPPING_NAMES", "fill-mask"),
+ ("MODEL_FOR_MASK_GENERATION_MAPPING_NAMES", "mask-generation"),
+ ("MODEL_FOR_PRETRAINING_MAPPING_NAMES", "pretraining"),
+ ]
+)
+
+
+def filter_outputs_from_example(docstring, **kwargs):
+ """
+ Removes the lines testing an output with the doctest syntax in a code sample when it's set to `None`.
+ """
+ for key, value in kwargs.items():
+ if value is not None:
+ continue
+
+ doc_key = "{" + key + "}"
+ docstring = re.sub(rf"\n([^\n]+)\n\s+{doc_key}\n", "\n", docstring)
+
+ return docstring
+
+
+def add_code_sample_docstrings(
+ *docstr,
+ processor_class=None,
+ checkpoint=None,
+ output_type=None,
+ config_class=None,
+ mask="[MASK]",
+ qa_target_start_index=14,
+ qa_target_end_index=15,
+ model_cls=None,
+ modality=None,
+ expected_output=None,
+ expected_loss=None,
+ real_checkpoint=None,
+ revision=None,
+):
+ def docstring_decorator(fn):
+ # model_class defaults to function's class if not specified otherwise
+ model_class = fn.__qualname__.split(".")[0] if model_cls is None else model_cls
+
+ sample_docstrings = PT_SAMPLE_DOCSTRINGS
+
+ # putting all kwargs for docstrings in a dict to be used
+ # with the `.format(**doc_kwargs)`. Note that string might
+ # be formatted with non-existing keys, which is fine.
+ doc_kwargs = {
+ "model_class": model_class,
+ "processor_class": processor_class,
+ "checkpoint": checkpoint,
+ "mask": mask,
+ "qa_target_start_index": qa_target_start_index,
+ "qa_target_end_index": qa_target_end_index,
+ "expected_output": expected_output,
+ "expected_loss": expected_loss,
+ "real_checkpoint": real_checkpoint,
+ "fake_checkpoint": checkpoint,
+ "true": "{true}", # For syntax that conflicts with formatting.
+ }
+
+ if ("SequenceClassification" in model_class or "AudioClassification" in model_class) and modality == "audio":
+ code_sample = sample_docstrings["AudioClassification"]
+ elif "SequenceClassification" in model_class:
+ code_sample = sample_docstrings["SequenceClassification"]
+ elif "QuestionAnswering" in model_class:
+ code_sample = sample_docstrings["QuestionAnswering"]
+ elif "TokenClassification" in model_class:
+ code_sample = sample_docstrings["TokenClassification"]
+ elif "MultipleChoice" in model_class:
+ code_sample = sample_docstrings["MultipleChoice"]
+ elif "MaskedLM" in model_class or model_class in ["FlaubertWithLMHeadModel", "XLMWithLMHeadModel"]:
+ code_sample = sample_docstrings["MaskedLM"]
+ elif "LMHead" in model_class or "CausalLM" in model_class:
+ code_sample = sample_docstrings["LMHead"]
+ elif "CTC" in model_class:
+ code_sample = sample_docstrings["CTC"]
+ elif "AudioFrameClassification" in model_class:
+ code_sample = sample_docstrings["AudioFrameClassification"]
+ elif "XVector" in model_class and modality == "audio":
+ code_sample = sample_docstrings["AudioXVector"]
+ elif "Model" in model_class and modality == "audio":
+ code_sample = sample_docstrings["SpeechBaseModel"]
+ elif "Model" in model_class and modality == "vision":
+ code_sample = sample_docstrings["VisionBaseModel"]
+ elif "Model" in model_class or "Encoder" in model_class:
+ code_sample = sample_docstrings["BaseModel"]
+ elif "ImageClassification" in model_class:
+ code_sample = sample_docstrings["ImageClassification"]
+ else:
+ raise ValueError(f"Docstring can't be built for model {model_class}")
+
+ code_sample = filter_outputs_from_example(
+ code_sample, expected_output=expected_output, expected_loss=expected_loss
+ )
+ if real_checkpoint is not None:
+ code_sample = FAKE_MODEL_DISCLAIMER + code_sample
+ func_doc = (fn.__doc__ or "") + "".join(docstr)
+ output_doc = "" if output_type is None else _prepare_output_docstrings(output_type, config_class)
+ built_doc = code_sample.format(**doc_kwargs)
+ if revision is not None:
+ if re.match(r"^refs/pr/\\d+", revision):
+ raise ValueError(
+ f"The provided revision '{revision}' is incorrect. It should point to"
+ " a pull request reference on the hub like 'refs/pr/6'"
+ )
+ built_doc = built_doc.replace(
+ f'from_pretrained("{checkpoint}")', f'from_pretrained("{checkpoint}", revision="{revision}")'
+ )
+
+ fn.__doc__ = func_doc + output_doc + built_doc
+ return fn
+
+ return docstring_decorator
+
+
+def replace_return_docstrings(output_type=None, config_class=None):
+ def docstring_decorator(fn):
+ func_doc = fn.__doc__
+ lines = func_doc.split("\n")
+ i = 0
+ while i < len(lines) and re.search(r"^\s*Returns?:\s*$", lines[i]) is None:
+ i += 1
+ if i < len(lines):
+ indent = len(_get_indent(lines[i]))
+ lines[i] = _prepare_output_docstrings(output_type, config_class, min_indent=indent)
+ func_doc = "\n".join(lines)
+ else:
+ raise ValueError(
+ f"The function {fn} should have an empty 'Return:' or 'Returns:' in its docstring as placeholder, "
+ f"current docstring is:\n{func_doc}"
+ )
+ fn.__doc__ = func_doc
+ return fn
+
+ return docstring_decorator
+
+
+def copy_func(f):
+ """Returns a copy of a function f."""
+ # Based on http://stackoverflow.com/a/6528148/190597 (Glenn Maynard)
+ g = types.FunctionType(f.__code__, f.__globals__, name=f.__name__, argdefs=f.__defaults__, closure=f.__closure__)
+ g = cast(types.FunctionType, functools.update_wrapper(g, f))
+ g.__kwdefaults__ = f.__kwdefaults__
+ return g
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_detectron2_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_detectron2_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..22ec32fe30a1b9abbc5d810510d97d5c81082561
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_detectron2_objects.py
@@ -0,0 +1,11 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import requires_backends
+
+
+class LayoutLMv2Model:
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["detectron2"])
+
+ @classmethod
+ def from_pretrained(cls, *args, **kwargs):
+ requires_backends(cls, ["detectron2"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6d75a6ec22e90427c972a753a24afd1a780758f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py
@@ -0,0 +1,23 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+class Pop2PianoFeatureExtractor(metaclass=DummyObject):
+ _backends = ["essentia", "librosa", "pretty_midi", "scipy", "torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["essentia", "librosa", "pretty_midi", "scipy", "torch"])
+
+
+class Pop2PianoTokenizer(metaclass=DummyObject):
+ _backends = ["essentia", "librosa", "pretty_midi", "scipy", "torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["essentia", "librosa", "pretty_midi", "scipy", "torch"])
+
+
+class Pop2PianoProcessor(metaclass=DummyObject):
+ _backends = ["essentia", "librosa", "pretty_midi", "scipy", "torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["essentia", "librosa", "pretty_midi", "scipy", "torch"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_mistral_common_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_mistral_common_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..36cdb01cea4534203b879b8c7f30778cc34fe5ad
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_mistral_common_objects.py
@@ -0,0 +1,9 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+class MistralCommonBackend(metaclass=DummyObject):
+ _backends = ["mistral-common"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["mistral-common"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_music_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_music_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..89052be47c1d32bac5cbd6fceab183fc1d75d3bf
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_music_objects.py
@@ -0,0 +1,16 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+class Pop2PianoFeatureExtractor(metaclass=DummyObject):
+ _backends = ["music"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["music"])
+
+
+class Pop2PianoTokenizer(metaclass=DummyObject):
+ _backends = ["music"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["music"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_pt_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_pt_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..191783b25df3cc8e9d9bed4a8101bf025c6df2a3
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_pt_objects.py
@@ -0,0 +1,488 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+class Cache(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class DynamicCache(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class EncoderDecoderCache(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class QuantizedCache(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class StaticCache(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class GlueDataset(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class GlueDataTrainingArguments(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class SquadDataset(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class SquadDataTrainingArguments(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class AlternatingCodebooksLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class BayesianDetectorConfig(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class BayesianDetectorModel(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class ClassifierFreeGuidanceLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class EncoderNoRepeatNGramLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class EncoderRepetitionPenaltyLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class EosTokenCriteria(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class EpsilonLogitsWarper(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class EtaLogitsWarper(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class ExponentialDecayLengthPenalty(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class ForcedBOSTokenLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class ForcedEOSTokenLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class GenerationMixin(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class InfNanRemoveLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class LogitNormalization(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class LogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class LogitsProcessorList(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class MaxLengthCriteria(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class MaxTimeCriteria(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class MinLengthLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class MinNewTokensLengthLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class MinPLogitsWarper(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class NoBadWordsLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class NoRepeatNGramLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class PrefixConstrainedLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class RepetitionPenaltyLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class SequenceBiasLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class StoppingCriteria(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class StoppingCriteriaList(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class StopStringCriteria(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class SuppressTokensAtBeginLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class SuppressTokensLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class SynthIDTextWatermarkDetector(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class SynthIDTextWatermarkingConfig(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class SynthIDTextWatermarkLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class TemperatureLogitsWarper(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class TopKLogitsWarper(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class TopPLogitsWarper(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class TypicalLogitsWarper(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class UnbatchedClassifierFreeGuidanceLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class WatermarkDetector(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class WatermarkLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class WhisperTimeStampLogitsProcessor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class TorchExportableModuleWithStaticCache(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+def convert_and_export_with_cache(*args, **kwargs):
+ requires_backends(convert_and_export_with_cache, ["torch"])
+
+
+class AttentionMaskInterface(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+def model_addition_debugger_context(*args, **kwargs):
+ requires_backends(model_addition_debugger_context, ["torch"])
+
+
+class GradientCheckpointingLayer(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+ROPE_INIT_FUNCTIONS = None
+
+
+def dynamic_rope_update(*args, **kwargs):
+ requires_backends(dynamic_rope_update, ["torch"])
+
+
+class AttentionInterface(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class PreTrainedModel(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+class Adafactor(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+def get_constant_schedule(*args, **kwargs):
+ requires_backends(get_constant_schedule, ["torch"])
+
+
+def get_constant_schedule_with_warmup(*args, **kwargs):
+ requires_backends(get_constant_schedule_with_warmup, ["torch"])
+
+
+def get_cosine_schedule_with_warmup(*args, **kwargs):
+ requires_backends(get_cosine_schedule_with_warmup, ["torch"])
+
+
+def get_cosine_with_hard_restarts_schedule_with_warmup(*args, **kwargs):
+ requires_backends(get_cosine_with_hard_restarts_schedule_with_warmup, ["torch"])
+
+
+def get_inverse_sqrt_schedule(*args, **kwargs):
+ requires_backends(get_inverse_sqrt_schedule, ["torch"])
+
+
+def get_linear_schedule_with_warmup(*args, **kwargs):
+ requires_backends(get_linear_schedule_with_warmup, ["torch"])
+
+
+def get_polynomial_decay_schedule_with_warmup(*args, **kwargs):
+ requires_backends(get_polynomial_decay_schedule_with_warmup, ["torch"])
+
+
+def get_scheduler(*args, **kwargs):
+ requires_backends(get_scheduler, ["torch"])
+
+
+def get_wsd_schedule(*args, **kwargs):
+ requires_backends(get_wsd_schedule, ["torch"])
+
+
+class Conv1D(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+def apply_chunking_to_forward(*args, **kwargs):
+ requires_backends(apply_chunking_to_forward, ["torch"])
+
+
+class Trainer(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
+
+
+def torch_distributed_zero_first(*args, **kwargs):
+ requires_backends(torch_distributed_zero_first, ["torch"])
+
+
+class Seq2SeqTrainer(metaclass=DummyObject):
+ _backends = ["torch"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torch"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..38775330a81d91030f000e58c0e6035bba1c0f31
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py
@@ -0,0 +1,9 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+SLOW_TO_FAST_CONVERTERS = None
+
+
+def convert_slow_tokenizer(*args, **kwargs):
+ requires_backends(convert_slow_tokenizer, ["sentencepiece", "tokenizers"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_speech_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_speech_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bf08ebea42b4595ae1f8bbc2afcddf0630dcf4b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_speech_objects.py
@@ -0,0 +1,16 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+class ASTFeatureExtractor(metaclass=DummyObject):
+ _backends = ["speech"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["speech"])
+
+
+class Speech2TextFeatureExtractor(metaclass=DummyObject):
+ _backends = ["speech"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["speech"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_timm_and_torchvision_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_timm_and_torchvision_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b67b5dac58db13278706e0838aebbe495a9d2fc
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_timm_and_torchvision_objects.py
@@ -0,0 +1,9 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+class TimmWrapperImageProcessor(metaclass=DummyObject):
+ _backends = ["timm", "torchvision"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["timm", "torchvision"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_tokenizers_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_tokenizers_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e592f28570fedf4870d185e92d504fa82f6b545
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_tokenizers_objects.py
@@ -0,0 +1,9 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+class PreTrainedTokenizerFast(metaclass=DummyObject):
+ _backends = ["tokenizers"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["tokenizers"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchaudio_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchaudio_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7aea4a70207a2ce26385868b4437ea478c9efc5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchaudio_objects.py
@@ -0,0 +1,30 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+class GraniteSpeechFeatureExtractor(metaclass=DummyObject):
+ _backends = ["torchaudio"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torchaudio"])
+
+
+class GraniteSpeechProcessor(metaclass=DummyObject):
+ _backends = ["torchaudio"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torchaudio"])
+
+
+class MusicgenMelodyFeatureExtractor(metaclass=DummyObject):
+ _backends = ["torchaudio"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torchaudio"])
+
+
+class MusicgenMelodyProcessor(metaclass=DummyObject):
+ _backends = ["torchaudio"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torchaudio"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchvision_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchvision_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d19003699b01ffc4027c1b2039894760729fb5b
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_torchvision_objects.py
@@ -0,0 +1,16 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+class TorchvisionBackend(metaclass=DummyObject):
+ _backends = ["torchvision"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torchvision"])
+
+
+class BaseVideoProcessor(metaclass=DummyObject):
+ _backends = ["torchvision"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["torchvision"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_vision_objects.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_vision_objects.py
new file mode 100644
index 0000000000000000000000000000000000000000..89aa3ad35872491b96bc102250d82425a4fc7766
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/dummy_vision_objects.py
@@ -0,0 +1,23 @@
+# This file is autogenerated by the command `make fix-copies`, do not edit.
+from ..utils import DummyObject, requires_backends
+
+
+class ImageProcessingMixin(metaclass=DummyObject):
+ _backends = ["vision"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["vision"])
+
+
+class BaseImageProcessor(metaclass=DummyObject):
+ _backends = ["vision"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["vision"])
+
+
+class ImageFeatureExtractionMixin(metaclass=DummyObject):
+ _backends = ["vision"]
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, ["vision"])
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/generic.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/generic.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6b5960f08493080cd568951edbbcac3635959e8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/generic.py
@@ -0,0 +1,1087 @@
+# 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.
+"""
+Generic utilities
+"""
+
+from __future__ import annotations
+
+import inspect
+import json
+import os
+import random
+import re
+import time
+import warnings
+from collections import OrderedDict, UserDict
+from collections.abc import Callable, Iterable, MutableMapping
+from contextlib import AbstractContextManager, ExitStack, nullcontext
+from dataclasses import fields, is_dataclass
+from enum import Enum
+from functools import partial, wraps
+from typing import TYPE_CHECKING, Any, TypedDict
+
+import numpy as np
+
+from ..utils import logging
+from .import_utils import is_mlx_available, is_torch_available, is_torch_fx_proxy
+
+
+if TYPE_CHECKING:
+ import torch
+ from torch import nn
+
+
+logger = logging.get_logger(__name__)
+
+
+_is_torch_available = False
+if is_torch_available():
+ _is_torch_available = True
+
+_registered_model_output_types: set[type[Any]] = set()
+
+
+def _register_model_output_pytree_node(output_type: type[ModelOutput]) -> None:
+ if not _is_torch_available:
+ return
+ import torch
+
+ # AMD CI runs PyTorch 2.8.0+rocm which does not support tracing `set.__contains__`
+ # through TorchDynamo. Skip registration during compilation since the pytree node
+ # is already registered from the preceding eager run.
+ if torch.compiler.is_compiling():
+ return
+ if output_type in _registered_model_output_types:
+ return
+
+ import torch.utils._pytree as torch_pytree
+
+ torch_pytree.register_pytree_node(
+ output_type,
+ _model_output_flatten,
+ partial(_model_output_unflatten, output_type=output_type),
+ serialized_type_name=f"{output_type.__module__}.{output_type.__name__}",
+ )
+ _registered_model_output_types.add(output_type)
+
+
+# required for @can_return_tuple decorator to work with torchdynamo
+_is_mlx_available = False
+if is_mlx_available():
+ _is_mlx_available = True
+
+
+# vendored from distutils.util
+def strtobool(val) -> int:
+ """Convert a string representation of truth to true (1) or false (0).
+
+ True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'.
+ Raises ValueError if 'val' is anything else.
+ """
+ val = val.lower()
+ if val in {"y", "yes", "t", "true", "on", "1"}:
+ return 1
+ if val in {"n", "no", "f", "false", "off", "0"}:
+ return 0
+ raise ValueError(f"invalid truth value {val!r}")
+
+
+def infer_framework_from_repr(x) -> str | None:
+ """
+ Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the
+ frameworks in a smart order, without the need to import the frameworks).
+ """
+ representation = str(type(x))
+ if representation.startswith(" bool:
+ """
+ Tests if `x` is a `torch.Tensor`, `np.ndarray` or `mlx.array` in the order defined by `infer_framework_from_repr`
+ """
+ # This gives us a smart order to test the frameworks with the corresponding tests.
+ framework_to_test_func = _get_frameworks_and_test_func(x)
+ for test_func in framework_to_test_func.values():
+ if test_func(x):
+ return True
+
+ # Tracers
+ if is_torch_fx_proxy(x):
+ return True
+
+ return False
+
+
+def is_numpy_array(x) -> bool:
+ """
+ Tests if `x` is a numpy array or not.
+ """
+ return isinstance(x, np.ndarray)
+
+
+def is_torch_tensor(x) -> bool:
+ """
+ Tests if `x` is a torch tensor or not. Safe to call even if torch is not installed.
+ """
+ if not _is_torch_available:
+ return False
+
+ import torch
+
+ return isinstance(x, torch.Tensor)
+
+
+def is_torch_device(x) -> bool:
+ """
+ Tests if `x` is a torch device or not. Safe to call even if torch is not installed.
+ """
+ if not _is_torch_available:
+ return False
+
+ import torch
+
+ return isinstance(x, torch.device)
+
+
+def is_torch_dtype(x) -> bool:
+ """
+ Tests if `x` is a torch dtype or not. Safe to call even if torch is not installed.
+ """
+ if not _is_torch_available:
+ return False
+
+ import torch
+
+ if isinstance(x, str):
+ if hasattr(torch, x):
+ x = getattr(torch, x)
+ else:
+ return False
+ return isinstance(x, torch.dtype)
+
+
+def _is_tensor_or_array_like(value):
+ """
+ Check if a value is array-like (includes ragged arrays)
+ """
+ if is_numpy_array(value):
+ return True
+ if is_torch_tensor(value):
+ return True
+ if isinstance(value, (int, float, bool, np.number)):
+ return True
+
+ if isinstance(value, (list, tuple)):
+ if len(value) == 0:
+ # consider empty list or nested list as array-like
+ return True
+ return _is_tensor_or_array_like(value[0])
+
+ return False
+
+
+def maybe_autocast(
+ device_type: str,
+ dtype: torch.dtype | None = None,
+ enabled: bool = True,
+ cache_enabled: bool | None = None,
+):
+ """
+ Context manager that only autocasts if:
+
+ - `autocast` is already enabled in this context
+ - Or this call to `maybe_autocast` has `enabled=True`
+
+ This prevents `autocast` being added to the graph when it is effectively a no-op.
+ Which makes graph splitting in `torch.compile` more flexible as it removes the
+ requirement that partition IDs be monotonically increasing.
+ """
+ if not _is_torch_available:
+ raise ImportError("`maybe_autocast` requires PyTorch to be installed.")
+
+ import torch
+
+ if device_type == "meta":
+ return nullcontext()
+ if torch.is_autocast_enabled(device_type) or enabled:
+ return torch.autocast(device_type, dtype=dtype, enabled=enabled, cache_enabled=cache_enabled)
+ else:
+ return nullcontext()
+
+
+def _is_mlx(x):
+ import mlx.core as mx
+
+ return isinstance(x, mx.array)
+
+
+def is_mlx_array(x) -> bool:
+ """
+ Tests if `x` is a mlx array or not. Safe to call even when mlx is not installed.
+ """
+ return False if not _is_mlx_available else _is_mlx(x)
+
+
+def is_flash_attention_requested(
+ config=None, requested_attention_implementation: str | None = None, version: int | None = None
+) -> bool:
+ """
+ Checks whether some flavor of flash attention is requested or not. Optionally, checks for a specific version of
+ flash attention.
+
+ This is checked against one of the two arguments, i.e. either the `config` or the directly passed value
+ `requested_attention_implementation`. Otherwise, an error will be raised (ambiguity).
+
+ The different versions of flash attention are usually
+ - Implementations based on the original flash attention repo: https://github.com/Dao-AILab/flash-attention
+ - Kernels implementations such as: https://huggingface.co/kernels-community/vllm-flash-attn3
+ """
+ if config is not None and requested_attention_implementation is not None:
+ raise ValueError(
+ "Requested attention implementation is ambiguous: "
+ "Please pass either the config or the name of the attention implementation, not both."
+ )
+
+ if config is not None:
+ checked_attention_implementation = config._attn_implementation
+ else:
+ checked_attention_implementation = requested_attention_implementation
+
+ # theoretically can happen, equivalent to default implementation (sdpa/eager)
+ if checked_attention_implementation is None:
+ return False
+
+ # If a specific version is requested, look for a pattern of type "flash...{version}"
+ if version is not None:
+ return re.match(r".*flash.*" + str(version), checked_attention_implementation) is not None
+ # Otherwise, just check "flash" is in the attention implementation
+ return "flash" in checked_attention_implementation
+
+
+def split_attention_implementation(implementation: str | None) -> tuple[bool, str | None]:
+ """
+ Split the optional `paged|` prefix from an attention implementation string.
+
+ Note that `None` means using the default attention implementation, which is either torch's native `sdpa` or `eager` (if `sdpa` is not implemented for that model).
+ """
+ if implementation is None:
+ return False, None
+
+ is_paged = implementation.startswith("paged|")
+ return is_paged, implementation.removeprefix("paged|")
+
+
+def to_py_obj(obj):
+ """
+ Convert a PyTorch tensor, Numpy array or python list to a python list.
+ """
+ if isinstance(obj, (int, float)):
+ return obj
+ elif isinstance(obj, (dict, UserDict)):
+ return {k: to_py_obj(v) for k, v in obj.items()}
+ elif isinstance(obj, (list, tuple)):
+ # Only convert directly if all elements are numeric scalars
+ if all(isinstance(x, (int, float, np.number)) for x in obj):
+ return list(obj)
+
+ # Otherwise recurse element-wise
+ return [to_py_obj(o) for o in obj]
+
+ framework_to_py_obj = {
+ "pt": lambda obj: obj.tolist(),
+ "np": lambda obj: obj.tolist(),
+ }
+
+ # This gives us a smart order to test the frameworks with the corresponding tests.
+ framework_to_test_func = _get_frameworks_and_test_func(obj)
+ for framework, test_func in framework_to_test_func.items():
+ if test_func(obj):
+ return framework_to_py_obj[framework](obj)
+
+ # tolist also works on 0d np arrays
+ if isinstance(obj, np.number):
+ return obj.tolist()
+ else:
+ return obj
+
+
+def to_numpy(obj):
+ """
+ Convert a PyTorch tensor, Numpy array or python list to a Numpy array.
+ """
+
+ framework_to_numpy = {
+ "pt": lambda obj: obj.detach().cpu().numpy(),
+ "np": lambda obj: obj,
+ }
+
+ if isinstance(obj, (dict, UserDict)):
+ return {k: to_numpy(v) for k, v in obj.items()}
+ elif isinstance(obj, (list, tuple)):
+ return np.array(obj)
+
+ # This gives us a smart order to test the frameworks with the corresponding tests.
+ framework_to_test_func = _get_frameworks_and_test_func(obj)
+ for framework, test_func in framework_to_test_func.items():
+ if test_func(obj):
+ return framework_to_numpy[framework](obj)
+
+ return obj
+
+
+def safe_load_json_file(json_file: str):
+ "A helper to load safe config files and raise a proper error message if it wasn't serialized correctly"
+ try:
+ with open(json_file, encoding="utf-8") as reader:
+ text = reader.read()
+ config_dict = json.loads(text)
+ except json.JSONDecodeError:
+ raise OSError(f"It looks like the config file at '{json_file}' is not a valid JSON file.")
+ return config_dict
+
+
+class ModelOutput(OrderedDict):
+ """
+ Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a
+ tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular
+ python dictionary.
+
+
+
+ You can't unpack a `ModelOutput` directly. Use the [`~utils.ModelOutput.to_tuple`] method to convert it to a tuple
+ before.
+
+
+ """
+
+ def __init_subclass__(cls) -> None:
+ """Register subclasses as pytree nodes.
+
+ This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with
+ `static_graph=True` with modules that output `ModelOutput` subclasses.
+ """
+ _register_model_output_pytree_node(cls)
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ _register_model_output_pytree_node(type(self))
+
+ # Subclasses of ModelOutput must use the @dataclass decorator
+ # This check is done in __init__ because the @dataclass decorator operates after __init_subclass__
+ # issubclass() would return True for issubclass(ModelOutput, ModelOutput) when False is needed
+ # Just need to check that the current class is not ModelOutput
+ is_modeloutput_subclass = self.__class__ != ModelOutput
+
+ if is_modeloutput_subclass and not is_dataclass(self):
+ raise TypeError(
+ f"{self.__module__}.{self.__class__.__name__} is not a dataclass."
+ " This is a subclass of ModelOutput and so must use the @dataclass decorator."
+ )
+
+ def __post_init__(self):
+ """Check the ModelOutput dataclass.
+
+ Only occurs if @dataclass decorator has been used.
+ """
+ _register_model_output_pytree_node(type(self))
+ class_fields = fields(self)
+
+ # Safety and consistency checks
+ if not len(class_fields):
+ raise ValueError(f"{self.__class__.__name__} has no fields.")
+ if not all(field.default is None for field in class_fields[1:]):
+ raise ValueError(f"{self.__class__.__name__} should not have more than one required field.")
+
+ first_field = getattr(self, class_fields[0].name)
+ other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])
+
+ if other_fields_are_none and not is_tensor(first_field):
+ if isinstance(first_field, dict):
+ iterator = first_field.items()
+ first_field_iterator = True
+ else:
+ try:
+ iterator = iter(first_field)
+ first_field_iterator = True
+ except TypeError:
+ first_field_iterator = False
+
+ # if we provided an iterator as first field and the iterator is a (key, value) iterator
+ # set the associated fields
+ if first_field_iterator:
+ # reset first field to None and remove it from the internal dictionary
+ setattr(self, class_fields[0].name, None)
+ super().__delitem__(class_fields[0].name)
+ for idx, element in enumerate(iterator):
+ if not isinstance(element, (list, tuple)) or len(element) != 2 or not isinstance(element[0], str):
+ if idx == 0:
+ # If we do not have an iterator of key/values, set it as attribute
+ self[class_fields[0].name] = first_field
+ else:
+ # If we have a mixed iterator, raise an error
+ raise ValueError(
+ f"Cannot set key/value for {element}. It needs to be a tuple (key, value)."
+ )
+ break
+ setattr(self, element[0], element[1])
+ if element[1] is not None:
+ self[element[0]] = element[1]
+ elif first_field is not None:
+ self[class_fields[0].name] = first_field
+ else:
+ for field in class_fields:
+ v = getattr(self, field.name)
+ if v is not None:
+ self[field.name] = v
+
+ def __delitem__(self, *args, **kwargs):
+ raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
+
+ def setdefault(self, *args, **kwargs):
+ raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
+
+ def pop(self, *args, **kwargs):
+ raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
+
+ def update(self, *args, **kwargs):
+ raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
+
+ def __getitem__(self, k):
+ if isinstance(k, str):
+ inner_dict = dict(self.items())
+ return inner_dict[k]
+ else:
+ return self.to_tuple()[k]
+
+ def __setattr__(self, name, value):
+ field_names = {field.name for field in fields(self)}
+ if name in field_names and value is not None:
+ # Don't call self.__setitem__ to avoid recursion errors
+ super().__setitem__(name, value)
+ super().__setattr__(name, value)
+
+ def __setitem__(self, key, value):
+ # Will raise a KeyException if needed
+ super().__setitem__(key, value)
+ # Don't call self.__setattr__ to avoid recursion errors
+ super().__setattr__(key, value)
+
+ def __reduce__(self):
+ if not is_dataclass(self):
+ return super().__reduce__()
+ callable, _args, *remaining = super().__reduce__()
+ args = tuple(getattr(self, field.name) for field in fields(self))
+ return callable, args, *remaining
+
+ def to_tuple(self) -> tuple:
+ """
+ Convert self to a tuple containing all the attributes/keys that are not `None`.
+ """
+ return tuple(self[k] for k in self.keys())
+
+
+def _model_output_flatten(output: ModelOutput) -> tuple[list[Any], list[str]]:
+ return list(output.values()), list(output.keys())
+
+
+def _model_output_unflatten(
+ values: Iterable[Any],
+ context: list[str],
+ output_type: type[ModelOutput] | None = None,
+) -> ModelOutput:
+ return output_type(**dict(zip(context, values)))
+
+
+class ExplicitEnum(str, Enum):
+ """
+ Enum with more explicit error message for missing values.
+ """
+
+ @classmethod
+ def _missing_(cls, value):
+ raise ValueError(
+ f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}"
+ )
+
+
+class PaddingStrategy(ExplicitEnum):
+ """
+ Possible values for the `padding` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an
+ IDE.
+ """
+
+ LONGEST = "longest"
+ MAX_LENGTH = "max_length"
+ DO_NOT_PAD = "do_not_pad"
+
+
+class TensorType(ExplicitEnum):
+ """
+ Possible values for the `return_tensors` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for
+ tab-completion in an IDE.
+ """
+
+ PYTORCH = "pt"
+ NUMPY = "np"
+ MLX = "mlx"
+
+
+class ContextManagers:
+ """
+ Wrapper for `contextlib.ExitStack` which enters a collection of context managers. Adaptation of `ContextManagers`
+ in the `fastcore` library.
+ """
+
+ def __init__(self, context_managers: list[AbstractContextManager]):
+ self.context_managers = context_managers
+ self.stack = ExitStack()
+
+ def __enter__(self):
+ for context_manager in self.context_managers:
+ self.stack.enter_context(context_manager)
+
+ def __exit__(self, *args, **kwargs):
+ self.stack.__exit__(*args, **kwargs)
+
+
+def can_return_loss(model_class):
+ """
+ Check if a given model can return loss.
+
+ Args:
+ model_class (`type`): The class of the model.
+ """
+ signature = inspect.signature(model_class.forward)
+
+ for p in signature.parameters:
+ if p == "return_loss" and signature.parameters[p].default is True:
+ return True
+
+ return False
+
+
+def find_labels(model_class):
+ """
+ Find the labels used by a given model.
+
+ Args:
+ model_class (`type`): The class of the model.
+ """
+ model_name = model_class.__name__
+ signature = inspect.signature(model_class.forward)
+
+ if "QuestionAnswering" in model_name:
+ return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
+ else:
+ return [p for p in signature.parameters if "label" in p]
+
+
+def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."):
+ """Flatten a nested dict into a single level dict."""
+
+ def _flatten_dict(d, parent_key="", delimiter="."):
+ for k, v in d.items():
+ key = str(parent_key) + delimiter + str(k) if parent_key else k
+ if v and isinstance(v, MutableMapping):
+ yield from flatten_dict(v, key, delimiter=delimiter).items()
+ else:
+ yield key, v
+
+ return dict(_flatten_dict(d, parent_key, delimiter))
+
+
+def transpose(array, axes=None):
+ """
+ Framework-agnostic version of transpose operation.
+ """
+ if is_numpy_array(array):
+ return np.transpose(array, axes=axes)
+ elif is_torch_tensor(array):
+ return array.T if axes is None else array.permute(*axes)
+ else:
+ raise ValueError(f"Type not supported for transpose: {type(array)}.")
+
+
+def reshape(array, newshape):
+ """
+ Framework-agnostic version of reshape operation.
+ """
+ if is_numpy_array(array):
+ return np.reshape(array, newshape)
+ elif is_torch_tensor(array):
+ return array.reshape(*newshape)
+ else:
+ raise ValueError(f"Type not supported for reshape: {type(array)}.")
+
+
+def squeeze(array, axis=None):
+ """
+ Framework-agnostic version of squeeze operation.
+ """
+ if is_numpy_array(array):
+ return np.squeeze(array, axis=axis)
+ elif is_torch_tensor(array):
+ return array.squeeze() if axis is None else array.squeeze(dim=axis)
+ else:
+ raise ValueError(f"Type not supported for squeeze: {type(array)}.")
+
+
+def expand_dims(array, axis):
+ """
+ Framework-agnostic version of expand_dims operation.
+ """
+ if is_numpy_array(array):
+ return np.expand_dims(array, axis)
+ elif is_torch_tensor(array):
+ return array.unsqueeze(dim=axis)
+ else:
+ raise ValueError(f"Type not supported for expand_dims: {type(array)}.")
+
+
+def tensor_size(array):
+ """
+ Framework-agnostic version of size operation.
+ """
+ if is_numpy_array(array):
+ return np.size(array)
+ elif is_torch_tensor(array):
+ return array.numel()
+ else:
+ raise ValueError(f"Type not supported for tensor_size: {type(array)}.")
+
+
+def torch_int(x):
+ """
+ Casts an input to a torch int64 tensor if we are in a tracing context, otherwise to a Python int.
+ """
+ if not _is_torch_available:
+ return int(x)
+
+ import torch
+
+ return x.to(torch.int64) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x)
+
+
+def torch_float(x):
+ """
+ Casts an input to a torch float32 tensor if we are in a tracing context, otherwise to a Python float.
+ """
+ if not _is_torch_available:
+ return int(x)
+
+ import torch
+
+ return x.to(torch.float32) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x)
+
+
+def filter_out_non_signature_kwargs(extra: list | None = None):
+ """
+ Decorator to filter out named arguments that are not in the function signature.
+
+ This decorator ensures that only the keyword arguments that match the function's signature, or are specified in the
+ `extra` list, are passed to the function. Any additional keyword arguments are filtered out and a warning is issued.
+
+ Parameters:
+ extra (`Optional[list]`, *optional*):
+ A list of extra keyword argument names that are allowed even if they are not in the function's signature.
+
+ Returns:
+ Callable:
+ A decorator that wraps the function and filters out invalid keyword arguments.
+
+ Example usage:
+
+ ```python
+ @filter_out_non_signature_kwargs(extra=["allowed_extra_arg"])
+ def my_function(arg1, arg2, **kwargs):
+ print(arg1, arg2, kwargs)
+
+ my_function(arg1=1, arg2=2, allowed_extra_arg=3, invalid_arg=4)
+ # This will print: 1 2 {"allowed_extra_arg": 3}
+ # And issue a warning: "The following named arguments are not valid for `my_function` and were ignored: 'invalid_arg'"
+ ```
+ """
+ extra = extra or []
+ extra_params_to_pass = set(extra)
+
+ def decorator(func):
+ sig = inspect.signature(func)
+ function_named_args = set(sig.parameters.keys())
+ valid_kwargs_to_pass = function_named_args.union(extra_params_to_pass)
+
+ # Required for better warning message
+ is_instance_method = "self" in function_named_args
+ is_class_method = "cls" in function_named_args
+
+ # Mark function as decorated
+ func._filter_out_non_signature_kwargs = True
+
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ valid_kwargs = {}
+ invalid_kwargs = {}
+
+ for k, v in kwargs.items():
+ if k in valid_kwargs_to_pass:
+ valid_kwargs[k] = v
+ else:
+ invalid_kwargs[k] = v
+
+ if invalid_kwargs:
+ invalid_kwargs_names = [f"'{k}'" for k in invalid_kwargs]
+ invalid_kwargs_names = ", ".join(invalid_kwargs_names)
+
+ # Get the class name for better warning message
+ if is_instance_method:
+ cls_prefix = args[0].__class__.__name__ + "."
+ elif is_class_method:
+ cls_prefix = args[0].__name__ + "."
+ else:
+ cls_prefix = ""
+
+ warnings.warn(
+ f"The following named arguments are not valid for `{cls_prefix}{func.__name__}`"
+ f" and were ignored: {invalid_kwargs_names}",
+ UserWarning,
+ stacklevel=2,
+ )
+
+ return func(*args, **valid_kwargs)
+
+ return wrapper
+
+ return decorator
+
+
+class TransformersKwargs(TypedDict, total=False):
+ """
+ Keyword arguments to be passed to the forward pass of a `PreTrainedModel`.
+
+ Attributes:
+ num_items_in_batch (`Optional[torch.Tensor]`, *optional*):
+ Number of items in the batch. It is recommended to pass it when you are doing gradient accumulation.
+ output_hidden_states (`Optional[bool]`, *optional*):
+ Most of the models support outputting all hidden states computed during the forward pass.
+ output_attentions (`Optional[bool]`, *optional*):
+ Turn this on to return the intermediary attention scores.
+ output_router_logits (`Optional[bool]`, *optional*):
+ For MoE models, this allows returning the router logits to compute the loss.
+ cu_seq_lens_q (`torch.LongTensor`, *optional*)
+ Gets cumulative sequence length for query state.
+ cu_seq_lens_k (`torch.LongTensor`, *optional*)
+ Gets cumulative sequence length for key state.
+ max_length_q (`int`, *optional*):
+ Maximum sequence length for query state.
+ max_length_k (`int`, *optional*):
+ Maximum sequence length for key state.
+ position_ids (`torch.LongTensor`, *optional*)
+ Indices of positions of each input sequence tokens.
+ is_causal (`bool`, *optional*)
+ Can be set to False to enable bi-directional attention, i.e. use decoder Attention modules as encoders.
+ """
+
+ num_items_in_batch: torch.Tensor | None
+ output_hidden_states: bool | None
+ output_attentions: bool | None
+ output_router_logits: bool | None
+ cu_seq_lens_q: torch.LongTensor | None
+ cu_seq_lens_k: torch.LongTensor | None
+ max_length_q: int | None
+ max_length_k: int | None
+ position_ids: torch.LongTensor | None
+ is_causal: bool | None
+
+
+def is_timm_config_dict(config_dict: dict[str, Any]) -> bool:
+ """Checks whether a config dict is a timm config dict."""
+ return "pretrained_cfg" in config_dict
+
+
+def is_timm_local_checkpoint(pretrained_model_path: str) -> bool:
+ """
+ Checks whether a checkpoint is a timm model checkpoint.
+ """
+ if pretrained_model_path is None:
+ return False
+
+ # in case it's Path, not str
+ pretrained_model_path = str(pretrained_model_path)
+
+ is_file = os.path.isfile(pretrained_model_path)
+ is_dir = os.path.isdir(pretrained_model_path)
+
+ # pretrained_model_path is a file
+ if is_file and pretrained_model_path.endswith(".json"):
+ with open(pretrained_model_path) as f:
+ config_dict = json.load(f)
+ return is_timm_config_dict(config_dict)
+
+ # pretrained_model_path is a directory with a config.json
+ if is_dir and os.path.exists(os.path.join(pretrained_model_path, "config.json")):
+ with open(os.path.join(pretrained_model_path, "config.json")) as f:
+ config_dict = json.load(f)
+ return is_timm_config_dict(config_dict)
+
+ return False
+
+
+def set_attribute_for_modules(module: nn.Module, key: str, value: Any):
+ """
+ Set a value to a module and all submodules.
+ """
+ setattr(module, key, value)
+ for submodule in module.children():
+ set_attribute_for_modules(submodule, key, value)
+
+
+def del_attribute_from_modules(module: nn.Module, key: str):
+ """
+ Delete a value from a module and all submodules.
+ """
+ # because we might remove it previously in case it's a shared module, e.g. activation function
+ if hasattr(module, key):
+ delattr(module, key)
+
+ for submodule in module.children():
+ del_attribute_from_modules(submodule, key)
+
+
+def can_return_tuple(func):
+ """
+ Decorator to wrap model method, to call output.to_tuple() if return_dict=False passed as a kwarg or
+ return_dict=False is set in the config.
+
+ Note:
+ output.to_tuple() convert output to tuple skipping all `None` values.
+ """
+
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ return_dict = self.config.return_dict if hasattr(self, "config") else True
+ return_dict_passed = kwargs.pop("return_dict", return_dict)
+ if return_dict_passed is not None:
+ return_dict = return_dict_passed
+ output = func(self, *args, **kwargs)
+ if not return_dict and not isinstance(output, tuple):
+ output = output.to_tuple()
+ return output
+
+ return wrapper
+
+
+def merge_with_config_defaults(func):
+ """
+ Decorator using config field (if they exist) as default value for some args and kwargs. Precedence is always
+ given to the args/kwargs that are explicitly passed.
+ """
+
+ @wraps(func)
+ def wrapper(self, *args, **kwargs):
+ args_with_config_defaults = [
+ "use_cache",
+ "vision_feature_layer",
+ "vision_feature_select_strategy",
+ "vision_aspect_ratio",
+ ]
+ for arg_name in args_with_config_defaults:
+ arg_index = None
+ if arg_name in func.__code__.co_varnames:
+ arg_index = func.__code__.co_varnames.index(arg_name) - 1 # -1 for self
+
+ if arg_index is not None and len(args) > arg_index and args[arg_index] is not None:
+ arg_value = args[arg_index]
+ elif kwargs.get(arg_name) is not None:
+ arg_value = kwargs[arg_name]
+ else:
+ arg_value = getattr(self.config, arg_name, None)
+
+ if arg_value is not None:
+ # Arg-specific handling
+ if arg_name == "use_cache":
+ if getattr(self, "gradient_checkpointing", False) and self.training and arg_value:
+ logger.warning_once(
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
+ )
+ arg_value = False
+ elif arg_name == "vision_feature_select_strategy":
+ valid_strategies = ["default", "full"]
+ if arg_value not in valid_strategies:
+ raise ValueError(
+ f"`Unexpected select feature strategy: {arg_value}. Please select from {valid_strategies}."
+ )
+
+ if arg_index is not None and len(args) > arg_index:
+ args = list(args)
+ args[arg_index] = arg_value
+ args = tuple(args)
+ else:
+ kwargs[arg_name] = arg_value
+
+ # Maybe temporarily overwrite config value to create the correct mask - kwarg takes precedence
+ is_causal = kwargs.get("is_causal", getattr(self.config, "is_causal", None))
+ if is_causal is not None:
+ is_causal_in_config = hasattr(self.config, "is_causal")
+ if is_causal_in_config:
+ is_causal_original_value = self.config.is_causal
+ # Set it to both config and kwargs (it's needed in both, and can come from only 1 of the sources)
+ self.config.is_causal = is_causal
+ kwargs["is_causal"] = is_causal
+
+ # Call the original forward with the updated kwargs/config
+ try:
+ if kwargs.get("debug_io", False):
+ from ..model_debugging_utils import model_addition_debugger_context
+
+ with model_addition_debugger_context(
+ self, kwargs.get("debug_io_dir", "model_debug"), kwargs.get("prune_layers")
+ ):
+ output = func(self, *args, **kwargs)
+ else:
+ output = func(self, *args, **kwargs)
+ # Restore original config value
+ finally:
+ if is_causal is not None:
+ if is_causal_in_config:
+ self.config.is_causal = is_causal_original_value
+ else:
+ del self.config.is_causal
+
+ return output
+
+ return wrapper
+
+
+# bc for check_model_inputs:
+
+
+def check_model_inputs(func):
+ logger.warning_once("The `check_model_inputs` decorator is deprecated in favor of `merge_with_config_defaults`.")
+ return merge_with_config_defaults(func)
+
+
+class GeneralInterface(MutableMapping):
+ """
+ Dict-like object keeping track of a class-wide mapping, as well as a local one. Allows to have library-wide
+ modifications through the class mapping, as well as local modifications in a single file with the local mapping.
+ """
+
+ # Class instance object, so that a call to `register` can be reflected into all other files correctly, even if
+ # a new instance is created (in order to locally override a given function)
+ _global_mapping = {}
+
+ def __init__(self):
+ self._local_mapping = {}
+
+ def __getitem__(self, key):
+ # First check if instance has a local override
+ if key in self._local_mapping:
+ return self._local_mapping[key]
+ return self._global_mapping[key]
+
+ def __setitem__(self, key, value):
+ # Allow local update of the default functions without impacting other instances
+ self._local_mapping.update({key: value})
+
+ def __delitem__(self, key):
+ del self._local_mapping[key]
+
+ def __iter__(self):
+ # Ensure we use all keys, with the overwritten ones on top
+ return iter({**self._global_mapping, **self._local_mapping})
+
+ def __len__(self):
+ return len(self._global_mapping.keys() | self._local_mapping.keys())
+
+ @classmethod
+ def register(cls, key: str, value: Callable):
+ cls._global_mapping.update({key: value})
+
+ def valid_keys(self) -> list[str]:
+ return list(self.keys())
+
+
+def retry(
+ max_retries=5,
+ initial_delay=1.0,
+ max_delay=30.0,
+ jitter=True,
+ exceptions=(Exception,),
+):
+ """
+ Decorator that retries a function call with exponential backoff.
+
+ Args:
+ max_retries (`int`, *optional*, defaults to 5):
+ Maximum number of retry attempts.
+ initial_delay (`float`, *optional*, defaults to 1.0):
+ Initial delay in seconds before the first retry.
+ max_delay (`float`, *optional*, defaults to 30.0):
+ Maximum delay in seconds between retries.
+ jitter (`bool`, *optional*, defaults to `True`):
+ Whether to add random jitter to the delay.
+ exceptions (`tuple`, *optional*, defaults to `(Exception,)`):
+ Tuple of exception types to catch and retry on.
+ """
+
+ def decorator(func):
+ @wraps(func)
+ def wrapper(*args, **kwargs):
+ delay = initial_delay
+
+ for attempt in range(1, max_retries + 1):
+ try:
+ return func(*args, **kwargs)
+ except exceptions as exc:
+ if attempt == max_retries:
+ raise
+
+ sleep_for = min(delay, max_delay)
+ if jitter:
+ sleep_for *= random.uniform(0.8, 1.2)
+
+ logger.info(
+ f"[{func.__name__}] attempt {attempt}/{max_retries} failed: {exc}\n"
+ f"Retrying in {sleep_for:.1f}s..."
+ )
+ time.sleep(sleep_for)
+ delay = min(delay * 2, max_delay)
+
+ return wrapper
+
+ return decorator
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hp_naming.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hp_naming.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7c5cb5259f8452b09cc910aee1fec7f1ba438c8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hp_naming.py
@@ -0,0 +1,162 @@
+# 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.
+
+import copy
+import re
+
+
+class TrialShortNamer:
+ PREFIX = "hp"
+ DEFAULTS = {}
+ NAMING_INFO = None
+
+ @classmethod
+ def set_defaults(cls, prefix, defaults):
+ cls.PREFIX = prefix
+ cls.DEFAULTS = defaults
+ cls.build_naming_info()
+
+ @staticmethod
+ def shortname_for_word(info, word):
+ if len(word) == 0:
+ return ""
+ short_word = None
+ if any(char.isdigit() for char in word):
+ raise Exception(f"Parameters should not contain numbers: '{word}' contains a number")
+ if word in info["short_word"]:
+ return info["short_word"][word]
+ for prefix_len in range(1, len(word) + 1):
+ prefix = word[:prefix_len]
+ if prefix in info["reverse_short_word"]:
+ continue
+ else:
+ short_word = prefix
+ break
+
+ if short_word is None:
+ # Paranoid fallback
+ def int_to_alphabetic(integer):
+ s = ""
+ while integer != 0:
+ s = chr(ord("A") + integer % 10) + s
+ integer //= 10
+ return s
+
+ i = 0
+ while True:
+ sword = word + "#" + int_to_alphabetic(i)
+ if sword in info["reverse_short_word"]:
+ continue
+ else:
+ short_word = sword
+ break
+
+ info["short_word"][word] = short_word
+ info["reverse_short_word"][short_word] = word
+ return short_word
+
+ @staticmethod
+ def shortname_for_key(info, param_name):
+ words = param_name.split("_")
+
+ shortname_parts = [TrialShortNamer.shortname_for_word(info, word) for word in words]
+
+ # We try to create a separatorless short name, but if there is a collision we have to fallback
+ # to a separated short name
+ separators = ["", "_"]
+
+ for separator in separators:
+ shortname = separator.join(shortname_parts)
+ if shortname not in info["reverse_short_param"]:
+ info["short_param"][param_name] = shortname
+ info["reverse_short_param"][shortname] = param_name
+ return shortname
+
+ return param_name
+
+ @staticmethod
+ def add_new_param_name(info, param_name):
+ short_name = TrialShortNamer.shortname_for_key(info, param_name)
+ info["short_param"][param_name] = short_name
+ info["reverse_short_param"][short_name] = param_name
+
+ @classmethod
+ def build_naming_info(cls):
+ if cls.NAMING_INFO is not None:
+ return
+
+ info = {
+ "short_word": {},
+ "reverse_short_word": {},
+ "short_param": {},
+ "reverse_short_param": {},
+ }
+
+ field_keys = list(cls.DEFAULTS.keys())
+
+ for k in field_keys:
+ cls.add_new_param_name(info, k)
+
+ cls.NAMING_INFO = info
+
+ @classmethod
+ def shortname(cls, params):
+ cls.build_naming_info()
+ assert cls.PREFIX is not None
+ name = [copy.copy(cls.PREFIX)]
+
+ for k, v in params.items():
+ if k not in cls.DEFAULTS:
+ raise Exception(f"You should provide a default value for the param name {k} with value {v}")
+ if v == cls.DEFAULTS[k]:
+ # The default value is not added to the name
+ continue
+
+ key = cls.NAMING_INFO["short_param"][k]
+
+ if isinstance(v, bool):
+ v = 1 if v else 0
+
+ sep = "" if isinstance(v, (int, float)) else "-"
+ e = f"{key}{sep}{v}"
+ name.append(e)
+
+ return "_".join(name)
+
+ @classmethod
+ def parse_repr(cls, repr):
+ repr = repr[len(cls.PREFIX) + 1 :]
+ if repr == "":
+ values = []
+ else:
+ values = repr.split("_")
+
+ parameters = {}
+
+ for value in values:
+ if "-" in value:
+ p_k, p_v = value.split("-")
+ else:
+ p_k = re.sub("[0-9.]", "", value)
+ p_v = float(re.sub("[^0-9.]", "", value))
+
+ key = cls.NAMING_INFO["reverse_short_param"][p_k]
+
+ parameters[key] = p_v
+
+ for k in cls.DEFAULTS:
+ if k not in parameters:
+ parameters[k] = cls.DEFAULTS[k]
+
+ return parameters
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hub.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hub.py
new file mode 100644
index 0000000000000000000000000000000000000000..616796e4fe22d056db7f6dc3de2c58d140775305
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/hub.py
@@ -0,0 +1,949 @@
+# 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.
+"""
+Hub utilities: utilities related to download and cache models
+"""
+
+import json
+import os
+import re
+import sys
+import tempfile
+from concurrent import futures
+from pathlib import Path
+from typing import TypedDict
+from uuid import uuid4
+
+import httpx
+from huggingface_hub import (
+ _CACHED_NO_EXIST,
+ CommitOperationAdd,
+ ModelCard,
+ ModelCardData,
+ constants,
+ create_branch,
+ create_commit,
+ create_repo,
+ hf_hub_download,
+ hf_hub_url,
+ is_offline_mode,
+ list_repo_tree,
+ snapshot_download,
+ try_to_load_from_cache,
+)
+from huggingface_hub.file_download import REGEX_COMMIT_HASH
+from huggingface_hub.utils import (
+ EntryNotFoundError,
+ GatedRepoError,
+ HfHubHTTPError,
+ LocalEntryNotFoundError,
+ OfflineModeIsEnabled,
+ RepositoryNotFoundError,
+ RevisionNotFoundError,
+ build_hf_headers,
+ get_session,
+ hf_raise_for_status,
+)
+
+from . import __version__, logging
+from .import_utils import (
+ ENV_VARS_TRUE_VALUES,
+ get_torch_version,
+ is_torch_available,
+ is_training_run_on_sagemaker,
+)
+
+
+LEGACY_PROCESSOR_CHAT_TEMPLATE_FILE = "chat_template.json"
+CHAT_TEMPLATE_FILE = "chat_template.jinja"
+CHAT_TEMPLATE_DIR = "additional_chat_templates"
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+class DownloadKwargs(TypedDict, total=False):
+ cache_dir: str | os.PathLike | None
+ force_download: bool
+ proxies: dict[str, str] | None
+ local_files_only: bool
+ token: str | bool | None
+ revision: str | None
+ subfolder: str
+ commit_hash: str | None
+ tqdm_class: type | None
+
+
+# Determine default cache directory.
+# The best way to set the cache path is with the environment variable HF_HOME. For more details, check out this
+# documentation page: https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables.
+
+HF_MODULES_CACHE = os.getenv("HF_MODULES_CACHE", os.path.join(constants.HF_HOME, "modules"))
+TRANSFORMERS_DYNAMIC_MODULE_NAME = "transformers_modules"
+SESSION_ID = uuid4().hex
+
+S3_BUCKET_PREFIX = "https://s3.amazonaws.com/models.huggingface.co/bert"
+CLOUDFRONT_DISTRIB_PREFIX = "https://cdn.huggingface.co"
+
+
+def _get_cache_file_to_return(
+ path_or_repo_id: str,
+ full_filename: str,
+ cache_dir: str | Path | None = None,
+ revision: str | None = None,
+ repo_type: str | None = None,
+):
+ # We try to see if we have a cached version (not up to date):
+ resolved_file = try_to_load_from_cache(
+ path_or_repo_id, full_filename, cache_dir=cache_dir, revision=revision, repo_type=repo_type
+ )
+ if resolved_file is not None and resolved_file != _CACHED_NO_EXIST:
+ return resolved_file
+ return None
+
+
+def list_repo_templates(
+ repo_id: str,
+ *,
+ local_files_only: bool,
+ revision: str | None = None,
+ cache_dir: str | None = None,
+ token: str | bool | None = None,
+) -> list[str]:
+ """List template files from a repo.
+
+ A template is a jinja file located under the `additional_chat_templates/` folder.
+ If working in offline mode or if internet is down, the method will list jinja template from the local cache - if any.
+ """
+
+ if not local_files_only:
+ try:
+ return [
+ entry.path.removeprefix(f"{CHAT_TEMPLATE_DIR}/")
+ for entry in list_repo_tree(
+ repo_id=repo_id,
+ revision=revision,
+ path_in_repo=CHAT_TEMPLATE_DIR,
+ recursive=False,
+ token=token,
+ )
+ if entry.path.endswith(".jinja")
+ ]
+ except (GatedRepoError, RepositoryNotFoundError, RevisionNotFoundError):
+ raise # valid errors => do not catch
+ except (HfHubHTTPError, OfflineModeIsEnabled, httpx.NetworkError):
+ pass # offline mode, internet down, etc. => try local files
+
+ # check local files
+ try:
+ snapshot_dir = snapshot_download(
+ repo_id=repo_id, revision=revision, cache_dir=cache_dir, local_files_only=True
+ )
+ except LocalEntryNotFoundError: # No local repo means no local files
+ return []
+ templates_dir = Path(snapshot_dir, CHAT_TEMPLATE_DIR)
+ if not templates_dir.is_dir():
+ return []
+ return [entry.stem for entry in templates_dir.iterdir() if entry.is_file() and entry.name.endswith(".jinja")]
+
+
+def define_sagemaker_information():
+ try:
+ instance_data = httpx.get(os.environ["ECS_CONTAINER_METADATA_URI"]).json()
+ dlc_container_used = instance_data["Image"]
+ dlc_tag = instance_data["Image"].split(":")[1]
+ except Exception:
+ dlc_container_used = None
+ dlc_tag = None
+
+ sagemaker_params = json.loads(os.getenv("SM_FRAMEWORK_PARAMS", "{}"))
+ runs_distributed_training = "sagemaker_distributed_dataparallel_enabled" in sagemaker_params
+ training_job_arn = os.getenv("TRAINING_JOB_ARN")
+ account_id = training_job_arn.split(":")[4] if training_job_arn is not None else None
+
+ sagemaker_object = {
+ "sm_framework": os.getenv("SM_FRAMEWORK_MODULE", None),
+ "sm_region": os.getenv("AWS_REGION", None),
+ "sm_number_gpu": os.getenv("SM_NUM_GPUS", "0"),
+ "sm_number_cpu": os.getenv("SM_NUM_CPUS", "0"),
+ "sm_distributed_training": runs_distributed_training,
+ "sm_deep_learning_container": dlc_container_used,
+ "sm_deep_learning_container_tag": dlc_tag,
+ "sm_account_id": account_id,
+ }
+ return sagemaker_object
+
+
+def http_user_agent(user_agent: dict | str | None = None) -> str:
+ """
+ Formats a user-agent string with basic info about a request.
+ """
+ ua = f"transformers/{__version__}; python/{sys.version.split()[0]}; session_id/{SESSION_ID}"
+ if is_torch_available():
+ ua += f"; torch/{get_torch_version()}"
+ if constants.HF_HUB_DISABLE_TELEMETRY:
+ return ua + "; telemetry/off"
+ if is_training_run_on_sagemaker():
+ ua += "; " + "; ".join(f"{k}/{v}" for k, v in define_sagemaker_information().items())
+ # CI will set this value to True
+ if os.environ.get("TRANSFORMERS_IS_CI", "").upper() in ENV_VARS_TRUE_VALUES:
+ ua += "; is_ci/true"
+ if isinstance(user_agent, dict):
+ ua += "; " + "; ".join(f"{k}/{v}" for k, v in user_agent.items())
+ elif isinstance(user_agent, str):
+ ua += "; " + user_agent
+ return ua
+
+
+def extract_commit_hash(resolved_file: str | None, commit_hash: str | None) -> str | None:
+ """
+ Extracts the commit hash from a resolved filename toward a cache file.
+ """
+ if resolved_file is None or commit_hash is not None:
+ return commit_hash
+ resolved_file = str(Path(resolved_file).as_posix())
+ search = re.search(r"snapshots/([^/]+)/", resolved_file)
+ if search is None:
+ return None
+ commit_hash = search.groups()[0]
+ return commit_hash if REGEX_COMMIT_HASH.match(commit_hash) else None
+
+
+def cached_file(
+ path_or_repo_id: str | os.PathLike,
+ filename: str,
+ **kwargs,
+) -> str | None:
+ """
+ Tries to locate a file in a local folder and repo, downloads and cache it if necessary.
+
+ Args:
+ path_or_repo_id (`str` or `os.PathLike`):
+ This can be either:
+ - a string, the *model id* of a model repo on huggingface.co.
+ - a path to a *directory* potentially containing the file.
+ filename (`str`):
+ The name of the file to locate in `path_or_repo`.
+ cache_dir (`str` or `os.PathLike`, *optional*):
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
+ cache should not be used.
+ force_download (`bool`, *optional*, defaults to `False`):
+ Whether or not to force to (re-)download the configuration files and override the cached versions if they
+ exist.
+ proxies (`dict[str, str]`, *optional*):
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
+ token (`str` or *bool*, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
+ when running `hf auth login` (stored in `~/.huggingface`).
+ revision (`str`, *optional*, defaults to `"main"`):
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
+ identifier allowed by git.
+ local_files_only (`bool`, *optional*, defaults to `False`):
+ If `True`, will only try to load the tokenizer configuration from local files.
+ subfolder (`str`, *optional*, defaults to `""`):
+ In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
+ specify the folder name here.
+ repo_type (`str`, *optional*):
+ Specify the repo type (useful when downloading from a space for instance).
+
+
+
+ Passing `token=True` is required when you want to use a private model.
+
+
+
+ Returns:
+ `Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo).
+
+ Examples:
+
+ ```python
+ # Download a model weight from the Hub and cache it.
+ model_weights_file = cached_file("google-bert/bert-base-uncased", "pytorch_model.bin")
+ ```
+ """
+ file = cached_files(path_or_repo_id=path_or_repo_id, filenames=[filename], **kwargs)
+ file = file[0] if file is not None else file
+ return file
+
+
+def cached_files(
+ path_or_repo_id: str | os.PathLike,
+ filenames: list[str],
+ cache_dir: str | os.PathLike | None = None,
+ force_download: bool = False,
+ proxies: dict[str, str] | None = None,
+ token: bool | str | None = None,
+ revision: str | None = None,
+ local_files_only: bool = False,
+ subfolder: str = "",
+ repo_type: str | None = None,
+ user_agent: str | dict[str, str] | None = None,
+ _raise_exceptions_for_gated_repo: bool = True,
+ _raise_exceptions_for_missing_entries: bool = True,
+ _raise_exceptions_for_connection_errors: bool = True,
+ _commit_hash: str | None = None,
+ tqdm_class: type | None = None,
+ **deprecated_kwargs,
+) -> list[str] | None:
+ """
+ Tries to locate several files in a local folder and repo, downloads and cache them if necessary.
+
+ Args:
+ path_or_repo_id (`str` or `os.PathLike`):
+ This can be either:
+ - a string, the *model id* of a model repo on huggingface.co.
+ - a path to a *directory* potentially containing the file.
+ filenames (`list[str]`):
+ The name of all the files to locate in `path_or_repo`.
+ cache_dir (`str` or `os.PathLike`, *optional*):
+ Path to a directory in which a downloaded pretrained model configuration should be cached if the standard
+ cache should not be used.
+ force_download (`bool`, *optional*, defaults to `False`):
+ Whether or not to force to (re-)download the configuration files and override the cached versions if they
+ exist.
+ proxies (`dict[str, str]`, *optional*):
+ A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
+ 'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
+ token (`str` or *bool*, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True`, will use the token generated
+ when running `hf auth login` (stored in `~/.huggingface`).
+ revision (`str`, *optional*, defaults to `"main"`):
+ The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
+ git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
+ identifier allowed by git.
+ local_files_only (`bool`, *optional*, defaults to `False`):
+ If `True`, will only try to load the tokenizer configuration from local files.
+ subfolder (`str`, *optional*, defaults to `""`):
+ In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
+ specify the folder name here.
+ repo_type (`str`, *optional*):
+ Specify the repo type (useful when downloading from a space for instance).
+
+ Private args:
+ _raise_exceptions_for_gated_repo (`bool`):
+ if False, do not raise an exception for gated repo error but return None.
+ _raise_exceptions_for_missing_entries (`bool`):
+ if False, do not raise an exception for missing entries but return None.
+ _raise_exceptions_for_connection_errors (`bool`):
+ if False, do not raise an exception for connection errors but return None.
+ _commit_hash (`str`, *optional*):
+ passed when we are chaining several calls to various files (e.g. when loading a tokenizer or
+ a pipeline). If files are cached for this commit hash, avoid calls to head and get from the cache.
+
+
+
+ Passing `token=True` is required when you want to use a private model.
+
+
+
+ Returns:
+ `Optional[str]`: Returns the resolved file (to the cache folder if downloaded from a repo).
+
+ Examples:
+
+ ```python
+ # Download a model weight from the Hub and cache it.
+ model_weights_file = cached_file("google-bert/bert-base-uncased", "pytorch_model.bin")
+ ```
+ """
+ if is_offline_mode() and not local_files_only:
+ logger.info("Offline mode: forcing local_files_only=True")
+ local_files_only = True
+ if subfolder is None:
+ subfolder = ""
+
+ # Add folder to filenames
+ full_filenames = [os.path.join(subfolder, file) for file in filenames]
+
+ path_or_repo_id = str(path_or_repo_id)
+ existing_files = []
+ for filename in full_filenames:
+ if os.path.isdir(path_or_repo_id):
+ resolved_file = os.path.join(path_or_repo_id, filename)
+ if not os.path.isfile(resolved_file):
+ if _raise_exceptions_for_missing_entries and filename != os.path.join(subfolder, "config.json"):
+ revision_ = "main" if revision is None else revision
+ raise OSError(
+ f"{path_or_repo_id} does not appear to have a file named {filename}. Checkout "
+ f"'https://huggingface.co/{path_or_repo_id}/tree/{revision_}' for available files."
+ )
+ else:
+ continue
+ existing_files.append(resolved_file)
+
+ if os.path.isdir(path_or_repo_id):
+ return existing_files if existing_files else None
+
+ if cache_dir is None:
+ cache_dir = constants.HF_HUB_CACHE
+ if isinstance(cache_dir, Path):
+ cache_dir = str(cache_dir)
+
+ existing_files = []
+ file_counter = 0
+ if _commit_hash is not None and not force_download:
+ for filename in full_filenames:
+ # If the file is cached under that commit hash, we return it directly.
+ resolved_file = try_to_load_from_cache(
+ path_or_repo_id, filename, cache_dir=cache_dir, revision=_commit_hash, repo_type=repo_type
+ )
+ if resolved_file is not None:
+ if resolved_file is not _CACHED_NO_EXIST:
+ file_counter += 1
+ existing_files.append(resolved_file)
+ elif not _raise_exceptions_for_missing_entries:
+ file_counter += 1
+ else:
+ raise OSError(f"Could not locate {filename} inside {path_or_repo_id}.")
+
+ # Either all the files were found, or some were _CACHED_NO_EXIST but we do not raise for missing entries
+ if file_counter == len(full_filenames):
+ return existing_files if len(existing_files) > 0 else None
+
+ user_agent = http_user_agent(user_agent)
+ # download the files if needed
+ try:
+ if len(full_filenames) == 1:
+ # This is slightly better for only 1 file
+ hf_hub_download(
+ path_or_repo_id,
+ filenames[0],
+ subfolder=None if len(subfolder) == 0 else subfolder,
+ repo_type=repo_type,
+ revision=revision,
+ cache_dir=cache_dir,
+ user_agent=user_agent,
+ force_download=force_download,
+ proxies=proxies,
+ token=token,
+ local_files_only=local_files_only,
+ tqdm_class=tqdm_class,
+ )
+ else:
+ snapshot_download(
+ path_or_repo_id,
+ allow_patterns=full_filenames,
+ repo_type=repo_type,
+ revision=revision,
+ cache_dir=cache_dir,
+ user_agent=user_agent,
+ force_download=force_download,
+ proxies=proxies,
+ token=token,
+ local_files_only=local_files_only,
+ tqdm_class=tqdm_class,
+ )
+
+ except Exception as e:
+ # We cannot recover from them
+ if isinstance(e, RepositoryNotFoundError) and not isinstance(e, GatedRepoError):
+ raise OSError(
+ f"{path_or_repo_id} is not a local folder and is not a valid model identifier "
+ "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a token "
+ "having permission to this repo either by logging in with `hf auth login` or by passing "
+ "`token=`"
+ ) from e
+ elif isinstance(e, RevisionNotFoundError):
+ raise OSError(
+ f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists "
+ "for this model name. Check the model page at "
+ f"'https://huggingface.co/{path_or_repo_id}' for available revisions."
+ ) from e
+ elif isinstance(e, PermissionError):
+ raise OSError(
+ f"PermissionError at {e.filename} when downloading {path_or_repo_id}. "
+ "Check cache directory permissions. Common causes: 1) another user is downloading the same model (please wait); "
+ "2) a previous download was canceled and the lock file needs manual removal."
+ ) from e
+ elif isinstance(e, ValueError):
+ raise OSError(f"{e}") from e
+
+ # Now we try to recover if we can find all files correctly in the cache
+ resolved_files = [
+ _get_cache_file_to_return(path_or_repo_id, filename, cache_dir, revision, repo_type)
+ for filename in full_filenames
+ ]
+ if all(file is not None for file in resolved_files):
+ return resolved_files
+
+ # Raise based on the flags. Note that we will raise for missing entries at the very end, even when
+ # not entering this Except block, as it may also happen when `snapshot_download` does not raise
+ if isinstance(e, GatedRepoError):
+ if not _raise_exceptions_for_gated_repo:
+ return None
+ raise OSError(
+ "You are trying to access a gated repo.\nMake sure to have access to it at "
+ f"https://huggingface.co/{path_or_repo_id}.\n{str(e)}"
+ ) from e
+ elif isinstance(e, LocalEntryNotFoundError):
+ if not _raise_exceptions_for_connection_errors:
+ return None
+ # Here we only raise if both flags for missing entry and connection errors are True (because it can be raised
+ # even when `local_files_only` is True, in which case raising for connections errors only would not make sense)
+ elif _raise_exceptions_for_missing_entries:
+ raise OSError(
+ f"We couldn't connect to '{constants.ENDPOINT}' to load the files, and couldn't find them in the"
+ f" cached files.\nCheck your internet connection or see how to run the library in offline mode at"
+ " 'https://huggingface.co/docs/transformers/installation#offline-mode'."
+ ) from e
+ # snapshot_download will not raise EntryNotFoundError, but hf_hub_download can. If this is the case, it will be treated
+ # later on anyway and re-raised if needed
+ elif isinstance(e, HfHubHTTPError) and not isinstance(e, EntryNotFoundError):
+ if not _raise_exceptions_for_connection_errors:
+ return None
+ raise OSError(f"There was a specific connection error when trying to load {path_or_repo_id}:\n{e}") from e
+ # Any other Exception type should now be re-raised, in order to provide helpful error messages and break the execution flow
+ # (EntryNotFoundError will be treated outside this block and correctly re-raised if needed)
+ elif not isinstance(e, EntryNotFoundError):
+ raise e
+
+ resolved_files = [
+ _get_cache_file_to_return(path_or_repo_id, filename, cache_dir, revision) for filename in full_filenames
+ ]
+ # If there are any missing file and the flag is active, raise
+ if any(file is None for file in resolved_files) and _raise_exceptions_for_missing_entries:
+ missing_entries = [original for original, resolved in zip(full_filenames, resolved_files) if resolved is None]
+ # Last escape
+ if len(resolved_files) == 1 and missing_entries[0] == os.path.join(subfolder, "config.json"):
+ return None
+ # Now we raise for missing entries
+ revision_ = "main" if revision is None else revision
+ msg = (
+ f"a file named {missing_entries[0]}" if len(missing_entries) == 1 else f"files named {(*missing_entries,)}"
+ )
+ raise OSError(
+ f"{path_or_repo_id} does not appear to have {msg}. Checkout 'https://huggingface.co/{path_or_repo_id}/tree/{revision_}'"
+ " for available files."
+ )
+
+ # Remove potential missing entries (we can silently remove them at this point based on the flags)
+ resolved_files = [file for file in resolved_files if file is not None]
+ # Return `None` if the list is empty, coherent with other Exception when the flag is not active
+ resolved_files = None if len(resolved_files) == 0 else resolved_files
+
+ return resolved_files
+
+
+def has_file(
+ path_or_repo: str | os.PathLike,
+ filename: str,
+ revision: str | None = None,
+ proxies: dict[str, str] | None = None,
+ token: bool | str | None = None,
+ *,
+ local_files_only: bool = False,
+ cache_dir: str | Path | None = None,
+ repo_type: str | None = None,
+ **deprecated_kwargs,
+):
+ """
+ Checks if a repo contains a given file without downloading it. Works for remote repos and local folders.
+
+ If offline mode is enabled, checks if the file exists in the cache.
+
+
+
+ This function will raise an error if the repository `path_or_repo` is not valid or if `revision` does not exist for
+ this repo, but will return False for regular connection errors.
+
+
+ """
+ # If path to local directory, check if the file exists
+ if os.path.isdir(path_or_repo):
+ return os.path.isfile(os.path.join(path_or_repo, filename))
+
+ # Else it's a repo => let's check if the file exists in local cache or on the Hub
+
+ # Check if file exists in cache
+ # This information might be outdated so it's best to also make a HEAD call (if allowed).
+ cached_path = try_to_load_from_cache(
+ repo_id=path_or_repo,
+ filename=filename,
+ revision=revision,
+ repo_type=repo_type,
+ cache_dir=cache_dir,
+ )
+ has_file_in_cache = isinstance(cached_path, str)
+
+ # If local_files_only, don't try the HEAD call
+ if local_files_only:
+ return has_file_in_cache
+
+ # Check if the file exists
+ try:
+ response = get_session().head(
+ hf_hub_url(path_or_repo, filename=filename, revision=revision, repo_type=repo_type),
+ headers=build_hf_headers(token=token, user_agent=http_user_agent()),
+ follow_redirects=False,
+ timeout=10,
+ )
+ except httpx.ProxyError:
+ # Actually raise for those subclasses of ConnectionError
+ raise
+ except (httpx.ConnectError, httpx.TimeoutException, OfflineModeIsEnabled):
+ return has_file_in_cache
+
+ try:
+ hf_raise_for_status(response)
+ return True
+ except GatedRepoError as e:
+ logger.error(e)
+ raise OSError(
+ f"{path_or_repo} is a gated repository. Make sure to request access at "
+ f"https://huggingface.co/{path_or_repo} and pass a token having permission to this repo either by "
+ "logging in with `hf auth login` or by passing `token=`."
+ ) from e
+ except RepositoryNotFoundError as e:
+ logger.error(e)
+ raise OSError(f"{path_or_repo} is not a local folder or a valid repository name on 'https://hf.co'.") from e
+ except RevisionNotFoundError as e:
+ logger.error(e)
+ raise OSError(
+ f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for this "
+ f"model name. Check the model page at 'https://huggingface.co/{path_or_repo}' for available revisions."
+ ) from e
+ except EntryNotFoundError:
+ return False # File does not exist
+ except HfHubHTTPError:
+ # Any authentication/authorization error will be caught here => default to cache
+ return has_file_in_cache
+
+
+class PushToHubMixin:
+ """
+ A Mixin containing the functionality to push a model or tokenizer to the hub.
+ """
+
+ def _get_files_timestamps(self, working_dir: str | os.PathLike):
+ """
+ Returns the list of files with their last modification timestamp.
+ """
+ return {f: os.path.getmtime(os.path.join(working_dir, f)) for f in os.listdir(working_dir)}
+
+ def _upload_modified_files(
+ self,
+ working_dir: str | os.PathLike,
+ repo_id: str,
+ files_timestamps: dict[str, float],
+ commit_message: str | None = None,
+ token: bool | str | None = None,
+ create_pr: bool = False,
+ revision: str | None = None,
+ commit_description: str | None = None,
+ ):
+ """
+ Uploads all modified files in `working_dir` to `repo_id`, based on `files_timestamps`.
+ """
+ if commit_message is None:
+ if "Model" in self.__class__.__name__:
+ commit_message = "Upload model"
+ elif "Config" in self.__class__.__name__:
+ commit_message = "Upload config"
+ elif "Tokenizer" in self.__class__.__name__:
+ commit_message = "Upload tokenizer"
+ elif "FeatureExtractor" in self.__class__.__name__:
+ commit_message = "Upload feature extractor"
+ elif "Processor" in self.__class__.__name__:
+ commit_message = "Upload processor"
+ else:
+ commit_message = f"Upload {self.__class__.__name__}"
+ modified_files = [
+ f
+ for f in os.listdir(working_dir)
+ if f not in files_timestamps or os.path.getmtime(os.path.join(working_dir, f)) > files_timestamps[f]
+ ]
+
+ # filter for actual files + folders at the root level
+ modified_files = [
+ f
+ for f in modified_files
+ if os.path.isfile(os.path.join(working_dir, f)) or os.path.isdir(os.path.join(working_dir, f))
+ ]
+
+ operations = []
+ # upload standalone files
+ for file in modified_files:
+ if os.path.isdir(os.path.join(working_dir, file)):
+ # go over individual files of folder
+ for f in os.listdir(os.path.join(working_dir, file)):
+ operations.append(
+ CommitOperationAdd(
+ path_or_fileobj=os.path.join(working_dir, file, f), path_in_repo=os.path.join(file, f)
+ )
+ )
+ else:
+ operations.append(
+ CommitOperationAdd(path_or_fileobj=os.path.join(working_dir, file), path_in_repo=file)
+ )
+
+ if revision is not None and not revision.startswith("refs/pr"):
+ try:
+ create_branch(repo_id=repo_id, branch=revision, token=token, exist_ok=True)
+ except HfHubHTTPError as e:
+ if e.response.status_code == 403 and create_pr:
+ # If we are creating a PR on a repo we don't have access to, we can't create the branch.
+ # so let's assume the branch already exists. If it's not the case, an error will be raised when
+ # calling `create_commit` below.
+ pass
+ else:
+ raise
+
+ logger.info(f"Uploading the following files to {repo_id}: {','.join(modified_files)}")
+ return create_commit(
+ repo_id=repo_id,
+ operations=operations,
+ commit_message=commit_message,
+ commit_description=commit_description,
+ token=token,
+ create_pr=create_pr,
+ revision=revision,
+ )
+
+ def save_pretrained(self, *args, **kwargs):
+ # explicit contract
+ raise NotImplementedError(f"{self.__class__.__name__} must implement `save_pretrained` to use `push_to_hub`.")
+
+ def push_to_hub(
+ self,
+ repo_id: str,
+ *,
+ # Commit details
+ commit_message: str | None = None,
+ commit_description: str | None = None,
+ # Repo / upload details
+ private: bool | None = None,
+ token: bool | str | None = None,
+ revision: str | None = None,
+ create_pr: bool = False,
+ # Serialization details
+ max_shard_size: int | str | None = "50GB",
+ tags: list[str] | None = None,
+ ) -> str:
+ """
+ Upload the {object_files} to the 🤗 Model Hub.
+
+ Parameters:
+ repo_id (`str`):
+ The name of the repository you want to push your {object} to. It should contain your organization name
+ when pushing to a given organization.
+ commit_message (`str`, *optional*):
+ Message to commit while pushing. Will default to `"Upload {object}"`.
+ commit_description (`str`, *optional*):
+ The description of the commit that will be created
+ private (`bool`, *optional*):
+ Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
+ token (`bool` or `str`, *optional*):
+ The token to use as HTTP bearer authorization for remote files. If `True` (default), will use the token generated
+ when running `hf auth login` (stored in `~/.huggingface`).
+ revision (`str`, *optional*):
+ Branch to push the uploaded files to.
+ create_pr (`bool`, *optional*, defaults to `False`):
+ Whether or not to create a PR with the uploaded files or directly commit.
+ max_shard_size (`int` or `str`, *optional*, defaults to `"50GB"`):
+ Only applicable for models. The maximum size for a checkpoint before being sharded. Checkpoints shard
+ will then be each of size lower than this size. If expressed as a string, needs to be digits followed
+ by a unit (like `"5MB"`).
+ tags (`list[str]`, *optional*):
+ List of tags to push on the Hub.
+
+ Examples:
+
+ ```python
+ from transformers import {object_class}
+
+ {object} = {object_class}.from_pretrained("google-bert/bert-base-cased")
+
+ # Push the {object} to your namespace with the name "my-finetuned-bert".
+ {object}.push_to_hub("my-finetuned-bert")
+
+ # Push the {object} to an organization with the name "my-finetuned-bert".
+ {object}.push_to_hub("huggingface/my-finetuned-bert")
+ ```
+ """
+ # Create repo if it doesn't exist yet
+ repo_id = create_repo(repo_id, private=private, token=token, exist_ok=True).repo_id
+
+ # Load model card or create a new one + eventually tag it
+ model_card = create_and_tag_model_card(repo_id, tags, token=token)
+
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ # Save all files.
+ self.save_pretrained(tmp_dir, max_shard_size=max_shard_size)
+
+ # Update model card
+ model_card.save(os.path.join(tmp_dir, "README.md"))
+
+ # Upload
+ return self._upload_modified_files(
+ tmp_dir,
+ repo_id,
+ files_timestamps={},
+ commit_message=commit_message,
+ token=token,
+ create_pr=create_pr,
+ revision=revision,
+ commit_description=commit_description,
+ )
+
+
+def convert_file_size_to_int(size: int | str):
+ """
+ Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes).
+
+ Args:
+ size (`int` or `str`): The size to convert. Will be directly returned if an `int`.
+
+ Example:
+ ```py
+ >>> convert_file_size_to_int("1MiB")
+ 1048576
+ ```
+ """
+ if isinstance(size, int):
+ return size
+ if size.upper().endswith("GIB"):
+ return int(size[:-3]) * (2**30)
+ if size.upper().endswith("MIB"):
+ return int(size[:-3]) * (2**20)
+ if size.upper().endswith("KIB"):
+ return int(size[:-3]) * (2**10)
+ if size.upper().endswith("GB"):
+ int_size = int(size[:-2]) * (10**9)
+ return int_size // 8 if size.endswith("b") else int_size
+ if size.upper().endswith("MB"):
+ int_size = int(size[:-2]) * (10**6)
+ return int_size // 8 if size.endswith("b") else int_size
+ if size.upper().endswith("KB"):
+ int_size = int(size[:-2]) * (10**3)
+ return int_size // 8 if size.endswith("b") else int_size
+ raise ValueError("`size` is not in a valid format. Use an integer followed by the unit, e.g., '5GB'.")
+
+
+def get_checkpoint_shard_files(
+ pretrained_model_name_or_path,
+ index_filename,
+ cache_dir=None,
+ force_download=False,
+ proxies=None,
+ local_files_only=False,
+ token=None,
+ user_agent=None,
+ revision=None,
+ subfolder="",
+ _commit_hash=None,
+ tqdm_class=None,
+ **deprecated_kwargs,
+):
+ """
+ For a given model:
+
+ - download and cache all the shards of a sharded checkpoint if `pretrained_model_name_or_path` is a model ID on the
+ Hub
+ - returns the list of paths to all the shards, as well as some metadata.
+
+ For the description of each arg, see [`PreTrainedModel.from_pretrained`]. `index_filename` is the full path to the
+ index (downloaded and cached if `pretrained_model_name_or_path` is a model ID on the Hub).
+ """
+ if not os.path.isfile(index_filename):
+ raise ValueError(f"Can't find a checkpoint index ({index_filename}) in {pretrained_model_name_or_path}.")
+
+ with open(index_filename) as f:
+ index = json.loads(f.read())
+
+ shard_filenames = sorted(set(index["weight_map"].values()))
+ sharded_metadata = index["metadata"]
+ sharded_metadata["all_checkpoint_keys"] = list(index["weight_map"].keys())
+ sharded_metadata["weight_map"] = index["weight_map"].copy()
+
+ # First, let's deal with local folder.
+ if os.path.isdir(pretrained_model_name_or_path):
+ shard_filenames = [os.path.join(pretrained_model_name_or_path, subfolder, f) for f in shard_filenames]
+ return shard_filenames, sharded_metadata
+
+ # At this stage pretrained_model_name_or_path is a model identifier on the Hub. Try to get everything from cache,
+ # or download the files
+ cached_filenames = cached_files(
+ pretrained_model_name_or_path,
+ shard_filenames,
+ cache_dir=cache_dir,
+ force_download=force_download,
+ proxies=proxies,
+ local_files_only=local_files_only,
+ token=token,
+ user_agent=user_agent,
+ revision=revision,
+ subfolder=subfolder,
+ _commit_hash=_commit_hash,
+ tqdm_class=tqdm_class,
+ )
+
+ return cached_filenames, sharded_metadata
+
+
+def create_and_tag_model_card(repo_id: str, tags: list[str] | None = None, token: str | None = None) -> ModelCard:
+ """
+ Creates or loads an existing model card and tags it.
+
+ Args:
+ repo_id (`str`):
+ The repo_id where to look for the model card.
+ tags (`list[str]`, *optional*):
+ The list of tags to add in the model card
+ token (`str`, *optional*):
+ Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token.
+ """
+ try:
+ # Check if the model card is present on the remote repo
+ model_card = ModelCard.load(repo_id, token=token)
+ except EntryNotFoundError:
+ # Otherwise create a simple model card from template
+ model_description = "This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated."
+ card_data = ModelCardData(tags=[] if tags is None else tags, library_name="transformers")
+ model_card = ModelCard.from_template(card_data, model_description=model_description)
+
+ if tags is not None:
+ # Ensure model_card.data.tags is a list and not None
+ if model_card.data.tags is None:
+ model_card.data.tags = []
+ for model_tag in tags:
+ if model_tag not in model_card.data.tags:
+ model_card.data.tags.append(model_tag)
+
+ return model_card
+
+
+class PushInProgress:
+ """
+ Internal class to keep track of a push in progress (which might contain multiple `Future` jobs).
+ """
+
+ def __init__(self, jobs: futures.Future | None = None) -> None:
+ self.jobs = [] if jobs is None else jobs
+
+ def is_done(self):
+ return all(job.done() for job in self.jobs)
+
+ def wait_until_done(self):
+ futures.wait(self.jobs)
+
+ def cancel(self) -> None:
+ self.jobs = [
+ job
+ for job in self.jobs
+ # Cancel the job if it wasn't started yet and remove cancelled/done jobs from the list
+ if not (job.cancel() or job.done())
+ ]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/import_utils.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/import_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8654bd083ba2cd5aade7283b415b72960e5dab59
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/import_utils.py
@@ -0,0 +1,3031 @@
+# 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.
+"""
+Import utilities: Utilities related to imports and our lazy inits.
+"""
+
+import functools
+import importlib.machinery
+import importlib.metadata
+import importlib.util
+import json
+import operator
+import os
+import re
+import shutil
+import subprocess
+import sys
+import warnings
+from collections import OrderedDict
+from collections.abc import Callable
+from enum import Enum
+from functools import lru_cache
+from itertools import chain
+from types import ModuleType
+from typing import Any
+
+import packaging.version
+from packaging import version
+
+from . import logging
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+PACKAGE_DISTRIBUTION_MAPPING = importlib.metadata.packages_distributions()
+
+
+def _is_package_available(pkg_name: str, return_version: bool = False) -> tuple[bool, str]:
+ """Check if `pkg_name` exist, and optionally try to get its version"""
+ spec = importlib.util.find_spec(pkg_name)
+ package_exists = spec is not None
+ package_version = "N/A"
+ if package_exists and return_version:
+ try:
+ # importlib.metadata works with the distribution package, which may be different from the import
+ # name (e.g. `PIL` is the import name, but `pillow` is the distribution name)
+ distributions = PACKAGE_DISTRIBUTION_MAPPING[pkg_name]
+ # Per PEP 503, underscores and hyphens are equivalent in package names.
+ # Prefer the distribution that matches the (normalized) package name.
+ normalized_pkg_name = pkg_name.replace("_", "-")
+ if normalized_pkg_name in distributions:
+ distribution_name = normalized_pkg_name
+ elif pkg_name in distributions:
+ distribution_name = pkg_name
+ else:
+ distribution_name = distributions[0]
+ package_version = importlib.metadata.version(distribution_name)
+ except (importlib.metadata.PackageNotFoundError, KeyError):
+ # If we cannot find the metadata (because of editable install for example), try to import directly.
+ # Note that this branch will almost never be run, so we do not import packages for nothing here
+ package = importlib.import_module(pkg_name)
+ package_version = getattr(package, "__version__", "N/A")
+ logger.debug(f"Detected {pkg_name} version: {package_version}")
+
+ if return_version:
+ return package_exists, package_version
+ else:
+ return package_exists, None
+
+
+def resolve_internal_import(module: ModuleType | None, chained_path: str) -> Callable | ModuleType | None:
+ """
+ Check if a given `module` has an internal import path as defined by the `chained_path`.
+ This can either be the full path (not exposed in `__init__`) OR the last part of the chain (exposed in `__init__`).
+
+ This is an important helper function for kernels based modules to apply the import from the module
+ itself, i.e. stay compatible with original libraries in certain cases.
+
+ Example:
+ Module: `mamba_ssm`
+ Chained Path: `ops.triton.selective_state_update.selective_state_update`
+ Resulting import attempt at:
+ - `mamba_ssm.selective_state_update`
+ - `mamba_ssm.ops.triton.selective_state_update.selective_state_update`
+ """
+ if not module:
+ return None
+
+ if final_module := getattr(module, chained_path.split(".")[-1], None):
+ return final_module
+
+ final_module = module
+ for path in chained_path.split("."):
+ final_module = getattr(final_module, path, None)
+ if not final_module:
+ return None
+
+ return final_module
+
+
+def is_env_variable_true(env_variable: str) -> bool:
+ """Detect whether `env_variable` has been set to a true value in the environment"""
+ return os.getenv(env_variable, "false").lower() in ("true", "1", "y", "yes", "on")
+
+
+def is_env_variable_false(env_variable: str) -> bool:
+ """Detect whether `env_variable` has been set to a false value in the environment"""
+ return os.getenv(env_variable, "true").lower() in ("false", "0", "n", "no", "off")
+
+
+ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
+ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
+
+# Try to run a native pytorch job in an environment with TorchXLA installed by setting this value to 0.
+USE_TORCH_XLA = os.environ.get("USE_TORCH_XLA", "1").upper()
+
+ACCELERATE_MIN_VERSION = "1.1.0"
+BITSANDBYTES_MIN_VERSION = "0.46.1"
+SCHEDULEFREE_MIN_VERSION = "1.2.6"
+FSDP_MIN_VERSION = "1.12.0"
+GGUF_MIN_VERSION = "0.10.0"
+XLA_FSDPV2_MIN_VERSION = "2.2.0"
+HQQ_MIN_VERSION = "0.2.1"
+VPTQ_MIN_VERSION = "0.0.4"
+TORCHAO_MIN_VERSION = "0.15.0"
+AUTOROUND_MIN_VERSION = "0.5.0"
+TRITON_MIN_VERSION = "1.0.0"
+KERNELS_MIN_VERSION = "0.10.2"
+
+
+@lru_cache
+def is_torch_available() -> bool:
+ try:
+ is_available, torch_version = _is_package_available("torch", return_version=True)
+ parsed_version = version.parse(torch_version)
+ if is_available and parsed_version < version.parse("2.4.0"):
+ logger.warning_once(f"Disabling PyTorch because PyTorch >= 2.4 is required but found {torch_version}")
+ return is_available and version.parse(torch_version) >= version.parse("2.4.0")
+ except packaging.version.InvalidVersion:
+ return False
+
+
+@lru_cache
+def get_torch_version() -> str:
+ _, torch_version = _is_package_available("torch", return_version=True)
+ return torch_version
+
+
+@lru_cache
+def is_torch_greater_or_equal(library_version: str, accept_dev: bool = False) -> bool:
+ """
+ Accepts a library version and returns True if the current version of the library is greater than or equal to the
+ given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
+ 2.7.0).
+ """
+ if not is_torch_available():
+ return False
+
+ if accept_dev:
+ return version.parse(version.parse(get_torch_version()).base_version) >= version.parse(library_version)
+ else:
+ return version.parse(get_torch_version()) >= version.parse(library_version)
+
+
+@lru_cache
+def is_torch_less_or_equal(library_version: str, accept_dev: bool = False) -> bool:
+ """
+ Accepts a library version and returns True if the current version of the library is less than or equal to the
+ given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
+ 2.7.0).
+ """
+ if not is_torch_available():
+ return False
+
+ if accept_dev:
+ return version.parse(version.parse(get_torch_version()).base_version) <= version.parse(library_version)
+ else:
+ return version.parse(get_torch_version()) <= version.parse(library_version)
+
+
+@lru_cache
+def is_torch_accelerator_available() -> bool:
+ if is_torch_available():
+ import torch
+
+ return hasattr(torch, "accelerator")
+
+ return False
+
+
+@lru_cache
+def is_torch_cuda_available() -> bool:
+ if is_torch_available():
+ import torch
+
+ return torch.cuda.is_available()
+ return False
+
+
+@lru_cache
+def is_cuda_platform() -> bool:
+ if is_torch_available():
+ import torch
+
+ return getattr(torch, "version").cuda is not None
+ return False
+
+
+@lru_cache
+def get_cuda_runtime_version() -> tuple[int, int]:
+ """Return the CUDA runtime version as (major, minor).
+
+ Prefers a direct query of ``cudaRuntimeGetVersion`` via ``libcudart.so``. If that's
+ not on the system loader path (common with pip-installed torch that bundles its own
+ CUDA runtime), falls back to ``torch.version.cuda`` — which equals the bundled
+ runtime's version for pip wheels. Returns ``(0, 0)`` for CPU-only torch.
+ """
+ import ctypes
+
+ try:
+ cudart = ctypes.CDLL("libcudart.so")
+ except OSError:
+ if not is_torch_available():
+ return 0, 0
+ import torch
+
+ cuda_version = getattr(torch.version, "cuda", None)
+ if cuda_version is None:
+ return 0, 0
+
+ major, minor, *_ = cuda_version.split(".")
+ return int(major), int(minor)
+
+ version = ctypes.c_int()
+ cudart.cudaRuntimeGetVersion(ctypes.byref(version))
+ return version.value // 1000, (version.value % 1000) // 10
+
+
+@lru_cache
+def is_rocm_platform() -> bool:
+ if is_torch_available():
+ import torch
+
+ return getattr(torch, "version").hip is not None
+ return False
+
+
+@lru_cache
+def is_habana_gaudi1() -> bool:
+ if not is_torch_hpu_available():
+ return False
+
+ import habana_frameworks.torch.utils.experimental as htexp
+
+ # Check if the device is Gaudi1 (vs Gaudi2, Gaudi3)
+ return htexp._get_device_type() == htexp.synDeviceType.synDeviceGaudi
+
+
+@lru_cache
+def is_torch_mps_available(min_version: str | None = None) -> bool:
+ if is_torch_available():
+ import torch
+
+ backend_available = torch.backends.mps.is_available() and torch.backends.mps.is_built()
+ if min_version is not None:
+ flag = version.parse(get_torch_version()) >= version.parse(min_version)
+ backend_available = backend_available and flag
+ return backend_available
+ return False
+
+
+@lru_cache
+def is_torch_npu_available(check_device=False) -> bool:
+ "Checks if `torch_npu` is installed and potentially if a NPU is in the environment"
+ if not is_torch_available() or not _is_package_available("torch_npu")[0]:
+ return False
+
+ import torch
+ import torch_npu # noqa: F401
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no NPU is found
+ if hasattr(torch, "npu"):
+ _ = torch.npu.device_count()
+ return torch.npu.is_available()
+ return False
+ except RuntimeError:
+ return False
+ return hasattr(torch, "npu") and torch.npu.is_available()
+
+
+@lru_cache
+def is_torch_xpu_available(check_device: bool = False) -> bool:
+ """
+ Checks if XPU acceleration is available via stock PyTorch (>=2.6) and
+ potentially if a XPU is in the environment.
+ """
+ if not is_torch_available():
+ return False
+
+ torch_version = version.parse(get_torch_version())
+ if torch_version.major == 2 and torch_version.minor < 6:
+ return False
+
+ import torch
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no XPU is found
+ _ = torch.xpu.device_count()
+ return torch.xpu.is_available()
+ except RuntimeError:
+ return False
+ return hasattr(torch, "xpu") and torch.xpu.is_available()
+
+
+@lru_cache
+def is_torch_mlu_available() -> bool:
+ """
+ Checks if `mlu` is available via an `cndev-based` check which won't trigger the drivers and leave mlu
+ uninitialized.
+ """
+ if not is_torch_available() or not _is_package_available("torch_mlu")[0]:
+ return False
+
+ import torch
+ import torch_mlu # noqa: F401
+
+ pytorch_cndev_based_mlu_check_previous_value = os.environ.get("PYTORCH_CNDEV_BASED_MLU_CHECK")
+ try:
+ os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = str(1)
+ available = torch.mlu.is_available() if hasattr(torch, "mlu") else False
+ finally:
+ if pytorch_cndev_based_mlu_check_previous_value:
+ os.environ["PYTORCH_CNDEV_BASED_MLU_CHECK"] = pytorch_cndev_based_mlu_check_previous_value
+ else:
+ os.environ.pop("PYTORCH_CNDEV_BASED_MLU_CHECK", None)
+
+ return available
+
+
+@lru_cache
+def is_torch_musa_available(check_device=False) -> bool:
+ "Checks if `torch_musa` is installed and potentially if a MUSA is in the environment"
+ if not is_torch_available() or not _is_package_available("torch_musa")[0]:
+ return False
+
+ import torch
+ import torch_musa # noqa: F401
+
+ torch_musa_min_version = "0.33.0"
+ accelerate_available, accelerate_version = _is_package_available("accelerate", return_version=True)
+ if accelerate_available and version.parse(accelerate_version) < version.parse(torch_musa_min_version):
+ return False
+
+ if check_device:
+ try:
+ # Will raise a RuntimeError if no MUSA is found
+ if hasattr(torch, "musa"):
+ _ = torch.musa.device_count()
+ return torch.musa.is_available()
+ return False
+ except RuntimeError:
+ return False
+ return hasattr(torch, "musa") and torch.musa.is_available()
+
+
+@lru_cache
+def is_torch_xla_available(check_is_tpu=False, check_is_gpu=False) -> bool:
+ """
+ Check if `torch_xla` is available. To train a native pytorch job in an environment with torch xla installed, set
+ the USE_TORCH_XLA to false.
+ """
+ assert not (check_is_tpu and check_is_gpu), "The check_is_tpu and check_is_gpu cannot both be true."
+
+ torch_xla_available = USE_TORCH_XLA in ENV_VARS_TRUE_VALUES and _is_package_available("torch_xla")[0]
+ if not torch_xla_available:
+ return False
+
+ import torch_xla
+
+ if check_is_gpu:
+ return torch_xla.runtime.device_type() in ["GPU", "CUDA"]
+ elif check_is_tpu:
+ return torch_xla.runtime.device_type() == "TPU"
+
+ return True
+
+
+@lru_cache
+def is_torch_hpu_available() -> bool:
+ "Checks if `torch.hpu` is available and potentially if a HPU is in the environment"
+ if (
+ not is_torch_available()
+ or not _is_package_available("habana_frameworks")[0]
+ or not _is_package_available("habana_frameworks.torch")[0]
+ ):
+ return False
+
+ torch_hpu_min_accelerate_version = "1.5.0"
+ accelerate_available, accelerate_version = _is_package_available("accelerate", return_version=True)
+ if accelerate_available and version.parse(accelerate_version) < version.parse(torch_hpu_min_accelerate_version):
+ return False
+
+ import torch
+
+ if os.environ.get("PT_HPU_LAZY_MODE", "1") == "1":
+ # import habana_frameworks.torch in case of lazy mode to patch torch with torch.hpu
+ import habana_frameworks.torch # noqa: F401
+
+ if not hasattr(torch, "hpu") or not torch.hpu.is_available():
+ return False
+
+ # We patch torch.gather for int64 tensors to avoid a bug on Gaudi
+ # Graph compile failed with synStatus 26 [Generic failure]
+ # This can be removed once bug is fixed but for now we need it.
+ original_gather = torch.gather
+
+ def patched_gather(input: torch.Tensor, dim: int, index: torch.LongTensor) -> torch.Tensor:
+ if input.dtype == torch.int64 and input.device.type == "hpu":
+ return original_gather(input.to(torch.int32), dim, index).to(torch.int64)
+ else:
+ return original_gather(input, dim, index)
+
+ torch.gather = patched_gather
+ torch.Tensor.gather = patched_gather
+
+ original_take_along_dim = torch.take_along_dim
+
+ def patched_take_along_dim(input: torch.Tensor, indices: torch.LongTensor, dim: int | None = None) -> torch.Tensor:
+ if input.dtype == torch.int64 and input.device.type == "hpu":
+ return original_take_along_dim(input.to(torch.int32), indices, dim).to(torch.int64)
+ else:
+ return original_take_along_dim(input, indices, dim)
+
+ torch.take_along_dim = patched_take_along_dim
+
+ original_cholesky = torch.linalg.cholesky
+
+ def safe_cholesky(A, *args, **kwargs):
+ output = original_cholesky(A, *args, **kwargs)
+
+ if torch.isnan(output).any():
+ jitter_value = 1e-9
+ diag_jitter = torch.eye(A.size(-1), dtype=A.dtype, device=A.device) * jitter_value
+ output = original_cholesky(A + diag_jitter, *args, **kwargs)
+
+ return output
+
+ torch.linalg.cholesky = safe_cholesky
+
+ original_scatter = torch.scatter
+
+ def patched_scatter(
+ input: torch.Tensor, dim: int, index: torch.Tensor, src: torch.Tensor, *args, **kwargs
+ ) -> torch.Tensor:
+ if input.device.type == "hpu" and input is src:
+ return original_scatter(input, dim, index, src.clone(), *args, **kwargs)
+ else:
+ return original_scatter(input, dim, index, src, *args, **kwargs)
+
+ torch.scatter = patched_scatter
+ torch.Tensor.scatter = patched_scatter
+
+ # IlyasMoutawwakil: we patch torch.compile to use the HPU backend by default
+ # https://github.com/huggingface/transformers/pull/38790#discussion_r2157043944
+ # This is necessary for cases where torch.compile is used as a decorator (defaulting to inductor)
+ # https://github.com/huggingface/transformers/blob/af6120b3eb2470b994c21421bb6eaa76576128b0/src/transformers/models/modernbert/modeling_modernbert.py#L204
+ original_compile = torch.compile
+
+ def hpu_backend_compile(*args, **kwargs):
+ if kwargs.get("backend") not in ["hpu_backend", "eager"]:
+ logger.warning(
+ f"Calling torch.compile with backend={kwargs.get('backend')} on a Gaudi device is not supported. "
+ "We will override the backend with 'hpu_backend' to avoid errors."
+ )
+ kwargs["backend"] = "hpu_backend"
+
+ return original_compile(*args, **kwargs)
+
+ torch.compile = hpu_backend_compile
+
+ return True
+
+
+@lru_cache
+def is_torch_neuron_available(check_device: bool = False) -> bool:
+ import torch
+
+ if importlib.util.find_spec("torch_neuronx") is None:
+ return False
+
+ if check_device:
+ try:
+ import torch_neuronx # noqa: F401
+
+ # Will raise a RuntimeError if no Neuron is found
+ if hasattr(torch, "neuron"):
+ _ = torch.neuron.device_count()
+ return torch.neuron.is_available()
+ return False
+ except RuntimeError:
+ return False
+
+ return hasattr(torch, "neuron") and torch.neuron.is_available()
+
+
+@lru_cache
+def is_torch_bf16_gpu_available() -> bool:
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if torch.cuda.is_available():
+ return torch.cuda.is_bf16_supported()
+ if is_torch_xpu_available():
+ return torch.xpu.is_bf16_supported()
+ if is_torch_hpu_available():
+ return True
+ if is_torch_npu_available() and hasattr(torch, "npu"):
+ return torch.npu.is_bf16_supported()
+ if is_torch_mps_available():
+ # Note: Emulated in software by Metal using fp32 for hardware without native support (like M1/M2)
+ return torch.backends.mps.is_macos_or_newer(14, 0)
+ if is_torch_musa_available() and hasattr(torch, "musa"):
+ return torch.musa.is_bf16_supported()
+ if is_torch_mlu_available() and hasattr(torch, "mlu"):
+ return torch.mlu.is_bf16_supported()
+ if is_torch_neuron_available() and hasattr(torch, "neuron"):
+ return torch.neuron.is_bf16_supported()
+ return False
+
+
+@lru_cache
+def is_torch_fp16_available_on_device(device: str) -> bool:
+ if not is_torch_available():
+ return False
+
+ if is_torch_hpu_available():
+ if is_habana_gaudi1():
+ return False
+ else:
+ return True
+
+ import torch
+
+ try:
+ x = torch.zeros(2, 2, dtype=torch.float16, device=device)
+ _ = x @ x
+ # At this moment, let's be strict of the check: check if `LayerNorm` is also supported on device, because many
+ # models use this layer.
+ batch, sentence_length, embedding_dim = 3, 4, 5
+ embedding = torch.randn(batch, sentence_length, embedding_dim, dtype=torch.float16, device=device)
+ layer_norm = torch.nn.LayerNorm(embedding_dim, dtype=torch.float16, device=device)
+ _ = layer_norm(embedding)
+ return True
+ except Exception:
+ return False
+
+
+@lru_cache
+def is_torch_bf16_available_on_device(device: str) -> bool:
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if device == "cuda":
+ return is_torch_bf16_gpu_available()
+
+ if device == "hpu":
+ return True
+
+ try:
+ x = torch.zeros(2, 2, dtype=torch.bfloat16, device=device)
+ _ = x @ x
+ return True
+ except Exception:
+ return False
+
+
+@lru_cache
+def is_torch_tf32_available() -> bool:
+ if not is_torch_available():
+ return False
+
+ import torch
+
+ if is_torch_musa_available() and hasattr(torch, "musa"):
+ device_info = torch.musa.get_device_properties(torch.musa.current_device())
+ if f"{device_info.major}{device_info.minor}" >= "22":
+ return True
+ return False
+ torch_version = getattr(torch, "version")
+ if not torch.cuda.is_available() or torch_version.cuda is None:
+ return False
+ if torch.cuda.get_device_properties(torch.cuda.current_device()).major < 8:
+ return False
+ return True
+
+
+@lru_cache
+def enable_tf32(enable: bool) -> None:
+ """
+ Set TF32 mode using the appropriate PyTorch API.
+ For PyTorch 2.9+, uses the new fp32_precision API.
+ For older versions, uses the legacy allow_tf32 flags.
+ Args:
+ enable: Whether to enable TF32 mode
+ """
+ import torch
+
+ pytorch_version = version.parse(get_torch_version())
+ if pytorch_version >= version.parse("2.9.0"):
+ precision_mode = "tf32" if enable else "ieee"
+ if hasattr(torch.backends, "fp32_precision"):
+ torch.backends.fp32_precision = precision_mode
+ else:
+ if is_torch_musa_available():
+ if hasattr(torch.backends, "mudnn"):
+ torch.backends.mudnn.allow_tf32 = enable
+ else:
+ torch.backends.cuda.matmul.allow_tf32 = enable
+ torch.backends.cudnn.allow_tf32 = enable
+
+
+@lru_cache
+def is_torch_flex_attn_available() -> bool:
+ return is_torch_available() and version.parse(get_torch_version()) >= version.parse("2.5.0")
+
+
+@lru_cache
+def is_grouped_mm_available() -> bool:
+ return is_torch_available() and version.parse(get_torch_version()) >= version.parse("2.9.0")
+
+
+@lru_cache
+def is_kenlm_available() -> bool:
+ return _is_package_available("kenlm")[0]
+
+
+@lru_cache
+def is_kernels_available(MIN_VERSION: str = KERNELS_MIN_VERSION) -> bool:
+ is_available, kernels_version = _is_package_available("kernels", return_version=True)
+ return is_available and version.parse(kernels_version) >= version.parse(MIN_VERSION)
+
+
+@lru_cache
+def is_cv2_available() -> bool:
+ return _is_package_available("cv2")[0]
+
+
+@lru_cache
+def is_yt_dlp_available() -> bool:
+ return _is_package_available("yt_dlp")[0]
+
+
+@lru_cache
+def is_libcst_available() -> bool:
+ return _is_package_available("libcst")[0]
+
+
+@lru_cache
+def is_accelerate_available(min_version: str = ACCELERATE_MIN_VERSION) -> bool:
+ if not is_torch_available():
+ return False
+ is_available, accelerate_version = _is_package_available("accelerate", return_version=True)
+ return is_available and version.parse(accelerate_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_triton_available(min_version: str = TRITON_MIN_VERSION) -> bool:
+ is_available, triton_version = _is_package_available("triton", return_version=True)
+ return is_available and version.parse(triton_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_hadamard_available() -> bool:
+ return _is_package_available("fast_hadamard_transform")[0]
+
+
+@lru_cache
+def is_hqq_available(min_version: str = HQQ_MIN_VERSION) -> bool:
+ is_available, hqq_version = _is_package_available("hqq", return_version=True)
+ return is_available and version.parse(hqq_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_pygments_available() -> bool:
+ return _is_package_available("pygments")[0]
+
+
+@lru_cache
+def is_torchvision_available() -> bool:
+ return is_vision_available() and is_torch_available() and _is_package_available("torchvision")[0]
+
+
+@lru_cache
+def is_torchvision_v2_available() -> bool:
+ return is_torchvision_available()
+
+
+@lru_cache
+def is_galore_torch_available() -> bool:
+ return _is_package_available("galore_torch")[0]
+
+
+@lru_cache
+def is_apollo_torch_available() -> bool:
+ return _is_package_available("apollo_torch")[0]
+
+
+@lru_cache
+def is_torch_optimi_available() -> bool:
+ return _is_package_available("optimi")[0]
+
+
+@lru_cache
+def is_lomo_available() -> bool:
+ return _is_package_available("lomo_optim")[0]
+
+
+@lru_cache
+def is_grokadamw_available() -> bool:
+ return _is_package_available("grokadamw")[0]
+
+
+@lru_cache
+def is_schedulefree_available(min_version: str = SCHEDULEFREE_MIN_VERSION) -> bool:
+ is_available, schedulefree_version = _is_package_available("schedulefree", return_version=True)
+ return is_available and version.parse(schedulefree_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_pyctcdecode_available() -> bool:
+ return _is_package_available("pyctcdecode")[0]
+
+
+@lru_cache
+def is_librosa_available() -> bool:
+ return _is_package_available("librosa")[0]
+
+
+@lru_cache
+def is_multipart_available() -> bool:
+ return _is_package_available("multipart")[0]
+
+
+@lru_cache
+def is_essentia_available() -> bool:
+ return _is_package_available("essentia")[0]
+
+
+@lru_cache
+def is_pydantic_available() -> bool:
+ return _is_package_available("pydantic")[0]
+
+
+@lru_cache
+def is_fastapi_available() -> bool:
+ return _is_package_available("fastapi")[0]
+
+
+@lru_cache
+def is_uvicorn_available() -> bool:
+ return _is_package_available("uvicorn")[0]
+
+
+@lru_cache
+def is_openai_available() -> bool:
+ return _is_package_available("openai")[0]
+
+
+@lru_cache
+def is_serve_available() -> bool:
+ return is_pydantic_available() and is_fastapi_available() and is_uvicorn_available() and is_openai_available()
+
+
+@lru_cache
+def is_pretty_midi_available() -> bool:
+ return _is_package_available("pretty_midi")[0]
+
+
+@lru_cache
+def is_mamba_ssm_available() -> bool:
+ return is_torch_cuda_available() and _is_package_available("mamba_ssm")[0]
+
+
+@lru_cache
+def is_mamba_2_ssm_available() -> bool:
+ is_available, mamba_ssm_version = _is_package_available("mamba_ssm", return_version=True)
+ return is_torch_cuda_available() and is_available and version.parse(mamba_ssm_version) >= version.parse("2.0.4")
+
+
+@lru_cache
+def is_flash_linear_attention_available():
+ is_available, fla_version = _is_package_available("fla", return_version=True)
+ return is_torch_cuda_available() and is_available and version.parse(fla_version) >= version.parse("0.2.2")
+
+
+@lru_cache
+def is_causal_conv1d_available() -> bool:
+ return is_torch_cuda_available() and _is_package_available("causal_conv1d")[0]
+
+
+@lru_cache
+def is_xlstm_available() -> bool:
+ return is_torch_available() and _is_package_available("xlstm")[0]
+
+
+@lru_cache
+def is_mambapy_available() -> bool:
+ return is_torch_available() and _is_package_available("mambapy")[0]
+
+
+@lru_cache
+def is_peft_available() -> bool:
+ return _is_package_available("peft")[0]
+
+
+@lru_cache
+def is_bs4_available() -> bool:
+ return _is_package_available("bs4")[0]
+
+
+@lru_cache
+def is_coloredlogs_available() -> bool:
+ return _is_package_available("coloredlogs")[0]
+
+
+@lru_cache
+def is_onnx_available() -> bool:
+ return _is_package_available("onnx")[0]
+
+
+@lru_cache
+def is_flute_available() -> bool:
+ is_available, flute_version = _is_package_available("flute", return_version=True)
+ return is_available and version.parse(flute_version) >= version.parse("0.4.1")
+
+
+@lru_cache
+def is_g2p_en_available() -> bool:
+ return _is_package_available("g2p_en")[0]
+
+
+@lru_cache
+def is_torch_neuroncore_available(check_device=True) -> bool:
+ return is_torch_xla_available() and _is_package_available("torch_neuronx")[0]
+
+
+@lru_cache
+def is_torch_tensorrt_fx_available() -> bool:
+ return _is_package_available("torch_tensorrt")[0] and _is_package_available("torch_tensorrt.fx")[0]
+
+
+@lru_cache
+def is_datasets_available() -> bool:
+ return _is_package_available("datasets")[0]
+
+
+@lru_cache
+def is_detectron2_available() -> bool:
+ # We need this try/except block because otherwise after uninstalling the library, it stays available for some reason
+ # i.e. `import detectron2` and `import detectron2.modeling` still work, even though the library is uninstalled
+ # (the package exists but the objects are not reachable) - so here we explicitly try to import an object from it
+ try:
+ from detectron2.modeling import META_ARCH_REGISTRY # noqa
+
+ return True
+ except Exception:
+ return False
+
+
+@lru_cache
+def is_rjieba_available() -> bool:
+ return _is_package_available("rjieba")[0]
+
+
+@lru_cache
+def is_psutil_available() -> bool:
+ return _is_package_available("psutil")[0]
+
+
+@lru_cache
+def is_py3nvml_available() -> bool:
+ return _is_package_available("py3nvml")[0]
+
+
+@lru_cache
+def is_sacremoses_available() -> bool:
+ return _is_package_available("sacremoses")[0]
+
+
+@lru_cache
+def is_apex_available() -> bool:
+ return _is_package_available("apex")[0]
+
+
+@lru_cache
+def is_aqlm_available() -> bool:
+ return _is_package_available("aqlm")[0]
+
+
+@lru_cache
+def is_vptq_available(min_version: str = VPTQ_MIN_VERSION) -> bool:
+ is_available, vptq_version = _is_package_available("vptq", return_version=True)
+ return is_available and version.parse(vptq_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_av_available() -> bool:
+ return _is_package_available("av")[0]
+
+
+@lru_cache
+def is_decord_available() -> bool:
+ return _is_package_available("decord")[0]
+
+
+@lru_cache
+def is_torchcodec_available() -> bool:
+ return _is_package_available("torchcodec")[0]
+
+
+@lru_cache
+def is_ninja_available() -> bool:
+ r"""
+ Code comes from *torch.utils.cpp_extension.is_ninja_available()*. Returns `True` if the
+ [ninja](https://ninja-build.org/) build system is available on the system, `False` otherwise.
+ """
+ try:
+ subprocess.check_output(["ninja", "--version"])
+ except Exception:
+ return False
+ else:
+ return True
+
+
+@lru_cache
+def is_bitsandbytes_available(min_version: str = BITSANDBYTES_MIN_VERSION) -> bool:
+ is_available, bitsandbytes_version = _is_package_available("bitsandbytes", return_version=True)
+ return is_available and version.parse(bitsandbytes_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_flash_attn_2_available() -> bool:
+ is_available, flash_attn_version = _is_package_available("flash_attn", return_version=True)
+ # FA4 is also distributed under "flash_attn", hence we need to check the naming here
+ is_available = is_available and "flash-attn" in [
+ pkg.replace("_", "-") for pkg in PACKAGE_DISTRIBUTION_MAPPING["flash_attn"]
+ ]
+
+ if not is_available or not (is_torch_cuda_available() or is_torch_mlu_available()):
+ return False
+
+ # Only allow versions >= 2.3.3 to avoid very old legacy workarounds that are now 2+ years old
+ try:
+ return version.parse(flash_attn_version) >= version.parse("2.3.3")
+ except packaging.version.InvalidVersion:
+ return False
+
+
+@lru_cache
+def is_flash_attn_3_available() -> bool:
+ # Universally available under `flash_attn_interface`
+ is_available = _is_package_available("flash_attn_interface")[0]
+ # Resolving and ensuring the proper name of FA3 being associated
+ is_available = is_available and "flash-attn-3" in [
+ pkg.replace("_", "-") for pkg in PACKAGE_DISTRIBUTION_MAPPING["flash_attn_interface"]
+ ]
+ return is_available and is_torch_cuda_available()
+
+
+@lru_cache
+def is_flash_attn_4_available() -> bool:
+ is_available = _is_package_available("flash_attn")[0]
+ # FA2 is also distributed under "flash_attn", hence we need to check the naming here
+ # NOTE: FA2 seems to distribute the `cute` subdirectory even if only FA2 has been installed
+ # -> check for the proper (normalized) distribution name
+ is_available = is_available and "flash-attn-4" in [
+ pkg.replace("_", "-") for pkg in PACKAGE_DISTRIBUTION_MAPPING["flash_attn"]
+ ]
+
+ return is_available and is_torch_cuda_available()
+
+
+@lru_cache
+def is_flash_attn_greater_or_equal(library_version: str) -> bool:
+ is_available, flash_attn_version = _is_package_available("flash_attn", return_version=True)
+ # FA4 is also distributed under "flash_attn", hence we need to check the naming here
+ is_available = is_available and "flash-attn" in [
+ pkg.replace("_", "-") for pkg in PACKAGE_DISTRIBUTION_MAPPING["flash_attn"]
+ ]
+
+ if not is_available:
+ return False
+ try:
+ return version.parse(flash_attn_version) >= version.parse(library_version)
+ except packaging.version.InvalidVersion:
+ return False
+
+
+@lru_cache
+def is_flash_attn_greater_or_equal_2_10() -> bool:
+ warnings.warn(
+ "`is_flash_attn_greater_or_equal_2_10` is deprecated and will be removed in v5.8. "
+ "Please use `is_flash_attn_greater_or_equal(library_version='2.1.0')` instead if needed.",
+ FutureWarning,
+ )
+ return is_flash_attn_greater_or_equal("2.1.0")
+
+
+@lru_cache
+def is_huggingface_hub_greater_or_equal(library_version: str, accept_dev: bool = False) -> bool:
+ is_available, hub_version = _is_package_available("huggingface_hub", return_version=True)
+ if not is_available:
+ return False
+
+ if accept_dev:
+ return version.parse(version.parse(hub_version).base_version) >= version.parse(library_version)
+ else:
+ return version.parse(hub_version) >= version.parse(library_version)
+
+
+@lru_cache
+def is_quanto_greater(library_version: str, accept_dev: bool = False) -> bool:
+ """
+ Accepts a library version and returns True if the current version of the library is greater than or equal to the
+ given version. If `accept_dev` is True, it will also accept development versions (e.g. 2.7.0.dev20250320 matches
+ 2.7.0).
+ """
+ if not is_optimum_quanto_available():
+ return False
+
+ _, quanto_version = _is_package_available("optimum.quanto", return_version=True)
+ if accept_dev:
+ return version.parse(version.parse(quanto_version).base_version) > version.parse(library_version)
+ else:
+ return version.parse(quanto_version) > version.parse(library_version)
+
+
+@lru_cache
+def is_torchdistx_available():
+ return _is_package_available("torchdistx")[0]
+
+
+@lru_cache
+def is_faiss_available() -> bool:
+ return _is_package_available("faiss")[0]
+
+
+@lru_cache
+def is_fouroversix_available() -> bool:
+ return _is_package_available("fouroversix")
+
+
+@lru_cache
+def is_scipy_available() -> bool:
+ return _is_package_available("scipy")[0]
+
+
+@lru_cache
+def is_sklearn_available() -> bool:
+ return _is_package_available("sklearn")[0]
+
+
+@lru_cache
+def is_sentencepiece_available() -> bool:
+ return _is_package_available("sentencepiece")[0]
+
+
+@lru_cache
+def is_seqio_available() -> bool:
+ return _is_package_available("seqio")[0]
+
+
+@lru_cache
+def is_gguf_available(min_version: str = GGUF_MIN_VERSION) -> bool:
+ is_available, gguf_version = _is_package_available("gguf", return_version=True)
+ return is_available and version.parse(gguf_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_protobuf_available() -> bool:
+ return _is_package_available("google")[0] and _is_package_available("google.protobuf")[0]
+
+
+@lru_cache
+def is_fsdp_available(min_version: str = FSDP_MIN_VERSION) -> bool:
+ return is_torch_available() and version.parse(get_torch_version()) >= version.parse(min_version)
+
+
+@lru_cache
+def is_optimum_available() -> bool:
+ return _is_package_available("optimum")[0]
+
+
+@lru_cache
+def is_llm_awq_available() -> bool:
+ return _is_package_available("awq")[0]
+
+
+@lru_cache
+def is_auto_round_available(min_version: str = AUTOROUND_MIN_VERSION) -> bool:
+ is_available, auto_round_version = _is_package_available("auto_round", return_version=True)
+ return is_available and version.parse(auto_round_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_optimum_quanto_available():
+ return is_optimum_available() and _is_package_available("optimum.quanto")[0]
+
+
+@lru_cache
+def is_quark_available() -> bool:
+ return _is_package_available("quark")[0]
+
+
+@lru_cache
+def is_fp_quant_available():
+ is_available, fp_quant_version = _is_package_available("fp_quant", return_version=True)
+ return is_available and version.parse(fp_quant_version) >= version.parse("0.3.2")
+
+
+@lru_cache
+def is_qutlass_available():
+ is_available, qutlass_version = _is_package_available("qutlass", return_version=True)
+ return is_available and version.parse(qutlass_version) >= version.parse("0.2.0")
+
+
+@lru_cache
+def is_compressed_tensors_available() -> bool:
+ return _is_package_available("compressed_tensors")[0]
+
+
+@lru_cache
+def is_sinq_available() -> bool:
+ return _is_package_available("sinq")
+
+
+@lru_cache
+def is_gptqmodel_available() -> bool:
+ return _is_package_available("gptqmodel")[0]
+
+
+@lru_cache
+def is_fbgemm_gpu_available() -> bool:
+ return _is_package_available("fbgemm_gpu")[0]
+
+
+@lru_cache
+def is_levenshtein_available() -> bool:
+ return _is_package_available("Levenshtein")[0]
+
+
+@lru_cache
+def is_optimum_neuron_available() -> bool:
+ return is_optimum_available() and _is_package_available("optimum.neuron")[0]
+
+
+@lru_cache
+def is_tokenizers_available() -> bool:
+ return _is_package_available("tokenizers")[0]
+
+
+@lru_cache
+def is_vision_available() -> bool:
+ try:
+ import PIL.Image # noqa: F401
+
+ return True
+ except ImportError:
+ return False
+
+
+@lru_cache
+def is_pytesseract_available() -> bool:
+ return _is_package_available("pytesseract")[0] and is_vision_available()
+
+
+@lru_cache
+def is_pytest_available() -> bool:
+ return _is_package_available("pytest")[0]
+
+
+@lru_cache
+def is_pytest_order_available() -> bool:
+ return is_pytest_available() and _is_package_available("pytest_order")[0]
+
+
+@lru_cache
+def is_spacy_available() -> bool:
+ return _is_package_available("spacy")[0]
+
+
+@lru_cache
+def is_pytorch_quantization_available() -> bool:
+ return _is_package_available("pytorch_quantization")[0]
+
+
+@lru_cache
+def is_pandas_available() -> bool:
+ return _is_package_available("pandas")[0]
+
+
+@lru_cache
+def is_soundfile_available() -> bool:
+ return _is_package_available("soundfile")[0]
+
+
+@lru_cache
+def is_timm_available() -> bool:
+ return is_vision_available() and is_torch_available() and _is_package_available("timm")[0]
+
+
+@lru_cache
+def is_natten_available() -> bool:
+ return _is_package_available("natten")[0]
+
+
+@lru_cache
+def is_nltk_available() -> bool:
+ return _is_package_available("nltk")[0]
+
+
+@lru_cache
+def is_numba_available() -> bool:
+ is_available = _is_package_available("numba")[0]
+ if not is_available:
+ return False
+
+ numpy_available, numpy_version = _is_package_available("numpy", return_version=True)
+ return not numpy_available or version.parse(numpy_version) < version.parse("2.2.0")
+
+
+@lru_cache
+def is_torchaudio_available() -> bool:
+ return is_torch_available() and _is_package_available("torchaudio")[0]
+
+
+@lru_cache
+def is_torchao_available(min_version: str = TORCHAO_MIN_VERSION) -> bool:
+ if not is_torch_available():
+ return False
+ is_available, torchao_version = _is_package_available("torchao", return_version=True)
+ return is_available and version.parse(torchao_version) >= version.parse(min_version)
+
+
+@lru_cache
+def is_speech_available() -> bool:
+ # For now this depends on torchaudio but the exact dependency might evolve in the future.
+ return is_torchaudio_available()
+
+
+@lru_cache
+def is_spqr_available() -> bool:
+ return _is_package_available("spqr_quant")[0]
+
+
+@lru_cache
+def is_phonemizer_available() -> bool:
+ return _is_package_available("phonemizer")[0]
+
+
+@lru_cache
+def is_uroman_available() -> bool:
+ return _is_package_available("uroman")[0]
+
+
+@lru_cache
+def is_sudachi_available() -> bool:
+ return _is_package_available("sudachipy")[0]
+
+
+@lru_cache
+def is_sudachi_projection_available() -> bool:
+ is_available, sudachipy_version = _is_package_available("sudachipy", return_version=True)
+ return is_available and version.parse(sudachipy_version) >= version.parse("0.6.8")
+
+
+@lru_cache
+def is_jumanpp_available() -> bool:
+ return _is_package_available("rhoknp")[0] and shutil.which("jumanpp") is not None
+
+
+@lru_cache
+def is_cython_available() -> bool:
+ return _is_package_available("pyximport")[0]
+
+
+@lru_cache
+def is_jinja_available() -> bool:
+ return _is_package_available("jinja2")[0]
+
+
+@lru_cache
+def is_jmespath_available() -> bool:
+ return _is_package_available("jmespath")[0]
+
+
+@lru_cache
+def is_mlx_available() -> bool:
+ return _is_package_available("mlx")[0]
+
+
+@lru_cache
+def is_num2words_available() -> bool:
+ return _is_package_available("num2words")[0]
+
+
+@lru_cache
+def is_tiktoken_available(with_blobfile: bool = True) -> bool:
+ if not _is_package_available("tiktoken")[0]:
+ return False
+ return with_blobfile and _is_package_available("blobfile")[0] or True
+
+
+@lru_cache
+def is_liger_kernel_available() -> bool:
+ is_available, liger_kernel_version = _is_package_available("liger_kernel", return_version=True)
+ return is_available and version.parse(liger_kernel_version) >= version.parse("0.3.0")
+
+
+@lru_cache
+def is_rich_available() -> bool:
+ return _is_package_available("rich")[0]
+
+
+@lru_cache
+def is_matplotlib_available() -> bool:
+ return _is_package_available("matplotlib")[0]
+
+
+@lru_cache
+def is_mistral_common_available() -> bool:
+ return is_vision_available() and _is_package_available("mistral_common")[0]
+
+
+@lru_cache
+def is_opentelemetry_available() -> bool:
+ try:
+ return _is_package_available("opentelemetry")[0] and version.parse(
+ importlib.metadata.version("opentelemetry-api")
+ ) >= version.parse("1.30.0")
+ except Exception as _:
+ return False
+
+
+@lru_cache
+def is_pynvml_available() -> bool:
+ return _is_package_available("pynvml")[0]
+
+
+def check_torch_load_is_safe() -> None:
+ if not is_torch_greater_or_equal("2.6"):
+ raise ValueError(
+ "Due to a serious vulnerability issue in `torch.load`, even with `weights_only=True`, we now require users "
+ "to upgrade torch to at least v2.6 in order to use the function. This version restriction does not apply "
+ "when loading files with safetensors."
+ "\nSee the vulnerability report here https://nvd.nist.gov/vuln/detail/CVE-2025-32434"
+ )
+
+
+def torch_only_method(fn: Callable) -> Callable:
+ def wrapper(*args, **kwargs):
+ if not is_torch_available():
+ raise ImportError("You need to install pytorch to use this method or class")
+ else:
+ return fn(*args, **kwargs)
+
+ return wrapper
+
+
+def is_torch_deterministic() -> bool:
+ """
+ Check whether pytorch uses deterministic algorithms by looking if torch.set_deterministic_debug_mode() is set to 1 or 2"
+ """
+ if is_torch_available():
+ import torch
+
+ if torch.get_deterministic_debug_mode() == 0:
+ return False
+ else:
+ return True
+
+ return False
+
+
+@lru_cache
+def get_torch_major_and_minor_version() -> str:
+ torch_version = get_torch_version()
+ if torch_version == "N/A":
+ return "N/A"
+ parsed_version = version.parse(torch_version)
+ return str(parsed_version.major) + "." + str(parsed_version.minor)
+
+
+def is_torchdynamo_compiling() -> bool:
+ # Importing torch._dynamo causes issues with PyTorch profiler (https://github.com/pytorch/pytorch/issues/130622)
+ # hence rather relying on `torch.compiler.is_compiling()` when possible (torch>=2.3)
+ try:
+ import torch
+
+ if hasattr(torch, "compiler"):
+ return torch.compiler.is_compiling()
+ return False
+ except Exception:
+ return False
+
+
+def is_torchdynamo_exporting() -> bool:
+ try:
+ import torch
+
+ if hasattr(torch, "compiler"):
+ return torch.compiler.is_exporting()
+ return False
+ except Exception:
+ return False
+
+
+def is_torch_fx_proxy(x) -> bool:
+ try:
+ import torch.fx
+
+ return isinstance(x, torch.fx.Proxy)
+ except Exception:
+ return False
+
+
+def is_fake_tensor(x) -> bool:
+ try:
+ import torch
+
+ return isinstance(x, getattr(torch, "_subclasses").FakeTensor)
+ except Exception:
+ return False
+
+
+def is_jax_jitting(x):
+ """returns True if we are inside of `jax.jit` context, False otherwise.
+
+ When a torch model is being compiled with `jax.jit` using torchax,
+ the tensor that goes through the model would be an instance of
+ `torchax.tensor.Tensor`, which is a tensor subclass. This tensor has
+ a `jax` method to return the inner Jax array
+ (https://github.com/google/torchax/blob/13ce870a1d9adb2430333c27bb623469e3aea34e/torchax/tensor.py#L134).
+ Here we use ducktyping to detect if the inner jax array is a jax Tracer
+ then we are in tracing context. (See more at: https://github.com/jax-ml/jax/discussions/9241)
+
+ Args:
+ x: torch.Tensor
+
+ Returns:
+ bool: whether we are inside of jax jit tracing.
+ """
+
+ if not hasattr(x, "jax"):
+ return False
+ try:
+ import jax
+
+ return isinstance(x.jax(), getattr(jax, "core").Tracer)
+ except Exception:
+ return False
+
+
+def is_jit_tracing() -> bool:
+ try:
+ import torch
+
+ return torch.jit.is_tracing()
+ except Exception:
+ return False
+
+
+def is_cuda_stream_capturing() -> bool:
+ try:
+ import torch
+
+ return torch.cuda.is_current_stream_capturing()
+ except Exception:
+ return False
+
+
+def is_tracing(tensor=None) -> bool:
+ """Checks whether we are tracing a graph with dynamo (compile or export), torch.jit, torch.fx, jax.jit (with torchax) or
+ CUDA stream capturing or FakeTensor"""
+
+ # Note that `is_torchdynamo_compiling` checks both compiling and exporting (the export check is stricter and
+ # only checks export)
+ _is_tracing = is_torchdynamo_compiling() or is_jit_tracing() or is_cuda_stream_capturing()
+ if tensor is not None:
+ _is_tracing |= is_torch_fx_proxy(tensor)
+ _is_tracing |= is_fake_tensor(tensor)
+ _is_tracing |= is_jax_jitting(tensor)
+
+ return _is_tracing
+
+
+def torch_compilable_check(cond: Any, msg: str | Callable[[], str], error_type: type[Exception] = ValueError) -> None:
+ """
+ Combines the functionalities of `torch._check`, `torch._check_with` and `torch._check_tensor_all_with` to provide a
+ unified way to perform checks that are compatible with TorchDynamo (torch.compile & torch.export).
+
+ The advantage of using `torch._check(cond, msg, error_type)` over `if cond: raise error_type(msg)` is that the former
+ works as a truthfulness hint for TorchDynamo, instead of failing with a data-dependent control flow error during compilation.
+
+ All checks using this method can be disabled in production environments by setting `TRANSFORMERS_DISABLE_TORCH_CHECK=1`.
+
+ Args:
+ cond (`bool`, `torch.Tensor` or `Callable[[], bool | torch.Tensor]`): The condition to check.
+ msg (`str` or `Callable[[], str]`): The error message to display if the condition is not met.
+ error_type (`type[Exception]`, *optional*, defaults to `ValueError`): The type of error to raise if the condition is not met.
+
+ Raises:
+ error_type: If the condition is not met.
+ """
+ if os.getenv("TRANSFORMERS_DISABLE_TORCH_CHECK", "0") == "1":
+ return
+
+ import torch
+
+ if not callable(msg):
+ # torch._check requires msg to be a callable but we want to keep the API simple for users
+ def msg_callable():
+ return msg
+ else:
+ msg_callable = msg
+
+ if callable(cond):
+ cond = cond()
+
+ # These checks are also compiler hints for TorchDynamo telling
+ # it that the condition is expected to be True during compilation
+ if isinstance(cond, torch.Tensor):
+ torch._check_tensor_all_with(error_type, cond, msg_callable)
+ else:
+ torch._check_with(error_type, cond, msg_callable)
+
+
+@lru_cache
+def is_ipython_available() -> bool:
+ return importlib.util.find_spec("IPython") is not None
+
+
+@lru_cache
+def is_in_notebook() -> bool:
+ try:
+ # Check if we are running inside Marimo
+ if "marimo" in sys.modules:
+ return True
+ # Test adapted from tqdm.autonotebook: https://github.com/tqdm/tqdm/blob/master/tqdm/autonotebook.py
+ get_ipython = sys.modules["IPython"].get_ipython
+ if "IPKernelApp" not in get_ipython().config:
+ raise ImportError("console")
+ # Removed the lines to include VSCode
+ if "DATABRICKS_RUNTIME_VERSION" in os.environ and os.environ["DATABRICKS_RUNTIME_VERSION"] < "11.0":
+ # Databricks Runtime 11.0 and above uses IPython kernel by default so it should be compatible with Jupyter notebook
+ # https://docs.microsoft.com/en-us/azure/databricks/notebooks/ipython-kernel
+ raise ImportError("databricks")
+
+ return importlib.util.find_spec("IPython") is not None
+ except (AttributeError, ImportError, KeyError):
+ return False
+
+
+def is_sagemaker_dp_enabled() -> bool:
+ # Get the sagemaker specific env variable.
+ sagemaker_params = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
+ try:
+ # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
+ sagemaker_params = json.loads(sagemaker_params)
+ if not sagemaker_params.get("sagemaker_distributed_dataparallel_enabled", False):
+ return False
+ except json.JSONDecodeError:
+ return False
+ # Lastly, check if the `smdistributed` module is present.
+ return _is_package_available("smdistributed")[0]
+
+
+def is_sagemaker_mp_enabled() -> bool:
+ # Get the sagemaker specific mp parameters from smp_options variable.
+ smp_options = os.getenv("SM_HP_MP_PARAMETERS", "{}")
+ try:
+ # Parse it and check the field "partitions" is included, it is required for model parallel.
+ smp_options = json.loads(smp_options)
+ if "partitions" not in smp_options:
+ return False
+ except json.JSONDecodeError:
+ return False
+
+ # Get the sagemaker specific framework parameters from mpi_options variable.
+ mpi_options = os.getenv("SM_FRAMEWORK_PARAMS", "{}")
+ try:
+ # Parse it and check the field "sagemaker_distributed_dataparallel_enabled".
+ mpi_options = json.loads(mpi_options)
+ if not mpi_options.get("sagemaker_mpi_enabled", False):
+ return False
+ except json.JSONDecodeError:
+ return False
+ # Lastly, check if the `smdistributed` module is present.
+ return _is_package_available("smdistributed")[0]
+
+
+def is_training_run_on_sagemaker() -> bool:
+ return "SAGEMAKER_JOB_NAME" in os.environ
+
+
+# docstyle-ignore
+AV_IMPORT_ERROR = """
+{0} requires the PyAv library but it was not found in your environment. You can install it with:
+```
+pip install av
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+YT_DLP_IMPORT_ERROR = """
+{0} requires the YT-DLP library but it was not found in your environment. You can install it with:
+```
+pip install yt-dlp
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+DECORD_IMPORT_ERROR = """
+{0} requires the PyAv library but it was not found in your environment. You can install it with:
+```
+pip install decord
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+TORCHCODEC_IMPORT_ERROR = """
+{0} requires the TorchCodec (https://github.com/pytorch/torchcodec) library, but it was not found in your environment. You can install it with:
+```
+pip install torchcodec
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+CV2_IMPORT_ERROR = """
+{0} requires the OpenCV library but it was not found in your environment. You can install it with:
+```
+pip install opencv-python
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+DATASETS_IMPORT_ERROR = """
+{0} requires the 🤗 Datasets library but it was not found in your environment. You can install it with:
+```
+pip install datasets
+```
+In a notebook or a colab, you can install it by executing a cell with
+```
+!pip install datasets
+```
+then restarting your kernel.
+
+Note that if you have a local folder named `datasets` or a local python file named `datasets.py` in your current
+working directory, python may try to import this instead of the 🤗 Datasets library. You should rename this folder or
+that python file if that's the case. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+TOKENIZERS_IMPORT_ERROR = """
+{0} requires the 🤗 Tokenizers library but it was not found in your environment. You can install it with:
+```
+pip install tokenizers
+```
+In a notebook or a colab, you can install it by executing a cell with
+```
+!pip install tokenizers
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SENTENCEPIECE_IMPORT_ERROR = """
+{0} requires the SentencePiece library but it was not found in your environment. Check out the instructions on the
+installation page of its repo: https://github.com/google/sentencepiece#installation and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PROTOBUF_IMPORT_ERROR = """
+{0} requires the protobuf library but it was not found in your environment. Check out the instructions on the
+installation page of its repo: https://github.com/protocolbuffers/protobuf/tree/master/python#installation and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+FAISS_IMPORT_ERROR = """
+{0} requires the faiss library but it was not found in your environment. Check out the instructions on the
+installation page of its repo: https://github.com/facebookresearch/faiss/blob/master/INSTALL.md and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PYTORCH_IMPORT_ERROR = """
+{0} requires the PyTorch library but it was not found in your environment. Check out the instructions on the
+installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+TORCHVISION_IMPORT_ERROR = """
+{0} requires the Torchvision library but it was not found in your environment. Check out the instructions on the
+installation page: https://pytorch.org/get-started/locally/ and follow the ones that match your environment.
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+BS4_IMPORT_ERROR = """
+{0} requires the Beautiful Soup library but it was not found in your environment. You can install it with pip:
+`pip install beautifulsoup4`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SKLEARN_IMPORT_ERROR = """
+{0} requires the scikit-learn library but it was not found in your environment. You can install it with:
+```
+pip install -U scikit-learn
+```
+In a notebook or a colab, you can install it by executing a cell with
+```
+!pip install -U scikit-learn
+```
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+DETECTRON2_IMPORT_ERROR = """
+{0} requires the detectron2 library but it was not found in your environment. Check out the instructions on the
+installation page: https://github.com/facebookresearch/detectron2/blob/master/INSTALL.md and follow the ones
+that match your environment. Please note that you may need to restart your runtime after installation.
+"""
+
+
+LEVENSHTEIN_IMPORT_ERROR = """
+{0} requires the python-Levenshtein library but it was not found in your environment. You can install it with pip: `pip
+install python-Levenshtein`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+G2P_EN_IMPORT_ERROR = """
+{0} requires the g2p-en library but it was not found in your environment. You can install it with pip:
+`pip install g2p-en`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYTORCH_QUANTIZATION_IMPORT_ERROR = """
+{0} requires the pytorch-quantization library but it was not found in your environment. You can install it with pip:
+`pip install pytorch-quantization --extra-index-url https://pypi.ngc.nvidia.com`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TORCHAUDIO_IMPORT_ERROR = """
+{0} requires the torchaudio library but it was not found in your environment. Please install it and restart your
+runtime.
+"""
+
+# docstyle-ignore
+PANDAS_IMPORT_ERROR = """
+{0} requires the pandas library but it was not found in your environment. You can install it with pip as
+explained here: https://pandas.pydata.org/pandas-docs/stable/getting_started/install.html.
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+PHONEMIZER_IMPORT_ERROR = """
+{0} requires the phonemizer library but it was not found in your environment. You can install it with pip:
+`pip install phonemizer`. Please note that you may need to restart your runtime after installation.
+"""
+# docstyle-ignore
+UROMAN_IMPORT_ERROR = """
+{0} requires the uroman library but it was not found in your environment. You can install it with pip:
+`pip install uroman`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+SACREMOSES_IMPORT_ERROR = """
+{0} requires the sacremoses library but it was not found in your environment. You can install it with pip:
+`pip install sacremoses`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+SCIPY_IMPORT_ERROR = """
+{0} requires the scipy library but it was not found in your environment. You can install it with pip:
+`pip install scipy`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+SPEECH_IMPORT_ERROR = """
+{0} requires the torchaudio library but it was not found in your environment. You can install it with pip:
+`pip install torchaudio`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+TIMM_IMPORT_ERROR = """
+{0} requires the timm library but it was not found in your environment. You can install it with pip:
+`pip install timm`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+NATTEN_IMPORT_ERROR = """
+{0} requires the natten library but it was not found in your environment. You can install it by referring to:
+shi-labs.com/natten . You can also install it with pip (may take longer to build):
+`pip install natten`. Please note that you may need to restart your runtime after installation.
+"""
+
+NUMEXPR_IMPORT_ERROR = """
+{0} requires the numexpr library but it was not found in your environment. You can install it by referring to:
+https://numexpr.readthedocs.io/en/latest/index.html.
+"""
+
+
+# docstyle-ignore
+NLTK_IMPORT_ERROR = """
+{0} requires the NLTK library but it was not found in your environment. You can install it by referring to:
+https://www.nltk.org/install.html. Please note that you may need to restart your runtime after installation.
+"""
+
+
+# docstyle-ignore
+VISION_IMPORT_ERROR = """
+{0} requires the PIL library but it was not found in your environment. You can install it with pip:
+`pip install pillow`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYDANTIC_IMPORT_ERROR = """
+{0} requires the pydantic library but it was not found in your environment. You can install it with pip:
+`pip install pydantic`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+FASTAPI_IMPORT_ERROR = """
+{0} requires the fastapi library but it was not found in your environment. You can install it with pip:
+`pip install fastapi`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+UVICORN_IMPORT_ERROR = """
+{0} requires the uvicorn library but it was not found in your environment. You can install it with pip:
+`pip install uvicorn`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+OPENAI_IMPORT_ERROR = """
+{0} requires the openai library but it was not found in your environment. You can install it with pip:
+`pip install openai`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYTESSERACT_IMPORT_ERROR = """
+{0} requires the PyTesseract library but it was not found in your environment. You can install it with pip:
+`pip install pytesseract`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PYCTCDECODE_IMPORT_ERROR = """
+{0} requires the pyctcdecode library but it was not found in your environment. You can install it with pip:
+`pip install pyctcdecode`. Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+ACCELERATE_IMPORT_ERROR = """
+{0} requires the accelerate library >= {ACCELERATE_MIN_VERSION} it was not found in your environment.
+You can install or update it with pip: `pip install --upgrade accelerate`. Please note that you may need to restart your
+runtime after installation.
+"""
+
+# docstyle-ignore
+ESSENTIA_IMPORT_ERROR = """
+{0} requires essentia library. But that was not found in your environment. You can install them with pip:
+`pip install essentia==2.1b6.dev1034`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+LIBROSA_IMPORT_ERROR = """
+{0} requires the librosa library. But that was not found in your environment. You can install them with pip:
+`pip install librosa`
+Please note that you may need to restart your runtime after installation.
+"""
+
+# docstyle-ignore
+PRETTY_MIDI_IMPORT_ERROR = """
+{0} requires the pretty_midi library. But that was not found in your environment. You can install them with pip:
+`pip install pretty_midi`
+Please note that you may need to restart your runtime after installation.
+"""
+
+
+CYTHON_IMPORT_ERROR = """
+{0} requires the Cython library but it was not found in your environment. You can install it with pip: `pip install
+Cython`. Please note that you may need to restart your runtime after installation.
+"""
+
+RJIEBA_IMPORT_ERROR = """
+{0} requires the rjieba library but it was not found in your environment. You can install it with pip: `pip install
+rjieba`. Please note that you may need to restart your runtime after installation.
+"""
+
+PEFT_IMPORT_ERROR = """
+{0} requires the peft library but it was not found in your environment. You can install it with pip: `pip install
+peft`. Please note that you may need to restart your runtime after installation.
+"""
+
+JINJA_IMPORT_ERROR = """
+{0} requires the jinja library but it was not found in your environment. You can install it with pip: `pip install
+jinja2`. Please note that you may need to restart your runtime after installation.
+"""
+
+RICH_IMPORT_ERROR = """
+{0} requires the rich library but it was not found in your environment. You can install it with pip: `pip install
+rich`. Please note that you may need to restart your runtime after installation.
+"""
+
+MISTRAL_COMMON_IMPORT_ERROR = """
+{0} requires the mistral-common library but it was not found in your environment. You can install it with pip: `pip install mistral-common`. Please note that you may need to restart your runtime after installation.
+"""
+
+
+BACKENDS_MAPPING = OrderedDict(
+ [
+ ("av", (is_av_available, AV_IMPORT_ERROR)),
+ ("bs4", (is_bs4_available, BS4_IMPORT_ERROR)),
+ ("cv2", (is_cv2_available, CV2_IMPORT_ERROR)),
+ ("datasets", (is_datasets_available, DATASETS_IMPORT_ERROR)),
+ ("decord", (is_decord_available, DECORD_IMPORT_ERROR)),
+ ("detectron2", (is_detectron2_available, DETECTRON2_IMPORT_ERROR)),
+ ("essentia", (is_essentia_available, ESSENTIA_IMPORT_ERROR)),
+ ("faiss", (is_faiss_available, FAISS_IMPORT_ERROR)),
+ ("g2p_en", (is_g2p_en_available, G2P_EN_IMPORT_ERROR)),
+ ("pandas", (is_pandas_available, PANDAS_IMPORT_ERROR)),
+ ("phonemizer", (is_phonemizer_available, PHONEMIZER_IMPORT_ERROR)),
+ ("uroman", (is_uroman_available, UROMAN_IMPORT_ERROR)),
+ ("pretty_midi", (is_pretty_midi_available, PRETTY_MIDI_IMPORT_ERROR)),
+ ("levenshtein", (is_levenshtein_available, LEVENSHTEIN_IMPORT_ERROR)),
+ ("librosa", (is_librosa_available, LIBROSA_IMPORT_ERROR)),
+ ("protobuf", (is_protobuf_available, PROTOBUF_IMPORT_ERROR)),
+ ("pyctcdecode", (is_pyctcdecode_available, PYCTCDECODE_IMPORT_ERROR)),
+ ("pytesseract", (is_pytesseract_available, PYTESSERACT_IMPORT_ERROR)),
+ ("sacremoses", (is_sacremoses_available, SACREMOSES_IMPORT_ERROR)),
+ ("pytorch_quantization", (is_pytorch_quantization_available, PYTORCH_QUANTIZATION_IMPORT_ERROR)),
+ ("sentencepiece", (is_sentencepiece_available, SENTENCEPIECE_IMPORT_ERROR)),
+ ("sklearn", (is_sklearn_available, SKLEARN_IMPORT_ERROR)),
+ ("speech", (is_speech_available, SPEECH_IMPORT_ERROR)),
+ ("timm", (is_timm_available, TIMM_IMPORT_ERROR)),
+ ("torchaudio", (is_torchaudio_available, TORCHAUDIO_IMPORT_ERROR)),
+ ("natten", (is_natten_available, NATTEN_IMPORT_ERROR)),
+ ("nltk", (is_nltk_available, NLTK_IMPORT_ERROR)),
+ ("tokenizers", (is_tokenizers_available, TOKENIZERS_IMPORT_ERROR)),
+ ("torch", (is_torch_available, PYTORCH_IMPORT_ERROR)),
+ ("torchvision", (is_torchvision_available, TORCHVISION_IMPORT_ERROR)),
+ ("torchcodec", (is_torchcodec_available, TORCHCODEC_IMPORT_ERROR)),
+ ("vision", (is_vision_available, VISION_IMPORT_ERROR)),
+ ("scipy", (is_scipy_available, SCIPY_IMPORT_ERROR)),
+ ("accelerate", (is_accelerate_available, ACCELERATE_IMPORT_ERROR)),
+ ("cython", (is_cython_available, CYTHON_IMPORT_ERROR)),
+ ("rjieba", (is_rjieba_available, RJIEBA_IMPORT_ERROR)),
+ ("peft", (is_peft_available, PEFT_IMPORT_ERROR)),
+ ("jinja", (is_jinja_available, JINJA_IMPORT_ERROR)),
+ ("yt_dlp", (is_yt_dlp_available, YT_DLP_IMPORT_ERROR)),
+ ("rich", (is_rich_available, RICH_IMPORT_ERROR)),
+ ("pydantic", (is_pydantic_available, PYDANTIC_IMPORT_ERROR)),
+ ("fastapi", (is_fastapi_available, FASTAPI_IMPORT_ERROR)),
+ ("uvicorn", (is_uvicorn_available, UVICORN_IMPORT_ERROR)),
+ ("openai", (is_openai_available, OPENAI_IMPORT_ERROR)),
+ ("mistral-common", (is_mistral_common_available, MISTRAL_COMMON_IMPORT_ERROR)),
+ ]
+)
+
+
+def requires_backends(obj, backends):
+ """
+ Method that automatically raises in case the specified backends are not available. It is often used during class
+ initialization to ensure the required dependencies are installed:
+
+ ```py
+ requires_backends(self, ["torch"])
+ ```
+
+ The backends should be defined in the `BACKEND_MAPPING` defined in `transformers.utils.import_utils`.
+
+ Args:
+ obj: object to be checked
+ backends: list or tuple of backends to check.
+ """
+ if not isinstance(backends, list | tuple):
+ backends = [backends]
+
+ name = obj.__name__ if hasattr(obj, "__name__") else obj.__class__.__name__
+
+ failed = []
+ for backend in backends:
+ if isinstance(backend, Backend):
+ available, msg = backend.is_satisfied, backend.error_message
+ else:
+ available, msg = BACKENDS_MAPPING[backend]
+
+ if not available():
+ failed.append(msg.format(name))
+
+ if failed:
+ raise ImportError("".join(failed))
+
+
+class DummyObject(type):
+ """
+ Metaclass for the dummy objects. Any class inheriting from it will return the ImportError generated by
+ `requires_backend` each time a user tries to access any method of that class.
+ """
+
+ is_dummy = True
+
+ def __getattribute__(cls, key):
+ if (key.startswith("_") and key != "_from_config") or key == "is_dummy" or key == "mro" or key == "call":
+ return super().__getattribute__(key)
+ requires_backends(cls, cls._backends)
+
+
+BACKENDS_T = frozenset[str]
+IMPORT_STRUCTURE_T = dict[BACKENDS_T, dict[str, set[str]]]
+
+
+class _LazyModule(ModuleType):
+ """
+ Module class that surfaces all objects but only performs associated imports when the objects are requested.
+ """
+
+ # Very heavily inspired by optuna.integration._IntegrationModule
+ # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py
+ def __init__(
+ self,
+ name: str,
+ module_file: str,
+ import_structure: IMPORT_STRUCTURE_T,
+ module_spec: importlib.machinery.ModuleSpec | None = None,
+ extra_objects: dict[str, object] | None = None,
+ explicit_import_shortcut: dict[str, list[str]] | None = None,
+ ):
+ super().__init__(name)
+
+ self._object_missing_backend = {}
+ self._explicit_import_shortcut = explicit_import_shortcut if explicit_import_shortcut else {}
+
+ if any(isinstance(key, frozenset) for key in import_structure):
+ self._modules = set()
+ self._class_to_module = {}
+ self.__all__ = []
+
+ _import_structure = {}
+
+ for backends, module in import_structure.items():
+ missing_backends = []
+
+ # This ensures that if a module is importable, then all other keys of the module are importable.
+ # As an example, in module.keys() we might have the following:
+ #
+ # dict_keys(['models.nllb_moe.configuration_nllb_moe', 'models.sew_d.configuration_sew_d'])
+ #
+ # with this, we don't only want to be able to import these explicitly, we want to be able to import
+ # every intermediate module as well. Therefore, this is what is returned:
+ #
+ # {
+ # 'models.nllb_moe.configuration_nllb_moe',
+ # 'models.sew_d.configuration_sew_d',
+ # 'models',
+ # 'models.sew_d', 'models.nllb_moe'
+ # }
+
+ module_keys = set(
+ chain(*[[k.rsplit(".", i)[0] for i in range(k.count(".") + 1)] for k in list(module.keys())])
+ )
+
+ for backend in backends:
+ if backend in BACKENDS_MAPPING:
+ callable, _ = BACKENDS_MAPPING[backend]
+ else:
+ if any(key in backend for key in ["=", "<", ">"]):
+ backend = Backend(backend)
+ callable = backend.is_satisfied
+ else:
+ raise ValueError(
+ f"Backend should be defined in the BACKENDS_MAPPING. Offending backend: {backend}"
+ )
+
+ try:
+ if not callable():
+ missing_backends.append(backend)
+ except (ModuleNotFoundError, RuntimeError):
+ missing_backends.append(backend)
+
+ self._modules = self._modules.union(module_keys)
+
+ for key, values in module.items():
+ if missing_backends:
+ self._object_missing_backend[key] = missing_backends
+
+ for value in values:
+ self._class_to_module[value] = key
+ if missing_backends:
+ self._object_missing_backend[value] = missing_backends
+ _import_structure.setdefault(key, []).extend(values)
+
+ # Needed for autocompletion in an IDE
+ self.__all__.extend(module_keys | set(chain(*module.values())))
+
+ self.__file__ = module_file
+ self.__spec__ = module_spec
+ self.__path__ = [os.path.dirname(module_file)]
+ self._objects = {} if extra_objects is None else extra_objects
+ self._name = name
+ self._import_structure = _import_structure
+
+ # This can be removed once every exportable object has a `require()` require.
+ else:
+ self._modules = set(import_structure.keys())
+ self._class_to_module = {}
+ for key, values in import_structure.items():
+ for value in values:
+ self._class_to_module[value] = key
+ # Needed for autocompletion in an IDE
+ self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values()))
+ self.__file__ = module_file
+ self.__spec__ = module_spec
+ self.__path__ = [os.path.dirname(module_file)]
+ self._objects = {} if extra_objects is None else extra_objects
+ self._name = name
+ self._import_structure = import_structure
+
+ # Needed for autocompletion in an IDE
+ def __dir__(self):
+ result = list(super().__dir__())
+ # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether
+ # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir.
+ for attr in self.__all__:
+ if attr not in result:
+ result.append(attr)
+ return result
+
+ def __getattr__(self, name: str) -> Any:
+ if name in self._objects:
+ return self._objects[name]
+ if name in self._object_missing_backend:
+ missing_backends = self._object_missing_backend[name]
+
+ # Backward-compat fallback: before the image processor refactoring, the base
+ # `ImageProcessor` name referred to the PIL/slow backend. After the refactoring
+ # it refers to the TorchvisionBackend (which requires torchvision). So if torchvision
+ # is not installed, transparently fall back to `ImageProcessorPil` and warn once.
+ if "torchvision" in missing_backends and name.endswith("ImageProcessor"):
+ pil_name = f"{name}Pil"
+ if pil_name in self._class_to_module and pil_name not in self._object_missing_backend:
+ try:
+ pil_module = self._get_module(self._class_to_module[pil_name])
+ pil_value = getattr(pil_module, pil_name)
+ logger.warning_once(
+ f"`{name}` requires torchvision (not installed); falling back to `{pil_name}` "
+ f"for backward compatibility. Install torchvision to use the default backend, "
+ f"or import `{pil_name}` directly to silence this warning."
+ )
+ setattr(self, name, pil_value)
+ return pil_value
+ except Exception as e:
+ logger.debug(f"Could not load PIL fallback {pil_name}: {e}")
+
+ class Placeholder(metaclass=DummyObject):
+ _backends = missing_backends
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, missing_backends)
+
+ def call(self, *args, **kwargs):
+ pass
+
+ Placeholder.__name__ = name
+
+ if name not in self._class_to_module:
+ module_name = f"transformers.{name}"
+ else:
+ module_name = self._class_to_module[name]
+ if not module_name.startswith("transformers."):
+ module_name = f"transformers.{module_name}"
+
+ Placeholder.__module__ = module_name
+
+ value = Placeholder
+ elif name in self._class_to_module:
+ try:
+ module = self._get_module(self._class_to_module[name])
+ value = getattr(module, name)
+ except (ModuleNotFoundError, RuntimeError, AttributeError) as e:
+ # V5: If trying to import a *TokenizerFast symbol, transparently fall back to the
+ # non-Fast symbol from the same module when available. This lets us keep only one
+ # backend tokenizer class while preserving legacy public names.
+ if name.endswith("TokenizerFast"):
+ fallback_name = name[:-4]
+ # Prefer importing the module that declares the fallback symbol if known
+ try:
+ if fallback_name in self._class_to_module:
+ fb_module = self._get_module(self._class_to_module[fallback_name])
+ fallback_value = getattr(fb_module, fallback_name)
+ else:
+ module = self._get_module(self._class_to_module[name])
+ fallback_value = getattr(module, fallback_name)
+ setattr(self, fallback_name, fallback_value)
+ value = fallback_value
+ except Exception:
+ # If we can't find the fallback here, try converter logic as a last resort
+ # before giving up
+ value = None
+ # Try converter mapping for Fast tokenizers that don't exist
+ if value is None and name.endswith("TokenizerFast"):
+ lookup_name = name[:-4]
+ try:
+ from ..convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS
+
+ if lookup_name in SLOW_TO_FAST_CONVERTERS:
+ converter_class = SLOW_TO_FAST_CONVERTERS[lookup_name]
+ converter_base_name = converter_class.__name__.replace("Converter", "")
+ preferred_tokenizer_name = f"{converter_base_name}Tokenizer"
+
+ candidate_names = [preferred_tokenizer_name]
+ for tokenizer_name, tokenizer_converter in SLOW_TO_FAST_CONVERTERS.items():
+ if tokenizer_converter is converter_class and tokenizer_name != lookup_name:
+ if tokenizer_name not in candidate_names:
+ candidate_names.append(tokenizer_name)
+
+ # Try to import the preferred candidate directly
+ import importlib
+
+ for candidate_name in candidate_names:
+ base_tokenizer_class = None
+
+ # Try to derive module path from tokenizer name (e.g., "AlbertTokenizer" -> "albert")
+ # Remove "Tokenizer" suffix and convert to lowercase
+ if candidate_name.endswith("Tokenizer"):
+ model_name = candidate_name[:-10].lower() # Remove "Tokenizer"
+ module_path = f"transformers.models.{model_name}.tokenization_{model_name}"
+ try:
+ module = importlib.import_module(module_path)
+ base_tokenizer_class = getattr(module, candidate_name)
+ except Exception:
+ logger.debug(f"{module_path} does not have {candidate_name} defined.")
+
+ # Fallback: try via _class_to_module
+ if base_tokenizer_class is None and candidate_name in self._class_to_module:
+ try:
+ alias_module_name = self._class_to_module[candidate_name]
+ alias_module = self._get_module(alias_module_name)
+ base_tokenizer_class = getattr(alias_module, candidate_name)
+ except Exception:
+ logger.debug(
+ f"{alias_module_name} does not have {candidate_name} defined"
+ )
+
+ # If we still don't have base_tokenizer_class, skip this candidate
+ if base_tokenizer_class is None:
+ logger.debug(f"skipping candidate {candidate_name}")
+ continue
+
+ # If we got here, we have base_tokenizer_class
+ value = base_tokenizer_class
+
+ setattr(self, candidate_name, base_tokenizer_class)
+ if lookup_name != candidate_name:
+ setattr(self, lookup_name, value)
+ setattr(self, name, value)
+ break
+ except Exception as e:
+ logger.debug(f"Could not create tokenizer alias: {e}")
+
+ if value is None:
+ raise ModuleNotFoundError(
+ f"Could not import module '{name}'. Are this object's requirements defined correctly?"
+ ) from e
+ else:
+ raise ModuleNotFoundError(
+ f"Could not import module '{name}'. Are this object's requirements defined correctly?"
+ ) from e
+
+ elif name in self._modules:
+ try:
+ value = self._get_module(name)
+ except (ModuleNotFoundError, RuntimeError) as e:
+ raise ModuleNotFoundError(
+ f"Could not import module '{name}'. Are this object's requirements defined correctly?"
+ ) from e
+ else:
+ # V5: If a *TokenizerFast symbol is requested but not present in the import structure,
+ # try to resolve to the corresponding non-Fast symbol's module if available.
+ if name.endswith("TokenizerFast"):
+ fallback_name = name[:-4]
+ if fallback_name in self._class_to_module:
+ try:
+ fb_module = self._get_module(self._class_to_module[fallback_name])
+ value = getattr(fb_module, fallback_name)
+ setattr(self, fallback_name, value)
+ setattr(self, name, value)
+ return value
+ except Exception as e:
+ logger.debug(f"Could not load fallback {fallback_name}: {e}")
+ # V5: Handle *ImageProcessorFast backward compatibility
+ # Similar to TokenizerFast, but for image processors
+ if name.endswith("ImageProcessorFast"):
+ fallback_name = name[:-4] # Remove "Fast"
+ if fallback_name in self._class_to_module:
+ logger.warning_once(
+ f"`{name}` is deprecated. The `Fast` suffix for image processors has been removed; "
+ f"use `{fallback_name}` instead."
+ )
+ if fallback_name in self._object_missing_backend:
+ # The Fast alias has no entry in the import structure, so `requires_backends` on
+ # the real class never runs. Handle the missing backend explicitly here, otherwise
+ # `_get_module` swallows the ImportError and the caller gets an AttributeError.
+ # Do not fall through to the PIL fallback since a legacy "Fast" image processor was explicitly requested.
+ missing_backends = self._object_missing_backend[fallback_name]
+
+ class Placeholder(metaclass=DummyObject):
+ _backends = missing_backends
+
+ def __init__(self, *args, **kwargs):
+ requires_backends(self, missing_backends)
+
+ def call(self, *args, **kwargs):
+ pass
+
+ Placeholder.__name__ = fallback_name
+ module_name = self._class_to_module[fallback_name]
+ Placeholder.__module__ = (
+ module_name if module_name.startswith("transformers.") else f"transformers.{module_name}"
+ )
+ setattr(self, name, Placeholder)
+ return Placeholder
+ try:
+ fb_module = self._get_module(self._class_to_module[fallback_name])
+ value = getattr(fb_module, fallback_name)
+ setattr(self, fallback_name, value)
+ setattr(self, name, value)
+ return value
+ except Exception as e:
+ logger.debug(f"Could not load fallback {fallback_name}: {e}")
+ # V5: If a tokenizer class doesn't exist, check if it should alias to another tokenizer
+ # via the converter mapping (e.g., FNetTokenizer -> AlbertTokenizer via AlbertConverter)
+ value = None
+ if name.endswith("Tokenizer") or name.endswith("TokenizerFast"):
+ # Strip "Fast" suffix for converter lookup if present
+ lookup_name = name[:-4] if name.endswith("TokenizerFast") else name
+
+ try:
+ # Lazy import to avoid circular dependencies
+ from ..convert_slow_tokenizer import SLOW_TO_FAST_CONVERTERS
+
+ # Check if this tokenizer has a converter mapping
+ if lookup_name in SLOW_TO_FAST_CONVERTERS:
+ converter_class = SLOW_TO_FAST_CONVERTERS[lookup_name]
+
+ # Find which tokenizer class uses the same converter (reverse lookup)
+ # Prefer the tokenizer that matches the converter name pattern
+ # (e.g., AlbertConverter -> AlbertTokenizer)
+ converter_base_name = converter_class.__name__.replace("Converter", "")
+ preferred_tokenizer_name = f"{converter_base_name}Tokenizer"
+
+ # Try preferred tokenizer first
+ candidate_names = [preferred_tokenizer_name]
+ # Then try all other tokenizers with the same converter
+ for tokenizer_name, tokenizer_converter in SLOW_TO_FAST_CONVERTERS.items():
+ if tokenizer_converter is converter_class and tokenizer_name != lookup_name:
+ if tokenizer_name not in candidate_names:
+ candidate_names.append(tokenizer_name)
+
+ # Try to import one of the candidate tokenizers
+ for candidate_name in candidate_names:
+ if candidate_name in self._class_to_module:
+ try:
+ alias_module = self._get_module(self._class_to_module[candidate_name])
+ base_tokenizer_class = getattr(alias_module, candidate_name)
+ value = base_tokenizer_class
+
+ # Cache both names for future imports
+ setattr(self, candidate_name, base_tokenizer_class)
+ if lookup_name != candidate_name:
+ setattr(self, lookup_name, value)
+ setattr(self, name, value)
+ break
+ except Exception:
+ # If this candidate fails, try the next one
+ continue
+ else:
+ # Candidate not in _class_to_module - might need recursive resolution
+ # Try importing it directly to trigger lazy loading
+ try:
+ # Try to get it from transformers module to trigger lazy loading
+ transformers_module = sys.modules.get("transformers")
+ if transformers_module and hasattr(transformers_module, candidate_name):
+ base_tokenizer_class = getattr(transformers_module, candidate_name)
+ value = base_tokenizer_class
+
+ if lookup_name != candidate_name:
+ setattr(self, lookup_name, value)
+ setattr(self, name, value)
+ break
+ except Exception:
+ continue
+ except (ImportError, AttributeError):
+ pass
+
+ if value is None:
+ for key, values in self._explicit_import_shortcut.items():
+ if name in values:
+ value = self._get_module(key)
+ break
+
+ if value is None:
+ raise AttributeError(f"module {self.__name__} has no attribute {name}")
+
+ setattr(self, name, value)
+ return value
+
+ def _get_module(self, module_name: str):
+ try:
+ return importlib.import_module("." + module_name, self.__name__)
+ except Exception as e:
+ raise e
+
+ def __reduce__(self):
+ return (self.__class__, (self._name, self.__file__, self._import_structure))
+
+
+class OptionalDependencyNotAvailable(BaseException):
+ """Internally used error class for signalling an optional dependency was not found."""
+
+
+def direct_transformers_import(path: str, file="__init__.py") -> ModuleType:
+ """Imports transformers directly
+
+ Args:
+ path (`str`): The path to the source file
+ file (`str`, *optional*): The file to join with the path. Defaults to "__init__.py".
+
+ Returns:
+ `ModuleType`: The resulting imported module
+ """
+ name = "transformers"
+ location = os.path.join(path, file)
+ spec = importlib.util.spec_from_file_location(name, location, submodule_search_locations=[path])
+ if spec is not None and spec.loader is not None:
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ module = sys.modules[name]
+ return module
+ raise ImportError(f"Could not load module {name} from {location}")
+
+
+class VersionComparison(Enum):
+ EQUAL = operator.eq
+ NOT_EQUAL = operator.ne
+ GREATER_THAN = operator.gt
+ LESS_THAN = operator.lt
+ GREATER_THAN_OR_EQUAL = operator.ge
+ LESS_THAN_OR_EQUAL = operator.le
+
+ @staticmethod
+ def from_string(version_string: str) -> "VersionComparison":
+ string_to_operator = {
+ "=": VersionComparison.EQUAL,
+ "==": VersionComparison.EQUAL,
+ "!=": VersionComparison.NOT_EQUAL,
+ ">": VersionComparison.GREATER_THAN,
+ "<": VersionComparison.LESS_THAN,
+ ">=": VersionComparison.GREATER_THAN_OR_EQUAL,
+ "<=": VersionComparison.LESS_THAN_OR_EQUAL,
+ }
+
+ return string_to_operator[version_string]
+
+
+@lru_cache
+def split_package_version(package_version_str) -> tuple[str, str, str]:
+ pattern = r"([a-zA-Z0-9_-]+)([!<>=~]+)([0-9.]+)"
+ match = re.match(pattern, package_version_str)
+ if match:
+ return (match.group(1), match.group(2), match.group(3))
+ else:
+ raise ValueError(f"Invalid package version string: {package_version_str}")
+
+
+class Backend:
+ def __init__(self, backend_requirement: str):
+ self.package_name, self.version_comparison, self.version = split_package_version(backend_requirement)
+
+ if self.package_name not in BACKENDS_MAPPING:
+ raise ValueError(
+ f"Backends should be defined in the BACKENDS_MAPPING. Offending backend: {self.package_name}"
+ )
+
+ def get_installed_version(self) -> str:
+ """Return the currently installed version of the backend"""
+ is_available, current_version = _is_package_available(self.package_name, return_version=True)
+ if not is_available:
+ raise RuntimeError(f"Backend {self.package_name} is not available.")
+ return current_version
+
+ def is_satisfied(self) -> bool:
+ return VersionComparison.from_string(self.version_comparison).value(
+ version.parse(self.get_installed_version()), version.parse(self.version)
+ )
+
+ def __repr__(self) -> str:
+ return f'Backend("{self.package_name}", {VersionComparison[self.version_comparison]}, "{self.version}")'
+
+ @property
+ def error_message(self):
+ return (
+ f"{{0}} requires the {self.package_name} library version {self.version_comparison}{self.version}. That"
+ f" library was not found with this version in your environment."
+ )
+
+
+def requires(*, backends=()):
+ """
+ This decorator enables two things:
+ - Attaching a `__backends` tuple to an object to see what are the necessary backends for it
+ to execute correctly without instantiating it
+ - The '@requires' string is used to dynamically import objects
+ """
+
+ if not isinstance(backends, (tuple, list)):
+ raise TypeError("Backends should be a tuple or list.")
+ backends = tuple(backends)
+
+ applied_backends = []
+ for backend in backends:
+ if backend in BACKENDS_MAPPING:
+ applied_backends.append(backend)
+ else:
+ if any(key in backend for key in ["=", "<", ">"]):
+ applied_backends.append(Backend(backend))
+ else:
+ raise ValueError(f"Backend should be defined in the BACKENDS_MAPPING. Offending backend: {backend}")
+
+ def inner_fn(fun):
+ if isinstance(fun, type):
+ # For classes, just attach the metadata — don't wrap, as that would
+ # turn the class into a plain function and break isinstance checks.
+ fun.__backends = applied_backends
+ return fun
+
+ @functools.wraps(fun)
+ def wrapper(*args, **kwargs):
+ requires_backends(fun, applied_backends)
+ return fun(*args, **kwargs)
+
+ wrapper.__backends = applied_backends # type: ignore [unresolved-attribute]
+ return wrapper
+
+ return inner_fn
+
+
+BASE_FILE_REQUIREMENTS = {
+ lambda name, content: "modeling_" in name: ("torch",),
+ lambda name, content: "tokenization_" in name and name.endswith("_fast"): ("tokenizers",),
+ lambda name, content: "image_processing_" in name and "TorchvisionBackend" in content: (
+ "vision",
+ "torch",
+ "torchvision",
+ ),
+ lambda name, content: "image_processing_" in name: ("vision",),
+ lambda name, content: "video_processing_" in name: ("vision", "torch", "torchvision"),
+}
+
+
+def fetch__all__(file_content) -> list[str]:
+ """
+ Returns the content of the __all__ variable in the file content.
+ Returns None if not defined, otherwise returns a list of strings.
+ """
+
+ if "__all__" not in file_content:
+ return []
+
+ start_index = None
+ lines = file_content.splitlines()
+ for index, line in enumerate(lines):
+ if line.startswith("__all__"):
+ start_index = index
+
+ # There is no line starting with `__all__`
+ if start_index is None:
+ return []
+
+ lines = lines[start_index:]
+
+ if not lines[0].startswith("__all__"):
+ raise ValueError(
+ "fetch__all__ accepts a list of lines, with the first line being the __all__ variable declaration"
+ )
+
+ # __all__ is defined on a single line
+ if lines[0].endswith("]"):
+ return [obj.strip("\"' ") for obj in lines[0].split("=")[1].strip(" []").split(",")]
+
+ # __all__ is defined on multiple lines
+ else:
+ _all: list[str] = []
+ for __all__line_index in range(1, len(lines)):
+ if lines[__all__line_index].strip() == "]":
+ return _all
+ else:
+ _all.append(lines[__all__line_index].strip("\"', "))
+
+ return _all
+
+
+@lru_cache
+def create_import_structure_from_path(module_path):
+ """
+ This method takes the path to a file/a folder and returns the import structure.
+ If a file is given, it will return the import structure of the parent folder.
+
+ Import structures are designed to be digestible by `_LazyModule` objects. They are
+ created from the __all__ definitions in each files as well as the `@require` decorators
+ above methods and objects.
+
+ The import structure allows explicit display of the required backends for a given object.
+ These backends are specified in two ways:
+
+ 1. Through their `@require`, if they are exported with that decorator. This `@require` decorator
+ accepts a `backend` tuple kwarg mentioning which backends are required to run this object.
+
+ 2. If an object is defined in a file with "default" backends, it will have, at a minimum, this
+ backend specified. The default backends are defined according to the filename:
+
+ - If a file is named like `modeling_*.py`, it will have a `torch` backend
+ - If a file is named like `tokenization_*_fast.py`, it will have a `tokenizers` backend
+ - If a file is named like `image_processing*_fast.py`, it will have a `torchvision` + `torch` backend
+
+ Backends serve the purpose of displaying a clear error message to the user in case the backends are not installed.
+ Should an object be imported without its required backends being in the environment, any attempt to use the
+ object will raise an error mentioning which backend(s) should be added to the environment in order to use
+ that object.
+
+ Here's an example of an input import structure at the src.transformers.models level:
+
+ {
+ 'albert': {
+ frozenset(): {
+ 'configuration_albert': {'AlbertConfig'}
+ },
+ frozenset({'tokenizers'}): {
+ 'tokenization_albert_fast': {'AlbertTokenizer'}
+ },
+ },
+ 'align': {
+ frozenset(): {
+ 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'processing_align': {'AlignProcessor'}
+ },
+ },
+ 'altclip': {
+ frozenset(): {
+ 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'processing_altclip': {'AltCLIPProcessor'},
+ }
+ }
+ }
+ """
+ import_structure = {}
+
+ if os.path.isfile(module_path):
+ module_path = os.path.dirname(module_path)
+
+ adjacent_modules = []
+
+ with os.scandir(module_path) as entries:
+ for entry in entries:
+ if entry.name == "__pycache__":
+ continue
+ if entry.is_dir():
+ import_structure[entry.name] = create_import_structure_from_path(entry.path)
+ elif not entry.name.startswith(("convert_", "modular_")):
+ adjacent_modules.append(entry.name)
+
+ # We're only taking a look at files different from __init__.py
+ # We could theoretically require things directly from the __init__.py
+ # files, but this is not supported at this time.
+ if "__init__.py" in adjacent_modules:
+ adjacent_modules.remove("__init__.py")
+
+ module_requirements = {}
+ for module_name in adjacent_modules:
+ # Only modules ending in `.py` are accepted here.
+ if not module_name.endswith(".py"):
+ continue
+
+ with open(os.path.join(module_path, module_name), encoding="utf-8") as f:
+ file_content = f.read()
+
+ # Remove the .py suffix
+ module_name = module_name[:-3]
+
+ previous_line = ""
+ previous_index = 0
+
+ # Some files have some requirements by default.
+ # For example, any file named `modeling_xxx.py`
+ # should have torch as a required backend.
+ base_requirements = ()
+ for check, requirements in BASE_FILE_REQUIREMENTS.items():
+ if check(module_name, file_content):
+ base_requirements = requirements
+ break
+
+ # Objects that have a `@require` assigned to them will get exported
+ # with the backends specified in the decorator as well as the file backends.
+ exported_objects = set()
+ if "@requires" in file_content:
+ lines = file_content.split("\n")
+ for index, line in enumerate(lines):
+ # This allows exporting items with other decorators. We'll take a look
+ # at the line that follows at the same indentation level.
+ if line.startswith((" ", "\t", "@", ")")) and not line.startswith("@requires"):
+ continue
+
+ # Skipping line enables putting whatever we want between the
+ # requires() call and the actual class/method definition.
+ # This is what enables having # Copied from statements, docs, etc.
+ skip_line = False
+
+ if "@requires" in previous_line:
+ skip_line = False
+
+ # Backends are defined on the same line as requires
+ if "backends" in previous_line:
+ try:
+ backends_string = previous_line.split("backends=")[1].split("(")[1].split(")")[0]
+ except IndexError:
+ raise ValueError(
+ f"Couldn't parse backends for @requires decorator in file {module_name}:{previous_line}"
+ )
+ backends = tuple(sorted([b.strip("'\",") for b in backends_string.split(", ") if b]))
+
+ # Backends are defined in the lines following requires, for example such as:
+ # @requires(
+ # backends=(
+ # "sentencepiece",
+ # "torch",
+ # )
+ # )
+ #
+ # or
+ #
+ # @requires(
+ # backends=(
+ # "sentencepiece",
+ # )
+ # )
+ elif "backends" in lines[previous_index + 1]:
+ backends = []
+ for backend_line in lines[previous_index:index]:
+ if "backends" in backend_line:
+ backend_line = backend_line.split("=")[1]
+ if '"' in backend_line or "'" in backend_line:
+ if ", " in backend_line:
+ backends.extend(backend.strip("()\"', ") for backend in backend_line.split(", "))
+ else:
+ backends.append(backend_line.strip("()\"', "))
+
+ # If the line is only a ')', then we reached the end of the backends and we break.
+ if backend_line.strip() == ")":
+ break
+ backends = tuple(backends)
+
+ # No backends are registered for requires
+ else:
+ backends = ()
+
+ backends = frozenset(backends + base_requirements)
+ if backends not in module_requirements:
+ module_requirements[backends] = {}
+ if module_name not in module_requirements[backends]:
+ module_requirements[backends][module_name] = set()
+
+ if not line.startswith("class") and not line.startswith("def"):
+ skip_line = True
+ else:
+ start_index = 6 if line.startswith("class") else 4
+ object_name = line[start_index:].split("(")[0].strip(":")
+ module_requirements[backends][module_name].add(object_name)
+ exported_objects.add(object_name)
+
+ if not skip_line:
+ previous_line = line
+ previous_index = index
+
+ # All objects that are in __all__ should be exported by default.
+ # These objects are exported with the file backends.
+ if "__all__" in file_content:
+ for _all_object in fetch__all__(file_content):
+ if _all_object not in exported_objects:
+ backends = frozenset(base_requirements)
+ if backends not in module_requirements:
+ module_requirements[backends] = {}
+ if module_name not in module_requirements[backends]:
+ module_requirements[backends][module_name] = set()
+
+ module_requirements[backends][module_name].add(_all_object)
+
+ import_structure = {**module_requirements, **import_structure}
+ return import_structure
+
+
+def spread_import_structure(nested_import_structure):
+ """
+ This method takes as input an unordered import structure and brings the required backends at the top-level,
+ aggregating modules and objects under their required backends.
+
+ Here's an example of an input import structure at the src.transformers.models level:
+
+ {
+ 'albert': {
+ frozenset(): {
+ 'configuration_albert': {'AlbertConfig'}
+ },
+ frozenset({'tokenizers'}): {
+ 'tokenization_albert_fast': {'AlbertTokenizer'}
+ },
+ },
+ 'align': {
+ frozenset(): {
+ 'configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'processing_align': {'AlignProcessor'}
+ },
+ },
+ 'altclip': {
+ frozenset(): {
+ 'configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'processing_altclip': {'AltCLIPProcessor'},
+ }
+ }
+ }
+
+ Here's an example of an output import structure at the src.transformers.models level:
+
+ {
+ frozenset({'tokenizers'}): {
+ 'albert.tokenization_albert_fast': {'AlbertTokenizer'}
+ },
+ frozenset(): {
+ 'albert.configuration_albert': {'AlbertConfig'},
+ 'align.processing_align': {'AlignProcessor'},
+ 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'altclip.processing_altclip': {'AltCLIPProcessor'}
+ }
+ }
+
+ """
+
+ def propagate_frozenset(unordered_import_structure):
+ frozenset_first_import_structure = {}
+ for _key, _value in unordered_import_structure.items():
+ # If the value is not a dict but a string, no need for custom manipulation
+ if not isinstance(_value, dict):
+ frozenset_first_import_structure[_key] = _value
+
+ elif any(isinstance(v, frozenset) for v in _value):
+ for k, v in _value.items():
+ if isinstance(k, frozenset):
+ # Here we want to switch around _key and k to propagate k upstream if it is a frozenset
+ if k not in frozenset_first_import_structure:
+ frozenset_first_import_structure[k] = {}
+ if _key not in frozenset_first_import_structure[k]:
+ frozenset_first_import_structure[k][_key] = {}
+
+ frozenset_first_import_structure[k][_key].update(v)
+
+ else:
+ # If k is not a frozenset, it means that the dictionary is not "level": some keys (top-level)
+ # are frozensets, whereas some are not -> frozenset keys are at an unknown depth-level of the
+ # dictionary.
+ #
+ # We recursively propagate the frozenset for this specific dictionary so that the frozensets
+ # are at the top-level when we handle them.
+ propagated_frozenset = propagate_frozenset({k: v})
+ for r_k, r_v in propagated_frozenset.items():
+ if isinstance(_key, frozenset):
+ if r_k not in frozenset_first_import_structure:
+ frozenset_first_import_structure[r_k] = {}
+ if _key not in frozenset_first_import_structure[r_k]:
+ frozenset_first_import_structure[r_k][_key] = {}
+
+ # _key is a frozenset -> we switch around the r_k and _key
+ frozenset_first_import_structure[r_k][_key].update(r_v)
+ else:
+ if _key not in frozenset_first_import_structure:
+ frozenset_first_import_structure[_key] = {}
+ if r_k not in frozenset_first_import_structure[_key]:
+ frozenset_first_import_structure[_key][r_k] = {}
+
+ # _key is not a frozenset -> we keep the order of r_k and _key
+ frozenset_first_import_structure[_key][r_k].update(r_v)
+
+ else:
+ frozenset_first_import_structure[_key] = propagate_frozenset(_value)
+
+ return frozenset_first_import_structure
+
+ def flatten_dict(_dict, previous_key=None):
+ items = []
+ for _key, _value in _dict.items():
+ _key = f"{previous_key}.{_key}" if previous_key is not None else _key
+ if isinstance(_value, dict):
+ items.extend(flatten_dict(_value, _key).items())
+ else:
+ items.append((_key, _value))
+ return dict(items)
+
+ # The tuples contain the necessary backends. We want these first, so we propagate them up the
+ # import structure.
+ ordered_import_structure = nested_import_structure
+
+ # 6 is a number that gives us sufficient depth to go through all files and foreseeable folder depths
+ # while not taking too long to parse.
+ for i in range(6):
+ ordered_import_structure = propagate_frozenset(ordered_import_structure)
+
+ # We then flatten the dict so that it references a module path.
+ flattened_import_structure = {}
+ for key, value in ordered_import_structure.copy().items():
+ if isinstance(key, str):
+ del ordered_import_structure[key]
+ else:
+ flattened_import_structure[key] = flatten_dict(value)
+
+ return flattened_import_structure
+
+
+@lru_cache
+def define_import_structure(module_path: str, prefix: str | None = None) -> IMPORT_STRUCTURE_T:
+ """
+ This method takes a module_path as input and creates an import structure digestible by a _LazyModule.
+
+ Here's an example of an output import structure at the src.transformers.models level:
+
+ {
+ frozenset({'tokenizers'}): {
+ 'albert.tokenization_albert_fast': {'AlbertTokenizer'}
+ },
+ frozenset(): {
+ 'albert.configuration_albert': {'AlbertConfig'},
+ 'align.processing_align': {'AlignProcessor'},
+ 'align.configuration_align': {'AlignConfig', 'AlignTextConfig', 'AlignVisionConfig'},
+ 'altclip.configuration_altclip': {'AltCLIPConfig', 'AltCLIPTextConfig', 'AltCLIPVisionConfig'},
+ 'altclip.processing_altclip': {'AltCLIPProcessor'}
+ }
+ }
+
+ The import structure is a dict defined with frozensets as keys, and dicts of strings to sets of objects.
+
+ If `prefix` is not None, it will add that prefix to all keys in the returned dict.
+ """
+ import_structure = create_import_structure_from_path(module_path)
+ spread_dict = spread_import_structure(import_structure)
+
+ if prefix is None:
+ return spread_dict
+ else:
+ spread_dict = {k: {f"{prefix}.{kk}": vv for kk, vv in v.items()} for k, v in spread_dict.items()}
+ return spread_dict
+
+
+def clear_import_cache() -> None:
+ """
+ Clear cached Transformers modules to allow reloading modified code.
+
+ This is useful when actively developing/modifying Transformers code.
+ """
+ # Get all transformers modules
+ transformers_modules = [mod_name for mod_name in sys.modules if mod_name.startswith("transformers.")]
+
+ # Remove them from sys.modules
+ for mod_name in transformers_modules:
+ module = sys.modules[mod_name]
+ # Clear _LazyModule caches if applicable
+ if isinstance(module, _LazyModule):
+ module._objects = {} # Clear cached objects
+ del sys.modules[mod_name]
+
+ # Force reload main transformers module
+ if "transformers" in sys.modules:
+ main_module = sys.modules["transformers"]
+ if isinstance(main_module, _LazyModule):
+ main_module._objects = {} # Clear cached objects
+ importlib.reload(main_module)
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/kernel_config.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/kernel_config.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb4f965ddbf4b22cb61dc465832af338478eb2f5
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/kernel_config.py
@@ -0,0 +1,281 @@
+# 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.
+
+from ..utils import PushToHubMixin
+
+
+def infer_device(model):
+ """
+ Infers the device type from the model parameters.
+ Args:
+ model: The model instance.
+
+ Returns:
+ The device type.
+ """
+ EXAMPLE_MAPPING = """
+ {
+ "RMSNorm": {
+ "cuda":
+ "kernels-community/layer_norm:LlamaRMSNorm",
+ ...
+ },
+ ...
+ }
+ """
+ try:
+ param = next(model.parameters())
+ except StopIteration:
+ raise ValueError(
+ f"Cannot determine model device, please provide a device to the mapping. Example: {EXAMPLE_MAPPING}"
+ )
+
+ dev_type = param.device.type
+ if dev_type == "cuda":
+ # Refine based on actual platform
+ from ..utils import is_torch_available
+
+ if is_torch_available():
+ import torch
+
+ if getattr(torch, "version").hip is not None:
+ return "rocm"
+
+ return dev_type
+
+
+def add_to_mapping(layer_name, device, repo_name, mode, compatible_mapping):
+ from kernels import LayerRepository
+
+ if device not in ["cuda", "rocm", "xpu", "npu", "neuron"]:
+ raise ValueError(f"Only cuda, rocm, xpu, npu and neuron devices supported, got: {device}")
+ repo_layer_name = repo_name.split(":")[1]
+ repo_id = repo_name.split(":")[0]
+ compatible_mapping[layer_name] = {
+ device: {
+ mode: LayerRepository(
+ repo_id=repo_id,
+ layer_name=repo_layer_name,
+ )
+ }
+ }
+
+
+def add_to_mapping_local(layer_name, device, repo_name, mode, compatible_mapping):
+ from pathlib import Path
+
+ from kernels import LocalLayerRepository
+
+ if device not in ["cuda", "rocm", "xpu", "npu", "neuron"]:
+ raise ValueError(f"Only cuda, rocm, xpu, npu and neuron devices supported, got: {device}")
+ repo_layer_name = repo_name.split(":")[1]
+ repo_path = repo_name.split(":")[0]
+ repo_package_name = repo_path.split("/")[-1]
+ compatible_mapping[layer_name] = {
+ device: {
+ mode: LocalLayerRepository(
+ repo_path=Path(repo_path),
+ package_name=repo_package_name,
+ layer_name=repo_layer_name,
+ )
+ }
+ }
+
+
+class KernelConfig(PushToHubMixin):
+ """
+ Kernel configuration class. This class is used to configure the kernel mapping for a model.
+ """
+
+ def __init__(self, kernel_mapping=None, use_local_kernel=False):
+ self.kernel_mapping = kernel_mapping if kernel_mapping is not None else {}
+ self.registered_layer_names = {}
+ self.use_local_kernel = use_local_kernel
+
+ def update_kernel(self, repo_id, registered_name, layer_name, device, mode, revision=None):
+ from kernels import LayerRepository
+
+ self.kernel_mapping[registered_name] = {
+ device: {
+ mode: LayerRepository(
+ repo_id=repo_id,
+ layer_name=layer_name,
+ revision=revision,
+ )
+ }
+ }
+
+ def store_registered_layer_names(self, model):
+ for name, module in model.named_modules():
+ if hasattr(module, "kernel_layer_name"):
+ self.registered_layer_names[name] = module.kernel_layer_name
+
+ def sanitize_kernel_mapping(self, model):
+ """
+ Validates the kernel_mapping to ensure that:
+ 1. Each layer_name in the mapping is registered in the model (i.e., the model contains a module with a matching kernel_layer_name).
+ 2. Each kernel value is either a string of the form 'org/repo:layer_name' or a dict mapping device types ("cuda", "rocm", "xpu", "npu") to such strings.
+ 3. Each device key in a dict is one of "cuda", "rocm", "xpu", or "npu".
+ 4. Each repo_name is a valid repository and layer name in the format 'org/repo:layer_name' (i.e., a string containing both a slash and a colon).
+ 5. If a local path is detected, it should be in the format '/abs/path:layer_name'. The absolute path must include the `package_name`, like "/home/user/layer_norm".
+
+ Args:
+ model: The model instance whose modules are checked for registered kernel_layer_name attributes.
+
+ Raises:
+ ValueError: If a layer_name is not registered in the model, if a device is not supported,
+ or if a repo_name is not a valid 'org/repo:layer_name' string.
+ """
+ MAPPING_FORMAT = """
+ For single device form remote
+ {
+ "RMSNorm":
+ "kernels-community/layer_norm:LlamaRMSNorm",
+ ...
+ },
+ For multiple devices form remote
+ {
+ "RMSNorm": {
+ "cuda":
+ "kernels-community/layer_norm:LlamaRMSNorm",
+ "rocm":
+ "kernels-community/layer_norm:LlamaRMSNorm",
+ ...
+ },
+ ...
+ }
+ For single device form local
+ {
+ "RMSNorm":
+ "/abs/path:LlamaRMSNorm",
+ ...
+ },
+ For multiple devices form local
+ {
+ "RMSNorm": {
+ "cuda":
+ "/abs/path:LlamaRMSNorm",
+ "rocm":
+ "/abs/path:LlamaRMSNorm",
+ ...
+ },
+ ...
+ }
+ """
+ self.store_registered_layer_names(model)
+ # Validate that the kernel mapping is a dict
+ if not isinstance(self.kernel_mapping, dict):
+ raise ValueError(
+ f"Kernel mapping must be a dict of the following format: {MAPPING_FORMAT}, got: {type(self.kernel_mapping)}"
+ )
+
+ for layer_name, kernel in self.kernel_mapping.items():
+ if layer_name not in self.registered_layer_names.values():
+ raise ValueError(
+ f"Layer {layer_name} is not registered in the model, please register it first using use_kernel_forward_from_hub"
+ )
+
+ if isinstance(kernel, str):
+ if "/" not in kernel or ":" not in kernel:
+ raise ValueError(
+ f"Kernel mapping for '{layer_name}' must be a valid repo name with a layer name (e.g., 'org/repo:layer_name' or '/abs/path:layer_name'), got: {kernel}"
+ )
+
+ elif isinstance(kernel, dict):
+ for device, repo_name in kernel.items():
+ if device not in ["cuda", "rocm", "xpu", "npu", "neuron"]:
+ raise ValueError(f"Only cuda, rocm, xpu, npu and neuron devices supported, got: {device}")
+
+ if not isinstance(repo_name, str) or "/" not in repo_name or ":" not in repo_name:
+ raise ValueError(
+ f"Kernel mapping for '{layer_name}' must be a valid repo name with a layer name (e.g., 'org/repo:layer_name' or '/abs/path:layer_name'), got: {repo_name}"
+ )
+ else:
+ raise ValueError(f"Kernel mapping must follow the format: {MAPPING_FORMAT}, got: {kernel}")
+
+ def create_compatible_mapping(self, model, compile=False):
+ """
+ Transforms a simple kernel_mapping of the form:
+ {
+ "RMSNorm":
+ "kernels-community/layer_norm:LlamaRMSNorm",
+ ...
+ },
+
+ or for local path:
+
+ {
+ "RMSNorm":
+ "/home/user/liger_kernels:LigerRMSNorm",
+ ...
+ },
+
+ into a nested mapping:
+
+ {
+ "RMSNorm": {
+ "cuda": {
+ Mode.INFERENCE: LayerRepository(
+ repo_id="kernels-community/layer_norm",
+ layer_name="LlamaRMSNorm",
+ )
+ }
+ }
+ }
+
+ or for local path:
+
+ {
+ "RMSNorm": {
+ "cuda": {
+ Mode.INFERENCE: LocalLayerRepository(
+ repo_path=Path("/home/user/liger_kernels"),
+ package_name="liger_kernels",
+ layer_name="LigerRMSNorm",
+ )
+ }
+ }
+ }
+
+ that's compatible with the kernels library.
+
+ The device is inferred from the model's parameters if not provided.
+ The Mode is inferred from the model's training state.
+ """
+ from kernels import Mode
+
+ compatible_mapping = {}
+ current_device = infer_device(model)
+ for layer_name, kernel in self.kernel_mapping.items():
+ # Infer Mode: use Mode.TRAINING if model is training, else use Mode.INFERENCE
+ mode = Mode.TRAINING if model.training else Mode.INFERENCE
+ if compile:
+ mode = mode | Mode.TORCH_COMPILE
+
+ if isinstance(kernel, str):
+ repo_name = kernel
+ if not self.use_local_kernel:
+ add_to_mapping(layer_name, current_device, repo_name, mode, compatible_mapping)
+ else:
+ add_to_mapping_local(layer_name, current_device, repo_name, mode, compatible_mapping)
+ elif isinstance(kernel, dict):
+ for device, repo_name in kernel.items():
+ if device != current_device:
+ continue
+ if not self.use_local_kernel:
+ add_to_mapping(layer_name, device, repo_name, mode, compatible_mapping)
+ else:
+ add_to_mapping_local(layer_name, device, repo_name, mode, compatible_mapping)
+
+ self.kernel_mapping = compatible_mapping
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/loading_report.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/loading_report.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e6ffcb77da4211bad1e8074cf28ed46181fc402
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/loading_report.py
@@ -0,0 +1,280 @@
+# 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.
+import logging
+import re
+import shutil
+import sys
+from collections import OrderedDict, defaultdict
+from dataclasses import dataclass
+from typing import Any
+
+
+_DIGIT_RX = re.compile(r"(?<=\.)(\d+)(?=\.|$)") # numbers between dots or at the end
+
+
+def _pattern_of(key: str) -> str:
+ """Replace every dot-delimited integer with '*' to get the structure."""
+ return _DIGIT_RX.sub("*", key)
+
+
+def _fmt_indices(values: list[int], cutoff=10) -> str:
+ """Format a list of ints as single number, {a, ..., b}, or first...last."""
+ if len(values) == 1:
+ return str(values[0])
+ values = sorted(values)
+ if len(values) > cutoff:
+ return f"{values[0]}...{values[-1]}"
+ return ", ".join(map(str, values))
+
+
+def update_key_name(mapping: dict[str, Any]) -> dict[str, Any]:
+ """
+ Merge keys like 'layers.0.x', 'layers.1.x' into 'layers.{0, 1}.x'
+ BUT only merge together keys that have the exact same value.
+ Returns a new dict {merged_key: value}.
+ """
+ # (pattern, value) -> list[set[int]] (per-star index values)
+ not_mapping = False
+ if not isinstance(mapping, dict):
+ mapping = {k: k for k in mapping}
+ not_mapping = True
+
+ bucket: dict[str, list[set[int] | Any]] = defaultdict(list)
+ for key, val in mapping.items():
+ digs = _DIGIT_RX.findall(key)
+ patt = _pattern_of(key)
+ for i, d in enumerate(digs):
+ if len(bucket[patt]) <= i:
+ bucket[patt].append(set())
+ bucket[patt][i].add(int(d))
+ bucket[patt].append(val)
+
+ out_items = {}
+ for patt, values in bucket.items():
+ sets, val = values[:-1], values[-1]
+ parts = patt.split("*") # stars are between parts
+ final = parts[0]
+ for i in range(1, len(parts)):
+ if i - 1 < len(sets) and sets[i - 1]:
+ insert = _fmt_indices(sorted(sets[i - 1]))
+ if len(sets[i - 1]) > 1:
+ final += "{" + insert + "}"
+ else:
+ final += insert
+ else:
+ final += "*"
+ final += parts[i]
+
+ out_items[final] = val
+ out = OrderedDict(out_items)
+ if not_mapping:
+ return out.keys()
+ return out
+
+
+_ansi_re = re.compile(r"\x1b\[[0-9;]*m")
+
+
+def _strip_ansi(s: str) -> str:
+ return _ansi_re.sub("", str(s))
+
+
+def _pad(text, width):
+ t = str(text)
+ pad = max(0, width - len(_strip_ansi(t)))
+ return t + " " * pad
+
+
+def _make_table(rows, headers):
+ # compute display widths while ignoring ANSI codes
+ cols = list(zip(*([headers] + rows))) if rows else [headers]
+ widths = [max(len(_strip_ansi(x)) for x in col) for col in cols]
+ header_line = " | ".join(_pad(h, w) for h, w in zip(headers, widths))
+ sep_line = "-+-".join("-" * w for w in widths)
+ body = [" | ".join(_pad(c, w) for c, w in zip(r, widths)) for r in rows]
+ return "\n".join([header_line, sep_line] + body)
+
+
+PALETTE = {
+ "reset": "[0m",
+ "red": "[31m",
+ "yellow": "[33m",
+ "orange": "[38;5;208m",
+ "purple": "[35m",
+ "bold": "[1m",
+ "italic": "[3m",
+ "dim": "[2m",
+}
+
+
+def _style(s, color):
+ """Return color/style-formatted input `s` if `sys.stdout` is interactive, e.g. connected to a terminal."""
+ if sys.stdout.isatty():
+ return f"{PALETTE[color]}{s}{PALETTE['reset']}"
+ else:
+ return s
+
+
+def _get_terminal_width(default=80):
+ try:
+ return shutil.get_terminal_size().columns
+ except Exception:
+ return default
+
+
+@dataclass
+class LoadStateDictInfo:
+ """
+ Mutable container for state-dict loading results and diagnostics. Each entry in this structure is mutable,
+ and will usually be mutated in-place during the loading pipeline.
+
+ Attributes:
+ missing_keys (`set[str]`):
+ Keys that are missing from the loaded checkpoints but expected in the model's architecture.
+ unexpected_keys (`set[str]`):
+ Keys that are found in the checkpoints, but not expected in the model's architecture.
+ mismatched_keys (`set[tuple[str, tuple[int], tuple[int]]]`):
+ Keys that are found in the checkpoints and are expected in the model's architecture, but with a different shape.
+ error_msgs ( `list[str]`):
+ Some potential error messages.
+ conversion_errors (`dict[str, str]`):
+ Errors happening during the on-the-fly weight conversion process.
+ """
+
+ missing_keys: set[str]
+ unexpected_keys: set[str]
+ mismatched_keys: set[tuple[str, tuple[int], tuple[int]]]
+ error_msgs: list[str]
+ conversion_errors: dict[str, str]
+
+ def missing_and_mismatched(self):
+ """Return all effective missing keys, including `missing` and `mismatched` keys."""
+ return self.missing_keys | {k[0] for k in self.mismatched_keys}
+
+ def to_dict(self):
+ # Does not include the `conversion_errors` to be coherent with legacy reporting in the tests
+ return {
+ "missing_keys": self.missing_keys,
+ "unexpected_keys": self.unexpected_keys,
+ "mismatched_keys": self.mismatched_keys,
+ "error_msgs": self.error_msgs,
+ }
+
+ def create_loading_report(self) -> str | None:
+ """Generate the minimal table of a loading report."""
+ term_w = _get_terminal_width()
+
+ rows = []
+ tips = "\n\nNotes:"
+ if self.unexpected_keys:
+ tips += f"\n- {_style('UNEXPECTED:', 'orange')}\t" + _style(
+ "can be ignored when loading from different task/architecture; not ok if you expect identical arch.",
+ "italic",
+ )
+ for k in update_key_name(self.unexpected_keys):
+ status = _style("UNEXPECTED", "orange")
+ rows.append([k, status, "", ""])
+
+ if self.missing_keys:
+ tips += f"\n- {_style('MISSING:', 'red')}\t" + _style(
+ "those params were newly initialized because missing from the checkpoint. Consider training on your downstream task.",
+ "italic",
+ )
+ for k in update_key_name(self.missing_keys):
+ status = _style("MISSING", "red")
+ rows.append([k, status, ""])
+
+ if self.mismatched_keys:
+ tips += f"\n- {_style('MISMATCH:', 'yellow')}\t" + _style(
+ "ckpt weights were loaded, but they did not match the original empty weight shapes.", "italic"
+ )
+ iterator = {a: (b, c) for a, b, c in self.mismatched_keys}
+ for key, (shape_ckpt, shape_model) in update_key_name(iterator).items():
+ status = _style("MISMATCH", "yellow")
+ data = [
+ key,
+ status,
+ f"Reinit due to size mismatch - ckpt: {str(shape_ckpt)} vs model:{str(shape_model)}",
+ ]
+ rows.append(data)
+
+ if self.conversion_errors:
+ tips += f"\n- {_style('CONVERSION:', 'purple')}\t" + _style(
+ "originate from the conversion scheme", "italic"
+ )
+ for k, v in update_key_name(self.conversion_errors).items():
+ status = _style("CONVERSION", "purple")
+ _details = f"\n\n{v}\n\n"
+ rows.append([k, status, _details])
+
+ # If nothing is wrong, return None
+ if len(rows) == 0:
+ return None
+
+ headers = ["Key", "Status"]
+ if term_w > 200:
+ headers += ["Details"]
+ else:
+ headers += ["", ""]
+ table = _make_table(rows, headers=headers)
+ report = table + tips
+
+ return report
+
+
+def log_state_dict_report(
+ model,
+ pretrained_model_name_or_path: str,
+ ignore_mismatched_sizes: bool,
+ loading_info: LoadStateDictInfo,
+ logger: logging.Logger | None = None,
+):
+ """
+ Log a readable report about state_dict loading issues.
+
+ This version is terminal-size aware: for very small terminals it falls back to a compact
+ Key | Status view so output doesn't wrap badly.
+ """
+ if logger is None:
+ logger = logging.getLogger(__name__)
+
+ # Re-raise errors early if needed
+ if loading_info.error_msgs:
+ error_msg = "\n\t".join(loading_info.error_msgs)
+ if "size mismatch" in error_msg:
+ error_msg += (
+ "\n\tYou may consider adding `ignore_mismatched_sizes=True` to `from_pretrained(...)` if appropriate."
+ )
+ raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}")
+
+ # Create the report table
+ report = loading_info.create_loading_report()
+ if report is None:
+ return
+
+ prelude = f"{PALETTE['bold']}{model.__class__.__name__} LOAD REPORT{PALETTE['reset']} from: {pretrained_model_name_or_path}\n"
+
+ # Log the report as warning
+ logger.warning(prelude + report)
+
+ # Re-raise in those case, after the report
+ if loading_info.conversion_errors:
+ raise RuntimeError(
+ "We encountered some issues during automatic conversion of the weights. For details look at the `CONVERSION` entries of "
+ "the above report!"
+ )
+ if not ignore_mismatched_sizes and loading_info.mismatched_keys:
+ raise RuntimeError(
+ "You set `ignore_mismatched_sizes` to `False`, thus raising an error. For details look at the above report!"
+ )
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/logging.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..32099c4afe104d77d949d8a6946eded08999f8a2
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/logging.py
@@ -0,0 +1,441 @@
+# Copyright 2020 Optuna, Hugging Face
+#
+# 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.
+"""Logging utilities."""
+
+import functools
+import logging
+import os
+import sys
+import threading
+from collections.abc import Callable
+from logging import (
+ CRITICAL, # NOQA
+ DEBUG,
+ ERROR,
+ FATAL, # NOQA
+ INFO,
+ NOTSET, # NOQA
+ WARN, # NOQA
+ WARNING,
+)
+from logging import captureWarnings as _captureWarnings
+from typing import Any
+
+import huggingface_hub.utils as hf_hub_utils
+from tqdm import auto as tqdm_lib
+
+from .._typing import TransformersLogger
+
+
+_lock = threading.Lock()
+_default_handler: logging.Handler | None = None
+
+log_levels = {
+ "detail": logging.DEBUG, # will also print filename and line number
+ "debug": logging.DEBUG,
+ "info": logging.INFO,
+ "warning": logging.WARNING,
+ "error": logging.ERROR,
+ "critical": logging.CRITICAL,
+}
+
+_default_log_level = logging.WARNING
+
+_tqdm_active = not hf_hub_utils.are_progress_bars_disabled()
+_tqdm_hook: Callable[[Callable[..., Any], tuple[Any, ...], dict[str, Any]], Any] | None = None
+
+
+def _get_default_logging_level():
+ """
+ If TRANSFORMERS_VERBOSITY env var is set to one of the valid choices return that as the new default level. If it is
+ not - fall back to `_default_log_level`
+ """
+ env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None)
+ if env_level_str:
+ if env_level_str in log_levels:
+ return log_levels[env_level_str]
+ else:
+ logging.getLogger().warning(
+ f"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, "
+ f"has to be one of: {', '.join(log_levels.keys())}"
+ )
+ return _default_log_level
+
+
+def _get_library_name() -> str:
+ return __name__.split(".")[0]
+
+
+def _get_library_root_logger() -> logging.Logger:
+ return logging.getLogger(_get_library_name())
+
+
+def _configure_library_root_logger() -> None:
+ global _default_handler
+
+ with _lock:
+ if _default_handler:
+ # This library has already configured the library root logger.
+ return
+ _default_handler = logging.StreamHandler() # Set sys.stderr as stream.
+ # set defaults based on https://github.com/pyinstaller/pyinstaller/issues/7334#issuecomment-1357447176
+ if sys.stderr is None:
+ sys.stderr = open(os.devnull, "w")
+
+ _default_handler.flush = sys.stderr.flush
+
+ # Apply our default configuration to the library root logger.
+ library_root_logger = _get_library_root_logger()
+ library_root_logger.addHandler(_default_handler)
+ library_root_logger.setLevel(_get_default_logging_level())
+ # Always show lib when logging in non-verbose mode. Note, other libs
+ # use `transformers.logger` directly, so we check `lib_name` to be safe
+ lib_name = _get_library_name()
+ logging_format = f"[{lib_name}] %(message)s"
+
+ # if logging level is debug, we add pathname and lineno to formatter for easy debugging
+ if os.getenv("TRANSFORMERS_VERBOSITY", None) == "detail":
+ logging_format = "%(levelname)s [%(name)s:%(lineno)s] %(asctime)s %(message)s"
+
+ formatter = logging.Formatter(logging_format)
+ _default_handler.setFormatter(formatter)
+
+ ci = os.getenv("CI")
+ is_ci = ci is not None and ci.upper() in {"1", "ON", "YES", "TRUE"}
+ library_root_logger.propagate = is_ci
+
+
+def _reset_library_root_logger() -> None:
+ global _default_handler
+
+ with _lock:
+ if not _default_handler:
+ return
+
+ library_root_logger = _get_library_root_logger()
+ library_root_logger.removeHandler(_default_handler)
+ library_root_logger.setLevel(logging.NOTSET)
+ _default_handler = None
+
+
+def get_log_levels_dict():
+ return log_levels
+
+
+def captureWarnings(capture):
+ """
+ Calls the `captureWarnings` method from the logging library to enable management of the warnings emitted by the
+ `warnings` library.
+
+ Read more about this method here:
+ https://docs.python.org/3/library/logging.html#integration-with-the-warnings-module
+
+ All warnings will be logged through the `py.warnings` logger.
+
+ Careful: this method also adds a handler to this logger if it does not already have one, and updates the logging
+ level of that logger to the library's root logger.
+ """
+ logger = get_logger("py.warnings")
+
+ if not logger.handlers:
+ logger.addHandler(_default_handler)
+
+ logger.setLevel(_get_library_root_logger().level)
+
+ _captureWarnings(capture)
+
+
+def get_logger(name: str | None = None) -> TransformersLogger:
+ """
+ Return a logger with the specified name.
+
+ This function is not supposed to be directly accessed unless you are writing a custom transformers module.
+ """
+
+ if name is None:
+ name = _get_library_name()
+
+ _configure_library_root_logger()
+ return logging.getLogger(name)
+
+
+def get_verbosity() -> int:
+ """
+ Return the current level for the 🤗 Transformers's root logger as an int.
+
+ Returns:
+ `int`: The logging level.
+
+
+
+ 🤗 Transformers has following logging levels:
+
+ - 50: `transformers.logging.CRITICAL` or `transformers.logging.FATAL`
+ - 40: `transformers.logging.ERROR`
+ - 30: `transformers.logging.WARNING` or `transformers.logging.WARN`
+ - 20: `transformers.logging.INFO`
+ - 10: `transformers.logging.DEBUG`
+
+ """
+
+ _configure_library_root_logger()
+ return _get_library_root_logger().getEffectiveLevel()
+
+
+def set_verbosity(verbosity: int) -> None:
+ """
+ Set the verbosity level for the 🤗 Transformers's root logger.
+
+ Args:
+ verbosity (`int`):
+ Logging level, e.g., one of:
+
+ - `transformers.logging.CRITICAL` or `transformers.logging.FATAL`
+ - `transformers.logging.ERROR`
+ - `transformers.logging.WARNING` or `transformers.logging.WARN`
+ - `transformers.logging.INFO`
+ - `transformers.logging.DEBUG`
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().setLevel(verbosity)
+
+
+def set_verbosity_info():
+ """Set the verbosity to the `INFO` level."""
+ return set_verbosity(INFO)
+
+
+def set_verbosity_warning():
+ """Set the verbosity to the `WARNING` level."""
+ return set_verbosity(WARNING)
+
+
+def set_verbosity_debug():
+ """Set the verbosity to the `DEBUG` level."""
+ return set_verbosity(DEBUG)
+
+
+def set_verbosity_error():
+ """Set the verbosity to the `ERROR` level."""
+ return set_verbosity(ERROR)
+
+
+def disable_default_handler() -> None:
+ """Disable the default handler of the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert _default_handler is not None
+ _get_library_root_logger().removeHandler(_default_handler)
+
+
+def enable_default_handler() -> None:
+ """Enable the default handler of the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert _default_handler is not None
+ _get_library_root_logger().addHandler(_default_handler)
+
+
+def add_handler(handler: logging.Handler) -> None:
+ """adds a handler to the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert handler is not None
+ _get_library_root_logger().addHandler(handler)
+
+
+def remove_handler(handler: logging.Handler) -> None:
+ """removes given handler from the HuggingFace Transformers's root logger."""
+
+ _configure_library_root_logger()
+
+ assert handler is not None and handler not in _get_library_root_logger().handlers
+ _get_library_root_logger().removeHandler(handler)
+
+
+def disable_propagation() -> None:
+ """
+ Disable propagation of the library log outputs. Note that log propagation is disabled by default.
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().propagate = False
+
+
+def enable_propagation() -> None:
+ """
+ Enable propagation of the library log outputs. Please disable the HuggingFace Transformers's default handler to
+ prevent double logging if the root logger has been configured.
+ """
+
+ _configure_library_root_logger()
+ _get_library_root_logger().propagate = True
+
+
+def enable_explicit_format() -> None:
+ """
+ Enable explicit formatting for every HuggingFace Transformers's logger. The explicit formatter is as follows:
+ ```
+ [LEVELNAME|FILENAME|LINE NUMBER] TIME >> MESSAGE
+ ```
+ All handlers currently bound to the root logger are affected by this method.
+ """
+ handlers = _get_library_root_logger().handlers
+
+ for handler in handlers:
+ formatter = logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s")
+ handler.setFormatter(formatter)
+
+
+def reset_format() -> None:
+ """
+ Resets the formatting for HuggingFace Transformers's loggers.
+
+ All handlers currently bound to the root logger are affected by this method.
+ """
+ handlers = _get_library_root_logger().handlers
+
+ for handler in handlers:
+ handler.setFormatter(None)
+
+
+def warning_advice(self, *args, **kwargs):
+ """
+ This method is identical to `logger.warning()`, but if env var TRANSFORMERS_NO_ADVISORY_WARNINGS=1 is set, this
+ warning will not be printed
+ """
+ no_advisory_warnings = os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS")
+ if no_advisory_warnings:
+ return
+ self.warning(*args, **kwargs)
+
+
+logging.Logger.warning_advice = warning_advice # type: ignore[unresolved-attribute]
+
+
+@functools.lru_cache(None)
+def warning_once(self, *args, **kwargs):
+ """
+ This method is identical to `logger.warning()`, but will emit the warning with the same message only once
+
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
+ The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
+ another type of cache that includes the caller frame information in the hashing function.
+ """
+ self.warning(*args, **kwargs)
+
+
+logging.Logger.warning_once = warning_once # type: ignore[unresolved-attribute]
+
+
+@functools.lru_cache(None)
+def info_once(self, *args, **kwargs):
+ """
+ This method is identical to `logger.info()`, but will emit the info with the same message only once
+
+ Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the cache.
+ The assumption here is that all warning messages are unique across the code. If they aren't then need to switch to
+ another type of cache that includes the caller frame information in the hashing function.
+ """
+ self.info(*args, **kwargs)
+
+
+logging.Logger.info_once = info_once # type: ignore[unresolved-attribute]
+
+
+class EmptyTqdm:
+ """Dummy tqdm which doesn't do anything."""
+
+ def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
+ self._iterator = args[0] if args else None
+
+ def __iter__(self):
+ return iter(self._iterator)
+
+ def __getattr__(self, _):
+ """Return empty function."""
+
+ def empty_fn(*args, **kwargs): # pylint: disable=unused-argument
+ return
+
+ return empty_fn
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type_, value, traceback):
+ return
+
+
+class _tqdm_cls:
+ def __call__(self, *args, **kwargs):
+ factory = tqdm_lib.tqdm if _tqdm_active else EmptyTqdm
+ if _tqdm_hook is not None:
+ return _tqdm_hook(factory, args, kwargs)
+ return factory(*args, **kwargs)
+
+ def set_lock(self, *args, **kwargs):
+ self._lock = None
+ if _tqdm_active:
+ return tqdm_lib.tqdm.set_lock(*args, **kwargs)
+
+ def get_lock(self):
+ if _tqdm_active:
+ return tqdm_lib.tqdm.get_lock()
+
+
+tqdm = _tqdm_cls()
+
+
+def is_progress_bar_enabled() -> bool:
+ """Return a boolean indicating whether tqdm progress bars are enabled."""
+ return bool(_tqdm_active)
+
+
+def enable_progress_bar():
+ """Enable tqdm progress bar."""
+ global _tqdm_active
+ _tqdm_active = True
+ hf_hub_utils.enable_progress_bars()
+
+
+def disable_progress_bar():
+ """Disable tqdm progress bar."""
+ global _tqdm_active
+ _tqdm_active = False
+ hf_hub_utils.disable_progress_bars()
+
+
+def set_tqdm_hook(hook: Callable[[Callable[..., Any], tuple[Any, ...], dict[str, Any]], Any] | None):
+ """
+ Set a hook that customizes tqdm creation.
+
+ The hook is called with the tqdm factory to use (either `tqdm.auto.tqdm` or an empty shim), along with the
+ positional and keyword arguments that would have been passed to tqdm. The hook should return an object compatible
+ with tqdm (i.e. implementing the methods your code relies on, such as `update`, `close`, context manager methods,
+ etc.).
+
+ Passing `None` clears the hook.
+
+ Returns:
+ The previous hook, which can be restored later.
+ """
+ global _tqdm_hook
+ previous_hook = _tqdm_hook
+ _tqdm_hook = hook
+ return previous_hook
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/metrics.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/metrics.py
new file mode 100644
index 0000000000000000000000000000000000000000..e62fa846ae022b1ee287ad02752ca0ee7910387f
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/metrics.py
@@ -0,0 +1,405 @@
+import functools
+import logging
+import time
+from collections.abc import Callable
+from enum import Enum
+from typing import Any
+
+from .import_utils import is_opentelemetry_available
+
+
+class RequestStatus(Enum):
+ """Status of a generation request through its lifecycle."""
+
+ PENDING = "pending"
+ PREFILLING = "prefilling"
+ PREFILLING_SPLIT = "prefilling_split"
+ SPLIT_PENDING_REMAINDER = "split_pending_remainder"
+ DECODING = "decoding"
+ FINISHED = "finished"
+ FAILED = "failed"
+
+
+if is_opentelemetry_available():
+ from opentelemetry import metrics
+ from opentelemetry.trace import Status, StatusCode, get_tracer
+
+ _has_opentelemetry = True
+else:
+ _has_opentelemetry = False
+
+
+def attach_tracer(tracer_name_template=None):
+ """
+ Decorator that attaches a tracer to a class.
+
+ This decorator should be applied to classes that need OpenTelemetry tracing.
+ It adds a tracer attribute to the class instance that can be used by the traced decorator.
+
+ Args:
+ tracer_name_template: Optional template string for the tracer name.
+ If provided, it should contain {module} which will be replaced with the class's full module path
+ and {class_name} for the class name.
+ If None, a default naming scheme will be used where:
+ - If the module already starts with "transformers.", it will use that directly
+ - Otherwise, it will prepend "transformers." to the module name
+
+ Returns:
+ Class decorator function
+ """
+ if not _has_opentelemetry:
+ return lambda cls: cls
+
+ def decorator(cls):
+ original_init = cls.__init__
+
+ @functools.wraps(original_init)
+ def init_with_tracer(self, *args, **kwargs):
+ original_init(self, *args, **kwargs)
+
+ module_name = cls.__module__
+ class_name = cls.__qualname__
+
+ if tracer_name_template is None:
+ if module_name.startswith("transformers."):
+ tracer_name = f"{module_name}.{class_name}"
+ else:
+ tracer_name = f"transformers.{module_name}.{class_name}"
+ else:
+ tracer_name = tracer_name_template.format(module=module_name, class_name=class_name)
+
+ self.tracer = get_tracer(tracer_name)
+
+ cls.__init__ = init_with_tracer
+ return cls
+
+ return decorator
+
+
+def traced(
+ func=None,
+ *,
+ span_name=None,
+ standalone=False,
+ additional_attributes: list[tuple[str, str, Any | Callable[[Any], Any]]] | None = None,
+):
+ """
+ Decorator to trace function calls with OpenTelemetry.
+
+ Can be used as @traced or @traced(span_name="custom_name")
+
+ Args:
+ func: The function to trace
+ span_name: Optional custom name for the span (defaults to function name)
+ standalone: If True, creates a parentless span
+ additional_attributes: Optional list of additional attributes to set on the span.
+ Each item is a tuple of (instance_attribute_name, span_attribute_key, value_or_transform_function)
+ where:
+ - instance_attribute_name: Name of the attribute to get from the class instance
+ - span_attribute_key: Key to use when setting the attribute on the span
+ - value_or_transform_function: Either a raw value to use directly, or a function to transform
+ the attribute value before setting it on the span
+
+ Returns:
+ Decorated function with tracing
+ """
+
+ def decorator(func):
+ if not _has_opentelemetry:
+ return func
+
+ @functools.wraps(func)
+ def wrapper(*args, **kwargs):
+ instance = args[0] if args and (hasattr(func, "__self__") and func.__self__ is not None) else None
+ is_method = instance is not None
+
+ if is_method and hasattr(instance, "tracer"):
+ tracer = instance.tracer
+ else:
+ tracer = get_tracer(f"transformers.{func.__module__}.{func.__name__}")
+
+ name = span_name or func.__name__
+ span_fn = tracer.start_span if standalone else tracer.start_as_current_span
+ with span_fn(name) as span:
+ span.set_attribute("function.name", func.__name__)
+ span.set_attribute("function.module", func.__module__)
+ span.set_attribute("function.is_method", is_method)
+
+ if args:
+ for i, arg in enumerate(args):
+ if isinstance(arg, (str, int, float, bool)) or arg is None:
+ span.set_attribute(f"args.{i}", str(arg))
+ else:
+ span.set_attribute(f"args.{i}", str(type(arg)))
+ if kwargs:
+ for key, value in kwargs.items():
+ if isinstance(value, (str, int, float, bool)) or value is None:
+ span.set_attribute(f"kwargs.{key}", str(value))
+ else:
+ span.set_attribute(f"kwargs.{key}", str(type(value)))
+
+ if additional_attributes and is_method:
+ for attr_config in additional_attributes:
+ instance_attribute_name, span_attribute_key, value_or_transform_function = attr_config
+ if hasattr(instance, instance_attribute_name):
+ attribute_value = getattr(instance, instance_attribute_name)
+ if callable(value_or_transform_function):
+ transformed_value = value_or_transform_function(attribute_value)
+ else:
+ transformed_value = value_or_transform_function
+ span.set_attribute(span_attribute_key, transformed_value)
+
+ try:
+ result = func(*args, **kwargs)
+ return result
+ except Exception as e:
+ span.set_status(Status(StatusCode.ERROR))
+ span.record_exception(e)
+ raise
+
+ return wrapper
+
+ if func is None:
+ return decorator
+ return decorator(func)
+
+
+logger = logging.getLogger(__name__)
+
+
+@attach_tracer()
+class ContinuousBatchProcessorMetrics:
+ """Metrics collection for ContinuousBatchProcessor."""
+
+ def __init__(self, max_batch_tokens: int):
+ """Initialize metrics for continuous batch processor.
+
+ Args:
+ max_batch_tokens: Maximum number of tokens in a batch
+ """
+ self.max_batch_tokens = max_batch_tokens
+
+ self._setup_metrics()
+
+ def _setup_metrics(self):
+ """Initialize OpenTelemetry metrics and tracing if the library is available."""
+
+ if not _has_opentelemetry:
+ logger.info(
+ "OpenTelemetry is not installed. Metrics and tracing will not be recorded."
+ "You can install it with `pip install opentelemetry-api>=1.30.0`"
+ )
+ return
+
+ self.meter = metrics.get_meter("transformers.generation.continuous_batch_processor")
+
+ # Define appropriate buckets for TTFT (typically ranges from ~50ms to several seconds)
+ ttft_buckets = [10, 25, 50, 75, 100, 150, 200, 300, 500, 750, 1000, 2000, 5000, 10000]
+
+ self.ttft_histogram = self.meter.create_histogram(
+ name="ttft_milliseconds",
+ description="Time to first token in milliseconds",
+ unit="ms",
+ explicit_bucket_boundaries_advisory=ttft_buckets,
+ )
+
+ self.active_requests_gauge = self.meter.create_gauge(
+ name="active_requests_count",
+ description="Number of active requests currently being processed",
+ unit="requests",
+ )
+
+ self.waiting_requests_gauge = self.meter.create_gauge(
+ name="waiting_requests_count",
+ description="Number of requests waiting to be processed",
+ unit="requests",
+ )
+
+ # Define appropriate buckets for request latency (similar to TTFT but with higher upper bounds)
+ latency_buckets = [50, 100, 250, 500, 1000, 2000, 5000, 10000, 20000, 30000, 60000]
+
+ self.request_latency_histogram = self.meter.create_histogram(
+ name="request_latency_milliseconds",
+ description="End-to-end latency for completed requests in milliseconds",
+ unit="ms",
+ explicit_bucket_boundaries_advisory=latency_buckets,
+ )
+
+ self.decode_prefill_ratio_gauge = self.meter.create_gauge(
+ name="decode_prefill_ratio",
+ description="Ratio of decode tokens to prefill tokens in a batch",
+ unit="ratio",
+ )
+
+ self.prefill_tokens_counter = self.meter.create_counter(
+ name="prefill_tokens_processed",
+ description="Number of prefill tokens processed",
+ unit="tokens",
+ )
+
+ self.decode_tokens_counter = self.meter.create_counter(
+ name="decode_tokens_processed",
+ description="Number of decode tokens processed",
+ unit="tokens",
+ )
+
+ # Define appropriate buckets for batch fill percentage (0-100%)
+ batch_fill_buckets = [5, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 98, 100]
+
+ self.batch_fill_percentage_histogram = self.meter.create_histogram(
+ name="batch_fill_percentage",
+ description="Percentage of max_batch_tokens utilized in each batch",
+ unit="percent",
+ explicit_bucket_boundaries_advisory=batch_fill_buckets,
+ )
+
+ self.kv_cache_free_memory_gauge = self.meter.create_gauge(
+ name="kv_cache_free_memory_bytes",
+ description="Free memory of the PagedAttentionCache in bytes",
+ unit="bytes",
+ )
+
+ self.kv_cache_memory_gauge = self.meter.create_gauge(
+ name="kv_cache_memory_bytes",
+ description="Memory usage of the PagedAttentionCache in bytes",
+ unit="bytes",
+ )
+
+ @traced
+ def record_ttft_metric(self, created_time: float, request_id: str) -> None:
+ """Record Time to First Token (TTFT).
+
+ Args:
+ created_time: The time the request was created
+ request_id: The ID of the request
+ """
+ if not _has_opentelemetry:
+ return
+
+ ttft_ms = (time.time() - created_time) * 1000.0
+
+ try:
+ self.ttft_histogram.record(ttft_ms)
+ logger.debug(f"Recorded TTFT for request {request_id}: {ttft_ms:.2f}ms")
+ except Exception as e:
+ logger.warning(f"Failed to record TTFT metric: {e}")
+
+ @traced
+ def record_batch_metrics(self, future_states: list) -> None:
+ """Record metrics about the batch composition including decode/prefill ratio and batch fill percentage.
+
+ Args:
+ requests_in_batch: List of request states in the current batch
+ """
+ if not _has_opentelemetry or not future_states:
+ return
+
+ decode_tokens = 0
+ prefill_tokens = 0
+
+ for future_state in future_states:
+ state = future_state.state
+ if state.status == RequestStatus.DECODING:
+ decode_tokens += 1
+ elif state.status in [RequestStatus.PREFILLING, RequestStatus.PREFILLING_SPLIT]:
+ prefill_tokens += len(state.prompt_ids)
+
+ total_batch_tokens = decode_tokens + prefill_tokens
+
+ try:
+ if prefill_tokens > 0:
+ self.prefill_tokens_counter.add(prefill_tokens)
+
+ if decode_tokens > 0:
+ self.decode_tokens_counter.add(decode_tokens)
+
+ if prefill_tokens > 0:
+ ratio = decode_tokens / prefill_tokens
+ self.decode_prefill_ratio_gauge.set(ratio)
+
+ fill_percentage = (total_batch_tokens / self.max_batch_tokens) * 100.0
+ self.batch_fill_percentage_histogram.record(fill_percentage)
+ logger.debug(
+ f"Batch metrics: {decode_tokens} decode tokens, {prefill_tokens} prefill tokens, "
+ f"batch fill: {fill_percentage:.2f}% ({total_batch_tokens}/{self.max_batch_tokens})"
+ )
+ except Exception as e:
+ logger.warning(f"Failed to record batch metrics: {e}")
+
+ @traced
+ def record_kv_cache_memory_metrics(self, cache) -> None:
+ """Record memory usage of the PagedAttentionCache without GPU synchronization.
+
+ This calculates the theoretical memory usage based on cache configuration
+ and the number of blocks currently in use.
+
+ Args:
+ cache: The PagedAttentionCache object to measure
+ """
+ if not _has_opentelemetry:
+ return
+
+ try:
+ # Retrieve the memory footprint of the cache
+ page_size = cache.head_dim * cache.num_key_value_heads
+ page_mem_in_bytes = page_size * cache.dtype.itemsize
+ # When a block is allocated, it is for both K and V, so we multiply by 2
+ # It's also allocated across all cache tensors, so we multiply by the nb of tensors: len(cache.key_cache)
+ block_mem_in_bytes = 2 * len(cache.key_cache) * cache.block_size * page_mem_in_bytes
+
+ # Retrieve the number of used and free blocks
+ free_blocks = cache.get_num_free_blocks()
+ used_blocks = cache.num_blocks - free_blocks
+
+ # Convert that into used and free memory in bytes
+ used_memory_bytes = used_blocks * block_mem_in_bytes
+ free_memory_bytes = free_blocks * block_mem_in_bytes
+
+ # Update the telemetry gauges and add a message in the logs
+ self.kv_cache_memory_gauge.set(used_memory_bytes)
+ self.kv_cache_free_memory_gauge.set(free_memory_bytes)
+ logger.debug(
+ f"KV Cache memory: {used_memory_bytes / (1024 * 1024):.2f}MB, "
+ f"Used blocks: {used_blocks}/{cache.num_blocks} "
+ f"({used_blocks / cache.num_blocks * 100:.1f}%)"
+ )
+ except Exception as e:
+ logger.warning(f"Failed to record KV cache memory metrics: {e}")
+
+ @traced
+ def record_queue_metrics(self, active_requests: int, waiting_requests: int) -> None:
+ """Record metrics about active and waiting requests.
+
+ Args:
+ active_requests: Number of active requests
+ waiting_requests: Number of waiting requests
+ """
+ if not _has_opentelemetry:
+ return
+
+ try:
+ self.active_requests_gauge.set(active_requests)
+ self.waiting_requests_gauge.set(waiting_requests)
+ logger.debug(f"Queue metrics: {active_requests} active requests, {waiting_requests} waiting requests")
+ except Exception as e:
+ logger.warning(f"Failed to record queue metrics: {e}")
+
+ @traced
+ def record_request_completion(self, created_time: float, request_id: str) -> None:
+ """Record metrics about a completed request.
+
+ Args:
+ created_time: The time the request was created
+ request_id: The ID of the request
+ """
+ if not _has_opentelemetry:
+ return
+
+ latency_ms = (time.time() - created_time) * 1000.0
+
+ try:
+ self.request_latency_histogram.record(latency_ms)
+
+ logger.debug(f"Recorded request completion for {request_id}: {latency_ms:.2f}ms")
+ except Exception as e:
+ logger.warning(f"Failed to record request completion metric: {e}")
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/network_logging.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/network_logging.py
new file mode 100644
index 0000000000000000000000000000000000000000..92f74ccd6d181bfa8b0fcf8a6fbfd8a39a19b4b8
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/network_logging.py
@@ -0,0 +1,485 @@
+# Copyright 2026 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 __future__ import annotations
+
+import inspect
+import json
+import os
+import threading
+import time
+from collections import defaultdict
+from functools import wraps
+from pathlib import Path
+from typing import Any
+
+import httpx
+
+from .generic import strtobool
+
+
+class _NetworkRequestTrace:
+ def __init__(self, request: httpx.Request):
+ self.request = request
+ self.started_at = time.perf_counter()
+ self.phase_started_at = {}
+ self.phases_ms = defaultdict(float)
+
+ def trace(self, name: str, info: dict[str, Any]) -> None:
+ parts = name.rsplit(".", 2)
+ if len(parts) != 3:
+ return
+
+ _, phase, state = parts
+ now = time.perf_counter()
+ if state == "started":
+ self.phase_started_at[phase] = now
+ elif state in {"complete", "failed"}:
+ phase_started_at = self.phase_started_at.pop(phase, None)
+ if phase_started_at is not None:
+ self.phases_ms[phase] += (now - phase_started_at) * 1000
+
+ def build_record(
+ self,
+ *,
+ response: httpx.Response | None = None,
+ error: BaseException | None = None,
+ stream: bool = False,
+ ) -> dict[str, Any]:
+ total_ms = (time.perf_counter() - self.started_at) * 1000
+ url = self.request.url
+ host = url.host or ""
+ port = url.port
+ default_port = {"http": 80, "https": 443}.get(url.scheme)
+ host_display = host if port in (None, default_port) else f"{host}:{port}"
+
+ http_version = None
+ status_code = None
+ bytes_downloaded = None
+ response_complete = False
+ if response is not None:
+ status_code = response.status_code
+ response_complete = response.is_closed
+ raw_http_version = response.extensions.get("http_version")
+ if isinstance(raw_http_version, bytes):
+ http_version = raw_http_version.decode("ascii", errors="replace")
+ elif raw_http_version is not None:
+ http_version = str(raw_http_version)
+
+ if response_complete:
+ try:
+ bytes_downloaded = len(response.content)
+ except httpx.ResponseNotRead:
+ pass
+
+ return {
+ "method": self.request.method,
+ "scheme": url.scheme,
+ "host": host,
+ "host_display": host_display,
+ "port": port,
+ "path": url.path,
+ "has_query": bool(url.query),
+ "url": f"{url.scheme}://{host_display}{url.path}{'?...' if url.query else ''}",
+ "request_id": self.request.headers.get("x-amzn-trace-id") or self.request.headers.get("x-request-id"),
+ "status_code": status_code,
+ "http_version": http_version,
+ "bytes_downloaded": bytes_downloaded,
+ "total_ms": total_ms,
+ "stream": stream,
+ "response_complete": response_complete,
+ "phases_ms": dict(sorted(self.phases_ms.items())),
+ "error": None if error is None else f"{type(error).__name__}: {error}",
+ }
+
+
+class _NetworkDebugProfiler:
+ def __init__(self):
+ self._records = []
+ self._lock = threading.Lock()
+ self._enabled = False
+ self._output_path = None
+ self._original_client_send = None
+ self._original_async_client_send = None
+ self._shared_dir = None
+
+ @property
+ def enabled(self) -> bool:
+ return self._enabled
+
+ def clear(self) -> None:
+ with self._lock:
+ self._records = []
+
+ def enable(self, output_path: str | os.PathLike | None = None) -> None:
+ if self._enabled:
+ self._output_path = None if output_path is None else os.fspath(output_path)
+ self.clear()
+ return
+
+ self._output_path = None if output_path is None else os.fspath(output_path)
+ self.clear()
+
+ profiler = self
+ self._original_client_send = httpx.Client.send
+ self._original_async_client_send = httpx.AsyncClient.send
+
+ @wraps(self._original_client_send)
+ def patched_client_send(client, request, *args, **kwargs):
+ return profiler._send_with_trace(profiler._original_client_send, client, request, *args, **kwargs)
+
+ @wraps(self._original_async_client_send)
+ async def patched_async_client_send(client, request, *args, **kwargs):
+ return await profiler._async_send_with_trace(
+ profiler._original_async_client_send, client, request, *args, **kwargs
+ )
+
+ httpx.Client.send = patched_client_send
+ httpx.AsyncClient.send = patched_async_client_send
+ self._enabled = True
+
+ def setup_shared_dir(self) -> str | None:
+ """Create a shared temp directory for xdist workers to dump records into."""
+ if self._shared_dir is None:
+ import tempfile
+
+ self._shared_dir = tempfile.mkdtemp(prefix="network_debug_")
+ return self._shared_dir
+
+ def set_shared_dir(self, shared_dir: str) -> None:
+ """Set the shared directory (called in xdist workers)."""
+ self._shared_dir = shared_dir
+
+ def dump_worker_records(self, worker_id: str | None = None) -> None:
+ """Write this process's records to a file in the shared directory (called in workers)."""
+ if not self._shared_dir or not self._records:
+ return
+ worker_id = worker_id or f"pid{os.getpid()}"
+ dump_path = os.path.join(self._shared_dir, f"records_{worker_id}.json")
+ with self._lock:
+ records = [{**record, "phases_ms": dict(record["phases_ms"])} for record in self._records]
+ Path(dump_path).write_text(json.dumps(records), encoding="utf-8")
+
+ def load_worker_records(self) -> None:
+ """Load all worker record files from the shared directory (called in controller)."""
+ if not self._shared_dir or not os.path.isdir(self._shared_dir):
+ return
+ import glob as glob_module
+
+ for record_file in glob_module.glob(os.path.join(self._shared_dir, "records_*.json")):
+ try:
+ records = json.loads(Path(record_file).read_text(encoding="utf-8"))
+ with self._lock:
+ for record in records:
+ record["phases_ms"] = defaultdict(float, record.get("phases_ms", {}))
+ self._records.append(record)
+ except (OSError, json.JSONDecodeError):
+ pass
+
+ def cleanup_shared_dir(self) -> None:
+ """Remove the shared temp directory."""
+ if self._shared_dir and os.path.isdir(self._shared_dir):
+ import shutil
+
+ shutil.rmtree(self._shared_dir, ignore_errors=True)
+ self._shared_dir = None
+
+ def disable(self) -> None:
+ if not self._enabled:
+ return
+
+ httpx.Client.send = self._original_client_send
+ httpx.AsyncClient.send = self._original_async_client_send
+ self._enabled = False
+ self._original_client_send = None
+ self._original_async_client_send = None
+ self._output_path = None
+ self.clear()
+
+ def _append_record(self, record: dict[str, Any]) -> None:
+ with self._lock:
+ self._records.append(record)
+
+ def _wrap_trace_callback(self, request: httpx.Request, trace: _NetworkRequestTrace):
+ existing_trace = request.extensions.get("trace")
+
+ def wrapped_trace(name: str, info: dict[str, Any]) -> Any:
+ trace.trace(name, info)
+ if existing_trace is not None:
+ return existing_trace(name, info)
+ return None
+
+ return wrapped_trace
+
+ async def _awrap_trace_callback(self, request: httpx.Request, trace: _NetworkRequestTrace):
+ existing_trace = request.extensions.get("trace")
+
+ async def wrapped_trace(name: str, info: dict[str, Any]) -> Any:
+ trace.trace(name, info)
+ if existing_trace is not None:
+ result = existing_trace(name, info)
+ if inspect.isawaitable(result):
+ return await result
+ return result
+ return None
+
+ return wrapped_trace
+
+ def _send_with_trace(self, original_send, client, request: httpx.Request, *args, **kwargs):
+ trace = _NetworkRequestTrace(request)
+ request.extensions = dict(request.extensions)
+ request.extensions["trace"] = self._wrap_trace_callback(request, trace)
+
+ try:
+ response = original_send(client, request, *args, **kwargs)
+ except Exception as error:
+ self._append_record(trace.build_record(error=error, stream=kwargs.get("stream", False)))
+ raise
+
+ self._append_record(trace.build_record(response=response, stream=kwargs.get("stream", False)))
+ return response
+
+ async def _async_send_with_trace(self, original_send, client, request: httpx.Request, *args, **kwargs):
+ trace = _NetworkRequestTrace(request)
+ request.extensions = dict(request.extensions)
+ request.extensions["trace"] = await self._awrap_trace_callback(request, trace)
+
+ try:
+ response = await original_send(client, request, *args, **kwargs)
+ except Exception as error:
+ self._append_record(trace.build_record(error=error, stream=kwargs.get("stream", False)))
+ raise
+
+ self._append_record(trace.build_record(response=response, stream=kwargs.get("stream", False)))
+ return response
+
+ def build_report(self) -> dict[str, Any]:
+ with self._lock:
+ records = [
+ {
+ **record,
+ "phases_ms": dict(record["phases_ms"]),
+ }
+ for record in self._records
+ ]
+
+ phase_totals_ms = defaultdict(float)
+ route_totals = {}
+ for record in records:
+ for phase, duration_ms in record["phases_ms"].items():
+ phase_totals_ms[phase] += duration_ms
+
+ route_key = (record["method"], record["host_display"], record["path"])
+ route_total = route_totals.setdefault(
+ route_key,
+ {
+ "method": record["method"],
+ "host_display": record["host_display"],
+ "path": record["path"],
+ "count": 0,
+ "failures": 0,
+ "total_ms": 0.0,
+ "phase_totals_ms": defaultdict(float),
+ },
+ )
+ route_total["count"] += 1
+ route_total["total_ms"] += record["total_ms"]
+ route_total["failures"] += int(record["error"] is not None)
+ for phase, duration_ms in record["phases_ms"].items():
+ route_total["phase_totals_ms"][phase] += duration_ms
+
+ routes = []
+ for route_total in route_totals.values():
+ route_total["avg_ms"] = route_total["total_ms"] / route_total["count"]
+ route_total["phase_totals_ms"] = dict(sorted(route_total["phase_totals_ms"].items()))
+ routes.append(route_total)
+
+ routes.sort(key=lambda route: route["total_ms"], reverse=True)
+ total_time_ms = sum(record["total_ms"] for record in records)
+ return {
+ "enabled": self._enabled,
+ "output_path": self._output_path,
+ "total_requests": len(records),
+ "failed_requests": sum(int(record["error"] is not None) for record in records),
+ "total_time_ms": total_time_ms,
+ "phase_totals_ms": dict(sorted(phase_totals_ms.items())),
+ "requests": records,
+ "routes": routes,
+ }
+
+ def maybe_write_report(self) -> str | None:
+ if self._output_path is None:
+ return None
+
+ report_path = Path(self._output_path)
+ report_path.parent.mkdir(parents=True, exist_ok=True)
+ report_path.write_text(json.dumps(self.build_report(), indent=2, sort_keys=True), encoding="utf-8")
+ return str(report_path)
+
+
+_NETWORK_DEBUG_PROFILER = _NetworkDebugProfiler()
+
+
+_DEFAULT_REPORT_PATH = "network_debug_report.json"
+
+
+def _parse_network_debug_env() -> tuple[bool, str]:
+ enabled_raw = os.environ.get("NETWORK_DEBUG_REPORT", "").strip()
+ try:
+ enabled = bool(strtobool(enabled_raw)) if enabled_raw else False
+ except ValueError:
+ enabled = False
+
+ output_path = os.environ.get("NETWORK_DEBUG_REPORT_PATH", "").strip() or _DEFAULT_REPORT_PATH
+ return enabled, output_path
+
+
+def _enable_network_debug_report(output_path: str | os.PathLike | None = None) -> None:
+ _NETWORK_DEBUG_PROFILER.enable(output_path=output_path)
+
+
+def _disable_network_debug_report() -> None:
+ _NETWORK_DEBUG_PROFILER.disable()
+
+
+def _clear_network_debug_report() -> None:
+ _NETWORK_DEBUG_PROFILER.clear()
+
+
+def _get_network_debug_report() -> dict[str, Any]:
+ return _NETWORK_DEBUG_PROFILER.build_report()
+
+
+def _enable_network_debug_report_from_env() -> bool:
+ enabled, output_path = _parse_network_debug_env()
+ if not enabled:
+ return False
+
+ _enable_network_debug_report(output_path=output_path)
+ return True
+
+
+def _format_network_debug_report(max_requests: int = 20, max_routes: int = 10) -> str:
+ report = _get_network_debug_report()
+ if report["total_requests"] == 0:
+ return "Network debug report: no httpx requests captured."
+
+ lines = [
+ "Network debug report",
+ f"Requests captured: {report['total_requests']}",
+ f"Failed requests: {report['failed_requests']}",
+ f"Cumulative request time: {report['total_time_ms']:.1f} ms",
+ ]
+
+ if report["phase_totals_ms"]:
+ phase_summary = ", ".join(
+ f"{phase}={duration_ms:.1f} ms"
+ for phase, duration_ms in sorted(report["phase_totals_ms"].items(), key=lambda item: item[1], reverse=True)
+ )
+ lines.append(f"Phase totals: {phase_summary}")
+
+ lines.append("")
+ lines.append("Slowest requests:")
+ for idx, record in enumerate(
+ sorted(report["requests"], key=lambda request: request["total_ms"], reverse=True)[:max_requests],
+ start=1,
+ ):
+ status = record["error"] or f"status={record['status_code']}"
+ phase_bits = []
+ for phase in ("connect_tcp", "start_tls", "receive_response_headers", "receive_response_body"):
+ duration_ms = record["phases_ms"].get(phase)
+ if duration_ms is not None:
+ phase_bits.append(f"{phase}={duration_ms:.1f} ms")
+ phase_suffix = f" ({', '.join(phase_bits)})" if phase_bits else ""
+ incomplete_suffix = " incomplete" if record["stream"] and not record["response_complete"] else ""
+ lines.append(
+ f"{idx:>2}. {record['method']} {record['url']} {record['total_ms']:.1f} ms {status}{incomplete_suffix}{phase_suffix}"
+ )
+
+ lines.append("")
+ lines.append("Slowest routes:")
+ for idx, route in enumerate(report["routes"][:max_routes], start=1):
+ lines.append(
+ f"{idx:>2}. {route['method']} {route['host_display']}{route['path']} count={route['count']} "
+ f"total={route['total_ms']:.1f} ms avg={route['avg_ms']:.1f} ms failures={route['failures']}"
+ )
+
+ return "\n".join(lines)
+
+
+class NetworkDebugPlugin:
+ """Pytest plugin that handles all network debug orchestration including xdist coordination."""
+
+ def pytest_configure(self, config):
+ _enable_network_debug_report_from_env()
+ if not _NETWORK_DEBUG_PROFILER.enabled:
+ return
+
+ # xdist controller: create shared dir for workers to dump network records
+ if not hasattr(config, "workerinput"):
+ shared_dir = _NETWORK_DEBUG_PROFILER.setup_shared_dir()
+ if shared_dir:
+ config._network_debug_shared_dir = shared_dir
+ else:
+ # xdist worker: receive shared dir from controller
+ shared_dir = config.workerinput.get("network_debug_shared_dir")
+ if shared_dir:
+ _NETWORK_DEBUG_PROFILER.set_shared_dir(shared_dir)
+
+ def pytest_configure_node(self, node):
+ """xdist hook: called on the controller to configure each worker node."""
+ shared_dir = getattr(node.config, "_network_debug_shared_dir", None)
+ if shared_dir:
+ node.workerinput["network_debug_shared_dir"] = shared_dir
+
+ def pytest_sessionfinish(self, session, exitstatus):
+ # xdist worker: dump network debug records for the controller to aggregate
+ if hasattr(session.config, "workerinput"):
+ worker_id = session.config.workerinput.get("workerid", f"pid{os.getpid()}")
+ _NETWORK_DEBUG_PROFILER.dump_worker_records(worker_id=worker_id)
+
+ def pytest_terminal_summary(self, terminalreporter):
+ if not _NETWORK_DEBUG_PROFILER.enabled:
+ return
+
+ # Skip report generation in xdist worker processes; only the controller should aggregate and report.
+ if hasattr(terminalreporter.config, "workerinput"):
+ return
+
+ # Aggregate worker records if running under xdist.
+ _NETWORK_DEBUG_PROFILER.load_worker_records()
+
+ report_path = None
+ try:
+ report_path = _NETWORK_DEBUG_PROFILER.maybe_write_report()
+ except OSError as error:
+ report_path = f"Failed to write JSON report: {error}"
+
+ terminalreporter.section("Network debug", sep="=")
+ for line in _format_network_debug_report().splitlines():
+ terminalreporter.write_line(line)
+ if report_path is not None:
+ terminalreporter.write_line(f"JSON report: {report_path}")
+
+ _NETWORK_DEBUG_PROFILER.cleanup_shared_dir()
+
+
+def register_network_debug_plugin(config) -> None:
+ """Register the network debug pytest plugin. Single entry point for conftest.py."""
+ config.pluginmanager.register(NetworkDebugPlugin(), "network_debug")
+
+
+__all__ = [
+ "register_network_debug_plugin",
+]
diff --git a/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/notebook.py b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/notebook.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c7fb7a77bea87d90c51f7823247f6318ca3d3b0
--- /dev/null
+++ b/micromamba_root/envs/pytorch_env/Lib/site-packages/transformers/utils/notebook.py
@@ -0,0 +1,408 @@
+# Copyright 2020 Hugging Face
+#
+# 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 os
+import re
+import time
+from typing import Optional, TypeVar
+
+import IPython.display as disp
+
+from ..trainer_callback import TrainerCallback
+from ..trainer_utils import IntervalStrategy, has_length
+
+
+_T = TypeVar("_T")
+
+
+def _require(x: _T | None, msg: str) -> _T:
+ if x is None:
+ raise RuntimeError(msg)
+ return x
+
+
+def format_time(t):
+ "Format `t` (in seconds) to (h):mm:ss"
+ t = int(t)
+ h, m, s = t // 3600, (t // 60) % 60, t % 60
+ return f"{h}:{m:02d}:{s:02d}" if h != 0 else f"{m:02d}:{s:02d}"
+
+
+def html_progress_bar(value, total, prefix, label, width=300):
+ # docstyle-ignore
+ return f"""
+
+ {prefix}
+
+ {label}
+
+ """
+
+
+def text_to_html_table(items):
+ "Put the texts in `items` in an HTML table."
+ html_code = """
\n"""
+ html_code += """ \n
\n"""
+ for i in items[0]:
+ html_code += f"
{i}
\n"
+ html_code += "
\n \n \n"
+ for line in items[1:]:
+ html_code += "
\n"
+ for elt in line:
+ elt = f"{elt:.6f}" if isinstance(elt, float) else str(elt)
+ html_code += f"