diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd2d9f7da5206518c7a4dbebbcc2ca97c96b3aad Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/mod_with_constant.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd96ef9d90dbc7f17c1581012e8f7a05c51c2c70 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/script-with-bom.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/server.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/server.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e255141827a479f392c46b4deb3d80bc2fee3fa5 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/server.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..139a198ee28c32174536885220f376601ddd0e0e Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_archive_util.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ae0d9968edec89f2ee353e30b7f39f51bc46740 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_bdist_wheel.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84bcfc0e9cf393c5b1526e149fff7f29cdfd8d11 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_ext.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e47d5ded36b06ab8b2c372b7cf64547a66146df7 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_build_py.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_core_metadata.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_core_metadata.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30bf313cd2ee3a2749db26e967c60777005b4a69 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_core_metadata.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99d731c43db5aa7788a4cbf08ff79b7e51ebf9ae Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_install_scripts.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_manifest.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_manifest.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d47236699eb66065a40f8710efee3cd933cb6bc4 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_manifest.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_namespaces.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_namespaces.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b19005c0621b229085a442dce351947091f40196 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_namespaces.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..218109dbb94a6a464e4c518c64010b736cadffdd Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_virtualenv.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6ea5050925bfae6b0d4d7b66be5d6903e5da7a5 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/__pycache__/test_wheel.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/__init__.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a93fd2f14abeb57dc4d370ee77de5437a685e02d Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/test_expand.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/test_expand.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6e524f0777bca846c2378426aa7d1d788047c9f Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/test_expand.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e481eafa525679ffc73afd85e01e288a6e6e16b9 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5292dee47e7be1ac4ea5a125961363fdcd20b613 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/config/__pycache__/test_pyprojecttoml_dynamic_deps.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/indexes/test_links_priority/external.html b/llava/lib/python3.10/site-packages/setuptools/tests/indexes/test_links_priority/external.html new file mode 100644 index 0000000000000000000000000000000000000000..92e4702f634dfb37a404bec3103b76f6afcaa917 --- /dev/null +++ b/llava/lib/python3.10/site-packages/setuptools/tests/indexes/test_links_priority/external.html @@ -0,0 +1,3 @@ + +bad old link + diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html b/llava/lib/python3.10/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html new file mode 100644 index 0000000000000000000000000000000000000000..fefb028bd3ee7d45a414d6e96a7b2a21ffd7eda7 --- /dev/null +++ b/llava/lib/python3.10/site-packages/setuptools/tests/indexes/test_links_priority/simple/foobar/index.html @@ -0,0 +1,4 @@ + +foobar-0.1.tar.gz
+external homepage
+ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/integration/__init__.py b/llava/lib/python3.10/site-packages/setuptools/tests/integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/__init__.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20bcfb9eb9ffbbe35f5c69121258ef6977bc9bb7 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/__init__.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..260a3e0ac50bbf4ad3935ac25bd3e3bd1d77d943 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-310.pyc b/llava/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ca0ea87b22e830e999d4ad9c91e6c6d11415546 Binary files /dev/null and b/llava/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-310.pyc differ diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/integration/helpers.py b/llava/lib/python3.10/site-packages/setuptools/tests/integration/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..77b196e029b6d2eeb25f0b84a4f7630f65201189 --- /dev/null +++ b/llava/lib/python3.10/site-packages/setuptools/tests/integration/helpers.py @@ -0,0 +1,77 @@ +"""Reusable functions and classes for different types of integration tests. + +For example ``Archive`` can be used to check the contents of distribution built +with setuptools, and ``run`` will always try to be as verbose as possible to +facilitate debugging. +""" + +import os +import subprocess +import tarfile +from pathlib import Path +from zipfile import ZipFile + + +def run(cmd, env=None): + r = subprocess.run( + cmd, + capture_output=True, + text=True, + encoding="utf-8", + env={**os.environ, **(env or {})}, + # ^-- allow overwriting instead of discarding the current env + ) + + out = r.stdout + "\n" + r.stderr + # pytest omits stdout/err by default, if the test fails they help debugging + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print(f"Command: {cmd}\nreturn code: {r.returncode}\n\n{out}") + + if r.returncode == 0: + return out + raise subprocess.CalledProcessError(r.returncode, cmd, r.stdout, r.stderr) + + +class Archive: + """Compatibility layer for ZipFile/Info and TarFile/Info""" + + def __init__(self, filename): + self._filename = filename + if filename.endswith("tar.gz"): + self._obj = tarfile.open(filename, "r:gz") + elif filename.endswith("zip"): + self._obj = ZipFile(filename) + else: + raise ValueError(f"{filename} doesn't seem to be a zip or tar.gz") + + def __iter__(self): + if hasattr(self._obj, "infolist"): + return iter(self._obj.infolist()) + return iter(self._obj) + + def get_name(self, zip_or_tar_info): + if hasattr(zip_or_tar_info, "filename"): + return zip_or_tar_info.filename + return zip_or_tar_info.name + + def get_content(self, zip_or_tar_info): + if hasattr(self._obj, "extractfile"): + content = self._obj.extractfile(zip_or_tar_info) + if content is None: + msg = f"Invalid {zip_or_tar_info.name} in {self._filename}" + raise ValueError(msg) + return str(content.read(), "utf-8") + return str(self._obj.read(zip_or_tar_info), "utf-8") + + +def get_sdist_members(sdist_path): + with tarfile.open(sdist_path, "r:gz") as tar: + files = [Path(f) for f in tar.getnames()] + # remove root folder + relative_files = ("/".join(f.parts[1:]) for f in files) + return {f for f in relative_files if f} + + +def get_wheel_members(wheel_path): + with ZipFile(wheel_path) as zipfile: + return set(zipfile.namelist()) diff --git a/llava/lib/python3.10/site-packages/setuptools/tests/integration/test_pip_install_sdist.py b/llava/lib/python3.10/site-packages/setuptools/tests/integration/test_pip_install_sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f1c080038bfd9c6db545ddfe5e9dd634d4147c --- /dev/null +++ b/llava/lib/python3.10/site-packages/setuptools/tests/integration/test_pip_install_sdist.py @@ -0,0 +1,223 @@ +# https://github.com/python/mypy/issues/16936 +# mypy: disable-error-code="has-type" +"""Integration tests for setuptools that focus on building packages via pip. + +The idea behind these tests is not to exhaustively check all the possible +combinations of packages, operating systems, supporting libraries, etc, but +rather check a limited number of popular packages and how they interact with +the exposed public API. This way if any change in API is introduced, we hope to +identify backward compatibility problems before publishing a release. + +The number of tested packages is purposefully kept small, to minimise duration +and the associated maintenance cost (changes in the way these packages define +their build process may require changes in the tests). +""" + +import json +import os +import shutil +import sys +from enum import Enum +from glob import glob +from hashlib import md5 +from urllib.request import urlopen + +import pytest +from packaging.requirements import Requirement + +from .helpers import Archive, run + +pytestmark = pytest.mark.integration + + +(LATEST,) = Enum("v", "LATEST") # type: ignore[misc] # https://github.com/python/mypy/issues/16936 +"""Default version to be checked""" +# There are positive and negative aspects of checking the latest version of the +# packages. +# The main positive aspect is that the latest version might have already +# removed the use of APIs deprecated in previous releases of setuptools. + + +# Packages to be tested: +# (Please notice the test environment cannot support EVERY library required for +# compiling binary extensions. In Ubuntu/Debian nomenclature, we only assume +# that `build-essential`, `gfortran` and `libopenblas-dev` are installed, +# due to their relevance to the numerical/scientific programming ecosystem) +EXAMPLES = [ + ("pip", LATEST), # just in case... + ("pytest", LATEST), # uses setuptools_scm + ("mypy", LATEST), # custom build_py + ext_modules + # --- Popular packages: https://hugovk.github.io/top-pypi-packages/ --- + ("botocore", LATEST), + ("kiwisolver", LATEST), # build_ext + ("brotli", LATEST), # not in the list but used by urllib3 + ("pyyaml", LATEST), # cython + custom build_ext + custom distclass + ("charset-normalizer", LATEST), # uses mypyc, used by aiohttp + ("protobuf", LATEST), + ("requests", LATEST), + ("celery", LATEST), + # When adding packages to this list, make sure they expose a `__version__` + # attribute, or modify the tests below +] + + +# Some packages have "optional" dependencies that modify their build behaviour +# and are not listed in pyproject.toml, others still use `setup_requires` +EXTRA_BUILD_DEPS = { + "pyyaml": ("Cython<3.0",), # constraint to avoid errors + "charset-normalizer": ("mypy>=1.4.1",), # no pyproject.toml available +} + +EXTRA_ENV_VARS = { + "pyyaml": {"PYYAML_FORCE_CYTHON": "1"}, + "charset-normalizer": {"CHARSET_NORMALIZER_USE_MYPYC": "1"}, +} + +IMPORT_NAME = { + "pyyaml": "yaml", + "protobuf": "google.protobuf", +} + + +VIRTUALENV = (sys.executable, "-m", "virtualenv") + + +# By default, pip will try to build packages in isolation (PEP 517), which +# means it will download the previous stable version of setuptools. +# `pip` flags can avoid that (the version of setuptools under test +# should be the one to be used) +INSTALL_OPTIONS = ( + "--ignore-installed", + "--no-build-isolation", + # Omit "--no-binary :all:" the sdist is supplied directly. + # Allows dependencies as wheels. +) +# The downside of `--no-build-isolation` is that pip will not download build +# dependencies. The test script will have to also handle that. + + +@pytest.fixture +def venv_python(tmp_path): + run([*VIRTUALENV, str(tmp_path / ".venv")]) + possible_path = (str(p.parent) for p in tmp_path.glob(".venv/*/python*")) + return shutil.which("python", path=os.pathsep.join(possible_path)) + + +@pytest.fixture(autouse=True) +def _prepare(tmp_path, venv_python, monkeypatch): + download_path = os.getenv("DOWNLOAD_PATH", str(tmp_path)) + os.makedirs(download_path, exist_ok=True) + + # Environment vars used for building some of the packages + monkeypatch.setenv("USE_MYPYC", "1") + + yield + + # Let's provide the maximum amount of information possible in the case + # it is necessary to debug the tests directly from the CI logs. + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print("Temporary directory:") + map(print, tmp_path.glob("*")) + print("Virtual environment:") + run([venv_python, "-m", "pip", "freeze"]) + + +@pytest.mark.parametrize(("package", "version"), EXAMPLES) +@pytest.mark.uses_network +def test_install_sdist(package, version, tmp_path, venv_python, setuptools_wheel): + venv_pip = (venv_python, "-m", "pip") + sdist = retrieve_sdist(package, version, tmp_path) + deps = build_deps(package, sdist) + if deps: + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") + print("Dependencies:", deps) + run([*venv_pip, "install", *deps]) + + # Use a virtualenv to simulate PEP 517 isolation + # but install fresh setuptools wheel to ensure the version under development + env = EXTRA_ENV_VARS.get(package, {}) + run([*venv_pip, "install", "--force-reinstall", setuptools_wheel]) + run([*venv_pip, "install", *INSTALL_OPTIONS, sdist], env) + + # Execute a simple script to make sure the package was installed correctly + pkg = IMPORT_NAME.get(package, package).replace("-", "_") + script = f"import {pkg}; print(getattr({pkg}, '__version__', 0))" + run([venv_python, "-c", script]) + + +# ---- Helper Functions ---- + + +def retrieve_sdist(package, version, tmp_path): + """Either use cached sdist file or download it from PyPI""" + # `pip download` cannot be used due to + # https://github.com/pypa/pip/issues/1884 + # https://discuss.python.org/t/pep-625-file-name-of-a-source-distribution/4686 + # We have to find the correct distribution file and download it + download_path = os.getenv("DOWNLOAD_PATH", str(tmp_path)) + dist = retrieve_pypi_sdist_metadata(package, version) + + # Remove old files to prevent cache to grow indefinitely + for file in glob(os.path.join(download_path, f"{package}*")): + if dist["filename"] != file: + os.unlink(file) + + dist_file = os.path.join(download_path, dist["filename"]) + if not os.path.exists(dist_file): + download(dist["url"], dist_file, dist["md5_digest"]) + return dist_file + + +def retrieve_pypi_sdist_metadata(package, version): + # https://warehouse.pypa.io/api-reference/json.html + id_ = package if version is LATEST else f"{package}/{version}" + with urlopen(f"https://pypi.org/pypi/{id_}/json") as f: + metadata = json.load(f) + + if metadata["info"]["yanked"]: + raise ValueError(f"Release for {package} {version} was yanked") + + version = metadata["info"]["version"] + release = metadata["releases"][version] if version is LATEST else metadata["urls"] + (sdist,) = filter(lambda d: d["packagetype"] == "sdist", release) + return sdist + + +def download(url, dest, md5_digest): + with urlopen(url) as f: + data = f.read() + + assert md5(data).hexdigest() == md5_digest + + with open(dest, "wb") as f: + f.write(data) + + assert os.path.exists(dest) + + +def build_deps(package, sdist_file): + """Find out what are the build dependencies for a package. + + "Manually" install them, since pip will not install build + deps with `--no-build-isolation`. + """ + # delay importing, since pytest discovery phase may hit this file from a + # testenv without tomli + from setuptools.compat.py310 import tomllib + + archive = Archive(sdist_file) + info = tomllib.loads(_read_pyproject(archive)) + deps = info.get("build-system", {}).get("requires", []) + deps += EXTRA_BUILD_DEPS.get(package, []) + # Remove setuptools from requirements (and deduplicate) + requirements = {Requirement(d).name: d for d in deps} + return [v for k, v in requirements.items() if k != "setuptools"] + + +def _read_pyproject(archive): + contents = ( + archive.get_content(member) + for member in archive + if os.path.basename(archive.get_name(member)) == "pyproject.toml" + ) + return next(contents, "") diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/__pycache__/__init__.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2279eba21d9144d99f02352db830fd0d84a57318 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/__pycache__/__init__.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/__init__.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a4d85c942d014f46c7dea2cb40eb6bfd5dc9d7c Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/__init__.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/classification.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/classification.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78eacce0d7458cec70bbf36dd7b9948bd76ee3a1 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/classification.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/coco_metric.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/coco_metric.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21a043917bfe7da0009fd547227fc2ceb9ce7018 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/coco_metric.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/eval_datasets.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/eval_datasets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..029bc8ec23ef5f4188e00a173a5c26c70194e7cf Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/eval_datasets.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/evaluate.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/evaluate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0550c009250708385c1bd1301c9899700ea5b9a1 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/evaluate.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/imagenet_utils.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/imagenet_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d675c96e82459b3dd4a4e3f972a16ee1a5ea8b21 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/imagenet_utils.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/ok_vqa_utils.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/ok_vqa_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e659c94a9031f227c3da48ac4eda3f242a9c0010 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/ok_vqa_utils.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/vqa_metric.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/vqa_metric.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9a72047c89f7791db01071bcddd2c92c58be7a8 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/__pycache__/vqa_metric.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/classification.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/classification.py new file mode 100644 index 0000000000000000000000000000000000000000..a6503b30a370faeb98410f158e50a8bc0e4484b2 --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/classification.py @@ -0,0 +1,147 @@ +from typing import Dict, Sequence, Tuple +import re +import numpy as np +import torch + + +def postprocess_classification_generation(predictions) -> str: + return re.split("Prompt|Completion", predictions, 1)[0] + + +def compute_classification_accuracy(predictions: Sequence[Dict[str, str]]) -> float: + """Compute the accuracy of a sequence of predictions.""" + + def _preprocess_fn(s): + """Function to preprocess both targets and predictions.""" + return s.lower() + + is_correct = [ + _preprocess_fn(x["prediction"]) == _preprocess_fn(x["class_label"]) + for x in predictions + ] + + return np.mean(is_correct).item() + + +def compute_shifted_logits_and_labels( + logits: torch.Tensor, encodings, tokenizer, eoc_token_id +) -> Tuple[torch.Tensor, torch.Tensor]: + """Helper function to compute shifted logits and labels. + + This allows for straightforward computation of the loss on shift_logits + and shift_labels such that the nth element of logits computes the n-1th + element of the original labels (in the outputs, the nth element of logits + corresponds to the nth element of the labels). + + Elements in shift_labels that correspond to inputs are masked with values + of -100 (by default in hf, loss is only computed on token IDs >= 0). + + Returns: tuple containing two elements: + shift_logits: a float Tensor of shape [batch_size, seq_len - 1]. + shift_labels: an integer Tensor of shape [batch_size, seq_len - 1] + """ + + labels = encodings["input_ids"].clone() + + # convert padding and EOC tokens to -100 so they are ignored in loss + labels[labels == tokenizer.pad_token_id] = -100 + labels[labels == eoc_token_id] = -100 + + # Convert all tokens in prefix until separator to -100 so they are + # ignored in loss + for idx in range(len(labels)): + # Find the location of the last token of prefix *from right*, + # since the first non-padding token of the sequence will also be + # eos_token (because bos_token and eos_token are the same for + # the tokenizer). + end_of_prefix = -labels[idx].tolist()[::-1].index(tokenizer.eos_token_id) - 1 + labels[idx, : end_of_prefix + 1] = -100 + + # Shift so that tokens < n predict n. The shifted tensors both have + # shape [batch_size, seq_len - 1]. + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + + return shift_logits, shift_labels + + +def compute_per_sample_probs( + encodings, tokenizer, logits: torch.Tensor, eoc_token_id +) -> torch.Tensor: + """Helper function to compute per-sample probability of the input sequence. + + Assumes is used to separate inputs from targets in the + prompt text + """ + shift_logits, shift_labels = compute_shifted_logits_and_labels( + logits, encodings, tokenizer, eoc_token_id + ) + + # Tuple of tensors for unmasked label tokens. The first element of the + # tuple contains the batch indices; the second element contains the + # sequence indices. + unmasked_indices = torch.nonzero(shift_labels != -100, as_tuple=True) + # Tensor where the i^th element is the token_id corresponding to the i^th + # element of unmasked_indices + unmasked_token_ids = shift_labels[unmasked_indices] + + # 3d tensor of [batch_idx, sequence_position, token_id] for unmasked tokens. + target_idxs = torch.column_stack([*unmasked_indices, unmasked_token_ids]) + target_idxs = target_idxs.to(shift_logits.device) + + # Sanity check that every element in batch has at least one unmasked + # target token + assert torch.all( + torch.bincount(target_idxs[:, 0]) != 0 + ), "At least one element in batch has no unmasked target tokens." + + # Renormalize over tokens to make sure they are proper probabilities via + # softmax over the token dimension. + shift_probs = torch.nn.functional.softmax(shift_logits, 2) + + # Compute the probability of the target sequence (as the product of the + # probability of the individual tokens in the sequence). + target_probs = torch.ones(len(shift_labels), device=shift_logits.device) + for i, j, k in target_idxs: + target_probs[i] *= shift_probs[i, j, k] + + return target_probs + + +def compute_per_sample_loss(encodings, tokenizer, logits, eoc_token_id) -> torch.Tensor: + """Helper function to compute per-sample classification loss. + + Assumes is used to separate inputs from targets in the + prompt text + """ + shift_logits, shift_labels = compute_shifted_logits_and_labels( + logits, encodings, tokenizer, eoc_token_id + ) + + device = shift_logits.device + + # Loss is computed token-wise, on Tensors of shape + # [batch_size * (seq_len - 1), vocab_size] + # and returns a loss tensor of shape + # [batch_size * (seq_len - 1)]. Most of the tokens will be masked + # in this computation. + loss = torch.nn.functional.cross_entropy( + shift_logits.view(-1, shift_logits.size(-1)), + shift_labels.view(-1).to(device), + reduction="none", + ) + + # Reshape to [batch_size, seq_len - 1] + loss = loss.view(shift_logits.size(0), shift_logits.size(1)).cpu() + + # loss_mask is 1 for tokens we want included in the loss, and 0 for tokens + # that should be ignored in the loss. + loss_mask = (shift_labels != -100).int().cpu() + + loss *= loss_mask + + # Compute per-element loss : sum loss over all (unmasked) tokens and + # divide by number of variable tokens to obtain tensor of + # shape [batch_size,] + loss = loss.sum(dim=1) / (shift_labels != -100).sum(dim=1).float() + return loss diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/coco_metric.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/coco_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1c8842d804f6d56bf878fe288f896c5e29e935 --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/coco_metric.py @@ -0,0 +1,22 @@ +from pycocoevalcap.eval import COCOEvalCap +from pycocotools.coco import COCO + + +def compute_cider( + result_path, + annotations_path="/data/yfcc-tmp/data/mscoco/annotations/captions_train2017.json", +): + # create coco object and coco_result object + coco = COCO(annotations_path) + coco_result = coco.loadRes(result_path) + + # create coco_eval object by taking coco and coco_result + coco_eval = COCOEvalCap(coco, coco_result) + coco_eval.params["image_id"] = coco_result.getImgIds() + coco_eval.evaluate() + + return coco_eval.eval + + +def postprocess_captioning_generation(predictions): + return predictions.split("Output", 1)[0] diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/imagenet_utils.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/imagenet_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5803c700249335b8ecf947ca81d543d51c9cbbb5 --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/eval/imagenet_utils.py @@ -0,0 +1,1007 @@ +# classnames via https://github.com/mlfoundations/wise-ft/blob/master/src/datasets/imagenet_classnames.py#L1 +openai_imagenet_classnames = [ + "tench", + "goldfish", + "great white shark", + "tiger shark", + "hammerhead shark", + "electric ray", + "stingray", + "rooster", + "hen", + "ostrich", + "brambling", + "goldfinch", + "house finch", + "junco", + "indigo bunting", + "American robin", + "bulbul", + "jay", + "magpie", + "chickadee", + "American dipper", + "kite (bird of prey)", + "bald eagle", + "vulture", + "great grey owl", + "fire salamander", + "smooth newt", + "newt", + "spotted salamander", + "axolotl", + "American bullfrog", + "tree frog", + "tailed frog", + "loggerhead sea turtle", + "leatherback sea turtle", + "mud turtle", + "terrapin", + "box turtle", + "banded gecko", + "green iguana", + "Carolina anole", + "desert grassland whiptail lizard", + "agama", + "frilled-necked lizard", + "alligator lizard", + "Gila monster", + "European green lizard", + "chameleon", + "Komodo dragon", + "Nile crocodile", + "American alligator", + "triceratops", + "worm snake", + "ring-necked snake", + "eastern hog-nosed snake", + "smooth green snake", + "kingsnake", + "garter snake", + "water snake", + "vine snake", + "night snake", + "boa constrictor", + "African rock python", + "Indian cobra", + "green mamba", + "sea snake", + "Saharan horned viper", + "eastern diamondback rattlesnake", + "sidewinder rattlesnake", + "trilobite", + "harvestman", + "scorpion", + "yellow garden spider", + "barn spider", + "European garden spider", + "southern black widow", + "tarantula", + "wolf spider", + "tick", + "centipede", + "black grouse", + "ptarmigan", + "ruffed grouse", + "prairie grouse", + "peafowl", + "quail", + "partridge", + "african grey parrot", + "macaw", + "sulphur-crested cockatoo", + "lorikeet", + "coucal", + "bee eater", + "hornbill", + "hummingbird", + "jacamar", + "toucan", + "duck", + "red-breasted merganser", + "goose", + "black swan", + "tusker", + "echidna", + "platypus", + "wallaby", + "koala", + "wombat", + "jellyfish", + "sea anemone", + "brain coral", + "flatworm", + "nematode", + "conch", + "snail", + "slug", + "sea slug", + "chiton", + "chambered nautilus", + "Dungeness crab", + "rock crab", + "fiddler crab", + "red king crab", + "American lobster", + "spiny lobster", + "crayfish", + "hermit crab", + "isopod", + "white stork", + "black stork", + "spoonbill", + "flamingo", + "little blue heron", + "great egret", + "bittern bird", + "crane bird", + "limpkin", + "common gallinule", + "American coot", + "bustard", + "ruddy turnstone", + "dunlin", + "common redshank", + "dowitcher", + "oystercatcher", + "pelican", + "king penguin", + "albatross", + "grey whale", + "killer whale", + "dugong", + "sea lion", + "Chihuahua", + "Japanese Chin", + "Maltese", + "Pekingese", + "Shih Tzu", + "King Charles Spaniel", + "Papillon", + "toy terrier", + "Rhodesian Ridgeback", + "Afghan Hound", + "Basset Hound", + "Beagle", + "Bloodhound", + "Bluetick Coonhound", + "Black and Tan Coonhound", + "Treeing Walker Coonhound", + "English foxhound", + "Redbone Coonhound", + "borzoi", + "Irish Wolfhound", + "Italian Greyhound", + "Whippet", + "Ibizan Hound", + "Norwegian Elkhound", + "Otterhound", + "Saluki", + "Scottish Deerhound", + "Weimaraner", + "Staffordshire Bull Terrier", + "American Staffordshire Terrier", + "Bedlington Terrier", + "Border Terrier", + "Kerry Blue Terrier", + "Irish Terrier", + "Norfolk Terrier", + "Norwich Terrier", + "Yorkshire Terrier", + "Wire Fox Terrier", + "Lakeland Terrier", + "Sealyham Terrier", + "Airedale Terrier", + "Cairn Terrier", + "Australian Terrier", + "Dandie Dinmont Terrier", + "Boston Terrier", + "Miniature Schnauzer", + "Giant Schnauzer", + "Standard Schnauzer", + "Scottish Terrier", + "Tibetan Terrier", + "Australian Silky Terrier", + "Soft-coated Wheaten Terrier", + "West Highland White Terrier", + "Lhasa Apso", + "Flat-Coated Retriever", + "Curly-coated Retriever", + "Golden Retriever", + "Labrador Retriever", + "Chesapeake Bay Retriever", + "German Shorthaired Pointer", + "Vizsla", + "English Setter", + "Irish Setter", + "Gordon Setter", + "Brittany dog", + "Clumber Spaniel", + "English Springer Spaniel", + "Welsh Springer Spaniel", + "Cocker Spaniel", + "Sussex Spaniel", + "Irish Water Spaniel", + "Kuvasz", + "Schipperke", + "Groenendael dog", + "Malinois", + "Briard", + "Australian Kelpie", + "Komondor", + "Old English Sheepdog", + "Shetland Sheepdog", + "collie", + "Border Collie", + "Bouvier des Flandres dog", + "Rottweiler", + "German Shepherd Dog", + "Dobermann", + "Miniature Pinscher", + "Greater Swiss Mountain Dog", + "Bernese Mountain Dog", + "Appenzeller Sennenhund", + "Entlebucher Sennenhund", + "Boxer", + "Bullmastiff", + "Tibetan Mastiff", + "French Bulldog", + "Great Dane", + "St. Bernard", + "husky", + "Alaskan Malamute", + "Siberian Husky", + "Dalmatian", + "Affenpinscher", + "Basenji", + "pug", + "Leonberger", + "Newfoundland dog", + "Great Pyrenees dog", + "Samoyed", + "Pomeranian", + "Chow Chow", + "Keeshond", + "brussels griffon", + "Pembroke Welsh Corgi", + "Cardigan Welsh Corgi", + "Toy Poodle", + "Miniature Poodle", + "Standard Poodle", + "Mexican hairless dog (xoloitzcuintli)", + "grey wolf", + "Alaskan tundra wolf", + "red wolf or maned wolf", + "coyote", + "dingo", + "dhole", + "African wild dog", + "hyena", + "red fox", + "kit fox", + "Arctic fox", + "grey fox", + "tabby cat", + "tiger cat", + "Persian cat", + "Siamese cat", + "Egyptian Mau", + "cougar", + "lynx", + "leopard", + "snow leopard", + "jaguar", + "lion", + "tiger", + "cheetah", + "brown bear", + "American black bear", + "polar bear", + "sloth bear", + "mongoose", + "meerkat", + "tiger beetle", + "ladybug", + "ground beetle", + "longhorn beetle", + "leaf beetle", + "dung beetle", + "rhinoceros beetle", + "weevil", + "fly", + "bee", + "ant", + "grasshopper", + "cricket insect", + "stick insect", + "cockroach", + "praying mantis", + "cicada", + "leafhopper", + "lacewing", + "dragonfly", + "damselfly", + "red admiral butterfly", + "ringlet butterfly", + "monarch butterfly", + "small white butterfly", + "sulphur butterfly", + "gossamer-winged butterfly", + "starfish", + "sea urchin", + "sea cucumber", + "cottontail rabbit", + "hare", + "Angora rabbit", + "hamster", + "porcupine", + "fox squirrel", + "marmot", + "beaver", + "guinea pig", + "common sorrel horse", + "zebra", + "pig", + "wild boar", + "warthog", + "hippopotamus", + "ox", + "water buffalo", + "bison", + "ram (adult male sheep)", + "bighorn sheep", + "Alpine ibex", + "hartebeest", + "impala (antelope)", + "gazelle", + "arabian camel", + "llama", + "weasel", + "mink", + "European polecat", + "black-footed ferret", + "otter", + "skunk", + "badger", + "armadillo", + "three-toed sloth", + "orangutan", + "gorilla", + "chimpanzee", + "gibbon", + "siamang", + "guenon", + "patas monkey", + "baboon", + "macaque", + "langur", + "black-and-white colobus", + "proboscis monkey", + "marmoset", + "white-headed capuchin", + "howler monkey", + "titi monkey", + "Geoffroy's spider monkey", + "common squirrel monkey", + "ring-tailed lemur", + "indri", + "Asian elephant", + "African bush elephant", + "red panda", + "giant panda", + "snoek fish", + "eel", + "silver salmon", + "rock beauty fish", + "clownfish", + "sturgeon", + "gar fish", + "lionfish", + "pufferfish", + "abacus", + "abaya", + "academic gown", + "accordion", + "acoustic guitar", + "aircraft carrier", + "airliner", + "airship", + "altar", + "ambulance", + "amphibious vehicle", + "analog clock", + "apiary", + "apron", + "trash can", + "assault rifle", + "backpack", + "bakery", + "balance beam", + "balloon", + "ballpoint pen", + "Band-Aid", + "banjo", + "baluster / handrail", + "barbell", + "barber chair", + "barbershop", + "barn", + "barometer", + "barrel", + "wheelbarrow", + "baseball", + "basketball", + "bassinet", + "bassoon", + "swimming cap", + "bath towel", + "bathtub", + "station wagon", + "lighthouse", + "beaker", + "military hat (bearskin or shako)", + "beer bottle", + "beer glass", + "bell tower", + "baby bib", + "tandem bicycle", + "bikini", + "ring binder", + "binoculars", + "birdhouse", + "boathouse", + "bobsleigh", + "bolo tie", + "poke bonnet", + "bookcase", + "bookstore", + "bottle cap", + "hunting bow", + "bow tie", + "brass memorial plaque", + "bra", + "breakwater", + "breastplate", + "broom", + "bucket", + "buckle", + "bulletproof vest", + "high-speed train", + "butcher shop", + "taxicab", + "cauldron", + "candle", + "cannon", + "canoe", + "can opener", + "cardigan", + "car mirror", + "carousel", + "tool kit", + "cardboard box / carton", + "car wheel", + "automated teller machine", + "cassette", + "cassette player", + "castle", + "catamaran", + "CD player", + "cello", + "mobile phone", + "chain", + "chain-link fence", + "chain mail", + "chainsaw", + "storage chest", + "chiffonier", + "bell or wind chime", + "china cabinet", + "Christmas stocking", + "church", + "movie theater", + "cleaver", + "cliff dwelling", + "cloak", + "clogs", + "cocktail shaker", + "coffee mug", + "coffeemaker", + "spiral or coil", + "combination lock", + "computer keyboard", + "candy store", + "container ship", + "convertible", + "corkscrew", + "cornet", + "cowboy boot", + "cowboy hat", + "cradle", + "construction crane", + "crash helmet", + "crate", + "infant bed", + "Crock Pot", + "croquet ball", + "crutch", + "cuirass", + "dam", + "desk", + "desktop computer", + "rotary dial telephone", + "diaper", + "digital clock", + "digital watch", + "dining table", + "dishcloth", + "dishwasher", + "disc brake", + "dock", + "dog sled", + "dome", + "doormat", + "drilling rig", + "drum", + "drumstick", + "dumbbell", + "Dutch oven", + "electric fan", + "electric guitar", + "electric locomotive", + "entertainment center", + "envelope", + "espresso machine", + "face powder", + "feather boa", + "filing cabinet", + "fireboat", + "fire truck", + "fire screen", + "flagpole", + "flute", + "folding chair", + "football helmet", + "forklift", + "fountain", + "fountain pen", + "four-poster bed", + "freight car", + "French horn", + "frying pan", + "fur coat", + "garbage truck", + "gas mask or respirator", + "gas pump", + "goblet", + "go-kart", + "golf ball", + "golf cart", + "gondola", + "gong", + "gown", + "grand piano", + "greenhouse", + "radiator grille", + "grocery store", + "guillotine", + "hair clip", + "hair spray", + "half-track", + "hammer", + "hamper", + "hair dryer", + "hand-held computer", + "handkerchief", + "hard disk drive", + "harmonica", + "harp", + "combine harvester", + "hatchet", + "holster", + "home theater", + "honeycomb", + "hook", + "hoop skirt", + "gymnastic horizontal bar", + "horse-drawn vehicle", + "hourglass", + "iPod", + "clothes iron", + "carved pumpkin", + "jeans", + "jeep", + "T-shirt", + "jigsaw puzzle", + "rickshaw", + "joystick", + "kimono", + "knee pad", + "knot", + "lab coat", + "ladle", + "lampshade", + "laptop computer", + "lawn mower", + "lens cap", + "letter opener", + "library", + "lifeboat", + "lighter", + "limousine", + "ocean liner", + "lipstick", + "slip-on shoe", + "lotion", + "music speaker", + "loupe magnifying glass", + "sawmill", + "magnetic compass", + "messenger bag", + "mailbox", + "tights", + "one-piece bathing suit", + "manhole cover", + "maraca", + "marimba", + "mask", + "matchstick", + "maypole", + "maze", + "measuring cup", + "medicine cabinet", + "megalith", + "microphone", + "microwave oven", + "military uniform", + "milk can", + "minibus", + "miniskirt", + "minivan", + "missile", + "mitten", + "mixing bowl", + "mobile home", + "ford model t", + "modem", + "monastery", + "monitor", + "moped", + "mortar and pestle", + "graduation cap", + "mosque", + "mosquito net", + "vespa", + "mountain bike", + "tent", + "computer mouse", + "mousetrap", + "moving van", + "muzzle", + "metal nail", + "neck brace", + "necklace", + "baby pacifier", + "notebook computer", + "obelisk", + "oboe", + "ocarina", + "odometer", + "oil filter", + "pipe organ", + "oscilloscope", + "overskirt", + "bullock cart", + "oxygen mask", + "product packet / packaging", + "paddle", + "paddle wheel", + "padlock", + "paintbrush", + "pajamas", + "palace", + "pan flute", + "paper towel", + "parachute", + "parallel bars", + "park bench", + "parking meter", + "railroad car", + "patio", + "payphone", + "pedestal", + "pencil case", + "pencil sharpener", + "perfume", + "Petri dish", + "photocopier", + "plectrum", + "Pickelhaube", + "picket fence", + "pickup truck", + "pier", + "piggy bank", + "pill bottle", + "pillow", + "ping-pong ball", + "pinwheel", + "pirate ship", + "drink pitcher", + "block plane", + "planetarium", + "plastic bag", + "plate rack", + "farm plow", + "plunger", + "Polaroid camera", + "pole", + "police van", + "poncho", + "pool table", + "soda bottle", + "plant pot", + "potter's wheel", + "power drill", + "prayer rug", + "printer", + "prison", + "missile", + "projector", + "hockey puck", + "punching bag", + "purse", + "quill", + "quilt", + "race car", + "racket", + "radiator", + "radio", + "radio telescope", + "rain barrel", + "recreational vehicle", + "fishing casting reel", + "reflex camera", + "refrigerator", + "remote control", + "restaurant", + "revolver", + "rifle", + "rocking chair", + "rotisserie", + "eraser", + "rugby ball", + "ruler measuring stick", + "sneaker", + "safe", + "safety pin", + "salt shaker", + "sandal", + "sarong", + "saxophone", + "scabbard", + "weighing scale", + "school bus", + "schooner", + "scoreboard", + "CRT monitor", + "screw", + "screwdriver", + "seat belt", + "sewing machine", + "shield", + "shoe store", + "shoji screen / room divider", + "shopping basket", + "shopping cart", + "shovel", + "shower cap", + "shower curtain", + "ski", + "balaclava ski mask", + "sleeping bag", + "slide rule", + "sliding door", + "slot machine", + "snorkel", + "snowmobile", + "snowplow", + "soap dispenser", + "soccer ball", + "sock", + "solar thermal collector", + "sombrero", + "soup bowl", + "keyboard space bar", + "space heater", + "space shuttle", + "spatula", + "motorboat", + "spider web", + "spindle", + "sports car", + "spotlight", + "stage", + "steam locomotive", + "through arch bridge", + "steel drum", + "stethoscope", + "scarf", + "stone wall", + "stopwatch", + "stove", + "strainer", + "tram", + "stretcher", + "couch", + "stupa", + "submarine", + "suit", + "sundial", + "sunglasses", + "sunglasses", + "sunscreen", + "suspension bridge", + "mop", + "sweatshirt", + "swim trunks / shorts", + "swing", + "electrical switch", + "syringe", + "table lamp", + "tank", + "tape player", + "teapot", + "teddy bear", + "television", + "tennis ball", + "thatched roof", + "front curtain", + "thimble", + "threshing machine", + "throne", + "tile roof", + "toaster", + "tobacco shop", + "toilet seat", + "torch", + "totem pole", + "tow truck", + "toy store", + "tractor", + "semi-trailer truck", + "tray", + "trench coat", + "tricycle", + "trimaran", + "tripod", + "triumphal arch", + "trolleybus", + "trombone", + "hot tub", + "turnstile", + "typewriter keyboard", + "umbrella", + "unicycle", + "upright piano", + "vacuum cleaner", + "vase", + "vaulted or arched ceiling", + "velvet fabric", + "vending machine", + "vestment", + "viaduct", + "violin", + "volleyball", + "waffle iron", + "wall clock", + "wallet", + "wardrobe", + "military aircraft", + "sink", + "washing machine", + "water bottle", + "water jug", + "water tower", + "whiskey jug", + "whistle", + "hair wig", + "window screen", + "window shade", + "Windsor tie", + "wine bottle", + "airplane wing", + "wok", + "wooden spoon", + "wool", + "split-rail fence", + "shipwreck", + "sailboat", + "yurt", + "website", + "comic book", + "crossword", + "traffic or street sign", + "traffic light", + "dust jacket", + "menu", + "plate", + "guacamole", + "consomme", + "hot pot", + "trifle", + "ice cream", + "popsicle", + "baguette", + "bagel", + "pretzel", + "cheeseburger", + "hot dog", + "mashed potatoes", + "cabbage", + "broccoli", + "cauliflower", + "zucchini", + "spaghetti squash", + "acorn squash", + "butternut squash", + "cucumber", + "artichoke", + "bell pepper", + "cardoon", + "mushroom", + "Granny Smith apple", + "strawberry", + "orange", + "lemon", + "fig", + "pineapple", + "banana", + "jackfruit", + "cherimoya (custard apple)", + "pomegranate", + "hay", + "carbonara", + "chocolate syrup", + "dough", + "meatloaf", + "pizza", + "pot pie", + "burrito", + "red wine", + "espresso", + "tea cup", + "eggnog", + "mountain", + "bubble", + "cliff", + "coral reef", + "geyser", + "lakeshore", + "promontory", + "sandbar", + "beach", + "valley", + "volcano", + "baseball player", + "bridegroom", + "scuba diver", + "rapeseed", + "daisy", + "yellow lady's slipper", + "corn", + "acorn", + "rose hip", + "horse chestnut seed", + "coral fungus", + "agaric", + "gyromitra", + "stinkhorn mushroom", + "earth star fungus", + "hen of the woods mushroom", + "bolete", + "corn cob", + "toilet paper", +] +# Maps numeric class ids to labels +IMAGENET_1K_CLASS_ID_TO_LABEL = dict( + zip(range(len(openai_imagenet_classnames)), openai_imagenet_classnames) +) diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__init__.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/__init__.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c5dc73804344b206d3516e6f904afa7fe3c7208 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/__init__.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/flamingo.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/flamingo.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bbc1b9db20f05da10d255004473eeaa99d533ee Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/flamingo.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/helpers.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/helpers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a206cecd738b40c12845544ef5e9d22f246b64b Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/helpers.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/utils.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d664ab59d5de0388a98b98eb6641c3ae112bf043 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/__pycache__/utils.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/src/flamingo.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/flamingo.py new file mode 100644 index 0000000000000000000000000000000000000000..a8eae254b3b6b4bc82d4ee5ddfbc5764c49702db --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/flamingo.py @@ -0,0 +1,198 @@ +import torch +from einops import rearrange +from torch import nn + +from .helpers import PerceiverResampler + + +class Flamingo(nn.Module): + def __init__( + self, + vision_encoder: nn.Module, + lang_encoder: nn.Module, + eoc_token_id: int, + media_token_id: int, + vis_dim: int, + cross_attn_every_n_layers: int = 1, + use_media_placement_augmentation: bool = False, + ): + """ + Args: + vision_encoder (nn.Module): HF CLIPModel + lang_encoder (nn.Module): HF causal language model + eoc_token_id (int): Token id for <|endofchunk|> + media_token_id (int): Token id for + vis_dim (int): Dimension of the visual features. + Visual features are projected to match this shape along the last dimension. + cross_attn_every_n_layers (int, optional): How often to apply cross attention after transformer layer. Defaults to 1. + use_media_placement_augmentation (bool, optional): Whether to randomly assign images to the preceding or following text in training. Defaults to False. + """ + super().__init__() + self.eoc_token_id = eoc_token_id + self.media_token_id = media_token_id + self.use_media_placement_augmentation = use_media_placement_augmentation + self.vis_dim = vis_dim + self.vision_encoder = vision_encoder + self.perceiver = PerceiverResampler(dim=self.vis_dim) + self.lang_encoder = lang_encoder + self.lang_encoder.init_flamingo( + media_token_id=media_token_id, + vis_hidden_size=self.vis_dim, + cross_attn_every_n_layers=cross_attn_every_n_layers, + use_media_placement_augmentation=self.use_media_placement_augmentation, + ) + + def forward( + self, + vision_x: torch.Tensor, + lang_x: torch.Tensor, + attention_mask: torch.Tensor = None, + labels: torch.Tensor = None, + use_cached_vision_x: bool = False, + clear_conditioned_layers: bool = True, + past_key_values=None, + use_cache: bool = False, + ): + """ + Forward pass of Flamingo. + + Args: + vision_x (torch.Tensor): Vision input + shape (B, T_img, F, C, H, W) with F=1 + lang_x (torch.Tensor): Language input ids + shape (B, T_txt) + attention_mask (torch.Tensor, optional): Attention mask. Defaults to None. + labels (torch.Tensor, optional): Labels. Defaults to None. + clear_conditioned_layers: if True, clear the conditioned layers + once the foward pass is completed. Set this to false if the + same set of images will be reused in another subsequent + forward pass. + past_key_values: pre-computed values to pass to language model. + See past_key_values documentation in Hugging Face + CausalLM models. + use_cache: whether to use cached key values. See use_cache + documentation in Hugging Face CausalLM models. + """ + assert ( + vision_x is not None + ) or use_cached_vision_x, ( + "Must provide either vision_x or use_cached_vision_x to True." + ) + + if use_cached_vision_x: + # Case: use cached; vision_x should be cached and other + # vision-related inputs should not be provided. + assert ( + vision_x is None + ), "Expect vision_x to be None when use_cached_vision_x is True." + assert self.lang_encoder.is_conditioned() + + else: + # Case: do not use caching (i.e. this is a standard forward pass); + self._encode_vision_x(vision_x=vision_x) + + output = self.lang_encoder( + input_ids=lang_x, + attention_mask=attention_mask, + labels=labels, + past_key_values=past_key_values, + use_cache=use_cache, + ) + + if clear_conditioned_layers: + self.lang_encoder.clear_conditioned_layers() + + return output + + def generate( + self, + vision_x: torch.Tensor, + lang_x: torch.Tensor, + attention_mask: torch.Tensor = None, + num_beams=1, + max_new_tokens=None, + temperature=1.0, + top_k=0, + top_p=1.0, + no_repeat_ngram_size=0, + prefix_allowed_tokens_fn=None, + length_penalty=1.0, + num_return_sequences=1, + do_sample=False, + early_stopping=False, + ): + """ + Generate text conditioned on vision and language inputs. + + Args: + vision_x (torch.Tensor): Vision input + shape (B, T_img, F, C, H, W) + images in the same chunk are collated along T_img, and frames are collated along F + currently only F=1 is supported (single-frame videos) + lang_x (torch.Tensor): Language input + shape (B, T_txt) + max_length (int, optional): Maximum length of the output. Defaults to None. + attention_mask (torch.Tensor, optional): Attention mask. Defaults to None. + num_beams (int, optional): Number of beams. Defaults to 1. + max_new_tokens (int, optional): Maximum new tokens. Defaults to None. + temperature (float, optional): Temperature. Defaults to 1.0. + top_k (int, optional): Top k. Defaults to 0. + top_p (float, optional): Top p. Defaults to 1.0. + no_repeat_ngram_size (int, optional): No repeat ngram size. Defaults to 0. + length_penalty (float, optional): Length penalty. Defaults to 1.0. + num_return_sequences (int, optional): Number of return sequences. Defaults to 1. + do_sample (bool, optional): Do sample. Defaults to False. + early_stopping (bool, optional): Early stopping. Defaults to False. + Returns: + torch.Tensor: lang_x with generated tokens appended to it + """ + if num_beams > 1: + vision_x = vision_x.repeat_interleave(num_beams, dim=0) + + self._encode_vision_x(vision_x=vision_x) + + output = self.lang_encoder.generate( + lang_x, + attention_mask=attention_mask, + eos_token_id=self.eoc_token_id, + num_beams=num_beams, + max_new_tokens=max_new_tokens, + temperature=temperature, + top_k=top_k, + top_p=top_p, + prefix_allowed_tokens_fn=prefix_allowed_tokens_fn, + no_repeat_ngram_size=no_repeat_ngram_size, + length_penalty=length_penalty, + num_return_sequences=num_return_sequences, + do_sample=do_sample, + early_stopping=early_stopping, + ) + + self.lang_encoder.clear_conditioned_layers() + return output + + def _encode_vision_x(self, vision_x: torch.Tensor): + """ + Compute media tokens from vision input by passing it through vision encoder and conditioning language model. + Args: + vision_x (torch.Tensor): Vision input + shape (B, T_img, F, C, H, W) + Images in the same chunk are collated along T_img, and frames are collated along F + Currently only F=1 is supported (single-frame videos) + + rearrange code based on https://github.com/dhansmair/flamingo-mini + """ + + assert vision_x.ndim == 6, "vision_x should be of shape (b, T_img, F, C, H, W)" + b, T, F = vision_x.shape[:3] + assert F == 1, "Only single frame supported" + + vision_x = rearrange(vision_x, "b T F c h w -> (b T F) c h w") + with torch.no_grad(): + vision_x = self.vision_encoder.visual(vision_x)[1] + vision_x = rearrange(vision_x, "(b T F) v d -> b T F v d", b=b, T=T, F=F) + + vision_x = self.perceiver(vision_x) # reshapes to (b, T, n, d) + + for layer in self.lang_encoder._get_decoder_layers(): + layer.condition_vis_x(vision_x) diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/src/flamingo_lm.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/flamingo_lm.py new file mode 100644 index 0000000000000000000000000000000000000000..c064d87ed140eb962d4ca0e951c08039cde68794 --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/flamingo_lm.py @@ -0,0 +1,138 @@ +import random + +import torch.nn as nn + +from .helpers import GatedCrossAttentionBlock +from .utils import getattr_recursive, setattr_recursive + + +class FlamingoLayer(nn.Module): + def __init__(self, gated_cross_attn_layer, decoder_layer): + super().__init__() + self.gated_cross_attn_layer = gated_cross_attn_layer + self.decoder_layer = decoder_layer + self.vis_x = None + self.media_locations = None + + def is_conditioned(self) -> bool: + """Check whether the layer is conditioned.""" + return self.vis_x is not None + + # Used this great idea from this implementation of Flamingo (https://github.com/dhansmair/flamingo-mini/) + def condition_vis_x(self, vis_x): + self.vis_x = vis_x + + def condition_media_locations(self, media_locations): + self.media_locations = media_locations + + def condition_attend_previous(self, attend_previous): + self.attend_previous = attend_previous + + def forward( + self, + lang_x, + attention_mask=None, + **decoder_layer_kwargs, + ): + if self.gated_cross_attn_layer is None: + return self.decoder_layer( + lang_x, attention_mask=attention_mask, **decoder_layer_kwargs + ) + + if self.vis_x is None: + raise ValueError("vis_x must be conditioned before forward pass") + + if self.media_locations is None: + raise ValueError("media_locations must be conditioned before forward pass") + + lang_x = self.gated_cross_attn_layer( + lang_x, + self.vis_x, + media_locations=self.media_locations, + attend_previous=self.attend_previous, + ) + lang_x = self.decoder_layer( + lang_x, attention_mask=attention_mask, **decoder_layer_kwargs + ) + return lang_x + + +class FlamingoLMMixin(nn.Module): + """ + Mixin to add cross-attention layers to a language model. + """ + + def set_decoder_layers_attr_name(self, decoder_layers_attr_name): + self.decoder_layers_attr_name = decoder_layers_attr_name + + def _get_decoder_layers(self): + return getattr_recursive(self, self.decoder_layers_attr_name) + + def _set_decoder_layers(self, value): + setattr_recursive(self, self.decoder_layers_attr_name, value) + + def init_flamingo( + self, + media_token_id, + vis_hidden_size, + cross_attn_every_n_layers, + use_media_placement_augmentation, + ): + """ + Initialize Flamingo by adding a new gated cross attn to the decoder. Store the media token id for computing the media locations. + """ + + self.gated_cross_attn_layers = nn.ModuleList( + [ + GatedCrossAttentionBlock( + dim=self.config.hidden_size, dim_visual=vis_hidden_size + ) + if (layer_idx + 1) % cross_attn_every_n_layers == 0 + else None + for layer_idx, _ in enumerate(self._get_decoder_layers()) + ] + ) + self._set_decoder_layers( + nn.ModuleList( + [ + FlamingoLayer(gated_cross_attn_layer, decoder_layer) + for gated_cross_attn_layer, decoder_layer in zip( + self.gated_cross_attn_layers, self._get_decoder_layers() + ) + ] + ) + ) + self.media_token_id = media_token_id + self.use_media_placement_augmentation = use_media_placement_augmentation + self.initialized_flamingo = True + + def forward(self, *input, **kwargs): + """Condition the Flamingo layers on the media locations before forward()""" + if not self.initialized_flamingo: + raise ValueError( + "Flamingo layers are not initialized. Please call `init_flamingo` first." + ) + + input_ids = kwargs["input_ids"] if "input_ids" in kwargs else input[0] + media_locations = input_ids == self.media_token_id + attend_previous = ( + (random.random() < 0.5) if self.use_media_placement_augmentation else False + ) + + for layer in self.get_decoder().layers: + layer.condition_media_locations(media_locations) + layer.condition_attend_previous(attend_previous) + + return super().forward( + *input, **kwargs + ) # Call the other parent's forward method + + def is_conditioned(self) -> bool: + """Check whether all decoder layers are already conditioned.""" + return all(l.is_conditioned() for l in self._get_decoder_layers()) + + def clear_conditioned_layers(self): + for layer in self._get_decoder_layers(): + layer.condition_vis_x(None) + layer.condition_media_locations(None) + layer.condition_attend_previous(None) diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/src/helpers.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..78b48969800b6490c8a2e54cf7e1909e85986625 --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/helpers.py @@ -0,0 +1,275 @@ +""" +Taken from https://github.com/lucidrains/flamingo-pytorch +""" + +import torch +from einops import rearrange, repeat +from einops_exts import rearrange_many +from torch import einsum, nn + + +def exists(val): + return val is not None + + +def FeedForward(dim, mult=4): + inner_dim = int(dim * mult) + return nn.Sequential( + nn.LayerNorm(dim), + nn.Linear(dim, inner_dim, bias=False), + nn.GELU(), + nn.Linear(inner_dim, dim, bias=False), + ) + + +class PerceiverAttention(nn.Module): + def __init__(self, *, dim, dim_head=64, heads=8): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + inner_dim = dim_head * heads + + self.norm_media = nn.LayerNorm(dim) + self.norm_latents = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + def forward(self, x, latents): + """ + Args: + x (torch.Tensor): image features + shape (b, T, n1, D) + latent (torch.Tensor): latent features + shape (b, T, n2, D) + """ + x = self.norm_media(x) + latents = self.norm_latents(latents) + + h = self.heads + + q = self.to_q(latents) + kv_input = torch.cat((x, latents), dim=-2) + k, v = self.to_kv(kv_input).chunk(2, dim=-1) + q, k, v = rearrange_many((q, k, v), "b t n (h d) -> b h t n d", h=h) + q = q * self.scale + + # attention + sim = einsum("... i d, ... j d -> ... i j", q, k) + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + attn = sim.softmax(dim=-1) + + out = einsum("... i j, ... j d -> ... i d", attn, v) + out = rearrange(out, "b h t n d -> b t n (h d)", h=h) + return self.to_out(out) + + +class PerceiverResampler(nn.Module): + def __init__( + self, + *, + dim, + depth=6, + dim_head=64, + heads=8, + num_latents=64, + max_num_media=None, + max_num_frames=None, + ff_mult=4, + ): + super().__init__() + self.latents = nn.Parameter(torch.randn(num_latents, dim)) + self.frame_embs = ( + nn.Parameter(torch.randn(max_num_frames, dim)) + if exists(max_num_frames) + else None + ) + self.media_time_embs = ( + nn.Parameter(torch.randn(max_num_media, 1, dim)) + if exists(max_num_media) + else None + ) + + self.layers = nn.ModuleList([]) + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads), + FeedForward(dim=dim, mult=ff_mult), + ] + ) + ) + + self.norm = nn.LayerNorm(dim) + + def forward(self, x): + """ + Args: + x (torch.Tensor): image features + shape (b, T, F, v, D) + Returns: + shape (b, T, n, D) where n is self.num_latents + """ + b, T, F, v = x.shape[:4] + + # frame and media time embeddings + if exists(self.frame_embs): + frame_embs = repeat(self.frame_embs[:F], "F d -> b T F v d", b=b, T=T, v=v) + x = x + frame_embs + x = rearrange( + x, "b T F v d -> b T (F v) d" + ) # flatten the frame and spatial dimensions + if exists(self.media_time_embs): + x = x + self.media_time_embs[:T] + + # blocks + latents = repeat(self.latents, "n d -> b T n d", b=b, T=T) + for attn, ff in self.layers: + latents = attn(x, latents) + latents + latents = ff(latents) + latents + return self.norm(latents) + + +# gated cross attention + + +class MaskedCrossAttention(nn.Module): + def __init__( + self, + *, + dim, + dim_visual, + dim_head=64, + heads=8, + only_attend_immediate_media=True, + ): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + inner_dim = dim_head * heads + + self.norm = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_kv = nn.Linear(dim_visual, inner_dim * 2, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + # whether for text to only attend to immediate preceding image, or all previous images + self.only_attend_immediate_media = only_attend_immediate_media + + def forward(self, x, media, media_locations=None, attend_previous=True): + """ + Args: + x (torch.Tensor): text features + shape (B, T_txt, D_txt) + media (torch.Tensor): image features + shape (B, T_img, n, D_img) where n is the dim of the latents + media_locations: boolean mask identifying the media tokens in x + shape (B, T_txt) + attend_previous: bool + If false, ignores immediately preceding image and starts attending when following image + """ + _, T_img, n = media.shape[:3] + h = self.heads + + x = self.norm(x) + + q = self.to_q(x) + media = rearrange(media, "b t n d -> b (t n) d") + + k, v = self.to_kv(media).chunk(2, dim=-1) + q, k, v = rearrange_many((q, k, v), "b n (h d) -> b h n d", h=h) + + q = q * self.scale + + sim = einsum("... i d, ... j d -> ... i j", q, k) + + if exists(media_locations): + # at each boolean of True, increment the time counter (relative to media time) + text_time = media_locations.cumsum(dim=-1) + media_time = torch.arange(T_img, device=x.device) + 1 + + if not attend_previous: + text_time[~media_locations] += 1 + # make sure max is still the number of images in the sequence + text_time[ + text_time + > repeat( + torch.count_nonzero(media_locations, dim=1), + "b -> b i", + i=text_time.shape[1], + ) + ] = 0 + + # text time must equal media time if only attending to most immediate image + # otherwise, as long as text time is greater than media time (if attending to all previous images / media) + mask_op = torch.eq if self.only_attend_immediate_media else torch.ge + + text_to_media_mask = mask_op( + rearrange(text_time, "b i -> b 1 i 1"), + repeat(media_time, "j -> 1 1 1 (j n)", n=n), + ) + sim = sim.masked_fill(~text_to_media_mask, -torch.finfo(sim.dtype).max) + + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + attn = sim.softmax(dim=-1) + + if exists(media_locations) and self.only_attend_immediate_media: + # any text without a preceding media needs to have attention zeroed out + text_without_media_mask = text_time == 0 + text_without_media_mask = rearrange( + text_without_media_mask, "b i -> b 1 i 1" + ) + attn = attn.masked_fill(text_without_media_mask, 0.0) + + out = einsum("... i j, ... j d -> ... i d", attn, v) + out = rearrange(out, "b h n d -> b n (h d)") + return self.to_out(out) + + +class GatedCrossAttentionBlock(nn.Module): + def __init__( + self, + *, + dim, + dim_visual, + dim_head=64, + heads=8, + ff_mult=4, + only_attend_immediate_media=True, + ): + super().__init__() + self.attn = MaskedCrossAttention( + dim=dim, + dim_visual=dim_visual, + dim_head=dim_head, + heads=heads, + only_attend_immediate_media=only_attend_immediate_media, + ) + self.attn_gate = nn.Parameter(torch.tensor([0.0])) + + self.ff = FeedForward(dim, mult=ff_mult) + self.ff_gate = nn.Parameter(torch.tensor([0.0])) + + def forward( + self, + x, + media, + media_locations=None, + attend_previous=True, + ): + x = ( + self.attn( + x, + media, + media_locations=media_locations, + attend_previous=attend_previous, + ) + * self.attn_gate.tanh() + + x + ) + x = self.ff(x) * self.ff_gate.tanh() + x + + return x diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/src/utils.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..815c70016c33ca9133aba60811a4948e31a2df27 --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/src/utils.py @@ -0,0 +1,31 @@ +def extend_instance(obj, mixin): + """Apply mixins to a class instance after creation""" + base_cls = obj.__class__ + base_cls_name = obj.__class__.__name__ + obj.__class__ = type( + base_cls_name, (mixin, base_cls), {} + ) # mixin needs to go first for our forward() logic to work + + +def getattr_recursive(obj, att): + """ + Return nested attribute of obj + Example: getattr_recursive(obj, 'a.b.c') is equivalent to obj.a.b.c + """ + if att == "": + return obj + i = att.find(".") + if i < 0: + return getattr(obj, att) + else: + return getattr_recursive(getattr(obj, att[:i]), att[i + 1 :]) + + +def setattr_recursive(obj, att, val): + """ + Set nested attribute of obj + Example: setattr_recursive(obj, 'a.b.c', val) is equivalent to obj.a.b.c = val + """ + if "." in att: + obj = getattr_recursive(obj, ".".join(att.split(".")[:-1])) + setattr(obj, att.split(".")[-1], val) diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__init__.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__init__.py @@ -0,0 +1 @@ + diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/__init__.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d72c4a62e40bbb1e6adc7154e9acf4642abc4a9c Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/__init__.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/data.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8157248163328af814835ebcc3180415b1fbada Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/data.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/distributed.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/distributed.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b97c32cece053c733a996c6d37b706c4e7b8779 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/distributed.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/train.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/train.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d742abc2943709dce110288a7191ecbb2d9f4ed1 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/train.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/train_utils.cpython-310.pyc b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/train_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0177863881c36f6335842d371023947759c21174 Binary files /dev/null and b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/__pycache__/train_utils.cpython-310.pyc differ diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/train/data.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2224e32979f5998f0866f79cde84759c72d022b7 --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/data.py @@ -0,0 +1,578 @@ +import ast +import functools +import io +import json +import logging +import math +import os +import random +import sys +import tarfile +from dataclasses import dataclass +from multiprocessing import Value + +import braceexpand +import torch +import torchvision +import webdataset as wds +from PIL import Image +from torch.utils.data import DataLoader, IterableDataset, get_worker_info +from torch.utils.data.distributed import DistributedSampler +from webdataset.filters import _shuffle +from webdataset.tariterators import ( + base_plus_ext, + tar_file_expander, + url_opener, + valid_sample, +) + +Image.MAX_IMAGE_PIXELS = 1000000000 +MAX_NUM_TOKENS = 256 +MAX_NUM_IMAGES = 5 +TINY_IMAGE_SIZE_THRESHOLD = 1 +N_CHANNELS = 3 +INTERLEAVED_IMAGE_SIZE = 224 + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + + +class SharedEpoch: + def __init__(self, epoch: int = 0): + self.shared_epoch = Value("i", epoch) + + def set_value(self, epoch): + self.shared_epoch.value = epoch + + def get_value(self): + return self.shared_epoch.value + + +@dataclass +class DataInfo: + dataloader: DataLoader + sampler: DistributedSampler = None + shared_epoch: SharedEpoch = None + + def set_epoch(self, epoch): + if self.shared_epoch is not None: + self.shared_epoch.set_value(epoch) + if self.sampler is not None and isinstance(self.sampler, DistributedSampler): + self.sampler.set_epoch(epoch) + + +def get_dataset_size(shards): + shards_list = list(braceexpand.braceexpand(shards)) + shards_list = shards + dir_path = os.path.dirname(shards[0]) + sizes_filename = os.path.join(dir_path, "sizes.json") + len_filename = os.path.join(dir_path, "__len__") + if os.path.exists(sizes_filename): + sizes = json.load(open(sizes_filename, "r")) + total_size = sum( + [ + int(sizes[os.path.basename(shard)]) + if os.path.basename(shard) in sizes + else 0 + for shard in shards_list + ] + ) + elif os.path.exists(len_filename): + # FIXME this used to be eval(open(...)) but that seemed rather unsafe + total_size = ast.literal_eval(open(len_filename, "r").read()) + else: + total_size = None # num samples undefined + # some common dataset sizes (at time of authors last download) + # CC3M (train): 2905954 + # CC12M: 10968539 + # LAION-400M: 407332084 + # LAION-2B (english): 2170337258 + num_shards = len(shards_list) + return total_size, num_shards + + +def count_samples(dataloader): + os.environ["WDS_EPOCH"] = "0" + n_elements, n_batches = 0, 0 + for images, texts in dataloader: + n_batches += 1 + n_elements += len(images) + assert len(images) == len(texts) + return n_elements, n_batches + + +def filter_no_caption_or_no_image(sample): + return ("txt" in sample) and ( + "png" in sample or "jpg" in sample or "jpeg" in sample + ) + + +def log_and_continue(exn): + """Call in an exception handler to ignore any exception, issue a warning, and continue.""" + if "No images in sample" in str(exn) or "Only one image in sample" in str( + exn + ): # Avoid spamming logs with these + return True + logging.warning(f"Handling webdataset error ({repr(exn)}). Ignoring.") + return True + + +def group_by_keys_nothrow( + data, keys=base_plus_ext, lcase=True, suffixes=None, handler=None +): + """Return function over iterator that groups key, value pairs into samples. + + :param keys: function that splits the key into key and extension (base_plus_ext) + :param lcase: convert suffixes to lower case (Default value = True) + """ + current_sample = None + for filesample in data: + assert isinstance(filesample, dict) + fname, value = filesample["fname"], filesample["data"] + prefix, suffix = keys(fname) + if prefix is None: + continue + if lcase: + suffix = suffix.lower() + # FIXME webdataset version throws if suffix in current_sample, but we have a potential for + # this happening in the current LAION400m dataset if a tar ends with same prefix as the next + # begins, rare, but can happen since prefix aren't unique across tar files in that dataset + if ( + current_sample is None + or prefix != current_sample["__key__"] + or suffix in current_sample + ): + if valid_sample(current_sample): + yield current_sample + current_sample = dict(__key__=prefix, __url__=filesample["__url__"]) + if suffixes is None or suffix in suffixes: + current_sample[suffix] = value + if valid_sample(current_sample): + yield current_sample + + +def tarfile_to_samples_nothrow(src, handler=log_and_continue): + # NOTE this is a re-impl of the webdataset impl with group_by_keys that doesn't throw + streams = url_opener(src, handler=handler) + files = tar_file_expander(streams, handler=handler) + samples = group_by_keys_nothrow(files, handler=handler) + return samples + + +def pytorch_worker_seed(increment=0): + """get dataloader worker seed from pytorch""" + worker_info = get_worker_info() + if worker_info is not None: + # favour using the seed already created for pytorch dataloader workers if it exists + seed = worker_info.seed + if increment: + # space out seed increments so they can't overlap across workers in different iterations + seed += increment * max(1, worker_info.num_workers) + return seed + # fallback to wds rank based seed + return wds.utils.pytorch_worker_seed() + + +_SHARD_SHUFFLE_SIZE = 2000 +_SHARD_SHUFFLE_INITIAL = 500 +_SAMPLE_SHUFFLE_SIZE = 5000 +_SAMPLE_SHUFFLE_INITIAL = 1000 + + +class detshuffle2(wds.PipelineStage): + def __init__( + self, + bufsize=1000, + initial=100, + seed=0, + epoch=-1, + ): + self.bufsize = bufsize + self.initial = initial + self.seed = seed + self.epoch = epoch + + def run(self, src): + if isinstance(self.epoch, SharedEpoch): + epoch = self.epoch.get_value() + else: + # NOTE: this is epoch tracking is problematic in a multiprocess (dataloader workers or train) + # situation as different workers may wrap at different times (or not at all). + self.epoch += 1 + epoch = self.epoch + rng = random.Random() + if self.seed < 0: + # If seed is negative, we use the worker's seed, this will be different across all nodes/workers + seed = pytorch_worker_seed(epoch) + else: + # This seed to be deterministic AND the same across all nodes/workers in each epoch + seed = self.seed + epoch + rng.seed(seed) + return _shuffle(src, self.bufsize, self.initial, rng) + + +class ResampledShards2(IterableDataset): + """An iterable dataset yielding a list of urls.""" + + def __init__( + self, + urls, + nshards=sys.maxsize, + worker_seed=None, + deterministic=False, + epoch=-1, + ): + """Sample shards from the shard list with replacement. + :param urls: a list of URLs as a Python list or brace notation string + """ + super().__init__() + urls = wds.shardlists.expand_urls(urls) + self.urls = urls + assert isinstance(self.urls[0], str) + self.nshards = nshards + self.rng = random.Random() + self.worker_seed = worker_seed + self.deterministic = deterministic + self.epoch = epoch + + def __iter__(self): + """Return an iterator over the shards.""" + if isinstance(self.epoch, SharedEpoch): + epoch = self.epoch.get_value() + else: + # NOTE: this is epoch tracking is problematic in a multiprocess (dataloader workers or train) + # situation as different workers may wrap at different times (or not at all). + self.epoch += 1 + epoch = self.epoch + + if self.deterministic: + # reset seed w/ epoch if deterministic + if self.worker_seed is None: + # pytorch worker seed should be deterministic due to being init by arg.seed + rank + worker id + seed = pytorch_worker_seed(epoch) + else: + seed = self.worker_seed() + epoch + self.rng.seed(seed) + for _ in range(self.nshards): + yield dict(url=self.rng.choice(self.urls)) + + +def preprocess_image(sample, image_processor): + image = [image_processor(s).unsqueeze(0) for s in sample] + image = torch.cat(image, dim=0) + # apply random horizontal flip and color jitter + image = torchvision.transforms.RandomHorizontalFlip(p=0.5)(image) + image = torchvision.transforms.ColorJitter(brightness=0.5, hue=0.3)(image) + return image + + +def preprocess_text(sample, tokenizer): + tokenizer.padding_side = "right" + sample = [ + (f"{s.strip()}<|endofchunk|>{tokenizer.eos_token}") for s in sample + ] + text = tokenizer( + sample, + max_length=32, + padding="longest", + truncation="only_first", + return_tensors="pt", + ) + return text["input_ids"], text["attention_mask"] + + +MIN_KB = 10 +MAX_NUM_IMAGES = 5 + + +def preprocess_interleaved(sample, tokenizer, clip_processor, sim_threshold): + info = json.loads(sample[0]) + tar_file_obj = io.BytesIO(sample[1]) + image_tar = tarfile.open(fileobj=tar_file_obj) + sentences = info["text_list"] + + images, image_idxs = [], [] + for image_path, sim in zip(info["image_info"], info["similarity_matrix"]): + # pick one image per sentence + if info["image_info"][image_path]["matched_text_index"] in image_idxs: + continue + rawbytes = image_tar.extractfile( + os.path.join(image_tar.getnames()[0], image_path) + ).read() + + # filter to images >= 10KB + if len(rawbytes) // 1000 <= MIN_KB: + continue + if sim[info["image_info"][image_path]["matched_text_index"]] < sim_threshold: + continue + image = Image.open(io.BytesIO(rawbytes)).convert("RGB") + + images.append(image) + image_idxs.append(info["image_info"][image_path]["matched_text_index"]) + + if len(images) == 0: + raise ValueError("No images in sample") + + # filter out images that are exact duplicates + images_tensors = preprocess_image(images, clip_processor) + keep_ixs = range(min(len(images_tensors), MAX_NUM_IMAGES)) + images_tensors = images_tensors[keep_ixs] + image_idxs = [image_idxs[ix] for ix in keep_ixs] + + # pad to 5 images + if len(images_tensors) < MAX_NUM_IMAGES: + zero_padding = torch.zeros( + (MAX_NUM_IMAGES - len(images_tensors), 3, 224, 224), dtype=torch.float + ) + images_tensors = torch.cat((images_tensors, zero_padding), dim=0) + + # add in and tokens + # eoc after sentence = "sentence loss" + for ix in image_idxs: + sentences[ix] = f"<|endofchunk|>{sentences[ix]}" + + text = " ".join(sentences) + text = text.replace("<|endofchunk|>", "", 1) # but remove first eoc + # whitespace cleanup + text = ( + text.replace(" <|endofchunk|>", "<|endofchunk|>") + .replace(" ", "") + .replace(" ", "") + ) + text = f"{text}<|endofchunk|>{tokenizer.eos_token}" + tokenizer.padding_side = "right" + text_tensor = tokenizer( + text, max_length=256, truncation=True, padding="max_length", return_tensors="pt" + ) + + # reject sequences with too few images (after truncation) + num_images = torch.count_nonzero( + text_tensor["input_ids"] + == tokenizer.additional_special_tokens_ids[ + tokenizer.additional_special_tokens.index("") + ] + ) + + if num_images == 0: + raise ValueError("No images in sample") + elif ( + num_images == 1 and random.random() <= 0.5 + ): # 50% chance of keeping single image samples + raise ValueError("Only one image in sample") + + return ( + images_tensors, + (text_tensor["input_ids"], text_tensor["attention_mask"]), + ) + + +def get_mmc4_dataset(args, image_processor, tokenizer, epoch=0, floor=False): + input_shards = args.mmc4_shards + assert input_shards is not None + resampled = getattr(args, "dataset_resampled", False) + + num_samples, num_shards = get_dataset_size(input_shards) + num_samples = None + if not num_samples: + num_samples = args.train_num_samples_mmc4 + if not num_samples: + raise RuntimeError( + "Currently, number of dataset samples must be specified for training dataset. " + "Please specify via `--train-num-samples` if no dataset length info present." + ) + + # create a shared epoch store to sync epoch to dataloader worker proc + shared_epoch = SharedEpoch(epoch=epoch) + if resampled: + pipeline = [ + ResampledShards2(input_shards, deterministic=True, epoch=shared_epoch) + ] + else: + pipeline = [wds.SimpleShardList(input_shards)] + + preprocess_fn = functools.partial( + preprocess_interleaved, + clip_processor=image_processor, + tokenizer=tokenizer, + sim_threshold=args.mmc4_textsim_threshold, + ) + + # at this point we have an iterator over all the shards + if not resampled: + pipeline.extend( + [ + detshuffle2( + bufsize=_SHARD_SHUFFLE_SIZE, + initial=_SHARD_SHUFFLE_INITIAL, + seed=args.seed, + epoch=shared_epoch, + ), + wds.split_by_node, + wds.split_by_worker, + ] + ) + pipeline.extend( + [ + # at this point, we have an iterator over the shards assigned to each worker at each node + # wds.tarfile_to_samples(handler=log_and_continue), + tarfile_to_samples_nothrow, + wds.shuffle( + bufsize=_SAMPLE_SHUFFLE_SIZE, + initial=_SAMPLE_SHUFFLE_INITIAL, + ), + ] + ) + + pipeline.extend( + [ + wds.to_tuple("json", "tar", handler=log_and_continue), + wds.map(preprocess_fn, handler=log_and_continue), + wds.batched(args.batch_size_mmc4, partial=False), + ] + ) + + dataset = wds.DataPipeline(*pipeline) + if not resampled: + assert ( + num_shards >= args.workers * args.world_size + ), "number of shards must be >= total workers" + # roll over and repeat a few samples to get same number of full batches on each node + round_fn = math.floor if floor else math.ceil + global_batch_size = args.batch_size_mmc4 * args.world_size + num_batches = round_fn(num_samples / global_batch_size) + num_workers = max(1, args.workers) + num_worker_batches = round_fn(num_batches / num_workers) # per dataloader worker + num_batches = num_worker_batches * num_workers + num_samples = num_batches * global_batch_size + # each worker is iterating over this + dataset = dataset.with_epoch(num_worker_batches) + + dataloader = wds.WebLoader( + dataset, + batch_size=None, + shuffle=False, + num_workers=args.workers, + persistent_workers=True, + ) + + # add meta-data to dataloader instance for convenience + dataloader.num_batches = num_batches + dataloader.num_samples = num_samples + + return DataInfo(dataloader=dataloader, shared_epoch=shared_epoch) + + +def get_laion_dataset(args, image_processor, tokenizer, epoch=0, floor=False): + input_shards = args.laion_shards + assert input_shards is not None + resampled = getattr(args, "dataset_resampled", False) + + num_samples, num_shards = get_dataset_size(input_shards) + num_samples = None + if not num_samples: + num_samples = args.train_num_samples_laion + if not num_samples: + raise RuntimeError( + "Currently, number of dataset samples must be specified for training dataset. " + "Please specify via `--train-num-samples` if no dataset length info present." + ) + + # create a shared epoch store to sync epoch to dataloader worker proc + shared_epoch = SharedEpoch(epoch=epoch) + if resampled: + pipeline = [ + ResampledShards2(input_shards, deterministic=True, epoch=shared_epoch) + ] + else: + pipeline = [wds.SimpleShardList(input_shards)] + + # create two preprocess functions that take in the passed in image_processor and tokenizer + preprocess_image_fn = functools.partial( + preprocess_image, image_processor=image_processor + ) + preprocess_text_fn = functools.partial(preprocess_text, tokenizer=tokenizer) + + # at this point we have an iterator over all the shards + if not resampled: + pipeline.extend( + [ + detshuffle2( + bufsize=_SHARD_SHUFFLE_SIZE, + initial=_SHARD_SHUFFLE_INITIAL, + seed=args.seed, + epoch=shared_epoch, + ), + wds.split_by_node, + wds.split_by_worker, + ] + ) + pipeline.extend( + [ + # at this point, we have an iterator over the shards assigned to each worker at each node + # wds.tarfile_to_samples(handler=log_and_continue), + tarfile_to_samples_nothrow, + wds.shuffle( + bufsize=_SAMPLE_SHUFFLE_SIZE, + initial=_SAMPLE_SHUFFLE_INITIAL, + ), + ] + ) + + pipeline.extend( + [ + wds.select(filter_no_caption_or_no_image), + wds.decode("pilrgb", handler=log_and_continue), + wds.to_tuple("jpg;png;jpeg", "txt", handler=log_and_continue), + wds.batched(args.batch_size_laion, partial=False), + wds.map_tuple( + preprocess_image_fn, preprocess_text_fn, handler=log_and_continue + ), + ] + ) + + dataset = wds.DataPipeline(*pipeline) + if not resampled: + assert ( + num_shards >= args.workers * args.world_size + ), "number of shards must be >= total workers" + # roll over and repeat a few samples to get same number of full batches on each node + round_fn = math.floor if floor else math.ceil + global_batch_size = args.batch_size_laion * args.world_size + num_batches = round_fn(num_samples / global_batch_size) + num_workers = max(1, args.workers) + num_worker_batches = round_fn(num_batches / num_workers) # per dataloader worker + num_batches = num_worker_batches * num_workers + num_samples = num_batches * global_batch_size + # each worker is iterating over this + dataset = dataset.with_epoch(num_worker_batches) + + dataloader = wds.WebLoader( + dataset, + batch_size=None, + shuffle=False, + num_workers=args.workers, + persistent_workers=True, + ) + + # add meta-data to dataloader instance for convenience + dataloader.num_batches = num_batches + dataloader.num_samples = num_samples + + return DataInfo(dataloader=dataloader, shared_epoch=shared_epoch) + + +def get_dataset_fn(dataset_type): + if dataset_type == "image_text": + return get_laion_dataset + elif dataset_type == "mmc4": + return get_mmc4_dataset + else: + raise ValueError(f"Unsupported dataset type: {dataset_type}") + + +def get_data(args, image_processor, tokenizer, dataset_type, epoch=0): + return get_dataset_fn(dataset_type)( + args, image_processor=image_processor, epoch=epoch, tokenizer=tokenizer + ) diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/train/distributed.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..3938d063d52218eefdfde83f850999b022538c47 --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/distributed.py @@ -0,0 +1,128 @@ +import os + +import torch + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + + +def is_global_master(args): + return args.rank == 0 + + +def is_local_master(args): + return args.local_rank == 0 + + +def is_master(args, local=False): + return is_local_master(args) if local else is_global_master(args) + + +def is_using_horovod(): + # NOTE w/ horovod run, OMPI vars should be set, but w/ SLURM PMI vars will be set + # Differentiating between horovod and DDP use via SLURM may not be possible, so horovod arg still required... + ompi_vars = ["OMPI_COMM_WORLD_RANK", "OMPI_COMM_WORLD_SIZE"] + pmi_vars = ["PMI_RANK", "PMI_SIZE"] + if all([var in os.environ for var in ompi_vars]) or all( + [var in os.environ for var in pmi_vars] + ): + return True + else: + return False + + +def is_using_distributed(): + if "WORLD_SIZE" in os.environ: + return int(os.environ["WORLD_SIZE"]) > 1 + if "SLURM_NTASKS" in os.environ: + return int(os.environ["SLURM_NTASKS"]) > 1 + return False + + +def world_info_from_env(): + local_rank = 0 + for v in ( + "LOCAL_RANK", + "MPI_LOCALRANKID", + "SLURM_LOCALID", + "OMPI_COMM_WORLD_LOCAL_RANK", + ): + if v in os.environ: + local_rank = int(os.environ[v]) + break + global_rank = 0 + for v in ("RANK", "PMI_RANK", "SLURM_PROCID", "OMPI_COMM_WORLD_RANK"): + if v in os.environ: + global_rank = int(os.environ[v]) + break + world_size = 1 + for v in ("WORLD_SIZE", "PMI_SIZE", "SLURM_NTASKS", "OMPI_COMM_WORLD_SIZE"): + if v in os.environ: + world_size = int(os.environ[v]) + break + + return local_rank, global_rank, world_size + + +def init_distributed_device(args): + # Distributed training = training on more than one GPU. + # Works in both single and multi-node scenarios. + args.distributed = False + args.world_size = 1 + args.rank = 0 # global rank + args.local_rank = 0 + if args.horovod: + assert hvd is not None, "Horovod is not installed" + hvd.init() + args.local_rank = int(hvd.local_rank()) + args.rank = hvd.rank() + args.world_size = hvd.size() + args.distributed = True + os.environ["LOCAL_RANK"] = str(args.local_rank) + os.environ["RANK"] = str(args.rank) + os.environ["WORLD_SIZE"] = str(args.world_size) + elif is_using_distributed(): + if "SLURM_PROCID" in os.environ: + # DDP via SLURM + args.local_rank, args.rank, args.world_size = world_info_from_env() + # SLURM var -> torch.distributed vars in case needed + os.environ["LOCAL_RANK"] = str(args.local_rank) + os.environ["RANK"] = str(args.rank) + os.environ["WORLD_SIZE"] = str(args.world_size) + torch.distributed.init_process_group( + backend=args.dist_backend, + init_method=args.dist_url, + world_size=args.world_size, + rank=args.rank, + ) + else: + # DDP via torchrun, torch.distributed.launch + args.local_rank, _, _ = world_info_from_env() + torch.distributed.init_process_group( + backend=args.dist_backend, init_method=args.dist_url + ) + args.world_size = torch.distributed.get_world_size() + args.rank = torch.distributed.get_rank() + args.distributed = True + else: + # needed to run on single gpu + torch.distributed.init_process_group( + backend=args.dist_backend, + init_method=args.dist_url, + world_size=1, + rank=0, + ) + + if torch.cuda.is_available(): + if args.distributed and not args.no_set_device_rank: + device = "cuda:%d" % args.local_rank + else: + device = "cuda:0" + torch.cuda.set_device(device) + else: + device = "cpu" + args.device = device + device = torch.device(device) + return device diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/train/train.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/train.py new file mode 100644 index 0000000000000000000000000000000000000000..74f5916a64aaf3232461cff6d011aea0c49a53e0 --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/train.py @@ -0,0 +1,332 @@ +""" Main training script """ + +import argparse +import copy +import glob +import os +import random + +import numpy as np +import torch +import wandb +from data import get_data +from distributed import init_distributed_device, world_info_from_env +from torch.nn.parallel import DistributedDataParallel as DDP +from train_utils import get_checkpoint, train_one_epoch +from transformers import ( + get_constant_schedule_with_warmup, + get_cosine_schedule_with_warmup, + get_linear_schedule_with_warmup, +) + +from open_flamingo import create_model_and_transforms + + +def random_seed(seed=42, rank=0): + torch.manual_seed(seed + rank) + np.random.seed(seed + rank) + random.seed(seed + rank) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--vision_encoder_path", default="ViT-L-14", type=str) + parser.add_argument("--vision_encoder_pretrained", default="openai", type=str) + parser.add_argument("--lm_path", default="facebook/opt-1.3b", type=str) + parser.add_argument( + "--tokenizer_path", + default="facebook/opt-30b", + type=str, + help="path to tokenizer", + ) + parser.add_argument( + "--cross_attn_every_n_layers", + type=int, + default=1, + help="how often to add a cross-attention layer after each transformer layer", + ) + parser.add_argument( + "--run_name", + type=str, + default="openflamingo3B", + help="used to name saving directory and wandb run", + ) + parser.add_argument("--use_media_placement_augmentation", action="store_true") + parser.add_argument("--offline", action="store_true") + parser.add_argument("--num_epochs", type=int, default=1) + parser.add_argument( + "--logging_steps", type=int, default=100, help="log loss every n steps" + ) + # Sum of gradient optimization batch size + parser.add_argument("--batch_size_mmc4", type=int, default=128) + parser.add_argument("--batch_size_laion", type=int, default=128) + parser.add_argument("--gradient_accumulation_steps", type=int, default=1) + parser.add_argument( + "--resume_from_checkpoint", + type=str, + help="path to checkpoint to resume from, this should contain model, optimizer, and lr_scheduler states", + default=None, + ) + parser.add_argument( + "--delete_previous_checkpoint", + action="store_true", + help="delete previous checkpoint when saving new checkpoint", + ) + parser.add_argument( + "--laion_shards", + type=str, + help="path to laion shards, this should be a glob pattern such as /path/to/shards/shard-{0000..0999}.tar", + ) + parser.add_argument( + "--mmc4_shards", + type=str, + help="path to c4 shards, this should be a glob pattern such as /path/to/shards/shard-{0000..0999}.tar", + ) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--learning_rate", default=1e-4, type=float) + parser.add_argument( + "--lr_scheduler", + default="constant", + type=str, + help="constant, linear, or cosine", + ) + parser.add_argument("--loss_multiplier_mmc4", type=float, default=1.0) + parser.add_argument("--loss_multiplier_laion", type=float, default=1.0) + parser.add_argument("--warmup_steps", default=5000, type=int) + parser.add_argument("--weight_decay", default=0.1, type=float) + parser.add_argument( + "--precision", + choices=["amp_bf16", "amp_bfloat16", "bf16", "fp16", "fp32"], + default="fp32", + help="Floating point precision.", + ) + # data args + parser.add_argument("--workers", type=int, default=1) + parser.add_argument("--train_num_samples_mmc4", type=int, default=10000) + parser.add_argument("--train_num_samples_laion", type=int, default=10000) + parser.add_argument("--dataset_resampled", action="store_true") + # distributed training args + parser.add_argument( + "--dist-url", + default="env://", + type=str, + help="url used to set up distributed training", + ) + parser.add_argument( + "--dist-backend", default="nccl", type=str, help="distributed backend" + ) + parser.add_argument( + "--horovod", + default=False, + action="store_true", + help="Use horovod for distributed training.", + ) + parser.add_argument( + "--no-set-device-rank", + default=False, + action="store_true", + help="Don't set device index from local rank (when CUDA_VISIBLE_DEVICES restricted to one per proc).", + ) + # wandb args + parser.add_argument("--report_to_wandb", default=False, action="store_true") + parser.add_argument( + "--wandb_project", + type=str, + ) + parser.add_argument( + "--wandb_entity", + type=str, + ) + parser.add_argument( + "--save_checkpoints_to_wandb", + default=False, + action="store_true", + help="save checkpoints to wandb", + ) + parser.add_argument( + "--mmc4_textsim_threshold", + default=30, + type=float, + help="threshold for filtering images in mmc4 based on image-text similarity", + ) + + args = parser.parse_args() + + if args.laion_shards.startswith("s3"): + args.laion_shards = f"pipe:aws s3 cp {args.laion_shards} -" + + if args.mmc4_shards.startswith("s3"): + args.mmc4_shards = f"pipe:aws s3 cp {args.mmc4_shards} -" + + if args.save_checkpoints_to_wandb and not args.report_to_wandb: + raise ValueError("save_checkpoints_to_wandb requires report_to_wandb") + + assert (args.train_num_samples_laion // args.batch_size_laion) == ( + args.train_num_samples_mmc4 // args.batch_size_mmc4 + ), "number of samples per epoch must be equal for mmc4 and laion" + + if args.offline: + os.environ["WANDB_MODE"] = "offline" + os.environ["TRANSFORMERS_OFFLINE"] = "1" + + args.local_rank, args.rank, args.world_size = world_info_from_env() + + device_id = init_distributed_device(args) + + random_seed(args.seed) + + model, image_processor, tokenizer = create_model_and_transforms( + args.vision_encoder_path, + args.vision_encoder_pretrained, + args.lm_path, + args.tokenizer_path if args.tokenizer_path else args.lm_path, + cross_attn_every_n_layers=args.cross_attn_every_n_layers, + use_local_files=args.offline, + use_media_placement_augmentation=args.use_media_placement_augmentation, + ) + + random_seed(args.seed, args.rank) + + print(f"Start running training on rank {args.rank}.") + + if args.rank == 0 and args.report_to_wandb: + wandb.init( + project=args.wandb_project, + entity=args.wandb_entity, + name=args.run_name, + config=vars(args), + ) + + device_id = args.rank % torch.cuda.device_count() + model = model.to(device_id) + + ddp_model = DDP(model, device_ids=[device_id]) + + laion_dataset = get_data(args, image_processor, tokenizer, "image_text") + mmc4_dataset = get_data(args, image_processor, tokenizer, "mmc4") + + def get_grouped_params(model): + params_with_wd, params_without_wd = [], [] + + def apply_decay(x): + return ( + "gated_cross_attn_layer" in x + and "ff_gate" not in x + and "attn_gate" not in x + and "norm" not in x + and "bias" not in x + ) + + for n, p in model.named_parameters(): + # if p.requires_grad: + if apply_decay(n): + params_with_wd.append(p) + else: + params_without_wd.append(p) + + return [ + {"params": params_with_wd, "weight_decay": args.weight_decay}, + {"params": params_without_wd, "weight_decay": 0.0}, + ] + + optimizer = torch.optim.AdamW(get_grouped_params(ddp_model), lr=args.learning_rate) + + total_training_steps = ( + (args.train_num_samples_mmc4) // (args.batch_size_mmc4 * args.world_size) + ) * args.num_epochs + + if args.rank == 0: + print(f"Total training steps: {total_training_steps}") + + if args.lr_scheduler == "linear": + lr_scheduler = get_linear_schedule_with_warmup( + optimizer, + num_warmup_steps=args.warmup_steps, + num_training_steps=total_training_steps, + ) + elif args.lr_scheduler == "cosine": + lr_scheduler = get_cosine_schedule_with_warmup( + optimizer, + num_warmup_steps=args.warmup_steps, + num_training_steps=total_training_steps, + ) + else: + lr_scheduler = get_constant_schedule_with_warmup( + optimizer, num_warmup_steps=args.warmup_steps + ) + + # check if a checkpoint exists for this run + if os.path.exists(f"{args.run_name}") and args.resume_from_checkpoint is None: + checkpoint_list = glob.glob(f"{args.run_name}/checkpoint_*.pt") + if len(checkpoint_list) == 0: + print(f"Found no checkpoints for run {args.run_name}.") + else: + args.resume_from_checkpoint = sorted( + checkpoint_list, key=lambda x: int(x.split("_")[-1].split(".")[0]) + )[-1] + print( + f"Found checkpoint {args.resume_from_checkpoint} for run {args.run_name}." + ) + + resume_from_epoch = 0 + if args.resume_from_checkpoint is not None: + if args.rank == 0: + print(f"Loading checkpoint from {args.resume_from_checkpoint}") + checkpoint = torch.load(args.resume_from_checkpoint, map_location="cpu") + ddp_model.load_state_dict(checkpoint["model_state_dict"], False) + optimizer.load_state_dict(checkpoint["optimizer_state_dict"]) + lr_scheduler.load_state_dict(checkpoint["lr_scheduler_state_dict"]) + resume_from_epoch = checkpoint["epoch"] + 1 + + ddp_model.train() + + for epoch in range(resume_from_epoch, args.num_epochs): + laion_dataset.set_epoch(epoch) + laion_loader = laion_dataset.dataloader + mmc4_dataset.set_epoch(epoch) + mmc4_loader = mmc4_dataset.dataloader + + train_one_epoch( + args=args, + model=ddp_model, + epoch=epoch, + tokenizer=tokenizer, + optimizer=optimizer, + lr_scheduler=lr_scheduler, + laion_loader=laion_loader, + mmc4_loader=mmc4_loader, + device_id=device_id, + wandb=wandb, + ) + + if args.rank == 0: + if not os.path.exists(args.run_name): + os.makedirs(args.run_name) + + checkpoint_dict = { + "epoch": epoch, + "model_state_dict": get_checkpoint(ddp_model), + "optimizer_state_dict": optimizer.state_dict(), + "lr_scheduler_state_dict": lr_scheduler.state_dict(), + } + + print(f"Saving checkpoint to {args.run_name}/checkpoint_{epoch}.pt") + torch.save(checkpoint_dict, f"{args.run_name}/checkpoint_{epoch}.pt") + if args.report_to_wandb and args.save_checkpoints_to_wandb: + wandb.save(f"{args.run_name}/checkpoint_{epoch}.pt") + + if args.delete_previous_checkpoint: + if epoch > 0: + os.remove(f"{args.run_name}/checkpoint_{epoch-1}.pt") + + if args.rank == 0: + if not os.path.exists(args.run_name): + os.makedirs(args.run_name) + + torch.save(get_checkpoint(ddp_model), f"{args.run_name}/final_weights.pt") + if args.report_to_wandb and args.save_checkpoints_to_wandb: + wandb.save(f"{args.run_name}/final_weights.pt") + + +if __name__ == "__main__": + main() diff --git a/minigpt2/lib/python3.10/site-packages/open_flamingo/train/train_utils.py b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/train_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..88fc271dbd89a76d4cb60f91aea7bfc91ae9aa06 --- /dev/null +++ b/minigpt2/lib/python3.10/site-packages/open_flamingo/train/train_utils.py @@ -0,0 +1,282 @@ +import time +from contextlib import suppress + +import torch +from tqdm import tqdm + + +def get_cast_dtype(precision: str): + cast_dtype = None + if precision == "bf16": + cast_dtype = torch.bfloat16 + elif precision == "fp16": + cast_dtype = torch.float16 + return cast_dtype + + +def get_autocast(precision): + if precision == "amp": + return torch.cuda.amp.autocast + elif precision == "amp_bfloat16" or precision == "amp_bf16": + # amp_bfloat16 is more stable than amp float16 for clip training + return lambda: torch.cuda.amp.autocast(dtype=torch.bfloat16) + else: + return suppress + + +def train_one_epoch( + args, + model, + epoch, + laion_loader, + mmc4_loader, + tokenizer, + optimizer, + lr_scheduler, + device_id, + wandb, +): + num_batches_per_epoch_laion = laion_loader.num_batches + num_batches_per_epoch_mmc4 = mmc4_loader.num_batches + + assert ( + num_batches_per_epoch_laion == num_batches_per_epoch_mmc4 + ), "Number of batches in laion and mmc4 datasets must be the same" + num_batches_per_epoch = num_batches_per_epoch_mmc4 + total_training_steps = num_batches_per_epoch * args.num_epochs + + autocast = get_autocast(args.precision) + cast_dtype = get_cast_dtype(args.precision) + + media_token_id = tokenizer("", add_special_tokens=False)["input_ids"][-1] + endofchunk_token_id = tokenizer("<|endofchunk|>", add_special_tokens=False)[ + "input_ids" + ][-1] + + model.train() + + # setup logging + step_time_m = ( + AverageMeter() + ) # time for one optimizer step (> 1 batch if using gradient accum) + data_time_m = ( + AverageMeter() + ) # avg time to load one batch of both C4 AND laion (= 1 batch regardless of gradient accum) + end = time.time() + + # loop through dataloader + for num_steps, (batch_laion, batch_mmc4) in tqdm( + enumerate(zip(laion_loader, mmc4_loader)), + disable=args.rank != 0, + total=total_training_steps, + initial=(epoch * num_batches_per_epoch), + ): + data_time_m.update(time.time() - end) + + global_step = num_steps + epoch * num_batches_per_epoch + + #### LAION FORWARD PASS #### + images = ( + batch_laion[0] + .to(device_id, dtype=cast_dtype, non_blocking=True) + .unsqueeze(1) + .unsqueeze(1) + ) + + input_ids = batch_laion[1][0].to(device_id, dtype=cast_dtype, non_blocking=True) + attention_mask = batch_laion[1][1].to( + device_id, dtype=cast_dtype, non_blocking=True + ) + + labels = input_ids.clone() + labels[labels == tokenizer.pad_token_id] = -100 + labels[:, 0] = -100 + labels[labels == media_token_id] = -100 + labels.to(device_id) + + with autocast(): + loss_laion = model( + vision_x=images, + lang_x=input_ids, + attention_mask=attention_mask, + labels=labels, + )[0] + divided_loss_laion = loss_laion / args.gradient_accumulation_steps + + #### C4 FORWARD PASS #### + images = ( + batch_mmc4[0] + .to(device_id, dtype=cast_dtype, non_blocking=True) + .unsqueeze(2) + ) + input_ids = torch.stack([x[0] for x in batch_mmc4[1]]).squeeze(1) + attention_mask = torch.stack([x[1] for x in batch_mmc4[1]]).squeeze(1) + + # NOTE: irena: expected shape of clip_text_input_ids / attention_mask is (N, I, max_seq_len) + labels = input_ids.clone() + labels[labels == tokenizer.pad_token_id] = -100 + labels[:, 0] = -100 + + for i in range(labels.shape[0]): + # remove loss for any token before the first token + label_idx = 0 + while ( + label_idx < labels.shape[1] and labels[i][label_idx] != media_token_id + ): + labels[i][label_idx] = -100 + label_idx += 1 + + # get index of all endofchunk tokens in the sequence + endofchunk_idxs = torch.where(labels[i] == endofchunk_token_id)[0] + for endofchunk_idx in endofchunk_idxs: + token_idx = endofchunk_idx + 1 + while ( + token_idx < labels.shape[1] + and labels[i][token_idx] != media_token_id + ): + labels[i][token_idx] = -100 + token_idx += 1 + + labels[labels == media_token_id] = -100 + labels.to(device_id) + + with autocast(): + loss_mmc4 = model( + vision_x=images, + lang_x=input_ids, + attention_mask=attention_mask, + labels=labels, + )[0] + + # if loss is nan, skip this batch + if torch.isnan(loss_mmc4): + print("loss is nan, skipping this batch") + print("input_ids: ", tokenizer.batch_decode(input_ids)) + print("labels: ", labels) + print("images: ", images) + optimizer.zero_grad() + continue + + divided_loss_mmc4 = loss_mmc4 / args.gradient_accumulation_steps + + #### BACKWARD PASS #### + loss = ( + divided_loss_laion * args.loss_multiplier_laion + + divided_loss_mmc4 * args.loss_multiplier_mmc4 + ) + loss.backward() + + #### MASK GRADIENTS FOR EMBEDDINGS #### + # Note (anas): Do not apply weight decay to embeddings as it will break this function. + def mask_embedding(m): + if isinstance(m, torch.nn.Embedding) and m.weight.requires_grad: + zero_mask = torch.zeros_like(m.weight.grad) + zero_mask[media_token_id] = torch.ones_like(zero_mask[media_token_id]) + zero_mask[endofchunk_token_id] = torch.ones_like( + zero_mask[endofchunk_token_id] + ) + m.weight.grad = m.weight.grad * zero_mask + + model.apply(mask_embedding) + + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + + # step optimizer and log + if (((num_steps + 1) % args.gradient_accumulation_steps) == 0) or ( + num_steps == num_batches_per_epoch - 1 + ): + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + # step time and reset end outside of rank 0 + step_time_m.update(time.time() - end) + end = time.time() + + if args.rank == 0 and args.report_to_wandb: + # compute within rank 0 + laion_samples_per_second = ( + args.gradient_accumulation_steps + * args.batch_size_laion + * args.world_size + / step_time_m.val + ) + laion_samples_per_second_per_gpu = ( + args.gradient_accumulation_steps + * args.batch_size_laion + / step_time_m.val + ) + + c4_samples_per_second = ( + args.gradient_accumulation_steps + * args.batch_size_mmc4 + * args.world_size + / step_time_m.val + ) + c4_samples_per_second_per_gpu = ( + args.gradient_accumulation_steps + * args.batch_size_mmc4 + / step_time_m.val + ) + + wandb.log( + { + "data_time": data_time_m.avg, + "step_time": step_time_m.avg, + "laion_samples_per_second": laion_samples_per_second, + "laion_samples_per_second_per_gpu": laion_samples_per_second_per_gpu, + "c4_samples_per_second": c4_samples_per_second, + "c4_samples_per_second_per_gpu": c4_samples_per_second_per_gpu, + "lr": optimizer.param_groups[0]["lr"], + }, + commit=False, + ) + step_time_m.reset() + data_time_m.reset() + + wandb.log( + { + "loss_laion": divided_loss_laion.item(), + "global_step": global_step, + }, + commit=False, + ) + wandb.log( + {"loss_mmc4": divided_loss_mmc4.item(), "global_step": global_step}, + commit=True, + ) + + # Log loss to console + if ((num_steps + 1) % args.logging_steps == 0) and args.rank == 0: + print( + f"Step {num_steps+1}/{num_batches_per_epoch} of epoch {epoch+1}/{args.num_epochs} complete. Loss LAION: {loss_laion.item():.3f} // Loss MMC4: {loss_mmc4.item():.3f}" + ) + + +def get_checkpoint(model): + state_dict = model.state_dict() + + for name, p in model.named_parameters(): + if not p.requires_grad: + del state_dict[name] + + return state_dict + + +class AverageMeter(object): + """Computes and stores the average and current value""" + + def __init__(self): + self.reset() + + def reset(self): + self.val = 0 + self.avg = 0 + self.sum = 0 + self.count = 0 + + def update(self, val, n=1): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sinh_compositeexplicitautograd_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sinh_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f350e7b37ab61f22ce033652162baccb67cf5ca1 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sinh_compositeexplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::vector _foreach_sinh(at::TensorList self); +TORCH_API void _foreach_sinh_out(at::TensorList out, at::TensorList self); +TORCH_API void _foreach_sinh_outf(at::TensorList self, at::TensorList out); +TORCH_API void _foreach_sinh_(at::TensorList self); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_neg_view_native.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_neg_view_native.h new file mode 100644 index 0000000000000000000000000000000000000000..32cf6972032e77a3f02b39af43dcbe9069f11166 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_neg_view_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor _neg_view(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_print_compositeexplicitautograd_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_print_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..e93d4ae6ef780742c1d7c81c47cf2748a38c6d3b --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_print_compositeexplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API void _print(c10::string_view s); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_initialize_state_compositeimplicitautograd_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_initialize_state_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..a9653ab22eea22df8e0b947fcfe0a002c84a4483 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_sobol_engine_initialize_state_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor & _sobol_engine_initialize_state_(at::Tensor & self, int64_t dimension); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_test_optional_filled_intlist.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_test_optional_filled_intlist.h new file mode 100644 index 0000000000000000000000000000000000000000..af9faa91074b5b13908b793b261718a4612330d5 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/_test_optional_filled_intlist.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_test_optional_filled_intlist(Tensor values, int[2]? addends) -> Tensor +inline at::Tensor _test_optional_filled_intlist(const at::Tensor & values, at::OptionalIntArrayRef addends) { + return at::_ops::_test_optional_filled_intlist::call(values, addends); +} + +// aten::_test_optional_filled_intlist.out(Tensor values, int[2]? addends, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _test_optional_filled_intlist_out(at::Tensor & out, const at::Tensor & values, at::OptionalIntArrayRef addends) { + return at::_ops::_test_optional_filled_intlist_out::call(values, addends, out); +} +// aten::_test_optional_filled_intlist.out(Tensor values, int[2]? addends, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _test_optional_filled_intlist_outf(const at::Tensor & values, at::OptionalIntArrayRef addends, at::Tensor & out) { + return at::_ops::_test_optional_filled_intlist_out::call(values, addends, out); +} + +} diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/ctc_loss_compositeimplicitautograd_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/ctc_loss_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6870f6a52f111f1135886c433e55c52c58450119 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/ctc_loss_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor ctc_loss(const at::Tensor & log_probs, const at::Tensor & targets, at::IntArrayRef input_lengths, at::IntArrayRef target_lengths, int64_t blank=0, int64_t reduction=at::Reduction::Mean, bool zero_infinity=false); +TORCH_API at::Tensor ctc_loss(const at::Tensor & log_probs, const at::Tensor & targets, const at::Tensor & input_lengths, const at::Tensor & target_lengths, int64_t blank=0, int64_t reduction=at::Reduction::Mean, bool zero_infinity=false); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_convolution_ops.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_convolution_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..7cd9a68b04c5742dc9898462c0be0b2e461b5976 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_convolution_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API cudnn_convolution { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymInt, bool, bool, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cudnn_convolution") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cudnn_convolution(Tensor self, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, bool allow_tf32); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, bool allow_tf32); +}; + +struct TORCH_API cudnn_convolution_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymInt, bool, bool, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::cudnn_convolution") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "cudnn_convolution.out(Tensor self, Tensor weight, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, bool benchmark, bool deterministic, bool allow_tf32, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, bool allow_tf32, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, bool allow_tf32, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/empty_ops.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/empty_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..8a6dde495c43884105d0d8d13afef586890169f5 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/empty_ops.h @@ -0,0 +1,61 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API empty_names { + using schema = at::Tensor (at::IntArrayRef, ::std::optional, ::std::optional, ::std::optional, ::std::optional, ::std::optional, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::empty") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "empty.names(int[] size, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor") + static at::Tensor call(at::IntArrayRef size, ::std::optional names, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::IntArrayRef size, ::std::optional names, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format); +}; + +struct TORCH_API empty_memory_format { + using schema = at::Tensor (c10::SymIntArrayRef, ::std::optional, ::std::optional, ::std::optional, ::std::optional, ::std::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::empty") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "memory_format") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "empty.memory_format(SymInt[] size, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=None) -> Tensor") + static at::Tensor call(c10::SymIntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymIntArrayRef size, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format); +}; + +struct TORCH_API empty_out { + using schema = at::Tensor & (c10::SymIntArrayRef, ::std::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::empty") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "empty.out(SymInt[] size, *, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(c10::SymIntArrayRef size, ::std::optional memory_format, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymIntArrayRef size, ::std::optional memory_format, at::Tensor & out); +}; + +struct TORCH_API empty_names_out { + using schema = at::Tensor & (at::IntArrayRef, ::std::optional, ::std::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::empty") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "empty.names_out(int[] size, *, Dimname[]? names, MemoryFormat? memory_format=None, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(at::IntArrayRef size, ::std::optional names, ::std::optional memory_format, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::IntArrayRef size, ::std::optional names, ::std::optional memory_format, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/glu_jvp_native.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/glu_jvp_native.h new file mode 100644 index 0000000000000000000000000000000000000000..e189038097f903385fa20ee7fc0097659c4b78ca --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/glu_jvp_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & glu_jvp_out(const at::Tensor & glu, const at::Tensor & x, const at::Tensor & dx, int64_t dim, at::Tensor & out); +TORCH_API at::Tensor glu_jvp(const at::Tensor & glu, const at::Tensor & x, const at::Tensor & dx, int64_t dim); +} // namespace native +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/igamma_meta.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/igamma_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..8b8b3afc2f1f5d95c8dc5e7814c1a8b5e50ac9f7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/igamma_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_igamma : public TensorIteratorBase { + + + void meta(const at::Tensor & self, const at::Tensor & other); +}; + +} // namespace native +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/im2col_cpu_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/im2col_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f894d1b0cc209549f95060ce8d2a94b08ceabb54 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/im2col_cpu_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor im2col(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef dilation, at::IntArrayRef padding, at::IntArrayRef stride); +TORCH_API at::Tensor & im2col_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef dilation, at::IntArrayRef padding, at::IntArrayRef stride); +TORCH_API at::Tensor & im2col_outf(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef dilation, at::IntArrayRef padding, at::IntArrayRef stride, at::Tensor & out); + +} // namespace cpu +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/is_set_to.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/is_set_to.h new file mode 100644 index 0000000000000000000000000000000000000000..a179cdd64ae896c2bbb3d37861cdb83326f19b46 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/is_set_to.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + + +} diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/log1p_compositeexplicitautogradnonfunctional_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/log1p_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..faa5515cd50444f2c47a711dfb55796886bc85ee --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/log1p_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor log1p(const at::Tensor & self); +TORCH_API at::Tensor & log1p_(at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/mm_cuda_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/mm_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..401d5c33c74252a465988ded89e34c4825512321 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/mm_cuda_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor mm(const at::Tensor & self, const at::Tensor & mat2); +TORCH_API at::Tensor & mm_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & mat2); +TORCH_API at::Tensor & mm_outf(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/rad2deg_compositeexplicitautograd_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/rad2deg_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..a7c3fe4b15bb393d83404b468a2f5b0571d28712 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/rad2deg_compositeexplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor rad2deg(const at::Tensor & self); +TORCH_API at::Tensor & rad2deg_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & rad2deg_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & rad2deg_(at::Tensor & self); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/result_type_compositeimplicitautograd_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/result_type_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f0e91f882b095f8bb3a35ec9e89b1b99f1ab8881 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/result_type_compositeimplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::ScalarType result_type(const at::Tensor & tensor, const at::Tensor & other); +TORCH_API at::ScalarType result_type(const at::Tensor & tensor, const at::Scalar & other); +TORCH_API at::ScalarType result_type(const at::Scalar & scalar, const at::Tensor & tensor); +TORCH_API at::ScalarType result_type(const at::Scalar & scalar1, const at::Scalar & scalar2); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/softshrink_backward_meta_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/softshrink_backward_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9cad570f44b4cd8cb3c9cb8310823fe71e65076c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/softshrink_backward_meta_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor softshrink_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & lambd); +TORCH_API at::Tensor & softshrink_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & lambd); +TORCH_API at::Tensor & softshrink_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Scalar & lambd, at::Tensor & grad_input); + +} // namespace meta +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_nearest3d_compositeexplicitautogradnonfunctional_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_nearest3d_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..421c1b3d0586382ecdbb5399dd2e612324fca9a7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_nearest3d_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor upsample_nearest3d(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional scales_d=::std::nullopt, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor upsample_nearest3d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales_d=::std::nullopt, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/where_compositeimplicitautograd_dispatch.h b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/where_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..36e00246c6e08e9b5bcf1365eadfb8eb971fa2bc --- /dev/null +++ b/parrot/lib/python3.10/site-packages/torch/include/ATen/ops/where_compositeimplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor where(const at::Tensor & condition, const at::Scalar & self, const at::Tensor & other); +TORCH_API at::Tensor where(const at::Tensor & condition, const at::Tensor & self, const at::Scalar & other); +TORCH_API at::Tensor where(const at::Tensor & condition, const at::Scalar & self, const at::Scalar & other); +TORCH_API ::std::vector where(const at::Tensor & condition); + +} // namespace compositeimplicitautograd +} // namespace at