diff --git a/videollama2/lib/python3.10/site-packages/setuptools/tests/indexes/test_links_priority/external.html b/videollama2/lib/python3.10/site-packages/setuptools/tests/indexes/test_links_priority/external.html new file mode 100644 index 0000000000000000000000000000000000000000..92e4702f634dfb37a404bec3103b76f6afcaa917 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/setuptools/tests/indexes/test_links_priority/external.html @@ -0,0 +1,3 @@ + +bad old link + diff --git a/videollama2/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-310.pyc b/videollama2/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/videollama2/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/helpers.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-310.pyc b/videollama2/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/videollama2/lib/python3.10/site-packages/setuptools/tests/integration/__pycache__/test_pip_install_sdist.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/setuptools/tests/mod_with_constant.py b/videollama2/lib/python3.10/site-packages/setuptools/tests/mod_with_constant.py new file mode 100644 index 0000000000000000000000000000000000000000..ef755dd1c7a8d1f116fe51f1b43315057f03379d --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/setuptools/tests/mod_with_constant.py @@ -0,0 +1 @@ +value = 'three, sir!' diff --git a/videollama2/lib/python3.10/site-packages/setuptools/tests/namespaces.py b/videollama2/lib/python3.10/site-packages/setuptools/tests/namespaces.py new file mode 100644 index 0000000000000000000000000000000000000000..248db98f97951aeeee0222131417e73074cc72d2 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/setuptools/tests/namespaces.py @@ -0,0 +1,90 @@ +import ast +import json +import textwrap +from pathlib import Path + + +def iter_namespace_pkgs(namespace): + parts = namespace.split(".") + for i in range(len(parts)): + yield ".".join(parts[: i + 1]) + + +def build_namespace_package(tmpdir, name, version="1.0", impl="pkg_resources"): + src_dir = tmpdir / name + src_dir.mkdir() + setup_py = src_dir / 'setup.py' + namespace, _, rest = name.rpartition('.') + namespaces = list(iter_namespace_pkgs(namespace)) + setup_args = { + "name": name, + "version": version, + "packages": namespaces, + } + + if impl == "pkg_resources": + tmpl = '__import__("pkg_resources").declare_namespace(__name__)' + setup_args["namespace_packages"] = namespaces + elif impl == "pkgutil": + tmpl = '__path__ = __import__("pkgutil").extend_path(__path__, __name__)' + else: + raise ValueError(f"Cannot recognise {impl=} when creating namespaces") + + args = json.dumps(setup_args, indent=4) + assert ast.literal_eval(args) # ensure it is valid Python + + script = textwrap.dedent( + """\ + import setuptools + args = {args} + setuptools.setup(**args) + """ + ).format(args=args) + setup_py.write_text(script, encoding='utf-8') + + ns_pkg_dir = Path(src_dir, namespace.replace(".", "/")) + ns_pkg_dir.mkdir(parents=True) + + for ns in namespaces: + pkg_init = src_dir / ns.replace(".", "/") / '__init__.py' + pkg_init.write_text(tmpl, encoding='utf-8') + + pkg_mod = ns_pkg_dir / (rest + '.py') + some_functionality = 'name = {rest!r}'.format(**locals()) + pkg_mod.write_text(some_functionality, encoding='utf-8') + return src_dir + + +def build_pep420_namespace_package(tmpdir, name): + src_dir = tmpdir / name + src_dir.mkdir() + pyproject = src_dir / "pyproject.toml" + namespace, _, rest = name.rpartition(".") + script = f"""\ + [build-system] + requires = ["setuptools"] + build-backend = "setuptools.build_meta" + + [project] + name = "{name}" + version = "3.14159" + """ + pyproject.write_text(textwrap.dedent(script), encoding='utf-8') + ns_pkg_dir = Path(src_dir, namespace.replace(".", "/")) + ns_pkg_dir.mkdir(parents=True) + pkg_mod = ns_pkg_dir / (rest + ".py") + some_functionality = f"name = {rest!r}" + pkg_mod.write_text(some_functionality, encoding='utf-8') + return src_dir + + +def make_site_dir(target): + """ + Add a sitecustomize.py module in target to cause + target to be added to site dirs such that .pth files + are processed there. + """ + sc = target / 'sitecustomize.py' + target_str = str(target) + tmpl = '__import__("site").addsitedir({target_str!r})' + sc.write_text(tmpl.format(**locals()), encoding='utf-8') diff --git a/videollama2/lib/python3.10/site-packages/setuptools/tests/test_archive_util.py b/videollama2/lib/python3.10/site-packages/setuptools/tests/test_archive_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e3efc62889994fa68bc9170e8a0e403f48a204e1 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/setuptools/tests/test_archive_util.py @@ -0,0 +1,36 @@ +import io +import tarfile + +import pytest + +from setuptools import archive_util + + +@pytest.fixture +def tarfile_with_unicode(tmpdir): + """ + Create a tarfile containing only a file whose name is + a zero byte file called testimäge.png. + """ + tarobj = io.BytesIO() + + with tarfile.open(fileobj=tarobj, mode="w:gz") as tgz: + data = b"" + + filename = "testimäge.png" + + t = tarfile.TarInfo(filename) + t.size = len(data) + + tgz.addfile(t, io.BytesIO(data)) + + target = tmpdir / 'unicode-pkg-1.0.tar.gz' + with open(str(target), mode='wb') as tf: + tf.write(tarobj.getvalue()) + return str(target) + + +@pytest.mark.xfail(reason="#710 and #712") +def test_unicode_files(tarfile_with_unicode, tmpdir): + target = tmpdir / 'out' + archive_util.unpack_archive(tarfile_with_unicode, str(target)) diff --git a/videollama2/lib/python3.10/site-packages/setuptools/tests/test_packageindex.py b/videollama2/lib/python3.10/site-packages/setuptools/tests/test_packageindex.py new file mode 100644 index 0000000000000000000000000000000000000000..2a6e5917a8733c71a5d9b29d4bde6fc12cc1e183 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/setuptools/tests/test_packageindex.py @@ -0,0 +1,267 @@ +import http.client +import re +import urllib.error +import urllib.request +from inspect import cleandoc + +import pytest + +import setuptools.package_index + +import distutils.errors + + +class TestPackageIndex: + def test_regex(self): + hash_url = 'http://other_url?:action=show_md5&' + hash_url += 'digest=0123456789abcdef0123456789abcdef' + doc = """ + Name + (md5) + """.lstrip().format(**locals()) + assert setuptools.package_index.PYPI_MD5.match(doc) + + def test_bad_url_bad_port(self): + index = setuptools.package_index.PackageIndex() + url = 'http://127.0.0.1:0/nonesuch/test_package_index' + with pytest.raises(Exception, match=re.escape(url)): + v = index.open_url(url) + assert isinstance(v, urllib.error.HTTPError) + + def test_bad_url_typo(self): + # issue 16 + # easy_install inquant.contentmirror.plone breaks because of a typo + # in its home URL + index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) + + url = 'url:%20https://svn.plone.org/svn/collective/inquant.contentmirror.plone/trunk' + + with pytest.raises(Exception, match=re.escape(url)): + v = index.open_url(url) + assert isinstance(v, urllib.error.HTTPError) + + def test_bad_url_bad_status_line(self): + index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) + + def _urlopen(*args): + raise http.client.BadStatusLine('line') + + index.opener = _urlopen + url = 'http://example.com' + with pytest.raises(Exception, match=r'line'): + index.open_url(url) + + def test_bad_url_double_scheme(self): + """ + A bad URL with a double scheme should raise a DistutilsError. + """ + index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) + + # issue 20 + url = 'http://http://svn.pythonpaste.org/Paste/wphp/trunk' + try: + index.open_url(url) + except distutils.errors.DistutilsError as error: + msg = str(error) + assert ( + 'nonnumeric port' in msg + or 'getaddrinfo failed' in msg + or 'Name or service not known' in msg + ) + return + raise RuntimeError("Did not raise") + + def test_url_ok(self): + index = setuptools.package_index.PackageIndex(hosts=('www.example.com',)) + url = 'file:///tmp/test_package_index' + assert index.url_ok(url, True) + + def test_parse_bdist_wininst(self): + parse = setuptools.package_index.parse_bdist_wininst + + actual = parse('reportlab-2.5.win32-py2.4.exe') + expected = 'reportlab-2.5', '2.4', 'win32' + assert actual == expected + + actual = parse('reportlab-2.5.win32.exe') + expected = 'reportlab-2.5', None, 'win32' + assert actual == expected + + actual = parse('reportlab-2.5.win-amd64-py2.7.exe') + expected = 'reportlab-2.5', '2.7', 'win-amd64' + assert actual == expected + + actual = parse('reportlab-2.5.win-amd64.exe') + expected = 'reportlab-2.5', None, 'win-amd64' + assert actual == expected + + def test__vcs_split_rev_from_url(self): + """ + Test the basic usage of _vcs_split_rev_from_url + """ + vsrfu = setuptools.package_index.PackageIndex._vcs_split_rev_from_url + url, rev = vsrfu('https://example.com/bar@2995') + assert url == 'https://example.com/bar' + assert rev == '2995' + + def test_local_index(self, tmpdir): + """ + local_open should be able to read an index from the file system. + """ + index_file = tmpdir / 'index.html' + with index_file.open('w') as f: + f.write('
content
') + url = 'file:' + urllib.request.pathname2url(str(tmpdir)) + '/' + res = setuptools.package_index.local_open(url) + assert 'content' in res.read() + + def test_egg_fragment(self): + """ + EGG fragments must comply to PEP 440 + """ + epoch = [ + '', + '1!', + ] + releases = [ + '0', + '0.0', + '0.0.0', + ] + pre = [ + 'a0', + 'b0', + 'rc0', + ] + post = ['.post0'] + dev = [ + '.dev0', + ] + local = [ + ('', ''), + ('+ubuntu.0', '+ubuntu.0'), + ('+ubuntu-0', '+ubuntu.0'), + ('+ubuntu_0', '+ubuntu.0'), + ] + versions = [ + [''.join([e, r, p, loc]) for loc in locs] + for e in epoch + for r in releases + for p in sum([pre, post, dev], ['']) + for locs in local + ] + for v, vc in versions: + dists = list( + setuptools.package_index.distros_for_url( + 'http://example.com/example-foo.zip#egg=example-foo-' + v + ) + ) + assert dists[0].version == '' + assert dists[1].version == vc + + def test_download_git_with_rev(self, tmp_path, fp): + url = 'git+https://github.example/group/project@master#egg=foo' + index = setuptools.package_index.PackageIndex() + + expected_dir = tmp_path / 'project@master' + fp.register([ + 'git', + 'clone', + '--quiet', + 'https://github.example/group/project', + expected_dir, + ]) + fp.register(['git', '-C', expected_dir, 'checkout', '--quiet', 'master']) + + result = index.download(url, tmp_path) + + assert result == str(expected_dir) + assert len(fp.calls) == 2 + + def test_download_git_no_rev(self, tmp_path, fp): + url = 'git+https://github.example/group/project#egg=foo' + index = setuptools.package_index.PackageIndex() + + expected_dir = tmp_path / 'project' + fp.register([ + 'git', + 'clone', + '--quiet', + 'https://github.example/group/project', + expected_dir, + ]) + index.download(url, tmp_path) + + def test_download_svn(self, tmp_path): + url = 'svn+https://svn.example/project#egg=foo' + index = setuptools.package_index.PackageIndex() + + msg = r".*SVN download is not supported.*" + with pytest.raises(distutils.errors.DistutilsError, match=msg): + index.download(url, tmp_path) + + +class TestContentCheckers: + def test_md5(self): + checker = setuptools.package_index.HashChecker.from_url( + 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478' + ) + checker.feed('You should probably not be using MD5'.encode('ascii')) + assert checker.hash.hexdigest() == 'f12895fdffbd45007040d2e44df98478' + assert checker.is_valid() + + def test_other_fragment(self): + "Content checks should succeed silently if no hash is present" + checker = setuptools.package_index.HashChecker.from_url( + 'http://foo/bar#something%20completely%20different' + ) + checker.feed('anything'.encode('ascii')) + assert checker.is_valid() + + def test_blank_md5(self): + "Content checks should succeed if a hash is empty" + checker = setuptools.package_index.HashChecker.from_url('http://foo/bar#md5=') + checker.feed('anything'.encode('ascii')) + assert checker.is_valid() + + def test_get_hash_name_md5(self): + checker = setuptools.package_index.HashChecker.from_url( + 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478' + ) + assert checker.hash_name == 'md5' + + def test_report(self): + checker = setuptools.package_index.HashChecker.from_url( + 'http://foo/bar#md5=f12895fdffbd45007040d2e44df98478' + ) + rep = checker.report(lambda x: x, 'My message about %s') + assert rep == 'My message about md5' + + +class TestPyPIConfig: + def test_percent_in_password(self, tmp_home_dir): + pypirc = tmp_home_dir / '.pypirc' + pypirc.write_text( + cleandoc( + """ + [pypi] + repository=https://pypi.org + username=jaraco + password=pity% + """ + ), + encoding="utf-8", + ) + cfg = setuptools.package_index.PyPIConfig() + cred = cfg.creds_by_repository['https://pypi.org'] + assert cred.username == 'jaraco' + assert cred.password == 'pity%' + + +@pytest.mark.timeout(1) +def test_REL_DoS(): + """ + REL should not hang on a contrived attack string. + """ + setuptools.package_index.REL.search('< rel=' + ' ' * 2**12) diff --git a/videollama2/lib/python3.10/site-packages/setuptools/tests/test_sdist.py b/videollama2/lib/python3.10/site-packages/setuptools/tests/test_sdist.py new file mode 100644 index 0000000000000000000000000000000000000000..3ee0511b1c485a1e4a9f028a29b7a17d8b4c8130 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/setuptools/tests/test_sdist.py @@ -0,0 +1,972 @@ +"""sdist tests""" + +import contextlib +import io +import logging +import os +import pathlib +import sys +import tarfile +import tempfile +import unicodedata +from inspect import cleandoc +from pathlib import Path +from unittest import mock + +import jaraco.path +import pytest + +from setuptools import Command, SetuptoolsDeprecationWarning +from setuptools._importlib import metadata +from setuptools.command.egg_info import manifest_maker +from setuptools.command.sdist import sdist +from setuptools.dist import Distribution +from setuptools.extension import Extension +from setuptools.tests import fail_on_ascii + +from .text import Filenames + +import distutils +from distutils.core import run_setup + +SETUP_ATTRS = { + 'name': 'sdist_test', + 'version': '0.0', + 'packages': ['sdist_test'], + 'package_data': {'sdist_test': ['*.txt']}, + 'data_files': [("data", [os.path.join("d", "e.dat")])], +} + +SETUP_PY = f"""\ +from setuptools import setup + +setup(**{SETUP_ATTRS!r}) +""" + +EXTENSION = Extension( + name="sdist_test.f", + sources=[os.path.join("sdist_test", "f.c")], + depends=[os.path.join("sdist_test", "f.h")], +) +EXTENSION_SOURCES = EXTENSION.sources + EXTENSION.depends + + +@contextlib.contextmanager +def quiet(): + old_stdout, old_stderr = sys.stdout, sys.stderr + sys.stdout, sys.stderr = io.StringIO(), io.StringIO() + try: + yield + finally: + sys.stdout, sys.stderr = old_stdout, old_stderr + + +# Convert to POSIX path +def posix(path): + if not isinstance(path, str): + return path.replace(os.sep.encode('ascii'), b'/') + else: + return path.replace(os.sep, '/') + + +# HFS Plus uses decomposed UTF-8 +def decompose(path): + if isinstance(path, str): + return unicodedata.normalize('NFD', path) + try: + path = path.decode('utf-8') + path = unicodedata.normalize('NFD', path) + path = path.encode('utf-8') + except UnicodeError: + pass # Not UTF-8 + return path + + +def read_all_bytes(filename): + with open(filename, 'rb') as fp: + return fp.read() + + +def latin1_fail(): + try: + desc, filename = tempfile.mkstemp(suffix=Filenames.latin_1) + os.close(desc) + os.remove(filename) + except Exception: + return True + + +fail_on_latin1_encoded_filenames = pytest.mark.xfail( + latin1_fail(), + reason="System does not support latin-1 filenames", +) + + +skip_under_xdist = pytest.mark.skipif( + "os.environ.get('PYTEST_XDIST_WORKER')", + reason="pytest-dev/pytest-xdist#843", +) +skip_under_stdlib_distutils = pytest.mark.skipif( + not distutils.__package__.startswith('setuptools'), + reason="the test is not supported with stdlib distutils", +) + + +def touch(path): + open(path, 'wb').close() + return path + + +def symlink_or_skip_test(src, dst): + try: + os.symlink(src, dst) + except (OSError, NotImplementedError): + pytest.skip("symlink not supported in OS") + return None + return dst + + +class TestSdistTest: + @pytest.fixture(autouse=True) + def source_dir(self, tmpdir): + tmpdir = tmpdir / "project_root" + tmpdir.mkdir() + + (tmpdir / 'setup.py').write_text(SETUP_PY, encoding='utf-8') + + # Set up the rest of the test package + test_pkg = tmpdir / 'sdist_test' + test_pkg.mkdir() + data_folder = tmpdir / 'd' + data_folder.mkdir() + # *.rst was not included in package_data, so c.rst should not be + # automatically added to the manifest when not under version control + for fname in ['__init__.py', 'a.txt', 'b.txt', 'c.rst']: + touch(test_pkg / fname) + touch(data_folder / 'e.dat') + # C sources are not included by default, but they will be, + # if an extension module uses them as sources or depends + for fname in EXTENSION_SOURCES: + touch(tmpdir / fname) + + with tmpdir.as_cwd(): + yield tmpdir + + def assert_package_data_in_manifest(self, cmd): + manifest = cmd.filelist.files + assert os.path.join('sdist_test', 'a.txt') in manifest + assert os.path.join('sdist_test', 'b.txt') in manifest + assert os.path.join('sdist_test', 'c.rst') not in manifest + assert os.path.join('d', 'e.dat') in manifest + + def setup_with_extension(self): + setup_attrs = {**SETUP_ATTRS, 'ext_modules': [EXTENSION]} + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + return cmd + + def test_package_data_in_sdist(self): + """Regression test for pull request #4: ensures that files listed in + package_data are included in the manifest even if they're not added to + version control. + """ + + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + self.assert_package_data_in_manifest(cmd) + + def test_package_data_and_include_package_data_in_sdist(self): + """ + Ensure package_data and include_package_data work + together. + """ + setup_attrs = {**SETUP_ATTRS, 'include_package_data': True} + assert setup_attrs['package_data'] + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + self.assert_package_data_in_manifest(cmd) + + def test_extension_sources_in_sdist(self): + """ + Ensure that the files listed in Extension.sources and Extension.depends + are automatically included in the manifest. + """ + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + for path in EXTENSION_SOURCES: + assert path in manifest + + def test_missing_extension_sources(self): + """ + Similar to test_extension_sources_in_sdist but the referenced files don't exist. + Missing files should not be included in distribution (with no error raised). + """ + for path in EXTENSION_SOURCES: + os.remove(path) + + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + for path in EXTENSION_SOURCES: + assert path not in manifest + + def test_symlinked_extension_sources(self): + """ + Similar to test_extension_sources_in_sdist but the referenced files are + instead symbolic links to project-local files. Referenced file paths + should be included. Symlink targets themselves should NOT be included. + """ + symlinked = [] + for path in EXTENSION_SOURCES: + base, ext = os.path.splitext(path) + target = base + "_target." + ext + + os.rename(path, target) + symlink_or_skip_test(os.path.basename(target), path) + symlinked.append(target) + + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + for path in EXTENSION_SOURCES: + assert path in manifest + for path in symlinked: + assert path not in manifest + + _INVALID_PATHS = { + "must be relative": lambda: ( + os.path.abspath(os.path.join("sdist_test", "f.h")) + ), + "can't have `..` segments": lambda: ( + os.path.join("sdist_test", "..", "sdist_test", "f.h") + ), + "doesn't exist": lambda: ( + os.path.join("sdist_test", "this_file_does_not_exist.h") + ), + "must be inside the project root": lambda: ( + symlink_or_skip_test( + touch(os.path.join("..", "outside_of_project_root.h")), + "symlink.h", + ) + ), + } + + @skip_under_stdlib_distutils + @pytest.mark.parametrize("reason", _INVALID_PATHS.keys()) + def test_invalid_extension_depends(self, reason, caplog): + """ + Due to backwards compatibility reasons, `Extension.depends` should accept + invalid/weird paths, but then ignore them when building a sdist. + + This test verifies that the source distribution is still built + successfully with such paths, but that instead of adding these paths to + the manifest, we emit an informational message, notifying the user that + the invalid path won't be automatically included. + """ + invalid_path = self._INVALID_PATHS[reason]() + extension = Extension( + name="sdist_test.f", + sources=[], + depends=[invalid_path], + ) + setup_attrs = {**SETUP_ATTRS, 'ext_modules': [extension]} + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(), caplog.at_level(logging.INFO): + cmd.run() + + self.assert_package_data_in_manifest(cmd) + manifest = cmd.filelist.files + assert invalid_path not in manifest + + expected_message = [ + message + for (logger, level, message) in caplog.record_tuples + if ( + logger == "root" # + and level == logging.INFO # + and invalid_path in message # + ) + ] + assert len(expected_message) == 1 + (expected_message,) = expected_message + assert reason in expected_message + + def test_custom_build_py(self): + """ + Ensure projects defining custom build_py don't break + when creating sdists (issue #2849) + """ + from distutils.command.build_py import build_py as OrigBuildPy + + using_custom_command_guard = mock.Mock() + + class CustomBuildPy(OrigBuildPy): + """ + Some projects have custom commands inheriting from `distutils` + """ + + def get_data_files(self): + using_custom_command_guard() + return super().get_data_files() + + setup_attrs = {**SETUP_ATTRS, 'include_package_data': True} + assert setup_attrs['package_data'] + + dist = Distribution(setup_attrs) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Make sure we use the custom command + cmd.cmdclass = {'build_py': CustomBuildPy} + cmd.distribution.cmdclass = {'build_py': CustomBuildPy} + assert cmd.distribution.get_command_class('build_py') == CustomBuildPy + + msg = "setuptools instead of distutils" + with quiet(), pytest.warns(SetuptoolsDeprecationWarning, match=msg): + cmd.run() + + using_custom_command_guard.assert_called() + self.assert_package_data_in_manifest(cmd) + + def test_setup_py_exists(self): + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'foo.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + manifest = cmd.filelist.files + assert 'setup.py' in manifest + + def test_setup_py_missing(self): + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'foo.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + if os.path.exists("setup.py"): + os.remove("setup.py") + with quiet(): + cmd.run() + + manifest = cmd.filelist.files + assert 'setup.py' not in manifest + + def test_setup_py_excluded(self): + with open("MANIFEST.in", "w", encoding="utf-8") as manifest_file: + manifest_file.write("exclude setup.py") + + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'foo.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + manifest = cmd.filelist.files + assert 'setup.py' not in manifest + + def test_defaults_case_sensitivity(self, source_dir): + """ + Make sure default files (README.*, etc.) are added in a case-sensitive + way to avoid problems with packages built on Windows. + """ + + touch(source_dir / 'readme.rst') + touch(source_dir / 'SETUP.cfg') + + dist = Distribution(SETUP_ATTRS) + # the extension deliberately capitalized for this test + # to make sure the actual filename (not capitalized) gets added + # to the manifest + dist.script_name = 'setup.PY' + cmd = sdist(dist) + cmd.ensure_finalized() + + with quiet(): + cmd.run() + + # lowercase all names so we can test in a + # case-insensitive way to make sure the files + # are not included. + manifest = map(lambda x: x.lower(), cmd.filelist.files) + assert 'readme.rst' not in manifest, manifest + assert 'setup.py' not in manifest, manifest + assert 'setup.cfg' not in manifest, manifest + + def test_exclude_dev_only_cache_folders(self, source_dir): + included = { + # Emulate problem in https://github.com/pypa/setuptools/issues/4601 + "MANIFEST.in": ( + "global-include LICEN[CS]E* COPYING* NOTICE* AUTHORS*\n" + "global-include *.txt\n" + ), + # For the sake of being conservative and limiting unforeseen side-effects + # we just exclude dev-only cache folders at the root of the repository: + "test/.venv/lib/python3.9/site-packages/bar-2.dist-info/AUTHORS.rst": "", + "src/.nox/py/lib/python3.12/site-packages/bar-2.dist-info/COPYING.txt": "", + "doc/.tox/default/lib/python3.11/site-packages/foo-4.dist-info/LICENSE": "", + # Let's test against false positives with similarly named files: + ".venv-requirements.txt": "", + ".tox-coveragerc.txt": "", + ".noxy/coveragerc.txt": "", + } + + excluded = { + # .tox/.nox/.venv are well-know folders present at the root of Python repos + # and therefore should be excluded + ".tox/release/lib/python3.11/site-packages/foo-4.dist-info/LICENSE": "", + ".nox/py/lib/python3.12/site-packages/bar-2.dist-info/COPYING.txt": "", + ".venv/lib/python3.9/site-packages/bar-2.dist-info/AUTHORS.rst": "", + } + + for file, content in {**excluded, **included}.items(): + Path(source_dir, file).parent.mkdir(parents=True, exist_ok=True) + Path(source_dir, file).write_text(content, encoding="utf-8") + + cmd = self.setup_with_extension() + self.assert_package_data_in_manifest(cmd) + manifest = {f.replace(os.sep, '/') for f in cmd.filelist.files} + for path in excluded: + assert os.path.exists(path) + assert path not in manifest, (path, manifest) + for path in included: + assert os.path.exists(path) + assert path in manifest, (path, manifest) + + @fail_on_ascii + def test_manifest_is_written_with_utf8_encoding(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + mm = manifest_maker(dist) + mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + os.mkdir('sdist_test.egg-info') + + # UTF-8 filename + filename = os.path.join('sdist_test', 'smörbröd.py') + + # Must create the file or it will get stripped. + touch(filename) + + # Add UTF-8 filename and write manifest + with quiet(): + mm.run() + mm.filelist.append(filename) + mm.write_manifest() + + contents = read_all_bytes(mm.manifest) + + # The manifest should be UTF-8 encoded + u_contents = contents.decode('UTF-8') + + # The manifest should contain the UTF-8 filename + assert posix(filename) in u_contents + + @fail_on_ascii + def test_write_manifest_allows_utf8_filenames(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + mm = manifest_maker(dist) + mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + os.mkdir('sdist_test.egg-info') + + filename = os.path.join(b'sdist_test', Filenames.utf_8) + + # Must touch the file or risk removal + touch(filename) + + # Add filename and write manifest + with quiet(): + mm.run() + u_filename = filename.decode('utf-8') + mm.filelist.files.append(u_filename) + # Re-write manifest + mm.write_manifest() + + contents = read_all_bytes(mm.manifest) + + # The manifest should be UTF-8 encoded + contents.decode('UTF-8') + + # The manifest should contain the UTF-8 filename + assert posix(filename) in contents + + # The filelist should have been updated as well + assert u_filename in mm.filelist.files + + @skip_under_xdist + def test_write_manifest_skips_non_utf8_filenames(self): + """ + Files that cannot be encoded to UTF-8 (specifically, those that + weren't originally successfully decoded and have surrogate + escapes) should be omitted from the manifest. + See https://bitbucket.org/tarek/distribute/issue/303 for history. + """ + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + mm = manifest_maker(dist) + mm.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + os.mkdir('sdist_test.egg-info') + + # Latin-1 filename + filename = os.path.join(b'sdist_test', Filenames.latin_1) + + # Add filename with surrogates and write manifest + with quiet(): + mm.run() + u_filename = filename.decode('utf-8', 'surrogateescape') + mm.filelist.append(u_filename) + # Re-write manifest + mm.write_manifest() + + contents = read_all_bytes(mm.manifest) + + # The manifest should be UTF-8 encoded + contents.decode('UTF-8') + + # The Latin-1 filename should have been skipped + assert posix(filename) not in contents + + # The filelist should have been updated as well + assert u_filename not in mm.filelist.files + + @fail_on_ascii + def test_manifest_is_read_with_utf8_encoding(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Create manifest + with quiet(): + cmd.run() + + # Add UTF-8 filename to manifest + filename = os.path.join(b'sdist_test', Filenames.utf_8) + cmd.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + manifest = open(cmd.manifest, 'ab') + manifest.write(b'\n' + filename) + manifest.close() + + # The file must exist to be included in the filelist + touch(filename) + + # Re-read manifest + cmd.filelist.files = [] + with quiet(): + cmd.read_manifest() + + # The filelist should contain the UTF-8 filename + filename = filename.decode('utf-8') + assert filename in cmd.filelist.files + + @fail_on_latin1_encoded_filenames + def test_read_manifest_skips_non_utf8_filenames(self): + # Test for #303. + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Create manifest + with quiet(): + cmd.run() + + # Add Latin-1 filename to manifest + filename = os.path.join(b'sdist_test', Filenames.latin_1) + cmd.manifest = os.path.join('sdist_test.egg-info', 'SOURCES.txt') + manifest = open(cmd.manifest, 'ab') + manifest.write(b'\n' + filename) + manifest.close() + + # The file must exist to be included in the filelist + touch(filename) + + # Re-read manifest + cmd.filelist.files = [] + with quiet(): + cmd.read_manifest() + + # The Latin-1 filename should have been skipped + filename = filename.decode('latin-1') + assert filename not in cmd.filelist.files + + @fail_on_ascii + @fail_on_latin1_encoded_filenames + def test_sdist_with_utf8_encoded_filename(self): + # Test for #303. + dist = Distribution(self.make_strings(SETUP_ATTRS)) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + filename = os.path.join(b'sdist_test', Filenames.utf_8) + touch(filename) + + with quiet(): + cmd.run() + + if sys.platform == 'darwin': + filename = decompose(filename) + + fs_enc = sys.getfilesystemencoding() + + if sys.platform == 'win32': + if fs_enc == 'cp1252': + # Python mangles the UTF-8 filename + filename = filename.decode('cp1252') + assert filename in cmd.filelist.files + else: + filename = filename.decode('mbcs') + assert filename in cmd.filelist.files + else: + filename = filename.decode('utf-8') + assert filename in cmd.filelist.files + + @classmethod + def make_strings(cls, item): + if isinstance(item, dict): + return {key: cls.make_strings(value) for key, value in item.items()} + if isinstance(item, list): + return list(map(cls.make_strings, item)) + return str(item) + + @fail_on_latin1_encoded_filenames + @skip_under_xdist + def test_sdist_with_latin1_encoded_filename(self): + # Test for #303. + dist = Distribution(self.make_strings(SETUP_ATTRS)) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + + # Latin-1 filename + filename = os.path.join(b'sdist_test', Filenames.latin_1) + touch(filename) + assert os.path.isfile(filename) + + with quiet(): + cmd.run() + + # not all windows systems have a default FS encoding of cp1252 + if sys.platform == 'win32': + # Latin-1 is similar to Windows-1252 however + # on mbcs filesys it is not in latin-1 encoding + fs_enc = sys.getfilesystemencoding() + if fs_enc != 'mbcs': + fs_enc = 'latin-1' + filename = filename.decode(fs_enc) + + assert filename in cmd.filelist.files + else: + # The Latin-1 filename should have been skipped + filename = filename.decode('latin-1') + assert filename not in cmd.filelist.files + + _EXAMPLE_DIRECTIVES = { + "setup.cfg - long_description and version": """ + [metadata] + name = testing + version = file: src/VERSION.txt + license_files = DOWHATYOUWANT + long_description = file: README.rst, USAGE.rst + """, + "pyproject.toml - static readme/license files and dynamic version": """ + [project] + name = "testing" + readme = "USAGE.rst" + license = {file = "DOWHATYOUWANT"} + dynamic = ["version"] + [tool.setuptools.dynamic] + version = {file = ["src/VERSION.txt"]} + """, + "pyproject.toml - directive with str instead of list": """ + [project] + name = "testing" + readme = "USAGE.rst" + license = {file = "DOWHATYOUWANT"} + dynamic = ["version"] + [tool.setuptools.dynamic] + version = {file = "src/VERSION.txt"} + """, + } + + @pytest.mark.parametrize("config", _EXAMPLE_DIRECTIVES.keys()) + def test_add_files_referenced_by_config_directives(self, source_dir, config): + config_file, _, _ = config.partition(" - ") + config_text = self._EXAMPLE_DIRECTIVES[config] + (source_dir / 'src').mkdir() + (source_dir / 'src/VERSION.txt').write_text("0.42", encoding="utf-8") + (source_dir / 'README.rst').write_text("hello world!", encoding="utf-8") + (source_dir / 'USAGE.rst').write_text("hello world!", encoding="utf-8") + (source_dir / 'DOWHATYOUWANT').write_text("hello world!", encoding="utf-8") + (source_dir / config_file).write_text(config_text, encoding="utf-8") + + dist = Distribution({"packages": []}) + dist.script_name = 'setup.py' + dist.parse_config_files() + + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + + assert ( + 'src/VERSION.txt' in cmd.filelist.files + or 'src\\VERSION.txt' in cmd.filelist.files + ) + assert 'USAGE.rst' in cmd.filelist.files + assert 'DOWHATYOUWANT' in cmd.filelist.files + assert '/' not in cmd.filelist.files + assert '\\' not in cmd.filelist.files + + def test_pyproject_toml_in_sdist(self, source_dir): + """ + Check if pyproject.toml is included in source distribution if present + """ + touch(source_dir / 'pyproject.toml') + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert 'pyproject.toml' in manifest + + def test_pyproject_toml_excluded(self, source_dir): + """ + Check that pyproject.toml can excluded even if present + """ + touch(source_dir / 'pyproject.toml') + with open('MANIFEST.in', 'w', encoding="utf-8") as mts: + print('exclude pyproject.toml', file=mts) + dist = Distribution(SETUP_ATTRS) + dist.script_name = 'setup.py' + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert 'pyproject.toml' not in manifest + + def test_build_subcommand_source_files(self, source_dir): + touch(source_dir / '.myfile~') + + # Sanity check: without custom commands file list should not be affected + dist = Distribution({**SETUP_ATTRS, "script_name": "setup.py"}) + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert '.myfile~' not in manifest + + # Test: custom command should be able to augment file list + dist = Distribution({**SETUP_ATTRS, "script_name": "setup.py"}) + build = dist.get_command_obj("build") + build.sub_commands = [*build.sub_commands, ("build_custom", None)] + + class build_custom(Command): + def initialize_options(self): ... + + def finalize_options(self): ... + + def run(self): ... + + def get_source_files(self): + return ['.myfile~'] + + dist.cmdclass.update(build_custom=build_custom) + + cmd = sdist(dist) + cmd.use_defaults = True + cmd.ensure_finalized() + with quiet(): + cmd.run() + manifest = cmd.filelist.files + assert '.myfile~' in manifest + + @pytest.mark.skipif("os.environ.get('SETUPTOOLS_USE_DISTUTILS') == 'stdlib'") + def test_build_base_pathlib(self, source_dir): + """ + Ensure if build_base is a pathlib.Path, the build still succeeds. + """ + dist = Distribution({ + **SETUP_ATTRS, + "script_name": "setup.py", + "options": {"build": {"build_base": pathlib.Path('build')}}, + }) + cmd = sdist(dist) + cmd.ensure_finalized() + with quiet(): + cmd.run() + + +def test_default_revctrl(): + """ + When _default_revctrl was removed from the `setuptools.command.sdist` + module in 10.0, it broke some systems which keep an old install of + setuptools (Distribute) around. Those old versions require that the + setuptools package continue to implement that interface, so this + function provides that interface, stubbed. See #320 for details. + + This interface must be maintained until Ubuntu 12.04 is no longer + supported (by Setuptools). + """ + (ep,) = metadata.EntryPoints._from_text( + """ + [setuptools.file_finders] + svn_cvs = setuptools.command.sdist:_default_revctrl + """ + ) + res = ep.load() + assert hasattr(res, '__iter__') + + +class TestRegressions: + """ + Can be removed/changed if the project decides to change how it handles symlinks + or external files. + """ + + @staticmethod + def files_for_symlink_in_extension_depends(tmp_path, dep_path): + return { + "external": { + "dir": {"file.h": ""}, + }, + "project": { + "setup.py": cleandoc( + f""" + from setuptools import Extension, setup + setup( + name="myproj", + version="42", + ext_modules=[ + Extension( + "hello", sources=["hello.pyx"], + depends=[{dep_path!r}] + ) + ], + ) + """ + ), + "hello.pyx": "", + "MANIFEST.in": "global-include *.h", + }, + } + + @pytest.mark.parametrize( + "dep_path", ("myheaders/dir/file.h", "myheaders/dir/../dir/file.h") + ) + def test_symlink_in_extension_depends(self, monkeypatch, tmp_path, dep_path): + # Given a project with a symlinked dir and a "depends" targeting that dir + files = self.files_for_symlink_in_extension_depends(tmp_path, dep_path) + jaraco.path.build(files, prefix=str(tmp_path)) + symlink_or_skip_test(tmp_path / "external", tmp_path / "project/myheaders") + + # When `sdist` runs, there should be no error + members = run_sdist(monkeypatch, tmp_path / "project") + # and the sdist should contain the symlinked files + for expected in ( + "myproj-42/hello.pyx", + "myproj-42/myheaders/dir/file.h", + ): + assert expected in members + + @staticmethod + def files_for_external_path_in_extension_depends(tmp_path, dep_path): + head, _, tail = dep_path.partition("$tmp_path$/") + dep_path = tmp_path / tail if tail else head + + return { + "external": { + "dir": {"file.h": ""}, + }, + "project": { + "setup.py": cleandoc( + f""" + from setuptools import Extension, setup + setup( + name="myproj", + version="42", + ext_modules=[ + Extension( + "hello", sources=["hello.pyx"], + depends=[{str(dep_path)!r}] + ) + ], + ) + """ + ), + "hello.pyx": "", + "MANIFEST.in": "global-include *.h", + }, + } + + @pytest.mark.parametrize( + "dep_path", ("$tmp_path$/external/dir/file.h", "../external/dir/file.h") + ) + def test_external_path_in_extension_depends(self, monkeypatch, tmp_path, dep_path): + # Given a project with a "depends" targeting an external dir + files = self.files_for_external_path_in_extension_depends(tmp_path, dep_path) + jaraco.path.build(files, prefix=str(tmp_path)) + # When `sdist` runs, there should be no error + members = run_sdist(monkeypatch, tmp_path / "project") + # and the sdist should not contain the external file + for name in members: + assert "file.h" not in name + + +def run_sdist(monkeypatch, project): + """Given a project directory, run the sdist and return its contents""" + monkeypatch.chdir(project) + with quiet(): + run_setup("setup.py", ["sdist"]) + + archive = next((project / "dist").glob("*.tar.gz")) + with tarfile.open(str(archive)) as tar: + return set(tar.getnames()) + + +def test_sanity_check_setuptools_own_sdist(setuptools_sdist): + with tarfile.open(setuptools_sdist) as tar: + files = tar.getnames() + + # setuptools sdist should not include the .tox folder + tox_files = [name for name in files if ".tox" in name] + assert len(tox_files) == 0, f"not empty {tox_files}" diff --git a/videollama2/lib/python3.10/site-packages/setuptools/tests/test_wheel.py b/videollama2/lib/python3.10/site-packages/setuptools/tests/test_wheel.py new file mode 100644 index 0000000000000000000000000000000000000000..70165c608b60bc70a908a8b56e1f1105feeb4712 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/setuptools/tests/test_wheel.py @@ -0,0 +1,714 @@ +"""wheel tests""" + +from __future__ import annotations + +import contextlib +import glob +import inspect +import os +import pathlib +import shutil +import stat +import subprocess +import sys +import zipfile +from typing import Any + +import pytest +from jaraco import path +from packaging.tags import parse_tag +from packaging.utils import canonicalize_name + +from pkg_resources import PY_MAJOR, Distribution, PathMetadata +from setuptools.wheel import Wheel + +from .contexts import tempdir +from .textwrap import DALS + +from distutils.sysconfig import get_config_var +from distutils.util import get_platform + +WHEEL_INFO_TESTS = ( + ('invalid.whl', ValueError), + ( + 'simplewheel-2.0-1-py2.py3-none-any.whl', + { + 'project_name': 'simplewheel', + 'version': '2.0', + 'build': '1', + 'py_version': 'py2.py3', + 'abi': 'none', + 'platform': 'any', + }, + ), + ( + 'simple.dist-0.1-py2.py3-none-any.whl', + { + 'project_name': 'simple.dist', + 'version': '0.1', + 'build': None, + 'py_version': 'py2.py3', + 'abi': 'none', + 'platform': 'any', + }, + ), + ( + 'example_pkg_a-1-py3-none-any.whl', + { + 'project_name': 'example_pkg_a', + 'version': '1', + 'build': None, + 'py_version': 'py3', + 'abi': 'none', + 'platform': 'any', + }, + ), + ( + 'PyQt5-5.9-5.9.1-cp35.cp36.cp37-abi3-manylinux1_x86_64.whl', + { + 'project_name': 'PyQt5', + 'version': '5.9', + 'build': '5.9.1', + 'py_version': 'cp35.cp36.cp37', + 'abi': 'abi3', + 'platform': 'manylinux1_x86_64', + }, + ), +) + + +@pytest.mark.parametrize( + ('filename', 'info'), WHEEL_INFO_TESTS, ids=[t[0] for t in WHEEL_INFO_TESTS] +) +def test_wheel_info(filename, info): + if inspect.isclass(info): + with pytest.raises(info): + Wheel(filename) + return + w = Wheel(filename) + assert {k: getattr(w, k) for k in info.keys()} == info + + +@contextlib.contextmanager +def build_wheel(extra_file_defs=None, **kwargs): + file_defs = { + 'setup.py': ( + DALS( + """ + # -*- coding: utf-8 -*- + from setuptools import setup + import setuptools + setup(**%r) + """ + ) + % kwargs + ).encode('utf-8'), + } + if extra_file_defs: + file_defs.update(extra_file_defs) + with tempdir() as source_dir: + path.build(file_defs, source_dir) + subprocess.check_call( + (sys.executable, 'setup.py', '-q', 'bdist_wheel'), cwd=source_dir + ) + yield glob.glob(os.path.join(source_dir, 'dist', '*.whl'))[0] + + +def tree_set(root): + contents = set() + for dirpath, dirnames, filenames in os.walk(root): + for filename in filenames: + contents.add(os.path.join(os.path.relpath(dirpath, root), filename)) + return contents + + +def flatten_tree(tree): + """Flatten nested dicts and lists into a full list of paths""" + output = set() + for node, contents in tree.items(): + if isinstance(contents, dict): + contents = flatten_tree(contents) + + for elem in contents: + if isinstance(elem, dict): + output |= {os.path.join(node, val) for val in flatten_tree(elem)} + else: + output.add(os.path.join(node, elem)) + return output + + +def format_install_tree(tree): + return { + x.format( + py_version=PY_MAJOR, + platform=get_platform(), + shlib_ext=get_config_var('EXT_SUFFIX') or get_config_var('SO'), + ) + for x in tree + } + + +def _check_wheel_install( + filename, install_dir, install_tree_includes, project_name, version, requires_txt +): + w = Wheel(filename) + egg_path = os.path.join(install_dir, w.egg_name()) + w.install_as_egg(egg_path) + if install_tree_includes is not None: + install_tree = format_install_tree(install_tree_includes) + exp = tree_set(install_dir) + assert install_tree.issubset(exp), install_tree - exp + + metadata = PathMetadata(egg_path, os.path.join(egg_path, 'EGG-INFO')) + dist = Distribution.from_filename(egg_path, metadata=metadata) + assert dist.project_name == project_name + assert dist.version == version + if requires_txt is None: + assert not dist.has_metadata('requires.txt') + else: + # Order must match to ensure reproducibility. + assert requires_txt == dist.get_metadata('requires.txt').lstrip() + + +class Record: + def __init__(self, id, **kwargs): + self._id = id + self._fields = kwargs + + def __repr__(self) -> str: + return f'{self._id}(**{self._fields!r})' + + +# Using Any to avoid possible type union issues later in test +# making a TypedDict is not worth in a test and anonymous/inline TypedDict are experimental +# https://github.com/python/mypy/issues/9884 +WHEEL_INSTALL_TESTS: tuple[dict[str, Any], ...] = ( + dict( + id='basic', + file_defs={'foo': {'__init__.py': ''}}, + setup_kwargs=dict( + packages=['foo'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': ['PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt'], + 'foo': ['__init__.py'], + } + }), + ), + dict( + id='utf-8', + setup_kwargs=dict( + description='Description accentuée', + ), + ), + dict( + id='data', + file_defs={ + 'data.txt': DALS( + """ + Some data... + """ + ), + }, + setup_kwargs=dict( + data_files=[('data_dir', ['data.txt'])], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': ['PKG-INFO', 'RECORD', 'WHEEL', 'top_level.txt'], + 'data_dir': ['data.txt'], + } + }), + ), + dict( + id='extension', + file_defs={ + 'extension.c': DALS( + """ + #include "Python.h" + + #if PY_MAJOR_VERSION >= 3 + + static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + "extension", + NULL, + 0, + NULL, + NULL, + NULL, + NULL, + NULL + }; + + #define INITERROR return NULL + + PyMODINIT_FUNC PyInit_extension(void) + + #else + + #define INITERROR return + + void initextension(void) + + #endif + { + #if PY_MAJOR_VERSION >= 3 + PyObject *module = PyModule_Create(&moduledef); + #else + PyObject *module = Py_InitModule("extension", NULL); + #endif + if (module == NULL) + INITERROR; + #if PY_MAJOR_VERSION >= 3 + return module; + #endif + } + """ + ), + }, + setup_kwargs=dict( + ext_modules=[ + Record( + 'setuptools.Extension', name='extension', sources=['extension.c'] + ) + ], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}-{platform}.egg': [ + 'extension{shlib_ext}', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ] + }, + ] + }), + ), + dict( + id='header', + file_defs={ + 'header.h': DALS( + """ + """ + ), + }, + setup_kwargs=dict( + headers=['header.h'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'header.h', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ] + }, + ] + }), + ), + dict( + id='script', + file_defs={ + 'script.py': DALS( + """ + #/usr/bin/python + print('hello world!') + """ + ), + 'script.sh': DALS( + """ + #/bin/sh + echo 'hello world!' + """ + ), + }, + setup_kwargs=dict( + scripts=['script.py', 'script.sh'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + {'scripts': ['script.py', 'script.sh']}, + ] + } + }), + ), + dict( + id='requires1', + install_requires='foobar==2.0', + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'requires.txt', + 'top_level.txt', + ] + } + }), + requires_txt=DALS( + """ + foobar==2.0 + """ + ), + ), + dict( + id='requires2', + install_requires=f""" + bar + foo<=2.0; {sys.platform!r} in sys_platform + """, + requires_txt=DALS( + """ + bar + foo<=2.0 + """ + ), + ), + dict( + id='requires3', + install_requires=f""" + bar; {sys.platform!r} != sys_platform + """, + ), + dict( + id='requires4', + install_requires=""" + foo + """, + extras_require={ + 'extra': 'foobar>3', + }, + requires_txt=DALS( + """ + foo + + [extra] + foobar>3 + """ + ), + ), + dict( + id='requires5', + extras_require={ + 'extra': f'foobar; {sys.platform!r} != sys_platform', + }, + requires_txt=DALS( + """ + [extra] + """ + ), + ), + dict( + id='requires_ensure_order', + install_requires=""" + foo + bar + baz + qux + """, + extras_require={ + 'extra': """ + foobar>3 + barbaz>4 + bazqux>5 + quxzap>6 + """, + }, + requires_txt=DALS( + """ + foo + bar + baz + qux + + [extra] + foobar>3 + barbaz>4 + bazqux>5 + quxzap>6 + """ + ), + ), + dict( + id='namespace_package', + file_defs={ + 'foo': { + 'bar': {'__init__.py': ''}, + }, + }, + setup_kwargs=dict( + namespace_packages=['foo'], + packages=['foo.bar'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'foo-1.0-py{py_version}-nspkg.pth', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'namespace_packages.txt', + 'top_level.txt', + ] + }, + { + 'foo': [ + '__init__.py', + {'bar': ['__init__.py']}, + ] + }, + ] + }), + ), + dict( + id='empty_namespace_package', + file_defs={ + 'foobar': { + '__init__.py': ( + "__import__('pkg_resources').declare_namespace(__name__)" + ) + }, + }, + setup_kwargs=dict( + namespace_packages=['foobar'], + packages=['foobar'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': [ + 'foo-1.0-py{py_version}-nspkg.pth', + { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'namespace_packages.txt', + 'top_level.txt', + ] + }, + { + 'foobar': [ + '__init__.py', + ] + }, + ] + }), + ), + dict( + id='data_in_package', + file_defs={ + 'foo': { + '__init__.py': '', + 'data_dir': { + 'data.txt': DALS( + """ + Some data... + """ + ), + }, + } + }, + setup_kwargs=dict( + packages=['foo'], + data_files=[('foo/data_dir', ['foo/data_dir/data.txt'])], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + ], + 'foo': [ + '__init__.py', + { + 'data_dir': [ + 'data.txt', + ] + }, + ], + } + }), + ), +) + + +@pytest.mark.parametrize( + 'params', + WHEEL_INSTALL_TESTS, + ids=[params['id'] for params in WHEEL_INSTALL_TESTS], +) +def test_wheel_install(params): + project_name = params.get('name', 'foo') + version = params.get('version', '1.0') + install_requires = params.get('install_requires', []) + extras_require = params.get('extras_require', {}) + requires_txt = params.get('requires_txt', None) + install_tree = params.get('install_tree') + file_defs = params.get('file_defs', {}) + setup_kwargs = params.get('setup_kwargs', {}) + with ( + build_wheel( + name=project_name, + version=version, + install_requires=install_requires, + extras_require=extras_require, + extra_file_defs=file_defs, + **setup_kwargs, + ) as filename, + tempdir() as install_dir, + ): + _check_wheel_install( + filename, install_dir, install_tree, project_name, version, requires_txt + ) + + +def test_wheel_install_pep_503(): + project_name = 'Foo_Bar' # PEP 503 canonicalized name is "foo-bar" + version = '1.0' + with ( + build_wheel( + name=project_name, + version=version, + ) as filename, + tempdir() as install_dir, + ): + new_filename = filename.replace(project_name, canonicalize_name(project_name)) + shutil.move(filename, new_filename) + _check_wheel_install( + new_filename, + install_dir, + None, + canonicalize_name(project_name), + version, + None, + ) + + +def test_wheel_no_dist_dir(): + project_name = 'nodistinfo' + version = '1.0' + wheel_name = f'{project_name}-{version}-py2.py3-none-any.whl' + with tempdir() as source_dir: + wheel_path = os.path.join(source_dir, wheel_name) + # create an empty zip file + zipfile.ZipFile(wheel_path, 'w').close() + with tempdir() as install_dir: + with pytest.raises(ValueError): + _check_wheel_install( + wheel_path, install_dir, None, project_name, version, None + ) + + +def test_wheel_is_compatible(monkeypatch): + def sys_tags(): + return { + (t.interpreter, t.abi, t.platform) + for t in parse_tag('cp36-cp36m-manylinux1_x86_64') + } + + monkeypatch.setattr('setuptools.wheel._get_supported_tags', sys_tags) + assert Wheel('onnxruntime-0.1.2-cp36-cp36m-manylinux1_x86_64.whl').is_compatible() + + +def test_wheel_mode(): + @contextlib.contextmanager + def build_wheel(extra_file_defs=None, **kwargs): + file_defs = { + 'setup.py': ( + DALS( + """ + # -*- coding: utf-8 -*- + from setuptools import setup + import setuptools + setup(**%r) + """ + ) + % kwargs + ).encode('utf-8'), + } + if extra_file_defs: + file_defs.update(extra_file_defs) + with tempdir() as source_dir: + path.build(file_defs, source_dir) + runsh = pathlib.Path(source_dir) / "script.sh" + os.chmod(runsh, 0o777) + subprocess.check_call( + (sys.executable, 'setup.py', '-q', 'bdist_wheel'), cwd=source_dir + ) + yield glob.glob(os.path.join(source_dir, 'dist', '*.whl'))[0] + + params = dict( + id='script', + file_defs={ + 'script.py': DALS( + """ + #/usr/bin/python + print('hello world!') + """ + ), + 'script.sh': DALS( + """ + #/bin/sh + echo 'hello world!' + """ + ), + }, + setup_kwargs=dict( + scripts=['script.py', 'script.sh'], + ), + install_tree=flatten_tree({ + 'foo-1.0-py{py_version}.egg': { + 'EGG-INFO': [ + 'PKG-INFO', + 'RECORD', + 'WHEEL', + 'top_level.txt', + {'scripts': ['script.py', 'script.sh']}, + ] + } + }), + ) + + project_name = params.get('name', 'foo') + version = params.get('version', '1.0') + install_tree = params.get('install_tree') + file_defs = params.get('file_defs', {}) + setup_kwargs = params.get('setup_kwargs', {}) + + with ( + build_wheel( + name=project_name, + version=version, + install_requires=[], + extras_require={}, + extra_file_defs=file_defs, + **setup_kwargs, + ) as filename, + tempdir() as install_dir, + ): + _check_wheel_install( + filename, install_dir, install_tree, project_name, version, None + ) + w = Wheel(filename) + base = pathlib.Path(install_dir) / w.egg_name() + script_sh = base / "EGG-INFO" / "scripts" / "script.sh" + assert script_sh.exists() + if sys.platform != 'win32': + # Editable file mode has no effect on Windows + assert oct(stat.S_IMODE(script_sh.stat().st_mode)) == "0o777" diff --git a/videollama2/lib/python3.10/site-packages/setuptools/tests/text.py b/videollama2/lib/python3.10/site-packages/setuptools/tests/text.py new file mode 100644 index 0000000000000000000000000000000000000000..e05cc633ede9e5ce4f74b66a7bf76327c2000caa --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/setuptools/tests/text.py @@ -0,0 +1,4 @@ +class Filenames: + unicode = 'smörbröd.py' + latin_1 = unicode.encode('latin-1') + utf_8 = unicode.encode('utf-8') diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/CUDAPluggableAllocator.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/CUDAPluggableAllocator.h new file mode 100644 index 0000000000000000000000000000000000000000..8652ef0f2bfde8be21d2121f4a1cd551325462d9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/CUDAPluggableAllocator.h @@ -0,0 +1,183 @@ +#pragma once + +#include +#include +#include +#include + +#include + +#include + +namespace torch::cuda::CUDAPluggableAllocator { + +using MallocFuncType = void*(size_t, int, cudaStream_t); +using FreeFuncType = void(void*, size_t, int, cudaStream_t); + +// A CUDAPluggableAllocatorDeleterContext object is used as the `ctx` +// argument for DataPtr. We need context because a user can use +// multiple allocators in the same PyTorch program, and +// the allocators can have different free functions, such as: +// free, cudaFree, cudaFreeAsync, ncclMemFree etc. +struct TORCH_CUDA_CPP_API CUDAPluggableAllocatorDeleterContext { + explicit CUDAPluggableAllocatorDeleterContext( + std::function free_fn, + void* data, + size_t size, + int device, + cudaStream_t stream); + + void free(); + + private: + std::function free_fn_; + void* data_; + size_t size_; + int device_; + cudaStream_t stream_; +}; + +#if defined(TORCH_HIP_VERSION) +using streamType = c10::hip::HIPStream; +#else +using streamType = c10::cuda::CUDAStream; +#endif + +TORCH_CUDA_CPP_API std::shared_ptr< + c10::cuda::CUDACachingAllocator::CUDAAllocator> +getCurrentAllocator(); +TORCH_CUDA_CPP_API std::shared_ptr< + c10::cuda::CUDACachingAllocator::CUDAAllocator> +createCustomAllocator( + std::function alloc_fn, + std::function free_fn); +TORCH_CUDA_CPP_API void changeCurrentAllocator( + const std::shared_ptr& + allocator); + +struct _AllocationMetadata { + _AllocationMetadata(); + _AllocationMetadata( + size_t size, + c10::DeviceIndex device_idx, + cudaStream_t stream); + size_t size; + c10::DeviceIndex device_idx; + cudaStream_t stream; +}; + +struct TORCH_CUDA_CPP_API CUDAPluggableAllocator + : public c10::cuda::CUDACachingAllocator::CUDAAllocator { + CUDAPluggableAllocator( + std::function alloc_fn, + std::function free_fn); + + CUDAPluggableAllocator(CUDAPluggableAllocator& other); + CUDAPluggableAllocator& operator=(CUDAPluggableAllocator& other) = delete; + + void set_init_fn(std::function init_fn); + + void set_reset_fn(std::function reset_fn); + + void set_memory_fraction_fn( + std::function memory_fraction_fn); + + void set_base_alloc_fn(std::function base_alloc_fn); + + void set_record_stream_fn( + std::function record_stream_fn); + + void set_begin_allocate_to_pool( + std::function< + void(int, c10::cuda::MempoolId_t, std::function)> + capture_begin_fn); + + void set_end_allocate_to_pool_fn( + std::function capture_about_to_end_fn); + + void set_release_pool( + std::function capture_destroy_fn); + + void* malloc(size_t size, c10::DeviceIndex device, cudaStream_t stream); + + c10::DataPtr allocate(size_t size) override; + c10::DeleterFnPtr raw_deleter() const override; + + void* raw_alloc(size_t nbytes) override; + void* raw_alloc_with_stream(size_t nbytes, cudaStream_t stream) override; + void raw_delete(void* ptr) override; + void init(int device_count) override; + bool initialized() override; + void setMemoryFraction(double fraction, c10::DeviceIndex device) override; + void emptyCache() override; + void cacheInfo(c10::DeviceIndex device, size_t* largestBlock) override; + void* getBaseAllocation(void* ptr, size_t* size) override; + + void recordStream(const c10::DataPtr&, streamType stream) override; + + c10::CachingDeviceAllocator::DeviceStats getDeviceStats( + c10::DeviceIndex device) override; + void resetAccumulatedStats(c10::DeviceIndex device) override; + void resetPeakStats(c10::DeviceIndex device) override; + c10::cuda::CUDACachingAllocator::SnapshotInfo snapshot() override; + void beginAllocateToPool( + c10::DeviceIndex device, + c10::cuda::MempoolId_t mempool_id, + std::function) override; + void endAllocateToPool( + c10::DeviceIndex device, + c10::cuda::MempoolId_t mempool_id) override; + void releasePool(c10::DeviceIndex device, c10::cuda::MempoolId_t mempool_id) + override; + std::shared_ptr getIpcDevPtr(std::string handle) override; + c10::cuda::CUDACachingAllocator::ShareableHandle shareIpcHandle( + void*) override; + void recordHistory( + bool enabled, + c10::cuda::CUDACachingAllocator::CreateContextFn context_recorder, + size_t alloc_trace_max_entries, + c10::cuda::CUDACachingAllocator::RecordContext when) override; + void attachOutOfMemoryObserver( + c10::cuda::CUDACachingAllocator::OutOfMemoryObserver observer) override; + void attachAllocatorTraceTracker( + c10::cuda::CUDACachingAllocator::AllocatorTraceTracker tracker) override; + std::shared_ptr + getCheckpointState(c10::DeviceIndex device, at::cuda::MempoolId_t id) + override; + c10::cuda::CUDACachingAllocator::CheckpointDelta setCheckpointPoolState( + c10::DeviceIndex device, + std::shared_ptr pps) + override; + void enablePeerAccess(c10::DeviceIndex dev, c10::DeviceIndex dev_to_access) + override; + cudaError_t memcpyAsync( + void* dst, + int dstDevice, + const void* src, + int srcDevice, + size_t count, + cudaStream_t stream, + bool p2p_enabled) override; + std::string name() override; + void copy_data(void* dest, const void* src, std::size_t count) const final; + + protected: + std::function alloc_fn_; + std::function free_fn_; + std::function init_fn_; + std::function reset_fn_; + std::function memory_fraction_fn_; + std::function base_alloc_fn_; + std::function record_stream_fn_; + std::function< + void(int, c10::cuda::MempoolId_t, std::function)> + begin_allocate_to_pool_fn_; + std::function end_allocate_to_pool_fn_; + std::function relase_pool_fn_; + std::mutex allocator_mutex_; + // We do the bookeeping here in order to simplify custom allocators + std::unordered_map allocation_metadata_; + + bool initialized_ = false; +}; +} // namespace torch::cuda::CUDAPluggableAllocator diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Event.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Event.h new file mode 100644 index 0000000000000000000000000000000000000000..5c4d95b285997fa4ddfce57423e0b264dde5898a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Event.h @@ -0,0 +1,18 @@ +#ifndef THCP_EVENT_INC +#define THCP_EVENT_INC + +#include +#include + +struct THCPEvent { + PyObject_HEAD at::cuda::CUDAEvent cuda_event; +}; +extern PyObject* THCPEventClass; + +void THCPEvent_init(PyObject* module); + +inline bool THCPEvent_Check(PyObject* obj) { + return THCPEventClass && PyObject_IsInstance(obj, THCPEventClass); +} + +#endif // THCP_EVENT_INC diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/GdsFile.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/GdsFile.h new file mode 100644 index 0000000000000000000000000000000000000000..0edf927393db75c52c980de7fe73963dc237819b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/GdsFile.h @@ -0,0 +1,7 @@ +#ifndef THCP_GDSFILE_INC +#define THCP_GDSFILE_INC + +#include + +void initGdsBindings(PyObject* module); +#endif // THCP_GDSFILE_INC diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Module.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Module.h new file mode 100644 index 0000000000000000000000000000000000000000..0c89e4bc65f2591c074083064e64eca421ee5760 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Module.h @@ -0,0 +1,11 @@ +#ifndef THCP_CUDA_MODULE_INC +#define THCP_CUDA_MODULE_INC + +PyObject* THCPModule_getDevice_wrap(PyObject* self); +PyObject* THCPModule_setDevice_wrap(PyObject* self, PyObject* arg); +PyObject* THCPModule_getDeviceName_wrap(PyObject* self, PyObject* arg); +PyObject* THCPModule_getDriverVersion(PyObject* self); +PyObject* THCPModule_isDriverSufficient(PyObject* self); +PyObject* THCPModule_getCurrentBlasHandle_wrap(PyObject* self); + +#endif diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Stream.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Stream.h new file mode 100644 index 0000000000000000000000000000000000000000..9b7197d74390c142744ec6d64df967b6c7f25903 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/Stream.h @@ -0,0 +1,20 @@ +#ifndef THCP_STREAM_INC +#define THCP_STREAM_INC + +#include +#include +#include + +// NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) +struct THCPStream : THPStream { + at::cuda::CUDAStream cuda_stream; +}; +extern PyObject* THCPStreamClass; + +void THCPStream_init(PyObject* module); + +inline bool THCPStream_Check(PyObject* obj) { + return THCPStreamClass && PyObject_IsInstance(obj, THCPStreamClass); +} + +#endif // THCP_STREAM_INC diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/THCP.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/THCP.h new file mode 100644 index 0000000000000000000000000000000000000000..697a66dc3ee91a22ae2503852db04dbba2fc74d4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/THCP.h @@ -0,0 +1,10 @@ +#ifndef THCP_H +#define THCP_H + +#include +#include +#include +#include +#include + +#endif diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/comm.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/comm.h new file mode 100644 index 0000000000000000000000000000000000000000..860629bcf2e9a3ec826d8be5b1c6c1364019a4c0 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/comm.h @@ -0,0 +1,52 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include + +namespace torch::cuda { + +using tensor_list2d = std::vector>; + +TORCH_CUDA_CU_API std::vector& broadcast_out( + const at::Tensor& tensor, + std::vector& out_tensors); +TORCH_CUDA_CU_API std::vector broadcast( + const at::Tensor& tensor, + at::IntArrayRef devices); +TORCH_CUDA_CU_API tensor_list2d broadcast_coalesced( + at::TensorList tensors, + at::IntArrayRef devices, + size_t buffer_size); + +TORCH_CUDA_CU_API std::vector& scatter_out( + const at::Tensor& tensor, + std::vector& out_tensors, + int64_t dim = 0, + const std::optional>>& + streams = std::nullopt); + +TORCH_CUDA_CU_API std::vector scatter( + const at::Tensor& tensor, + at::IntArrayRef devices, + const std::optional>& chunk_sizes = std::nullopt, + int64_t dim = 0, + const std::optional>>& + streams = std::nullopt); + +TORCH_CUDA_CU_API at::Tensor& gather_out( + at::TensorList tensors, + at::Tensor& out_tensor, + int64_t dim); + +TORCH_CUDA_CU_API at::Tensor gather( + at::TensorList tensors, + int64_t dim, + std::optional destination_index); + +} // namespace torch::cuda diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/device_set.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/device_set.h new file mode 100644 index 0000000000000000000000000000000000000000..c533dae3baad36a42e0f97f55b9eb7a747191dc3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/device_set.h @@ -0,0 +1,11 @@ +#pragma once + +#include +#include +#include + +namespace torch { + +using device_set = std::bitset; + +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/memory_snapshot.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/memory_snapshot.h new file mode 100644 index 0000000000000000000000000000000000000000..fe5699af416012cbd8a758939fa55f452fc953a4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/memory_snapshot.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch::cuda { + +// C++-only versions of these, for python use +// those defined in cuda/Module.cpp which also record python state. +TORCH_CUDA_CU_API void _record_memory_history( + bool enabled, + bool record_context = true, + int64_t trace_alloc_max_entries = 1, + bool trace_alloc_record_context = false, + bool record_cpp_context = false); + +TORCH_CUDA_CU_API void _record_memory_history( + std::optional enabled = "all", + std::optional context = "all", + const std::string& stacks = "all", + size_t max_entries = SIZE_MAX); + +TORCH_CUDA_CU_API std::string _memory_snapshot_pickled(); + +} // namespace torch::cuda diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/nccl.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/nccl.h new file mode 100644 index 0000000000000000000000000000000000000000..1415cccc25ab947a2f2613253e3646525f0ec3b2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/nccl.h @@ -0,0 +1,219 @@ +#pragma once + +#include +#include + +#include +#include +#include + +// NCCL BFloat16 is enabled only for CUDA 11+ and NCCL versions 2.10+, or for +// HIP 3.1+ +#if defined(__CUDA_BF16_TYPES_EXIST__) +#define HAS_NCCL_BF16_DATATYPE \ + ((NCCL_MAJOR > 2) || (NCCL_MAJOR == 2) && (NCCL_MINOR >= 10)) +#elif defined(USE_ROCM) && (TORCH_HIP_VERSION >= 301) +#define HAS_NCCL_BF16_DATATYPE 1 +#else +#define HAS_NCCL_BF16_DATATYPE 0 +#endif + +namespace torch::cuda::nccl { + +/* The following are copied from and redefined in torch::cuda::nccl + * namespace */ +/* pytorch should only use the following definition within pytorch scope */ + +/* Opaque handle to communicator to ncclComm*, this will reinterpret as ncclComm + * in nccl.cpp */ +typedef void* ncclComm_t; + +/** redefine nccl unique ID in torch scope. this should be identical to native + * nccl impp. */ +#define NCCL_UNIQUE_ID_BYTES 128 +// NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) +typedef struct { + char internal[NCCL_UNIQUE_ID_BYTES]; +} ncclUniqueId; + +/* Error type */ +enum class ncclResult { + Success = 0, + UnhandledCudaError = 1, + SystemError = 2, + InternalError = 3, + InvalidArgument = 4, + InvalidUsage = 5, + RemoteError = 6, + InProgress = 7, + NumResults = 8 +}; + +/* Reduction operation selector */ +enum class ncclRedOp { Sum = 0, Prod = 1, Max = 2, Min = 3, NumOps = 4 }; + +/* Data types */ +enum class ncclDataType { + Int8 = 0, + Char = 0, + Uint8 = 1, + Int32 = 2, + Int = 2, + Uint32 = 3, + Int64 = 4, + Uint64 = 5, + Float16 = 6, + Half = 6, + Float32 = 7, + Float = 7, + Float64 = 8, + Double = 8, + Bfloat16 = 9, + NumTypes = 10 +}; + +// RAII helper class to manage NCCL group API and CUDA free mutex. +// The destructor is allowed to throw since this helper class only +// manages group and lock lifetimes. +struct AutoNcclGroup { + AutoNcclGroup(); + AutoNcclGroup(ncclComm_t comm, bool comm_nonblocking); + ~AutoNcclGroup() noexcept(false); + ncclComm_t comm_; + bool comm_nonblocking_; +}; + +// NOTE: this is exposed only so that python_nccl.cpp can some of these helpers. +// Don't use them outside of these files. +namespace detail { + +TORCH_CUDA_CPP_API void throw_nccl_error(ncclResult status); + +inline void NCCL_CHECK(ncclResult status) { + if (status != ncclResult::Success) { + throw_nccl_error(status); + } +} + +TORCH_CUDA_CPP_API at::ArrayRef get_communicators( + at::TensorList inputs); +TORCH_CUDA_CPP_API void check_inputs( + at::TensorList inputs, + at::TensorList outputs, + int input_multiplier, + int output_multiplier); +TORCH_CUDA_CPP_API void check_inputs( + at::TensorList inputs, + const at::Tensor& output, + int root, + int input_multiplier, + int output_multiplier); + +} // namespace detail + +using comm_list = std::vector; +using stream_list = std::vector>; + +TORCH_CUDA_CPP_API std::uint64_t version(); +TORCH_CUDA_CPP_API const char* version_suffix(); + +bool is_available(at::TensorList tensors); + +TORCH_CUDA_CPP_API void get_unique_id(ncclUniqueId& id); +TORCH_CUDA_CPP_API ncclComm_t +comm_init_rank(int nranks, const ncclUniqueId& comm_id, int rank); +TORCH_CUDA_CPP_API void comm_destroy(ncclComm_t comm); + +TORCH_CUDA_CPP_API void broadcast( + at::TensorList tensors, + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +size_t get_max_count(); + +TORCH_CUDA_CPP_API void reduce( + const std::vector& inputs, + at::Tensor& output, + int32_t root = 0, + int32_t op = static_cast(ncclRedOp::Sum), + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +TORCH_CUDA_CPP_API void reduce( + std::vector& inputs, + int32_t root = 0, + int32_t op = static_cast(ncclRedOp::Sum), + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +TORCH_CUDA_CPP_API void all_reduce( + const std::vector& inputs, + std::vector& outputs, + int32_t op = static_cast(ncclRedOp::Sum), + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +TORCH_CUDA_CPP_API void reduce_scatter( + const std::vector& inputs, + std::vector& outputs, + int32_t op = static_cast(ncclRedOp::Sum), + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +TORCH_CUDA_CPP_API void scatter( + const std::vector& inputs, + at::Tensor& outputs, + ncclComm_t comm, + at::cuda::CUDAStream& stream, + int32_t root = 0); + +TORCH_CUDA_CPP_API void all_gather( + const std::vector& inputs, + std::vector& outputs, + const stream_list& streams = {}, + const comm_list& user_comms = {}); + +TORCH_CUDA_CPP_API void gather( + const at::Tensor& inputs, + std::vector& outputs, + ncclComm_t comm, + at::cuda::CUDAStream& stream, + int32_t root = 0); + +TORCH_CUDA_CPP_API void all2all_single_equal_split( + at::Tensor& input, + at::Tensor& output, + int size, + ncclComm_t comm, + at::cuda::CUDAStream& stream); + +TORCH_CUDA_CPP_API void all2all_single_unequal_split( + void* sendbuff, + const size_t* sendcounts, + const size_t* senddispls, + void* recvbuff, + const size_t* recvcounts, + const size_t* recvdispls, + size_t size, + c10::ScalarType type, + ncclComm_t comm, + at::cuda::CUDAStream& stream); + +TORCH_CUDA_CPP_API void all2all( + std::vector& outputTensors, + std::vector& inputTensors, + ncclComm_t _comm, + at::cuda::CUDAStream& stream); + +TORCH_CUDA_CPP_API void send( + const at::Tensor& input, + ncclComm_t comm, + at::cuda::CUDAStream stream, + int dst); + +TORCH_CUDA_CPP_API void recv( + at::Tensor& output, + ncclComm_t comm, + at::cuda::CUDAStream stream, + int src); +} // namespace torch::cuda::nccl diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_comm.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_comm.h new file mode 100644 index 0000000000000000000000000000000000000000..e87ae053fbe7fc59d1713cf8b148dfe52cbd01dc --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_comm.h @@ -0,0 +1,7 @@ +#pragma once + +namespace torch::cuda::python { + +void initCommMethods(PyObject* module); + +} // namespace torch::cuda::python diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_nccl.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_nccl.h new file mode 100644 index 0000000000000000000000000000000000000000..ebaa666a22d2cff60e2ef2a2701003d0ca61a8e4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/cuda/python_nccl.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +PyObject* THCPModule_nccl_version(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_version_suffix(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_unique_id(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_init_rank(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_reduce(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_all_reduce(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_broadcast(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_all_gather(PyObject* self, PyObject* args); +PyObject* THCPModule_nccl_reduce_scatter(PyObject* self, PyObject* args); diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/jit_log.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/jit_log.h new file mode 100644 index 0000000000000000000000000000000000000000..6282e53f4bff1773e7f8a8249e444c8e5da45d87 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/jit_log.h @@ -0,0 +1,126 @@ +#pragma once +#include +#include +#include +#include +#include + +// `TorchScript` offers a simple logging facility that can enabled by setting an +// environment variable `PYTORCH_JIT_LOG_LEVEL`. + +// Logging is enabled on a per file basis. To enable logging in +// `dead_code_elimination.cpp`, `PYTORCH_JIT_LOG_LEVEL` should be +// set to `dead_code_elimination.cpp` or, simply, to `dead_code_elimination` +// (i.e. `PYTORCH_JIT_LOG_LEVEL=dead_code_elimination`). + +// Multiple files can be logged by separating each file name with a colon `:` as +// in the following example, +// `PYTORCH_JIT_LOG_LEVEL=dead_code_elimination:guard_elimination` + +// There are 3 logging levels available for your use ordered by the detail level +// from lowest to highest. + +// * `GRAPH_DUMP` should be used for printing entire graphs after optimization +// passes +// * `GRAPH_UPDATE` should be used for reporting graph transformations (i.e. +// node deletion, constant folding, etc) +// * `GRAPH_DEBUG` should be used for providing information useful for debugging +// the internals of a particular optimization pass or analysis + +// The default logging level is `GRAPH_DUMP` meaning that only `GRAPH_DUMP` +// statements will be enabled when one specifies a file(s) in +// `PYTORCH_JIT_LOG_LEVEL`. + +// `GRAPH_UPDATE` can be enabled by prefixing a file name with an `>` as in +// `>alias_analysis`. +// `GRAPH_DEBUG` can be enabled by prefixing a file name with an `>>` as in +// `>>alias_analysis`. +// `>>>` is also valid and **currently** is equivalent to `GRAPH_DEBUG` as there +// is no logging level that is higher than `GRAPH_DEBUG`. + +namespace torch::jit { + +struct Node; +struct Graph; + +enum class JitLoggingLevels { + GRAPH_DUMP = 0, + GRAPH_UPDATE, + GRAPH_DEBUG, +}; + +TORCH_API std::string get_jit_logging_levels(); + +TORCH_API void set_jit_logging_levels(std::string level); + +TORCH_API void set_jit_logging_output_stream(std::ostream& out_stream); + +TORCH_API std::ostream& get_jit_logging_output_stream(); + +TORCH_API std::string getHeader(const Node* node); + +TORCH_API std::string log_function(const std::shared_ptr& graph); + +TORCH_API ::torch::jit::JitLoggingLevels jit_log_level(); + +// Prefix every line in a multiline string \p IN_STR with \p PREFIX. +TORCH_API std::string jit_log_prefix( + const std::string& prefix, + const std::string& in_str); + +TORCH_API std::string jit_log_prefix( + ::torch::jit::JitLoggingLevels level, + const char* fn, + int l, + const std::string& in_str); + +TORCH_API bool is_enabled( + const char* cfname, + ::torch::jit::JitLoggingLevels level); + +TORCH_API std::ostream& operator<<( + std::ostream& out, + ::torch::jit::JitLoggingLevels level); + +#define JIT_LOG(level, ...) \ + if (is_enabled(__FILE__, level)) { \ + ::torch::jit::get_jit_logging_output_stream() \ + << ::torch::jit::jit_log_prefix( \ + level, __FILE__, __LINE__, ::c10::str(__VA_ARGS__)); \ + } + +// tries to reconstruct original python source +#define SOURCE_DUMP(MSG, G) \ + JIT_LOG( \ + ::torch::jit::JitLoggingLevels::GRAPH_DUMP, \ + MSG, \ + "\n", \ + ::torch::jit::log_function(G)); +// use GRAPH_DUMP for dumping graphs after optimization passes +#define GRAPH_DUMP(MSG, G) \ + JIT_LOG( \ + ::torch::jit::JitLoggingLevels::GRAPH_DUMP, MSG, "\n", (G)->toString()); +// use GRAPH_UPDATE for reporting graph transformations (i.e. node deletion, +// constant folding, CSE) +#define GRAPH_UPDATE(...) \ + JIT_LOG(::torch::jit::JitLoggingLevels::GRAPH_UPDATE, __VA_ARGS__); +// use GRAPH_DEBUG to provide information useful for debugging a particular opt +// pass +#define GRAPH_DEBUG(...) \ + JIT_LOG(::torch::jit::JitLoggingLevels::GRAPH_DEBUG, __VA_ARGS__); +// use GRAPH_EXPORT to export a graph so that the IR can be loaded by a script +#define GRAPH_EXPORT(MSG, G) \ + JIT_LOG( \ + ::torch::jit::JitLoggingLevels::GRAPH_DEBUG, \ + MSG, \ + "\n\n", \ + (G)->toString(), \ + ""); + +#define GRAPH_DUMP_ENABLED \ + (is_enabled(__FILE__, ::torch::jit::JitLoggingLevels::GRAPH_DUMP)) +#define GRAPH_UPDATE_ENABLED \ + (is_enabled(__FILE__, ::torch::jit::JitLoggingLevels::GRAPH_UPDATE)) +#define GRAPH_DEBUG_ENABLED \ + (is_enabled(__FILE__, ::torch::jit::JitLoggingLevels::GRAPH_DEBUG)) +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/jit_opt_limit.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/jit_opt_limit.h new file mode 100644 index 0000000000000000000000000000000000000000..c013431a19cd3e3a6773f4b36dc6627ddc3d21a7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/jit_opt_limit.h @@ -0,0 +1,37 @@ +#pragma once +#include +#include +#include + +// `TorchScript` offers a simple optimization limit checker +// that can be configured through environment variable `PYTORCH_JIT_OPT_LIMIT`. +// The purpose is to limit how many optimization you can make per pass. +// This is useful for debugging any passes. + +// Opt limit checker is enabled on a per file basis (hence per pass). For +// example, in `constant_propagation.cpp`, `PYTORCH_JIT_OPT_LIMIT` should be set +// to `constant_propagation=` or, simply, to +// `constant_propagation=` where is the number of +// optimizations you want to make for the pass. (i.e. +// `PYTORCH_JIT_OPT_LIMIT="constant_propagation="`). + +// Multiple files can be configured by separating each file name with a colon +// `:` as in the following example, +// `PYTORCH_JIT_OPT_LIMIT="constant_propagation=:dead_code_elimination="` + +// You can call opt limiter by calling JIT_OPT_ALLOWED. It will return true if +// we haven't reached the optimization limit yet. Otherwise, it will return +// false. Typical usage: + +// if (!JIT_OPT_ALLOWED) { +// GRAPH_DUMP(...); //supplied from jit_log +// return; +// } + +namespace torch::jit { + +TORCH_API bool opt_limit(const char* pass_name); + +#define JIT_OPT_ALLOWED opt_limit(__FILE__) + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/add_if_then_else.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/add_if_then_else.h new file mode 100644 index 0000000000000000000000000000000000000000..6495e1eaed5838bc5ae742739195e4ae1ca47919 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/add_if_then_else.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace torch::jit { + +TORCH_API bool AddIfThenElseOp(std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/canonicalize.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/canonicalize.h new file mode 100644 index 0000000000000000000000000000000000000000..46d941aabab22a47b5b4eb7c145789c1ee503426 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/canonicalize.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace torch::jit { + +TORCH_API std::shared_ptr Canonicalize( + const std::shared_ptr& graph, + bool keep_unique_names = true); + +TORCH_API void CanonicalizeOutputs(std::shared_ptr& graph); + +TORCH_API std::optional firstOrLastUse(Value* v, bool find_first); + +TORCH_API bool isBeforeOrAfter( + const Use& a, + const Use& b, + bool checking_before); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/canonicalize_graph_fuser_ops.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/canonicalize_graph_fuser_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..6e95cc199d2b261e04bdcd52d4a95ffdaceb4a01 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/canonicalize_graph_fuser_ops.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void CanonicalizeOps(const std::shared_ptr& graph); + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/check_strict_fusion.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/check_strict_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..a2c2280d5d8d147dd05ccc19b292faf66fa6f369 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/check_strict_fusion.h @@ -0,0 +1,10 @@ + +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void CheckStrictFusion(std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/concat_opt.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/concat_opt.h new file mode 100644 index 0000000000000000000000000000000000000000..040ade790be6b0ed04c6e13d641d22cee7be1730 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/concat_opt.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace torch::jit { + +// Eliminates common inputs among `aten::cat` ops. +TORCH_API bool EliminateConcatCommonInputs(const std::shared_ptr& graph); + +// Expands `aten::cat` ops into `aten::copy` ops and eliminates redudancies +// in the buffers used for concatenation if possible. +TORCH_API void ExpandConcatAndEliminateRedundancy( + const std::shared_ptr& graph); + +TORCH_API bool CombineConcats(const std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_propagation.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_propagation.h new file mode 100644 index 0000000000000000000000000000000000000000..858da81458ba9edf61437ed3c89915307c51d9bc --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_propagation.h @@ -0,0 +1,30 @@ +#pragma once + +#include + +namespace torch::jit { + +// Runs constant propagation on all objects unless ignore_custom_classes is +// specified as true, in which case user defined classes are skipped. This is +// useful to prevent early fusion of packing operations, which end up lowering +// away information about their constructors (e.g. packed::linear_clamp_prepack +// and prepacked::conv2d_clamp_prepack) +// Returns True if the pass made a change to the graph +TORCH_API bool ConstantPropagation( + std::shared_ptr& graph, + bool ignore_custom_classes = false); + +// runs constant propagation only on ops that have non-aliasing inputs & outputs +// Returns True if the pass made a change to the graph +TORCH_API bool ConstantPropagationImmutableTypes(std::shared_ptr& graph); + +// Runs the node if its inputs are constants. Callers of this function must +// make their own determination if constant prop is appropriate - for example +// non-deterministic ops or ops with side effects. If ignore_custom_classes is +// specified, nodes that output user defined classes are not run. +TORCH_API std::optional runNodeIfInputsAreConstant( + const Node* node, + bool ignore_custom_classes = false, + AliasDb* db = nullptr); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_functional_graphs.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_functional_graphs.h new file mode 100644 index 0000000000000000000000000000000000000000..49a9ae52378cb2574dd55c9bf9040760b28c5ca5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_functional_graphs.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +namespace torch::jit { + +TORCH_API void CreateFunctionalGraphs(const std::shared_ptr& graph); + +TORCH_API void InlineFunctionalGraphs(const std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/decompose_ops.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/decompose_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..a1a20d5e1e714e707242012adc8e5c04470c2aed --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/decompose_ops.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void DecomposeOps(std::shared_ptr& graph); + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/erase_number_types.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/erase_number_types.h new file mode 100644 index 0000000000000000000000000000000000000000..847b5e60c95efb904fa8b6bf3bf54ea394f02927 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/erase_number_types.h @@ -0,0 +1,21 @@ +#pragma once + +#include + +namespace torch::jit { + +// Erase NumberType information. This is necessary for and only used in +// exporting to ONNX. This pass ensures that no remaining Values have +// NumberType types, replacing them with tensors. +// The following things are done to erase NumberType info: +// - NumberType outputs are changed to DynamicType. +// - prim::Constant nodes which are numbers get changed into 0-dim tensors of +// the corresponding type +// - prim::TensorToNum, aten::Float, aten::Int and prim::NumToTensor nodes +// are erased. +// +// The pass assumes that DCE will be called sometime after. +TORCH_API void EraseNumberTypes(const std::shared_ptr& graph); +TORCH_API void EraseNumberTypesOnBlock(Block* block); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fixup_trace_scope_blocks.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fixup_trace_scope_blocks.h new file mode 100644 index 0000000000000000000000000000000000000000..8061e9e78005e77e73377cf2481c531ee1082748 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fixup_trace_scope_blocks.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include + +namespace torch::jit { + +// Directly after tracing, we have an ill-formed graph with blocks inserted. +// Example: +// +// graph(%self : ClassType, +// %input.1 : Float(3, 4)): +// %1 : ClassType = prim::GetAttr[name="relu1"](%self) +// %2 : ClassType = prim::GetAttr[name="relu2"](%self) +// %3 : ClassType = prim::GetAttr[name="rrr"](%2) +// = prim::TracedModuleForward[scope="__module.relu1"]() +// block0(): +// %input : Float(3, 4) = aten::relu(%input.1), +// -> () +// = prim::TracedModuleForward[scope="__module.relu2"](), +// block0(): +// = prim::TracedModuleForward[scope="__module.relu2.rrr"](), +// block0(): +// %6 : Float(3, 4) = aten::relu(%input), +// -> () +// -> () +// return (%6) +// +// In this pass, we: +// 1) Lift Value defs to as high of a scope as needed to ensure that +// they dominate all their uses. For example, `input` in the above +// graph needs to be lifted to the top-level block so that its use +// in the second `relu` operator is dominated. +// 2) Lambda lift the blocks. This ensures that all values used within +// each scope have their defs captured. +// 3) Convert the scope blocks into methods on their respective Modules, +// and convert TracedModuleForward nodes to CallMethod nodes into those +// methods. +// +// Then, we'll have a well-formed graph with proper method calls. +TORCH_API void FixupTraceScopeBlocks( + std::shared_ptr& graph, + Module* self); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_ops_to_mkldnn.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_ops_to_mkldnn.h new file mode 100644 index 0000000000000000000000000000000000000000..adbd8f357f1e55fc5dafd890e7357ded6c1c2071 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_ops_to_mkldnn.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +namespace torch::jit { + +// Converts operators & their parameters to mkldnn if it is profitable +// Currently encompassing Conv2d and Conv3d, and Linear +// Op must be in float32 and mkldnn must be built +// This pass only works on frozen graph +TORCH_API void ConvertFrozenOpsToMKLDNN(std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_grad_of.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_grad_of.h new file mode 100644 index 0000000000000000000000000000000000000000..528220875c08f66a403c623577c9423a76dcd1f8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_grad_of.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +namespace torch::jit { + +// This pass removes 'grad_of' nodes, replacing them with conditionals of +// the form: +// if any_defined(inputs): +// outputs = +// else: +// outputs = undefineds +TORCH_API void LowerGradOf(Graph& g); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_graph.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..48308d122f6e0a26d395d1c66337ef616ffa896e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_graph.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace torch::jit { + +using ModulePtr = c10::intrusive_ptr; + +// Given a graph with of a method which first argument is %self, lower it to a +// graph where all attributes accesses are replaced with explicit inputs of the +// graph (rather than results of prim::GetAttr executed on %self). +// +// Returns a tuple (graph, parameters) where the last module.parameters.size() +// inputs to the graph are the trainable parameters used in this method. The +// remaining inputs are the true inputs to the function. +TORCH_API std::pair, std::vector> LowerGraph( + Graph& graph, + const ModulePtr& self); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mkldnn_rewrite.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mkldnn_rewrite.h new file mode 100644 index 0000000000000000000000000000000000000000..b51f29f0de714c56f71bd0cc4ff70b873bd11bc1 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mkldnn_rewrite.h @@ -0,0 +1,32 @@ +#pragma once + +#include +#include +#include +#include + +#if AT_MKLDNN_ENABLED() + +#include + +#endif // AT_MKLDNN_ENABLED() + +namespace torch::jit { + +#if AT_MKLDNN_ENABLED() + +namespace mkldnn { + +const static std::map> + fusion_rewrite_map = { + {"none", {}}, + {"relu", {}}, +}; + +} // namespace mkldnn + +#endif // AT_MKLDNN_ENABLED() + +void FuseConvWithEltwise(std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/normalize_ops.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/normalize_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..885076584427546e6cd92525fb9dc3195ac1ed8e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/normalize_ops.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +namespace torch::jit { + +// This pass converts aten ops to a normalized form. It is +// run immediately after IR generation in both the tracer and compiler, +// so downstream consumers of the IR do not need handle ops in their +// pre-normalized form. +// Currently only handles normalization of op aliases. +TORCH_API void NormalizeOps(const std::shared_ptr& graph); + +const std::unordered_map& getOperatorAliasMap(); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/pass_manager.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/pass_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..efb19de59b5306ad09d096c8ee332204865c59e9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/pass_manager.h @@ -0,0 +1,134 @@ +#pragma once + +#include + +/* `getCustomPrePasses()` returns a vector of passes that will be executed + * after differentiation but before any fusion. This is the de-facto location + * for compiler backends to insert passes. + * + * `getCustomPostPasses()` returns a vector of passes that will be + * executed after differentiation and after fusion (if any). This is the + * location for fusion cleanup passes if they are needed. + * + * Static registration of a pass can be done by creating a global + * `Register{Pre,Post}Pass r(Pass)` variable in a compilation unit. + * + * pass_manager.h uses a Meyer's singleton to store a vector of `Pass`es, which + * modify the IR graph in place. + */ + +namespace torch::jit { + +// A pass modifies a Graph in place. +using GraphPass = std::function&)>; + +// Since Passes are std::functions, we associate a UUID to each pass, this way +// if we want to deregister a pass, we have something to reference it by. +using GraphPassNameType = unsigned int; + +// Graph pass entries have a name associated with them +using GraphPassEntry = std::pair; + +// Return currently registered passes. Passes are stored in a static vector +TORCH_API std::vector>& +getCustomPostPasses(); +TORCH_API std::vector>& +getCustomPrePasses(); + +TORCH_API GraphPassNameType registerPostPass(GraphPass p); +TORCH_API GraphPassNameType registerPrePass(GraphPass p); + +// Look up pass by name passed in, remove it from registered passes +TORCH_API void clearPostPass(GraphPassNameType p); +TORCH_API void clearPrePass(GraphPassNameType p); + +// Remove all passes +TORCH_API void clearAllPostPasses(); +TORCH_API void clearAllPrePasses(); + +// LEGACY CALL +struct TORCH_API RegisterPostPass { + RegisterPostPass(GraphPass p); +}; + +using RegisterPass = RegisterPostPass; + +/* + * PassManager is a wrapper on the register/clear PostPass functions above. It + * will register the pass provided in "registerPass" and will hold on to its + * associated name that way clearPass can be later called and will delete the + * pass used to register when called. + * + * PassManager is templated because we want static variables based on a + * particular GraphPass. When deriving from PassManager, you should send as the + * template parameter your derived class as you would for the curiously + * recurring template pattern. This template parameter isn't actually used and + * is simply done to prevent static members from being shared across derived + * types. + */ +template +struct C10_EXPORT PassManager { + private: + // We want this class to be abstract because it's + virtual void abstract() = 0; + + protected: + /* + * isRegistered() will return if a pass has been registered + * isRegistered(true) will change the value of the internal static bool + * + * There's an internal static bool to this function to keep track of the + * state, this is so when functions are derived from this class, they don't + * have to worry about initializing the static members. + */ + static bool isRegistered(bool flip_bit = false) { + static bool val = false; + if (flip_bit) + val = !val; + return val; + } + + /* + * name() will return the name of the registered pass + * name(pass_name, true) will set the name of the pass + * Similarly to isRegistered we use an internal static variable to hold the + * name. + */ + static GraphPassNameType passID( + GraphPassNameType PassID = 0, + bool set = false) { + static GraphPassNameType pass_id = 0; + if (set) + pass_id = PassID; + return pass_id; + } + + public: + // registerPass(pass) will register the pass provided and set the + // name/isRegistered functions appropriately, it returns a bool value + // indicating whether the given pass is already registered previously. + static bool registerPass(GraphPass p) { + if (!isRegistered()) { + // If we don't already have a registered pass, register pass + // hold on to its name, change isRegistered to true + passID(registerPostPass(std::move(p)), true); + isRegistered(true); + return false; + } + return true; + } + + // Calls ClearPostPass(passID()) + static void clearPass() { + // If the pass is registered, clear it and change isRegistered to false. + if (isRegistered()) { + clearPostPass(passID()); + isRegistered(true); + } + } + + // clang-tidy requires virtual destructor; + virtual ~PassManager() = default; +}; + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_alias_sensitive.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_alias_sensitive.h new file mode 100644 index 0000000000000000000000000000000000000000..d98b8ac58a1264218b08e93a454e9748279c086b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_alias_sensitive.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +namespace torch::jit { + +// Peephole Optimizes alias sensitive peepholes +// Currently this is invoked as part of PeepholeOptimize +// return true if graph is modified +// Optimizes on TensorType if shape_peepholes is true +TORCH_API bool PeepholeOptimizeAliasSensitive( + const std::shared_ptr& graph, + bool shape_peepholes); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/refine_tuple_types.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/refine_tuple_types.h new file mode 100644 index 0000000000000000000000000000000000000000..49b8750b72ce8591deca5617654c91ab61d30cb3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/refine_tuple_types.h @@ -0,0 +1,10 @@ +#pragma once + +#include + +namespace torch::jit { + +// updates the types of tuples according to the type of their current inputs. +TORCH_API void RefineTupleTypes(std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_expands.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_expands.h new file mode 100644 index 0000000000000000000000000000000000000000..483649d0e918c00cbd47b262110e3cbe24e42a11 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_expands.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void RemoveExpands(const std::shared_ptr& graph); + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_mutation.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_mutation.h new file mode 100644 index 0000000000000000000000000000000000000000..4f13698c8810608e31124679a6a07fae440e55c8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_mutation.h @@ -0,0 +1,81 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace torch::jit { + +struct TORCH_API MutationRemover { + MutationRemover( + std::shared_ptr graph, + std::optional> mutation_filter = std::nullopt) + : mutation_filter_(std::move(mutation_filter)), + aliasDb_(nullptr), + graph_(std::move(graph)) {} + + // return true if graph is modified + bool removeListMutation(); + + // return true if graph is modified + bool removeTensorMutation(); + + bool isSpecialMappedOp(Node* n) { + return n->matches("aten::zero_(Tensor(a!) self) -> Tensor(a!)") || + n->matches( + "aten::fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!)") || + n->matches( + "aten::normal_(Tensor(a!) self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor(a!)"); + } + + bool inplaceOpVariant(Node* n); + + static bool hasSideEffectOrAlias(Value* v, AliasDb* aliasDb); + + private: + Node* createSpecialMappedOp(Node* n); + bool listMutationFollowingListConstruct(Node* n); + bool tryMakeCreationAndMutationAtomic( + Value* mutated_value, + Node* mutating_op); + bool tryMakeUnaliasedIfOutputAndMutationAtomic( + Value* mutated_value, + Node* mutating_op); + // return true if graph is modified + bool RemoveListMutation(Block* block); + // return true if graph is modified + bool RemoveTensorMutation(Block* block); + + AliasDb* getOrCreateAliasDb() { + if (!aliasDb_) { + aliasDb_ = std::make_unique(graph_); + } + return aliasDb_.get(); + } + + std::optional> mutation_filter_; + std::unique_ptr aliasDb_ = nullptr; + std::shared_ptr graph_; +}; + +// Removes list mutation with functional equivalents +// return true if graph is modified +TORCH_API bool RemoveListMutation(const std::shared_ptr& graph); + +// Replaces in-place aten ops with their functional equivalents +// when it can be proven that this does not change graph semantics +// if `mutation_filter` is present, the pass will only attempt to +// remove mutation on nodes which return true for the filter +// return true if graph is modified +TORCH_API bool RemoveTensorMutation( + const std::shared_ptr& graph, + std::optional> mutation_filter = std::nullopt); + +// Replaces in-place aten activation ops with their functional equivalence +TORCH_API bool InplaceToFunctionalActivation( + const std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_redundant_profiles.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_redundant_profiles.h new file mode 100644 index 0000000000000000000000000000000000000000..0360bdf2092e571113847827592cbd6edba1fb1d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_redundant_profiles.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace torch::jit { + +TORCH_API void RemoveRedundantProfiles(std::shared_ptr& graph); +TORCH_API void RemoveRedundantProfiles(Block* block, AliasDb& db); +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/replacement_of_old_operators.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/replacement_of_old_operators.h new file mode 100644 index 0000000000000000000000000000000000000000..ec702fe6416edf20bfb8119cd8a1256f8aff32d5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/replacement_of_old_operators.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +namespace torch::jit { + +// Find the valid upgrader graph for the upgrader and cache the result +// for later lookups. Will error out if there is no valid upgrader graph +// provided for the upgrader name. +std::shared_ptr getUpgraderGraph(const std::string& upgrader_name); + +TORCH_API void ReplaceOldOperatorsWithUpgraders(std::shared_ptr graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/requires_grad_analysis.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/requires_grad_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..bd60e4e249dbf5d550e4156760aa80b0830112c0 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/requires_grad_analysis.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +#include + +namespace torch::jit { + +struct Graph; +struct ArgumentSpec; + +TORCH_API void PropagateRequiresGrad(std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_analysis.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..0f056fb5082064d23fef6278287b59e987d3fafb --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_analysis.h @@ -0,0 +1,56 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace torch::jit { + +// CAUTION NOT TO BE USED, STILL A WIP, NOT STABLE + +TORCH_API void PropagateShapesOnGraph(std::shared_ptr& graph); + +// CAUTION NOT TO BE USED, STILL A WIP, NOT STABLE +// From [beg, end) attempt to propagate shapes and +// build up a graph that will compute all remaining symbolic +// shapes in [beg, end) that can be executed before beg + +struct ShapeComputeGraphMapping { + ShapeComputeGraphMapping( + std::shared_ptr partial_eval_shape_graph, + std::unordered_map + enclosing_graph_value_to_shape_graph_input, + std::unordered_map graph_output_to_symbolic_shape_dim) + : partial_eval_shape_graph(std::move(partial_eval_shape_graph)), + enclosing_graph_value_to_shape_graph_input_( + std::move(enclosing_graph_value_to_shape_graph_input)), + graph_output_to_symbolic_shape_dim_( + std::move(graph_output_to_symbolic_shape_dim)){}; + + std::shared_ptr partial_eval_shape_graph; + std::unordered_map + enclosing_graph_value_to_shape_graph_input_; + std::unordered_map graph_output_to_symbolic_shape_dim_; +}; + +TORCH_API std::optional +PropagateShapesAndBuildLargeShapeComputeGraph( + std::shared_ptr& graph, + Node* beg, + Node* end); + +// don't insert complete tensor shapes in shape compute graphs and instead +// rely on our partial evaluation pipeline to propagate information. +// this is a good proxy for our ability to propagate non-complete shape +// information. +TORCH_API bool setSymbolicShapeAnalysisTestMode(bool value); +TORCH_API bool symbolicShapeAnalysisTestModeEnabled(); + +using SSAInput = std::variant; +TORCH_API std::optional> +calculateSymbolicShapesOnOp( + const FunctionSchema* schema, + const std::vector& inputs); +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/variadic_ops.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/variadic_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..afc033a57263bf6715a4a59a9192d739b3fb91cb --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/variadic_ops.h @@ -0,0 +1,29 @@ +#pragma once + +#include + +namespace torch::jit { + +// Try to replace an op that takes a list input with another op that takes a +// variadic number of arguments. +TORCH_API bool UseVariadicOp( + const std::shared_ptr& graph, + NodeKind op, + NodeKind variadic_op); + +TORCH_API bool RemoveListMutationAndUseVariadicOp( + const std::shared_ptr& graph, + NodeKind op, + NodeKind variadic_op); + +// Convenient functions for replacing aten::stack/aten::cat with their +// variadic versions. +TORCH_API bool UseVariadicCat(const std::shared_ptr& graph); +TORCH_API bool RemoveListMutationAndUseVariadicCat( + const std::shared_ptr& graph); + +TORCH_API bool UseVariadicStack(const std::shared_ptr& graph); +TORCH_API bool RemoveListMutationAndUseVariadicStack( + const std::shared_ptr& graph); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/resource_guard.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/resource_guard.h new file mode 100644 index 0000000000000000000000000000000000000000..a78022a0c6fe07645a2855ad17a50f3b0319b766 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/resource_guard.h @@ -0,0 +1,25 @@ +#pragma once +#include + +namespace torch::jit { + +class ResourceGuard { + std::function _destructor; + bool _released{false}; + + public: + ResourceGuard(std::function destructor) + : _destructor(std::move(destructor)) {} + + // NOLINTNEXTLINE(bugprone-exception-escape) + ~ResourceGuard() { + if (!_released) + _destructor(); + } + + void release() { + _released = true; + } +}; + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/callstack_debug_info_serialization.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/callstack_debug_info_serialization.h new file mode 100644 index 0000000000000000000000000000000000000000..6d09bf56b2c1d295feae30eb6054d017c7c3e9c6 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/callstack_debug_info_serialization.h @@ -0,0 +1,89 @@ +#pragma once + +#include +#include +#include + +#include + +#include + +#include + +namespace c10 { +struct IValue; +} + +namespace torch::jit { + +class Pickler; +class InlinedCallStackSerializer { + public: + // Serialize InlinedCallStack as + // SerializedInlinedCallStack = + // [module_info, source range tag, SerializedInlinedCallStack] + // module_info = [ClassType.qualifiedName, instance_name] + // source_range_tag = unique source range id + c10::IValue serialize( + const InlinedCallStackPtr& cs_ptr, + const SourceRangeTagMap& source_range_tags); + + private: + // module_info = [ClassType.qualifiedName, instance_name] + c10::IValue serialize_module_instance_info( + const std::optional& m); + + // This caches serialized inlined callstack ptr, since many + // InlinedCallStackPtr can refer to the same one. + ska::flat_hash_map + serialized_inlined_callstack_; + // This caches serialized module instance info. + // There might be many nodes that are part of the same + // parent, grandparent etc. module. + ska::flat_hash_map serialized_module_instance_info_; +}; + +class TORCH_API CallStackDebugInfoPickler { + public: + CallStackDebugInfoPickler() = default; + + std::vector pickle( + const std::unordered_map& callstack_ptrs, + const SourceRangeTagMap& source_range_tags); + + private: + InlinedCallStackSerializer css_; +}; + +class InlinedCallStackDeserializer { + public: + InlinedCallStackPtr deserialize( + const c10::IValue& iv, + const ska::flat_hash_map& source_range_map, + const std::shared_ptr& cu); + + private: + std::optional deserialize_module_instance_info( + const c10::IValue& iv, + const std::shared_ptr& cu); + + ska:: + flat_hash_map, InlinedCallStackPtr> + cached_inlined_callstacks_; + ska::flat_hash_map, ModuleInstanceInfo> + cached_module_instance_info_; +}; + +class TORCH_API CallStackDebugInfoUnpickler { + public: + ska::flat_hash_map unpickle( + const at::DataPtr& data, + size_t size, + const ska::flat_hash_map& source_range_map, + const std::shared_ptr& cu); + + private: + InlinedCallStackDeserializer csds_; +}; + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export.h new file mode 100644 index 0000000000000000000000000000000000000000..8b2d6d84716ae5bfc5763c38f53bb5f349234f7f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export.h @@ -0,0 +1,279 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ONNX_NAMESPACE { +class ModelProto; +} + +namespace torch::jit { + +// This map is used to keep track of parameters that should be exported +// externally. When `defer_weight_export` is true, the returned map contains +// kv pairs that map {external reference name} -> {at::Tensor to be exported}. +// It is the responsibility of the caller to export these appropriately. +// +// For example, when exporting to a zip archive, the caller may write out files +// for each entry in the export map, with the filename being the key and the +// file contents being the raw tensor data. +using RawDataExportMap = std::unordered_map; + +using SymbolDimMap = std::map; +using DimSymbolMap = std::map; + +using NodeNameMap = std::unordered_map; + +// Used for modularized export settling function and node attributes. +using NodeAttrNameMap = std:: + unordered_map>; + +TORCH_API std::tuple< + std::shared_ptr<::ONNX_NAMESPACE::ModelProto>, + RawDataExportMap, + SymbolDimMap, + bool, + NodeNameMap> +export_onnx( + const std::shared_ptr& graph, + const std::map& initializers, + int64_t onnx_opset_version, + const std::unordered_map< + std::string, + std::unordered_map>& dynamic_axes, + bool defer_weight_export = false, + ::torch::onnx::OperatorExportTypes operator_export_type = + ::torch::onnx::OperatorExportTypes::ONNX, + bool strip_doc_string = true, + bool keep_initializers_as_inputs = true, + const std::map& custom_opsets = {}, + bool add_node_names = true, + bool use_external_data_format = false, + const std::string& onnx_file_path = std::string(), + const NodeAttrNameMap& node_attr_to_name = {}); + +TORCH_API std::string serialize_model_proto_to_string( + const std::shared_ptr<::ONNX_NAMESPACE::ModelProto>& model_proto); + +TORCH_API void check_onnx_proto(const std::string& proto_string); + +// Serializer for both oldsyle and unified format TorchScript serialization +class TORCH_API ScriptModuleSerializer { + public: + explicit ScriptModuleSerializer( + caffe2::serialize::PyTorchStreamWriter& export_writer) + : writer_(export_writer) {} + + void writeFiles(const std::string& code_dir); + void serialize( + const Module& module, + const ExtraFilesMap& extra_files, + bool bytecode_format, + bool save_mobile_debug_info); + void serialize_unified_format(Module& module, uint64_t script_module_id); + SerializationStorageContext& storage_context(); + + ~ScriptModuleSerializer() = default; + + private: + void convertNamedType(const c10::NamedTypePtr& class_type); + void convertTypes(const at::NamedTypePtr& root_type); + void writeExtraFiles(const Module& module, const ExtraFilesMap& extra_files); + void writeByteCode(const Module& module, bool save_mobile_debug_info); + void writeArchive( + const IValue& value, + const std::string& archive_name, + const std::string& archive_dir, + const std::string& tensor_dir, + bool use_storage_context = false, + bool skip_tensor_data = false); + void updateSourceRangeTags(const SourceRangeRecords& ranges); + + caffe2::serialize::PyTorchStreamWriter& writer_; + std::vector constant_table_; + + std::unordered_set converted_types_; + PrintDepsTable class_deps_; + TypeNameUniquer type_name_uniquer_; + // qualifier, e.g. '__torch__.Bar' -> PythonPrint for the file that will be + // created + OrderedDict file_streams_; + // Used to keep references of storages around during serialization to solve + // for ABA memory reuse problem hit when storages are created/destroyed + // during serialization process. Also used to coordinate sharing of storages + // between Script and eager modules in torch.package. + SerializationStorageContext storage_context_; + + // Uniquely identifies a SourceRange in a model. + // SourceRanges are associated with Nodes of Graphs. + // However for mobile deployment we dont intend to ship + // full JIT with capabilities of reading code and constructing + // graphs. + // Instead we serialize the Code generated from graph of the methods. + // Code is serialized in bytecode format that contains instructions + // corresponding to the nodes of the graph. Since original graph is gone, the + // question is how do we identify where the ops, in serialized bytecode, come + // from in original model code. We do this in two parts. + // 1. Associate a unique tag to SourceRange. + // 2. Serialize this unique_tag. + // 2.1 Meaning save instead of + // + // 3. During serializing model for mobile, i.e. bytecode generation, + // save unique tag of SourceRange corresponding to the Node. + // 4. During deserialization, read all the debug_pkl, to construct a map + // of and use tag saved with OPs in bytecode + // to lookup the source range. + // Strictly speaking we will serialize InlinedCallStack directly, which + // contains SourceRange. This way we have access to entire callstack and not + // just source information about where the node is, since bytecode inlines the + // graph before saving it. + SourceRangeTagMap source_range_tags_; + int64_t current_source_range_tag_{0}; +}; + +// For testing purposes +TORCH_API std::string pretty_print_onnx( + const std::shared_ptr& graph, + const std::map& initializers, + int64_t onnx_opset_version, + bool defer_weight_export, + ::torch::onnx::OperatorExportTypes operator_export_type = + ::torch::onnx::OperatorExportTypes::ONNX, + bool google_printer = false, + bool keep_initializers_as_inputs = true, + const std::map& custom_opsets = {}, + bool add_node_names = true); + +TORCH_API void ExportModule( + const Module& module, + std::ostream& out, + const ExtraFilesMap& metadata = ExtraFilesMap(), + bool bytecode_format = false, + bool save_mobile_debug_info = false, + bool use_flatbuffer = false); + +TORCH_API void ExportModule( + const Module& module, + const std::string& filename, + const ExtraFilesMap& metadata = ExtraFilesMap(), + bool bytecode_format = false, + bool save_mobile_debug_info = false, + bool use_flatbuffer = false); + +TORCH_API void ExportModule( + const Module& module, + const std::function& writer_func, + const ExtraFilesMap& metadata = ExtraFilesMap(), + bool bytecode_format = false, + bool save_mobile_debug_info = false, + bool use_flatbuffer = false); + +// Write the bytes of a pickle archive and the tensors referenced inside that +// archive +TORCH_API void writeArchiveAndTensors( + const std::string& archive_name, + const char* pickle_bytes, + size_t size, + const std::vector& tensors, + caffe2::serialize::PyTorchStreamWriter& out); + +// Surrounding system can install an additional hook to produce extra files +// with metadata based on environment every time a module is serialized. +using ExportModuleExtraFilesHook = std::function; +TORCH_API void SetExportModuleExtraFilesHook(ExportModuleExtraFilesHook hook); + +/** + * Generates new bytecode for a Script module and returns what the op list + * would be for a LiteScriptModule based off the current code base. If you + * have a LiteScriptModule and want to get the currently present + * list of ops call _export_operator_list instead. + */ +TORCH_API std::vector export_opnames(const Module& m); + +struct TORCH_API BytecodeEmitMode { + static bool is_default_value_for_unspecified_arg_enabled(); + static void set_default_value_for_unspecified_arg_enabled(bool enabled); + + static bool is_default_args_before_out_args_enabled(); + static void set_default_args_before_out_args_enabled(bool enabled); + + static bool is_emit_promoted_ops_enabled(); + static void set_default_emit_promoted_ops_enabled(bool enabled); +}; + +// RAII guard to switch the way JIT emits the bytecode for inputs. +// default_value_for_unspecified_arg: +// true: instruction of default argument values (like LOADC) is emitted. +// false: instruction of default argument values are not emitted. Instead +// they are fetched from operator schema. +// default_args_before_out_args (to forward compatibile support +// operators allowing out arguments and default arguments): +// true: the number of specified arguments will deserialized to (#all_args - +// #default_args). false: the number of specified arguments will deserialized to +// (#all_args). +struct TORCH_API BytecodeEmitModeGuard { + BytecodeEmitModeGuard( + bool enable_default_value_for_unspecified_arg, + bool enable_default_args_before_out_args, + bool enable_emit_promoted_ops) + : prev_default_value_for_unspecified_arg_mode( + BytecodeEmitMode::is_default_value_for_unspecified_arg_enabled()), + prev_default_args_before_out_args( + BytecodeEmitMode::is_default_args_before_out_args_enabled()), + prev_default_emit_promoted_ops( + BytecodeEmitMode::is_emit_promoted_ops_enabled()) { + BytecodeEmitMode::set_default_value_for_unspecified_arg_enabled( + enable_default_value_for_unspecified_arg); + BytecodeEmitMode::set_default_args_before_out_args_enabled( + enable_default_args_before_out_args); + BytecodeEmitMode::set_default_emit_promoted_ops_enabled( + enable_emit_promoted_ops); + } + ~BytecodeEmitModeGuard() { + BytecodeEmitMode::set_default_value_for_unspecified_arg_enabled( + prev_default_value_for_unspecified_arg_mode); + BytecodeEmitMode::set_default_args_before_out_args_enabled( + prev_default_args_before_out_args); + BytecodeEmitMode::set_default_emit_promoted_ops_enabled( + prev_default_emit_promoted_ops); + } + bool prev_default_value_for_unspecified_arg_mode; + bool prev_default_args_before_out_args; + bool prev_default_emit_promoted_ops; +}; + +TORCH_API IValue to_tuple(std::vector ivalues); +TORCH_API IValue +Table(const std::vector>& entries); + +// TODO remove these switches once interface call is rolled out. +TORCH_API void enableMobileInterfaceCallExport(); +bool getMobileInterfaceCallExport(); + +TORCH_API CompilationOptions getOptionsFromGlobal(); + +TORCH_API void save_jit_module( + const Module& module, + const std::string& filename, + const ExtraFilesMap& extra_files = ExtraFilesMap()); + +TORCH_API DetachedBuffer::UniqueDetachedBuffer save_jit_module_to_bytes( + const Module& module, + const ExtraFilesMap& extra_files = ExtraFilesMap()); + +TORCH_API void save_jit_module_to_write_func( + const Module& module, + const ExtraFilesMap& extra_files, + bool save_mobile_debug_info, + const std::function& writer_func); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export_bytecode.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export_bytecode.h new file mode 100644 index 0000000000000000000000000000000000000000..d06a2e0c137d424fdd2514a096ae0a547e343740 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/export_bytecode.h @@ -0,0 +1,41 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +struct TORCH_API CompilationOptions { + bool incl_interface_call = false; + bool enable_default_value_for_unspecified_arg = false; + bool enable_default_args_before_out_args = true; + bool enable_emit_promoted_ops = true; + int model_version = caffe2::serialize::kProducedBytecodeVersion; +}; + +TORCH_API mobile::Module jitModuleToMobile( + const Module& module, + const CompilationOptions& options); + +mobile::Code compileGraphToMobileCode( + const std::string& name, + const std::shared_ptr& graph, + const CompilationOptions& compilation_options, + BackendDebugInfoRecorder& debug_info_recorder); + +TORCH_API std::unique_ptr convertJitFunctionToMobileFunction( + const GraphFunction& function, + const CompilationOptions& options); + +TORCH_API IValue convertMobileFunctionToCodeTable( + const mobile::Function& func, + const CompilationOptions& compilation_options); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer.h new file mode 100644 index 0000000000000000000000000000000000000000..41fb52415a129772266fc7bb4685da3f8bad1ce5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer.h @@ -0,0 +1,92 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include + +/** + * Defines the public API for serializing mobile modules to flatbuffer. + * Note that this header must not include or depend on flatbuffer-defined + * types, to avoid leaking those details to PyTorch clients. + */ + +namespace torch::jit { + +/// Maps file names to file contents. +using ExtraFilesMap = std::unordered_map; + +/** + * Represents a span of data. Typically owned by a UniqueDetachedBuffer. + */ +class TORCH_API DetachedBuffer final { + public: + /// Creates a new DetachedBuffer with an optional data owner. This interface + /// is provided to let users create objects of this type for testing. + DetachedBuffer(void* data, size_t size, void* internal_data_owner = nullptr) + : data_(data), size_(size), data_owner_(internal_data_owner) {} + + /// Returns a pointer to the data. + C10_NODISCARD void* data() { + return data_; + } + /// Returns a pointer to the data. + C10_NODISCARD const void* data() const { + return data_; + } + /// Returns the size of the data, in bytes. + C10_NODISCARD size_t size() const { + return size_; + } + + /// Wrapper type that typically owns data_owner_. + using UniqueDetachedBuffer = + std::unique_ptr>; + + private: + /// Deletes the owner, if present, and the buf itself. + /// Note: we could have provided a movable type with a destructor that did + /// this work, but the unique wrapper was easier in practice. + static void destroy(DetachedBuffer* buf); + + /// Provides access to destroy() for implementation and testing. + friend struct DetachedBufferFriend; + friend struct DetachedBufferTestingFriend; + + /// Pointer to the data. Not owned by this class. + void* data_; + /// The size of `data_`, in bytes. + size_t size_; + /// Opaque pointer to the underlying owner of `data_`. This class + /// (DetachedBuffer) does not own the owner or the data. It will typically be + /// owned by a UniqueDetachedBuffer that knows how to delete the owner along + /// with this class. + void* data_owner_; +}; + +TORCH_API void save_mobile_module( + const mobile::Module& module, + const std::string& filename, + const ExtraFilesMap& extra_files = ExtraFilesMap(), + const ExtraFilesMap& jit_sources = ExtraFilesMap(), + const std::vector& jit_constants = {}); + +TORCH_API DetachedBuffer::UniqueDetachedBuffer save_mobile_module_to_bytes( + const mobile::Module& module, + const ExtraFilesMap& extra_files = ExtraFilesMap(), + const ExtraFilesMap& jit_sources = ExtraFilesMap(), + const std::vector& jit_constants = {}); + +TORCH_API void save_mobile_module_to_func( + const mobile::Module& module, + const std::function& writer_func); + +// TODO(qihan): delete +TORCH_API bool register_flatbuffer_serializer(); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer_jit.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer_jit.h new file mode 100644 index 0000000000000000000000000000000000000000..17cac01783e352a45a1267aae8f51f17abbc899c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/flatbuffer_serializer_jit.h @@ -0,0 +1,9 @@ +#pragma once + +#include + +namespace torch::jit { + +TORCH_API bool register_flatbuffer_all(); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import.h new file mode 100644 index 0000000000000000000000000000000000000000..0e2024483f4a0d9542796d2f597a05e571be9b92 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import.h @@ -0,0 +1,153 @@ +#pragma once + +#include +#include +#include +#include + +#include + +namespace caffe2::serialize { +class ReadAdapterInterface; +} // namespace caffe2::serialize + +namespace torch::jit { + +class DeserializationStorageContext; + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + const std::string& filename, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::istream& in, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::unique_ptr rai, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + const std::string& filename, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true, + bool restore_shapes = false); + +// For reading unified serialization format from torch.Package +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::shared_ptr reader, + std::shared_ptr storage_context, + std::optional device, + const std::string& ts_id /* torchscript identifier inside package */); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::istream& in, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true, + bool restore_shapes = false); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::unique_ptr rai, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +TORCH_API Module import_ir_module( + std::shared_ptr cu, + std::shared_ptr rai, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +/// Loads a serialized `Module` from the given `istream`. +/// +/// The istream must contain a serialized `Module`, exported via +/// `torch::jit::ExportModule` in C++. +TORCH_API Module load( + std::istream& in, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module load( + std::istream& in, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +/// Loads a serialized `Module` from the given `filename`. +/// +/// The file stored at the location given in `filename` must contain a +/// serialized `Module`, exported either via `ScriptModule.save()` in +/// Python or `torch::jit::ExportModule` in C++. +TORCH_API Module load( + const std::string& filename, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module load( + const std::string& filename, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +/// Loads a serialized `Module` from the given shared_ptr `rai`. +/// +/// The reader adapter, which is for customized input stream, must contain a +/// serialized `Module`, exported either via `ScriptModule.save()` in +/// Python or `torch::jit::ExportModule` in C++. +TORCH_API Module load( + std::shared_ptr rai, + std::optional device = std::nullopt, + bool load_debug_files = true); + +TORCH_API Module load( + std::shared_ptr rai, + std::optional device, + ExtraFilesMap& extra_files, + bool load_debug_files = true); + +TORCH_API Module jitModuleFromSourceAndConstants( + const IValue& ivalue, + const ExtraFilesMap& source, + const std::vector& constants, + int32_t version); + +TORCH_API Module parse_and_initialize_jit_module( + const std::shared_ptr& data, + size_t size, + ExtraFilesMap& extra_files, + std::optional device = std::nullopt); + +TORCH_API Module load_jit_module_from_file( + const std::string& filename, + ExtraFilesMap& extra_files, + std::optional device = std::nullopt); + +TORCH_API Module load_jit_module_from_stream( + std::istream& in, + ExtraFilesMap& extra_files, + std::optional device = std::nullopt); + +TORCH_API Module parse_and_initialize_jit_module( + const std::shared_ptr& data, + size_t size, + ExtraFilesMap& extra_files, + std::optional device); + +TORCH_API c10::intrusive_ptr ObjLoaderFunc( + const at::StrongTypePtr& type, + IValue input); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_constants.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_constants.h new file mode 100644 index 0000000000000000000000000000000000000000..dda1bd8fd8bb0da61f6f1dd098cd60414471bd5a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_constants.h @@ -0,0 +1,19 @@ +#pragma once +#include + +namespace torch::jit { +constexpr size_t BYTECODE_INDEX_INSTRUCTION = 0; +constexpr size_t BYTECODE_INDEX_OPERATOR = 1; +constexpr size_t BYTECODE_INDEX_CONSTANT = 2; +constexpr size_t BYTECODE_INDEX_TYPE = 3; +constexpr size_t BYTECODE_INDEX_REGISTER_SIZE = 4; + +constexpr size_t BYTECODE_INDEX_SCHEMA_ARGUMENTS = 0; +constexpr size_t BYTECODE_INDEX_SCHEMA_RETURNS = 1; + +constexpr size_t BYTECODE_INDEX_ARGUMENT_NAME = 0; +constexpr size_t BYTECODE_INDEX_ARGUMENT_TYPE = 1; +constexpr size_t BYTECODE_INDEX_ARGUMENT_DEFAULT_VALUE = 2; + +constexpr size_t BYTECODE_INDEX_MODULE_DEBUG_HANDLES = 0; +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_functions.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_functions.h new file mode 100644 index 0000000000000000000000000000000000000000..b267f4924e1b8032159546afbe6a1778214f1401 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_functions.h @@ -0,0 +1,15 @@ +#pragma once +#include + +// Functions that are used in both import and export processes + +namespace torch::jit { +using c10::IValue; +IValue expect_field( + c10::ivalue::TupleElements& elements, + const std::string& expected_name, + size_t entry); +std::string operator_str( + const std::string& name, + const std::string& overloadname); +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_helpers.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..4cd2bd8c43c8b84c70d1b8bbf009c10bb5a5081a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_export_helpers.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +namespace caffe2::serialize { +class PyTorchStreamReader; +} + +namespace torch::jit { + +struct Source; + +// Convert a class type's qualifier name to the corresponding path the source +// file it should be written to. +// +// Qualifier is like: foo.bar.baz +// Returns: libs/foo/bar/baz.py +std::string qualifierToArchivePath( + const std::string& qualifier, + const std::string& export_prefix); + +std::shared_ptr findSourceInArchiveFromQualifier( + caffe2::serialize::PyTorchStreamReader& reader, + const std::string& export_prefix, + const std::string& qualifier); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_read.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_read.h new file mode 100644 index 0000000000000000000000000000000000000000..90629bc86736f159453329f87c4c6e18d5a1bd65 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_read.h @@ -0,0 +1,27 @@ +#pragma once + +#include +#include + +namespace caffe2::serialize { +class PyTorchStreamReader; +} // namespace caffe2::serialize + +namespace torch::jit { + +TORCH_API IValue readArchiveAndTensors( + const std::string& archive_name, + const std::string& pickle_prefix, + const std::string& tensor_prefix, + std::optional type_resolver, + std::optional obj_loader, + std::optional device, + caffe2::serialize::PyTorchStreamReader& stream_reader, + c10::TypePtr (*type_parser)(const std::string&) = + Unpickler::defaultTypeParser, + std::shared_ptr storage_context = nullptr); + +bool check_zip_file( + const std::shared_ptr& rai); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_source.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_source.h new file mode 100644 index 0000000000000000000000000000000000000000..f8510e6aa851a8bb67f5b527557d254d70f31548 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/import_source.h @@ -0,0 +1,100 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +using SourceLoader = std::function(const std::string&)>; + +struct SourceImporterImpl : public Resolver, + std::enable_shared_from_this { + SourceImporterImpl( + std::shared_ptr cu, + const std::vector* constant_table, + SourceLoader source_loader, + size_t version); + TypePtr findNamedType(const QualifiedName& name); + Function* findFunction(const QualifiedName& name); + void parseSourceIfNeeded(const std::string& qualifier); + void LEGACY_import_methods( + const Module& mod, + const std::shared_ptr& src); + + std::shared_ptr resolveValue( + const std::string& name, + GraphFunction& m, + const SourceRange& loc) override; + TypePtr resolveType(const std::string& name, const SourceRange& loc) override; + + private: + void importFunction(const std::string& qualifier, const Def& def); + void importNamedType(const std::string& qualifier, const ClassDef& class_def); + std::optional attributeAssignmentSpecialHandlingHack( + const QualifiedName& qualified_classname, + const Assign& assign); + void importClass( + const QualifiedName& qualified_classname, + const ClassDef& class_def, + bool is_module); + void importEnum( + const QualifiedName& qualified_name, + const ClassDef& enum_def); + void importNamedTuple( + const QualifiedName& qualified_name, + const ClassDef& named_tuple_def); + + void parsePossibleVersionNumber(Lexer& L); + + void parseImports(Lexer& L); + + std::shared_ptr cu_; + std::unordered_map> env_; + SourceLoader source_loader_; + std::optional version_ = std::nullopt; + std::unordered_set loaded_sources_; + // named types and functions loaded from a file but not yet defined because + // their type has not been requested yet. + std::unordered_map to_be_defined_; +}; + +// Given a directory of serialized TorchScript sources, +// This class allows the loading of individual named types in source. +// Resolves the dependencies between source files and parses +// the source files as necessary. + +struct TORCH_API SourceImporter { + SourceImporter( + // The compilation unit that will own the imported source + std::shared_ptr cu, + const std::vector* constant_table, + SourceLoader loader, + size_t version); + + TypePtr loadType(const QualifiedName& name) const; + + // Add the methods defined in `src` to the module `mod`, using SourceImporter + // to resolve any classes via loadType + void LEGACY_import_methods( + const Module& mod, + const std::shared_ptr& src); + ~SourceImporter(); + + private: + std::shared_ptr pImpl; +}; + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/mobile_bytecode_generated.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/mobile_bytecode_generated.h new file mode 100644 index 0000000000000000000000000000000000000000..cffe8bc7a636457ea3452fba9c040a71cb71fa5e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/mobile_bytecode_generated.h @@ -0,0 +1,2599 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_MOBILEBYTECODE_TORCH_JIT_MOBILE_SERIALIZATION_H_ +#define FLATBUFFERS_GENERATED_MOBILEBYTECODE_TORCH_JIT_MOBILE_SERIALIZATION_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 23 && + FLATBUFFERS_VERSION_MINOR == 3 && + FLATBUFFERS_VERSION_REVISION == 3, + "Non-compatible flatbuffers version included"); + +namespace torch { +namespace jit { +namespace mobile { +namespace serialization { + +struct Int; + +struct Bool; + +struct Double; + +struct PerTensorAffineSchema; + +struct QuantizedSchema; +struct QuantizedSchemaBuilder; + +struct TensorMetadata; +struct TensorMetadataBuilder; + +struct String; +struct StringBuilder; + +struct Device; +struct DeviceBuilder; + +struct List; +struct ListBuilder; + +struct IntList; +struct IntListBuilder; + +struct DoubleList; +struct DoubleListBuilder; + +struct BoolList; +struct BoolListBuilder; + +struct Tuple; +struct TupleBuilder; + +struct Dict; +struct DictBuilder; + +struct ObjectType; +struct ObjectTypeBuilder; + +struct Object; +struct ObjectBuilder; + +struct ComplexDouble; + +struct EnumValue; +struct EnumValueBuilder; + +struct Instruction; + +struct Operator; +struct OperatorBuilder; + +struct Arg; +struct ArgBuilder; + +struct Schema; +struct SchemaBuilder; + +struct DebugInfo; +struct DebugInfoBuilder; + +struct Function; +struct FunctionBuilder; + +struct StorageData; +struct StorageDataBuilder; + +struct IValue; +struct IValueBuilder; + +struct ExtraFile; +struct ExtraFileBuilder; + +struct Module; +struct ModuleBuilder; + +enum class TypeType : uint8_t { + UNSET = 0, + CLASS_WITH_FIELD = 1, + CUSTOM_CLASS = 2, + CLASS_WITH_SETSTATE = 3, + NON_OBJ = 4, + MIN = UNSET, + MAX = NON_OBJ +}; + +inline const TypeType (&EnumValuesTypeType())[5] { + static const TypeType values[] = { + TypeType::UNSET, + TypeType::CLASS_WITH_FIELD, + TypeType::CUSTOM_CLASS, + TypeType::CLASS_WITH_SETSTATE, + TypeType::NON_OBJ + }; + return values; +} + +inline const char * const *EnumNamesTypeType() { + static const char * const names[6] = { + "UNSET", + "CLASS_WITH_FIELD", + "CUSTOM_CLASS", + "CLASS_WITH_SETSTATE", + "NON_OBJ", + nullptr + }; + return names; +} + +inline const char *EnumNameTypeType(TypeType e) { + if (::flatbuffers::IsOutRange(e, TypeType::UNSET, TypeType::NON_OBJ)) return ""; + const size_t index = static_cast(e); + return EnumNamesTypeType()[index]; +} + +enum class IValueUnion : uint8_t { + NONE = 0, + Int = 1, + Bool = 2, + Double = 3, + ComplexDouble = 4, + TensorMetadata = 5, + String = 6, + List = 7, + Tuple = 8, + Dict = 9, + Object = 10, + IntList = 11, + DoubleList = 12, + BoolList = 13, + Device = 14, + EnumValue = 15, + Function = 16, + MIN = NONE, + MAX = Function +}; + +inline const IValueUnion (&EnumValuesIValueUnion())[17] { + static const IValueUnion values[] = { + IValueUnion::NONE, + IValueUnion::Int, + IValueUnion::Bool, + IValueUnion::Double, + IValueUnion::ComplexDouble, + IValueUnion::TensorMetadata, + IValueUnion::String, + IValueUnion::List, + IValueUnion::Tuple, + IValueUnion::Dict, + IValueUnion::Object, + IValueUnion::IntList, + IValueUnion::DoubleList, + IValueUnion::BoolList, + IValueUnion::Device, + IValueUnion::EnumValue, + IValueUnion::Function + }; + return values; +} + +inline const char * const *EnumNamesIValueUnion() { + static const char * const names[18] = { + "NONE", + "Int", + "Bool", + "Double", + "ComplexDouble", + "TensorMetadata", + "String", + "List", + "Tuple", + "Dict", + "Object", + "IntList", + "DoubleList", + "BoolList", + "Device", + "EnumValue", + "Function", + nullptr + }; + return names; +} + +inline const char *EnumNameIValueUnion(IValueUnion e) { + if (::flatbuffers::IsOutRange(e, IValueUnion::NONE, IValueUnion::Function)) return ""; + const size_t index = static_cast(e); + return EnumNamesIValueUnion()[index]; +} + +template struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::NONE; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Int; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Bool; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Double; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::ComplexDouble; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::TensorMetadata; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::String; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::List; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Tuple; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Dict; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Object; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::IntList; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::DoubleList; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::BoolList; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Device; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::EnumValue; +}; + +template<> struct IValueUnionTraits { + static const IValueUnion enum_value = IValueUnion::Function; +}; + +bool VerifyIValueUnion(::flatbuffers::Verifier &verifier, const void *obj, IValueUnion type); +bool VerifyIValueUnionVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Int FLATBUFFERS_FINAL_CLASS { + private: + int64_t int_val_; + + public: + Int() + : int_val_(0) { + } + Int(int64_t _int_val) + : int_val_(::flatbuffers::EndianScalar(_int_val)) { + } + int64_t int_val() const { + return ::flatbuffers::EndianScalar(int_val_); + } + void mutate_int_val(int64_t _int_val) { + ::flatbuffers::WriteScalar(&int_val_, _int_val); + } +}; +FLATBUFFERS_STRUCT_END(Int, 8); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(1) Bool FLATBUFFERS_FINAL_CLASS { + private: + uint8_t bool_val_; + + public: + Bool() + : bool_val_(0) { + } + Bool(bool _bool_val) + : bool_val_(::flatbuffers::EndianScalar(static_cast(_bool_val))) { + } + bool bool_val() const { + return ::flatbuffers::EndianScalar(bool_val_) != 0; + } + void mutate_bool_val(bool _bool_val) { + ::flatbuffers::WriteScalar(&bool_val_, static_cast(_bool_val)); + } +}; +FLATBUFFERS_STRUCT_END(Bool, 1); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Double FLATBUFFERS_FINAL_CLASS { + private: + double double_val_; + + public: + Double() + : double_val_(0) { + } + Double(double _double_val) + : double_val_(::flatbuffers::EndianScalar(_double_val)) { + } + double double_val() const { + return ::flatbuffers::EndianScalar(double_val_); + } + void mutate_double_val(double _double_val) { + ::flatbuffers::WriteScalar(&double_val_, _double_val); + } +}; +FLATBUFFERS_STRUCT_END(Double, 8); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) PerTensorAffineSchema FLATBUFFERS_FINAL_CLASS { + private: + double q_scale_; + int32_t q_zero_point_; + int32_t padding0__; + + public: + PerTensorAffineSchema() + : q_scale_(0), + q_zero_point_(0), + padding0__(0) { + (void)padding0__; + } + PerTensorAffineSchema(double _q_scale, int32_t _q_zero_point) + : q_scale_(::flatbuffers::EndianScalar(_q_scale)), + q_zero_point_(::flatbuffers::EndianScalar(_q_zero_point)), + padding0__(0) { + (void)padding0__; + } + double q_scale() const { + return ::flatbuffers::EndianScalar(q_scale_); + } + void mutate_q_scale(double _q_scale) { + ::flatbuffers::WriteScalar(&q_scale_, _q_scale); + } + int32_t q_zero_point() const { + return ::flatbuffers::EndianScalar(q_zero_point_); + } + void mutate_q_zero_point(int32_t _q_zero_point) { + ::flatbuffers::WriteScalar(&q_zero_point_, _q_zero_point); + } +}; +FLATBUFFERS_STRUCT_END(PerTensorAffineSchema, 16); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) ComplexDouble FLATBUFFERS_FINAL_CLASS { + private: + double real_; + double imag_; + + public: + ComplexDouble() + : real_(0), + imag_(0) { + } + ComplexDouble(double _real, double _imag) + : real_(::flatbuffers::EndianScalar(_real)), + imag_(::flatbuffers::EndianScalar(_imag)) { + } + double real() const { + return ::flatbuffers::EndianScalar(real_); + } + void mutate_real(double _real) { + ::flatbuffers::WriteScalar(&real_, _real); + } + double imag() const { + return ::flatbuffers::EndianScalar(imag_); + } + void mutate_imag(double _imag) { + ::flatbuffers::WriteScalar(&imag_, _imag); + } +}; +FLATBUFFERS_STRUCT_END(ComplexDouble, 16); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Instruction FLATBUFFERS_FINAL_CLASS { + private: + int8_t op_; + int8_t padding0__; + uint16_t n_; + int32_t x_; + + public: + Instruction() + : op_(0), + padding0__(0), + n_(0), + x_(0) { + (void)padding0__; + } + Instruction(int8_t _op, uint16_t _n, int32_t _x) + : op_(::flatbuffers::EndianScalar(_op)), + padding0__(0), + n_(::flatbuffers::EndianScalar(_n)), + x_(::flatbuffers::EndianScalar(_x)) { + (void)padding0__; + } + int8_t op() const { + return ::flatbuffers::EndianScalar(op_); + } + void mutate_op(int8_t _op) { + ::flatbuffers::WriteScalar(&op_, _op); + } + uint16_t n() const { + return ::flatbuffers::EndianScalar(n_); + } + void mutate_n(uint16_t _n) { + ::flatbuffers::WriteScalar(&n_, _n); + } + int32_t x() const { + return ::flatbuffers::EndianScalar(x_); + } + void mutate_x(int32_t _x) { + ::flatbuffers::WriteScalar(&x_, _x); + } +}; +FLATBUFFERS_STRUCT_END(Instruction, 8); + +struct QuantizedSchema FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef QuantizedSchemaBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_QSCHEME = 4, + VT_SCALE = 6, + VT_ZERO_POINT = 8, + VT_SCALES = 10, + VT_ZERO_POINTS = 12, + VT_AXIS = 14 + }; + int8_t qscheme() const { + return GetField(VT_QSCHEME, 0); + } + bool mutate_qscheme(int8_t _qscheme = 0) { + return SetField(VT_QSCHEME, _qscheme, 0); + } + double scale() const { + return GetField(VT_SCALE, 0.0); + } + bool mutate_scale(double _scale = 0.0) { + return SetField(VT_SCALE, _scale, 0.0); + } + int32_t zero_point() const { + return GetField(VT_ZERO_POINT, 0); + } + bool mutate_zero_point(int32_t _zero_point = 0) { + return SetField(VT_ZERO_POINT, _zero_point, 0); + } + const torch::jit::mobile::serialization::TensorMetadata *scales() const { + return GetPointer(VT_SCALES); + } + torch::jit::mobile::serialization::TensorMetadata *mutable_scales() { + return GetPointer(VT_SCALES); + } + const torch::jit::mobile::serialization::TensorMetadata *zero_points() const { + return GetPointer(VT_ZERO_POINTS); + } + torch::jit::mobile::serialization::TensorMetadata *mutable_zero_points() { + return GetPointer(VT_ZERO_POINTS); + } + int32_t axis() const { + return GetField(VT_AXIS, 0); + } + bool mutate_axis(int32_t _axis = 0) { + return SetField(VT_AXIS, _axis, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_QSCHEME, 1) && + VerifyField(verifier, VT_SCALE, 8) && + VerifyField(verifier, VT_ZERO_POINT, 4) && + VerifyOffset(verifier, VT_SCALES) && + verifier.VerifyTable(scales()) && + VerifyOffset(verifier, VT_ZERO_POINTS) && + verifier.VerifyTable(zero_points()) && + VerifyField(verifier, VT_AXIS, 4) && + verifier.EndTable(); + } +}; + +struct QuantizedSchemaBuilder { + typedef QuantizedSchema Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_qscheme(int8_t qscheme) { + fbb_.AddElement(QuantizedSchema::VT_QSCHEME, qscheme, 0); + } + void add_scale(double scale) { + fbb_.AddElement(QuantizedSchema::VT_SCALE, scale, 0.0); + } + void add_zero_point(int32_t zero_point) { + fbb_.AddElement(QuantizedSchema::VT_ZERO_POINT, zero_point, 0); + } + void add_scales(::flatbuffers::Offset scales) { + fbb_.AddOffset(QuantizedSchema::VT_SCALES, scales); + } + void add_zero_points(::flatbuffers::Offset zero_points) { + fbb_.AddOffset(QuantizedSchema::VT_ZERO_POINTS, zero_points); + } + void add_axis(int32_t axis) { + fbb_.AddElement(QuantizedSchema::VT_AXIS, axis, 0); + } + explicit QuantizedSchemaBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateQuantizedSchema( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t qscheme = 0, + double scale = 0.0, + int32_t zero_point = 0, + ::flatbuffers::Offset scales = 0, + ::flatbuffers::Offset zero_points = 0, + int32_t axis = 0) { + QuantizedSchemaBuilder builder_(_fbb); + builder_.add_scale(scale); + builder_.add_axis(axis); + builder_.add_zero_points(zero_points); + builder_.add_scales(scales); + builder_.add_zero_point(zero_point); + builder_.add_qscheme(qscheme); + return builder_.Finish(); +} + +struct TensorMetadata FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TensorMetadataBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_STORAGE_LOCATION_INDEX = 4, + VT_SCALAR_TYPE = 6, + VT_STORAGE_OFFSET = 8, + VT_SIZES = 10, + VT_STRIDES = 12, + VT_REQUIRES_GRAD = 14, + VT_QUANTIZED_SCHEMA = 16 + }; + uint32_t storage_location_index() const { + return GetField(VT_STORAGE_LOCATION_INDEX, 0); + } + bool mutate_storage_location_index(uint32_t _storage_location_index = 0) { + return SetField(VT_STORAGE_LOCATION_INDEX, _storage_location_index, 0); + } + int8_t scalar_type() const { + return GetField(VT_SCALAR_TYPE, 0); + } + bool mutate_scalar_type(int8_t _scalar_type = 0) { + return SetField(VT_SCALAR_TYPE, _scalar_type, 0); + } + int32_t storage_offset() const { + return GetField(VT_STORAGE_OFFSET, 0); + } + bool mutate_storage_offset(int32_t _storage_offset = 0) { + return SetField(VT_STORAGE_OFFSET, _storage_offset, 0); + } + const ::flatbuffers::Vector *sizes() const { + return GetPointer *>(VT_SIZES); + } + ::flatbuffers::Vector *mutable_sizes() { + return GetPointer<::flatbuffers::Vector *>(VT_SIZES); + } + const ::flatbuffers::Vector *strides() const { + return GetPointer *>(VT_STRIDES); + } + ::flatbuffers::Vector *mutable_strides() { + return GetPointer<::flatbuffers::Vector *>(VT_STRIDES); + } + bool requires_grad() const { + return GetField(VT_REQUIRES_GRAD, 0) != 0; + } + bool mutate_requires_grad(bool _requires_grad = 0) { + return SetField(VT_REQUIRES_GRAD, static_cast(_requires_grad), 0); + } + const torch::jit::mobile::serialization::QuantizedSchema *quantized_schema() const { + return GetPointer(VT_QUANTIZED_SCHEMA); + } + torch::jit::mobile::serialization::QuantizedSchema *mutable_quantized_schema() { + return GetPointer(VT_QUANTIZED_SCHEMA); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_STORAGE_LOCATION_INDEX, 4) && + VerifyField(verifier, VT_SCALAR_TYPE, 1) && + VerifyField(verifier, VT_STORAGE_OFFSET, 4) && + VerifyOffset(verifier, VT_SIZES) && + verifier.VerifyVector(sizes()) && + VerifyOffset(verifier, VT_STRIDES) && + verifier.VerifyVector(strides()) && + VerifyField(verifier, VT_REQUIRES_GRAD, 1) && + VerifyOffset(verifier, VT_QUANTIZED_SCHEMA) && + verifier.VerifyTable(quantized_schema()) && + verifier.EndTable(); + } +}; + +struct TensorMetadataBuilder { + typedef TensorMetadata Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_storage_location_index(uint32_t storage_location_index) { + fbb_.AddElement(TensorMetadata::VT_STORAGE_LOCATION_INDEX, storage_location_index, 0); + } + void add_scalar_type(int8_t scalar_type) { + fbb_.AddElement(TensorMetadata::VT_SCALAR_TYPE, scalar_type, 0); + } + void add_storage_offset(int32_t storage_offset) { + fbb_.AddElement(TensorMetadata::VT_STORAGE_OFFSET, storage_offset, 0); + } + void add_sizes(::flatbuffers::Offset<::flatbuffers::Vector> sizes) { + fbb_.AddOffset(TensorMetadata::VT_SIZES, sizes); + } + void add_strides(::flatbuffers::Offset<::flatbuffers::Vector> strides) { + fbb_.AddOffset(TensorMetadata::VT_STRIDES, strides); + } + void add_requires_grad(bool requires_grad) { + fbb_.AddElement(TensorMetadata::VT_REQUIRES_GRAD, static_cast(requires_grad), 0); + } + void add_quantized_schema(::flatbuffers::Offset quantized_schema) { + fbb_.AddOffset(TensorMetadata::VT_QUANTIZED_SCHEMA, quantized_schema); + } + explicit TensorMetadataBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTensorMetadata( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t storage_location_index = 0, + int8_t scalar_type = 0, + int32_t storage_offset = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> sizes = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> strides = 0, + bool requires_grad = false, + ::flatbuffers::Offset quantized_schema = 0) { + TensorMetadataBuilder builder_(_fbb); + builder_.add_quantized_schema(quantized_schema); + builder_.add_strides(strides); + builder_.add_sizes(sizes); + builder_.add_storage_offset(storage_offset); + builder_.add_storage_location_index(storage_location_index); + builder_.add_requires_grad(requires_grad); + builder_.add_scalar_type(scalar_type); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTensorMetadataDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t storage_location_index = 0, + int8_t scalar_type = 0, + int32_t storage_offset = 0, + const std::vector *sizes = nullptr, + const std::vector *strides = nullptr, + bool requires_grad = false, + ::flatbuffers::Offset quantized_schema = 0) { + auto sizes__ = sizes ? _fbb.CreateVector(*sizes) : 0; + auto strides__ = strides ? _fbb.CreateVector(*strides) : 0; + return torch::jit::mobile::serialization::CreateTensorMetadata( + _fbb, + storage_location_index, + scalar_type, + storage_offset, + sizes__, + strides__, + requires_grad, + quantized_schema); +} + +struct String FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StringBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DATA = 4 + }; + const ::flatbuffers::String *data() const { + return GetPointer(VT_DATA); + } + ::flatbuffers::String *mutable_data() { + return GetPointer<::flatbuffers::String *>(VT_DATA); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_DATA) && + verifier.VerifyString(data()) && + verifier.EndTable(); + } +}; + +struct StringBuilder { + typedef String Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_data(::flatbuffers::Offset<::flatbuffers::String> data) { + fbb_.AddOffset(String::VT_DATA, data); + } + explicit StringBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateString( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> data = 0) { + StringBuilder builder_(_fbb); + builder_.add_data(data); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateStringDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *data = nullptr) { + auto data__ = data ? _fbb.CreateString(data) : 0; + return torch::jit::mobile::serialization::CreateString( + _fbb, + data__); +} + +struct Device FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef DeviceBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_STR = 4 + }; + const ::flatbuffers::String *str() const { + return GetPointer(VT_STR); + } + ::flatbuffers::String *mutable_str() { + return GetPointer<::flatbuffers::String *>(VT_STR); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_STR) && + verifier.VerifyString(str()) && + verifier.EndTable(); + } +}; + +struct DeviceBuilder { + typedef Device Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_str(::flatbuffers::Offset<::flatbuffers::String> str) { + fbb_.AddOffset(Device::VT_STR, str); + } + explicit DeviceBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateDevice( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> str = 0) { + DeviceBuilder builder_(_fbb); + builder_.add_str(str); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateDeviceDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *str = nullptr) { + auto str__ = str ? _fbb.CreateString(str) : 0; + return torch::jit::mobile::serialization::CreateDevice( + _fbb, + str__); +} + +struct List FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ListBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ITEMS = 4, + VT_ANNOTATION_STR = 6 + }; + const ::flatbuffers::Vector *items() const { + return GetPointer *>(VT_ITEMS); + } + ::flatbuffers::Vector *mutable_items() { + return GetPointer<::flatbuffers::Vector *>(VT_ITEMS); + } + const ::flatbuffers::String *annotation_str() const { + return GetPointer(VT_ANNOTATION_STR); + } + ::flatbuffers::String *mutable_annotation_str() { + return GetPointer<::flatbuffers::String *>(VT_ANNOTATION_STR); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ITEMS) && + verifier.VerifyVector(items()) && + VerifyOffset(verifier, VT_ANNOTATION_STR) && + verifier.VerifyString(annotation_str()) && + verifier.EndTable(); + } +}; + +struct ListBuilder { + typedef List Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_items(::flatbuffers::Offset<::flatbuffers::Vector> items) { + fbb_.AddOffset(List::VT_ITEMS, items); + } + void add_annotation_str(::flatbuffers::Offset<::flatbuffers::String> annotation_str) { + fbb_.AddOffset(List::VT_ANNOTATION_STR, annotation_str); + } + explicit ListBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateList( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> items = 0, + ::flatbuffers::Offset<::flatbuffers::String> annotation_str = 0) { + ListBuilder builder_(_fbb); + builder_.add_annotation_str(annotation_str); + builder_.add_items(items); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateListDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *items = nullptr, + const char *annotation_str = nullptr) { + auto items__ = items ? _fbb.CreateVector(*items) : 0; + auto annotation_str__ = annotation_str ? _fbb.CreateString(annotation_str) : 0; + return torch::jit::mobile::serialization::CreateList( + _fbb, + items__, + annotation_str__); +} + +struct IntList FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef IntListBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ITEMS = 4 + }; + const ::flatbuffers::Vector *items() const { + return GetPointer *>(VT_ITEMS); + } + ::flatbuffers::Vector *mutable_items() { + return GetPointer<::flatbuffers::Vector *>(VT_ITEMS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ITEMS) && + verifier.VerifyVector(items()) && + verifier.EndTable(); + } +}; + +struct IntListBuilder { + typedef IntList Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_items(::flatbuffers::Offset<::flatbuffers::Vector> items) { + fbb_.AddOffset(IntList::VT_ITEMS, items); + } + explicit IntListBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateIntList( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> items = 0) { + IntListBuilder builder_(_fbb); + builder_.add_items(items); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateIntListDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *items = nullptr) { + auto items__ = items ? _fbb.CreateVector(*items) : 0; + return torch::jit::mobile::serialization::CreateIntList( + _fbb, + items__); +} + +struct DoubleList FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef DoubleListBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ITEMS = 4 + }; + const ::flatbuffers::Vector *items() const { + return GetPointer *>(VT_ITEMS); + } + ::flatbuffers::Vector *mutable_items() { + return GetPointer<::flatbuffers::Vector *>(VT_ITEMS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ITEMS) && + verifier.VerifyVector(items()) && + verifier.EndTable(); + } +}; + +struct DoubleListBuilder { + typedef DoubleList Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_items(::flatbuffers::Offset<::flatbuffers::Vector> items) { + fbb_.AddOffset(DoubleList::VT_ITEMS, items); + } + explicit DoubleListBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateDoubleList( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> items = 0) { + DoubleListBuilder builder_(_fbb); + builder_.add_items(items); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateDoubleListDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *items = nullptr) { + auto items__ = items ? _fbb.CreateVector(*items) : 0; + return torch::jit::mobile::serialization::CreateDoubleList( + _fbb, + items__); +} + +struct BoolList FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef BoolListBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ITEMS = 4 + }; + const ::flatbuffers::Vector *items() const { + return GetPointer *>(VT_ITEMS); + } + ::flatbuffers::Vector *mutable_items() { + return GetPointer<::flatbuffers::Vector *>(VT_ITEMS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ITEMS) && + verifier.VerifyVector(items()) && + verifier.EndTable(); + } +}; + +struct BoolListBuilder { + typedef BoolList Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_items(::flatbuffers::Offset<::flatbuffers::Vector> items) { + fbb_.AddOffset(BoolList::VT_ITEMS, items); + } + explicit BoolListBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateBoolList( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> items = 0) { + BoolListBuilder builder_(_fbb); + builder_.add_items(items); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateBoolListDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *items = nullptr) { + auto items__ = items ? _fbb.CreateVector(*items) : 0; + return torch::jit::mobile::serialization::CreateBoolList( + _fbb, + items__); +} + +struct Tuple FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TupleBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ITEMS = 4 + }; + const ::flatbuffers::Vector *items() const { + return GetPointer *>(VT_ITEMS); + } + ::flatbuffers::Vector *mutable_items() { + return GetPointer<::flatbuffers::Vector *>(VT_ITEMS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ITEMS) && + verifier.VerifyVector(items()) && + verifier.EndTable(); + } +}; + +struct TupleBuilder { + typedef Tuple Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_items(::flatbuffers::Offset<::flatbuffers::Vector> items) { + fbb_.AddOffset(Tuple::VT_ITEMS, items); + } + explicit TupleBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTuple( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> items = 0) { + TupleBuilder builder_(_fbb); + builder_.add_items(items); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTupleDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *items = nullptr) { + auto items__ = items ? _fbb.CreateVector(*items) : 0; + return torch::jit::mobile::serialization::CreateTuple( + _fbb, + items__); +} + +struct Dict FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef DictBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_KEYS = 4, + VT_VALUES = 6, + VT_ANNOTATION_STR = 8 + }; + const ::flatbuffers::Vector *keys() const { + return GetPointer *>(VT_KEYS); + } + ::flatbuffers::Vector *mutable_keys() { + return GetPointer<::flatbuffers::Vector *>(VT_KEYS); + } + const ::flatbuffers::Vector *values() const { + return GetPointer *>(VT_VALUES); + } + ::flatbuffers::Vector *mutable_values() { + return GetPointer<::flatbuffers::Vector *>(VT_VALUES); + } + const ::flatbuffers::String *annotation_str() const { + return GetPointer(VT_ANNOTATION_STR); + } + ::flatbuffers::String *mutable_annotation_str() { + return GetPointer<::flatbuffers::String *>(VT_ANNOTATION_STR); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_KEYS) && + verifier.VerifyVector(keys()) && + VerifyOffset(verifier, VT_VALUES) && + verifier.VerifyVector(values()) && + VerifyOffset(verifier, VT_ANNOTATION_STR) && + verifier.VerifyString(annotation_str()) && + verifier.EndTable(); + } +}; + +struct DictBuilder { + typedef Dict Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_keys(::flatbuffers::Offset<::flatbuffers::Vector> keys) { + fbb_.AddOffset(Dict::VT_KEYS, keys); + } + void add_values(::flatbuffers::Offset<::flatbuffers::Vector> values) { + fbb_.AddOffset(Dict::VT_VALUES, values); + } + void add_annotation_str(::flatbuffers::Offset<::flatbuffers::String> annotation_str) { + fbb_.AddOffset(Dict::VT_ANNOTATION_STR, annotation_str); + } + explicit DictBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateDict( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> keys = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> values = 0, + ::flatbuffers::Offset<::flatbuffers::String> annotation_str = 0) { + DictBuilder builder_(_fbb); + builder_.add_annotation_str(annotation_str); + builder_.add_values(values); + builder_.add_keys(keys); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateDictDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *keys = nullptr, + const std::vector *values = nullptr, + const char *annotation_str = nullptr) { + auto keys__ = keys ? _fbb.CreateVector(*keys) : 0; + auto values__ = values ? _fbb.CreateVector(*values) : 0; + auto annotation_str__ = annotation_str ? _fbb.CreateString(annotation_str) : 0; + return torch::jit::mobile::serialization::CreateDict( + _fbb, + keys__, + values__, + annotation_str__); +} + +struct ObjectType FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ObjectTypeBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_TYPE_NAME = 4, + VT_TYPE = 6, + VT_ATTR_NAMES = 8 + }; + const ::flatbuffers::String *type_name() const { + return GetPointer(VT_TYPE_NAME); + } + ::flatbuffers::String *mutable_type_name() { + return GetPointer<::flatbuffers::String *>(VT_TYPE_NAME); + } + torch::jit::mobile::serialization::TypeType type() const { + return static_cast(GetField(VT_TYPE, 0)); + } + bool mutate_type(torch::jit::mobile::serialization::TypeType _type = static_cast(0)) { + return SetField(VT_TYPE, static_cast(_type), 0); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *attr_names() const { + return GetPointer> *>(VT_ATTR_NAMES); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_attr_names() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_ATTR_NAMES); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_TYPE_NAME) && + verifier.VerifyString(type_name()) && + VerifyField(verifier, VT_TYPE, 1) && + VerifyOffset(verifier, VT_ATTR_NAMES) && + verifier.VerifyVector(attr_names()) && + verifier.VerifyVectorOfStrings(attr_names()) && + verifier.EndTable(); + } +}; + +struct ObjectTypeBuilder { + typedef ObjectType Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_type_name(::flatbuffers::Offset<::flatbuffers::String> type_name) { + fbb_.AddOffset(ObjectType::VT_TYPE_NAME, type_name); + } + void add_type(torch::jit::mobile::serialization::TypeType type) { + fbb_.AddElement(ObjectType::VT_TYPE, static_cast(type), 0); + } + void add_attr_names(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> attr_names) { + fbb_.AddOffset(ObjectType::VT_ATTR_NAMES, attr_names); + } + explicit ObjectTypeBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateObjectType( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> type_name = 0, + torch::jit::mobile::serialization::TypeType type = torch::jit::mobile::serialization::TypeType::UNSET, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> attr_names = 0) { + ObjectTypeBuilder builder_(_fbb); + builder_.add_attr_names(attr_names); + builder_.add_type_name(type_name); + builder_.add_type(type); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateObjectTypeDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *type_name = nullptr, + torch::jit::mobile::serialization::TypeType type = torch::jit::mobile::serialization::TypeType::UNSET, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *attr_names = nullptr) { + auto type_name__ = type_name ? _fbb.CreateString(type_name) : 0; + auto attr_names__ = attr_names ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*attr_names) : 0; + return torch::jit::mobile::serialization::CreateObjectType( + _fbb, + type_name__, + type, + attr_names__); +} + +struct Object FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ObjectBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_TYPE_INDEX = 4, + VT_STATE = 6, + VT_ATTRS = 8, + VT_SETSTATE_FUNC = 10 + }; + uint32_t type_index() const { + return GetField(VT_TYPE_INDEX, 0); + } + bool mutate_type_index(uint32_t _type_index = 0) { + return SetField(VT_TYPE_INDEX, _type_index, 0); + } + uint32_t state() const { + return GetField(VT_STATE, 0); + } + bool mutate_state(uint32_t _state = 0) { + return SetField(VT_STATE, _state, 0); + } + const ::flatbuffers::Vector *attrs() const { + return GetPointer *>(VT_ATTRS); + } + ::flatbuffers::Vector *mutable_attrs() { + return GetPointer<::flatbuffers::Vector *>(VT_ATTRS); + } + uint32_t setstate_func() const { + return GetField(VT_SETSTATE_FUNC, 0); + } + bool mutate_setstate_func(uint32_t _setstate_func = 0) { + return SetField(VT_SETSTATE_FUNC, _setstate_func, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_TYPE_INDEX, 4) && + VerifyField(verifier, VT_STATE, 4) && + VerifyOffset(verifier, VT_ATTRS) && + verifier.VerifyVector(attrs()) && + VerifyField(verifier, VT_SETSTATE_FUNC, 4) && + verifier.EndTable(); + } +}; + +struct ObjectBuilder { + typedef Object Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_type_index(uint32_t type_index) { + fbb_.AddElement(Object::VT_TYPE_INDEX, type_index, 0); + } + void add_state(uint32_t state) { + fbb_.AddElement(Object::VT_STATE, state, 0); + } + void add_attrs(::flatbuffers::Offset<::flatbuffers::Vector> attrs) { + fbb_.AddOffset(Object::VT_ATTRS, attrs); + } + void add_setstate_func(uint32_t setstate_func) { + fbb_.AddElement(Object::VT_SETSTATE_FUNC, setstate_func, 0); + } + explicit ObjectBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateObject( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t type_index = 0, + uint32_t state = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> attrs = 0, + uint32_t setstate_func = 0) { + ObjectBuilder builder_(_fbb); + builder_.add_setstate_func(setstate_func); + builder_.add_attrs(attrs); + builder_.add_state(state); + builder_.add_type_index(type_index); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateObjectDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t type_index = 0, + uint32_t state = 0, + const std::vector *attrs = nullptr, + uint32_t setstate_func = 0) { + auto attrs__ = attrs ? _fbb.CreateVector(*attrs) : 0; + return torch::jit::mobile::serialization::CreateObject( + _fbb, + type_index, + state, + attrs__, + setstate_func); +} + +struct EnumValue FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef EnumValueBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_TYPE_NAME = 4, + VT_VALUE = 6 + }; + const ::flatbuffers::String *type_name() const { + return GetPointer(VT_TYPE_NAME); + } + ::flatbuffers::String *mutable_type_name() { + return GetPointer<::flatbuffers::String *>(VT_TYPE_NAME); + } + uint32_t value() const { + return GetField(VT_VALUE, 0); + } + bool mutate_value(uint32_t _value = 0) { + return SetField(VT_VALUE, _value, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_TYPE_NAME) && + verifier.VerifyString(type_name()) && + VerifyField(verifier, VT_VALUE, 4) && + verifier.EndTable(); + } +}; + +struct EnumValueBuilder { + typedef EnumValue Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_type_name(::flatbuffers::Offset<::flatbuffers::String> type_name) { + fbb_.AddOffset(EnumValue::VT_TYPE_NAME, type_name); + } + void add_value(uint32_t value) { + fbb_.AddElement(EnumValue::VT_VALUE, value, 0); + } + explicit EnumValueBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateEnumValue( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> type_name = 0, + uint32_t value = 0) { + EnumValueBuilder builder_(_fbb); + builder_.add_value(value); + builder_.add_type_name(type_name); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateEnumValueDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *type_name = nullptr, + uint32_t value = 0) { + auto type_name__ = type_name ? _fbb.CreateString(type_name) : 0; + return torch::jit::mobile::serialization::CreateEnumValue( + _fbb, + type_name__, + value); +} + +struct Operator FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef OperatorBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_NAME = 4, + VT_OVERLOAD_NAME = 6, + VT_NUM_ARGS_SERIALIZED = 8 + }; + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + const ::flatbuffers::String *overload_name() const { + return GetPointer(VT_OVERLOAD_NAME); + } + ::flatbuffers::String *mutable_overload_name() { + return GetPointer<::flatbuffers::String *>(VT_OVERLOAD_NAME); + } + int32_t num_args_serialized() const { + return GetField(VT_NUM_ARGS_SERIALIZED, -1); + } + bool mutate_num_args_serialized(int32_t _num_args_serialized = -1) { + return SetField(VT_NUM_ARGS_SERIALIZED, _num_args_serialized, -1); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_OVERLOAD_NAME) && + verifier.VerifyString(overload_name()) && + VerifyField(verifier, VT_NUM_ARGS_SERIALIZED, 4) && + verifier.EndTable(); + } +}; + +struct OperatorBuilder { + typedef Operator Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Operator::VT_NAME, name); + } + void add_overload_name(::flatbuffers::Offset<::flatbuffers::String> overload_name) { + fbb_.AddOffset(Operator::VT_OVERLOAD_NAME, overload_name); + } + void add_num_args_serialized(int32_t num_args_serialized) { + fbb_.AddElement(Operator::VT_NUM_ARGS_SERIALIZED, num_args_serialized, -1); + } + explicit OperatorBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateOperator( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::String> overload_name = 0, + int32_t num_args_serialized = -1) { + OperatorBuilder builder_(_fbb); + builder_.add_num_args_serialized(num_args_serialized); + builder_.add_overload_name(overload_name); + builder_.add_name(name); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateOperatorDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *name = nullptr, + const char *overload_name = nullptr, + int32_t num_args_serialized = -1) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto overload_name__ = overload_name ? _fbb.CreateString(overload_name) : 0; + return torch::jit::mobile::serialization::CreateOperator( + _fbb, + name__, + overload_name__, + num_args_serialized); +} + +struct Arg FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ArgBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_NAME = 4, + VT_TYPE = 6, + VT_DEFAULT_VALUE = 8 + }; + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + const ::flatbuffers::String *type() const { + return GetPointer(VT_TYPE); + } + ::flatbuffers::String *mutable_type() { + return GetPointer<::flatbuffers::String *>(VT_TYPE); + } + uint32_t default_value() const { + return GetField(VT_DEFAULT_VALUE, 0); + } + bool mutate_default_value(uint32_t _default_value = 0) { + return SetField(VT_DEFAULT_VALUE, _default_value, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_TYPE) && + verifier.VerifyString(type()) && + VerifyField(verifier, VT_DEFAULT_VALUE, 4) && + verifier.EndTable(); + } +}; + +struct ArgBuilder { + typedef Arg Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Arg::VT_NAME, name); + } + void add_type(::flatbuffers::Offset<::flatbuffers::String> type) { + fbb_.AddOffset(Arg::VT_TYPE, type); + } + void add_default_value(uint32_t default_value) { + fbb_.AddElement(Arg::VT_DEFAULT_VALUE, default_value, 0); + } + explicit ArgBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateArg( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::String> type = 0, + uint32_t default_value = 0) { + ArgBuilder builder_(_fbb); + builder_.add_default_value(default_value); + builder_.add_type(type); + builder_.add_name(name); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateArgDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *name = nullptr, + const char *type = nullptr, + uint32_t default_value = 0) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto type__ = type ? _fbb.CreateString(type) : 0; + return torch::jit::mobile::serialization::CreateArg( + _fbb, + name__, + type__, + default_value); +} + +struct Schema FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef SchemaBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ARGUMENTS = 4, + VT_RETURNS = 6 + }; + const ::flatbuffers::Vector<::flatbuffers::Offset> *arguments() const { + return GetPointer> *>(VT_ARGUMENTS); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_arguments() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_ARGUMENTS); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *returns() const { + return GetPointer> *>(VT_RETURNS); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_returns() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_RETURNS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ARGUMENTS) && + verifier.VerifyVector(arguments()) && + verifier.VerifyVectorOfTables(arguments()) && + VerifyOffset(verifier, VT_RETURNS) && + verifier.VerifyVector(returns()) && + verifier.VerifyVectorOfTables(returns()) && + verifier.EndTable(); + } +}; + +struct SchemaBuilder { + typedef Schema Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_arguments(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> arguments) { + fbb_.AddOffset(Schema::VT_ARGUMENTS, arguments); + } + void add_returns(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> returns) { + fbb_.AddOffset(Schema::VT_RETURNS, returns); + } + explicit SchemaBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateSchema( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> arguments = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> returns = 0) { + SchemaBuilder builder_(_fbb); + builder_.add_returns(returns); + builder_.add_arguments(arguments); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateSchemaDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector<::flatbuffers::Offset> *arguments = nullptr, + const std::vector<::flatbuffers::Offset> *returns = nullptr) { + auto arguments__ = arguments ? _fbb.CreateVector<::flatbuffers::Offset>(*arguments) : 0; + auto returns__ = returns ? _fbb.CreateVector<::flatbuffers::Offset>(*returns) : 0; + return torch::jit::mobile::serialization::CreateSchema( + _fbb, + arguments__, + returns__); +} + +struct DebugInfo FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef DebugInfoBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DEBUG_HANDLE = 4 + }; + const ::flatbuffers::Vector *debug_handle() const { + return GetPointer *>(VT_DEBUG_HANDLE); + } + ::flatbuffers::Vector *mutable_debug_handle() { + return GetPointer<::flatbuffers::Vector *>(VT_DEBUG_HANDLE); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_DEBUG_HANDLE) && + verifier.VerifyVector(debug_handle()) && + verifier.EndTable(); + } +}; + +struct DebugInfoBuilder { + typedef DebugInfo Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_debug_handle(::flatbuffers::Offset<::flatbuffers::Vector> debug_handle) { + fbb_.AddOffset(DebugInfo::VT_DEBUG_HANDLE, debug_handle); + } + explicit DebugInfoBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateDebugInfo( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> debug_handle = 0) { + DebugInfoBuilder builder_(_fbb); + builder_.add_debug_handle(debug_handle); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateDebugInfoDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *debug_handle = nullptr) { + auto debug_handle__ = debug_handle ? _fbb.CreateVector(*debug_handle) : 0; + return torch::jit::mobile::serialization::CreateDebugInfo( + _fbb, + debug_handle__); +} + +struct Function FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef FunctionBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_QN = 4, + VT_INSTRUCTIONS = 6, + VT_OPERATORS = 8, + VT_CONSTANTS = 10, + VT_TYPE_ANNOTATIONS = 12, + VT_REGISTER_SIZE = 14, + VT_SCHEMA = 16, + VT_DEBUG_INFO = 18, + VT_CLASS_TYPE = 20 + }; + const ::flatbuffers::String *qn() const { + return GetPointer(VT_QN); + } + ::flatbuffers::String *mutable_qn() { + return GetPointer<::flatbuffers::String *>(VT_QN); + } + const ::flatbuffers::Vector *instructions() const { + return GetPointer *>(VT_INSTRUCTIONS); + } + ::flatbuffers::Vector *mutable_instructions() { + return GetPointer<::flatbuffers::Vector *>(VT_INSTRUCTIONS); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *operators() const { + return GetPointer> *>(VT_OPERATORS); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_operators() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_OPERATORS); + } + const ::flatbuffers::Vector *constants() const { + return GetPointer *>(VT_CONSTANTS); + } + ::flatbuffers::Vector *mutable_constants() { + return GetPointer<::flatbuffers::Vector *>(VT_CONSTANTS); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *type_annotations() const { + return GetPointer> *>(VT_TYPE_ANNOTATIONS); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_type_annotations() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TYPE_ANNOTATIONS); + } + int32_t register_size() const { + return GetField(VT_REGISTER_SIZE, 0); + } + bool mutate_register_size(int32_t _register_size = 0) { + return SetField(VT_REGISTER_SIZE, _register_size, 0); + } + const torch::jit::mobile::serialization::Schema *schema() const { + return GetPointer(VT_SCHEMA); + } + torch::jit::mobile::serialization::Schema *mutable_schema() { + return GetPointer(VT_SCHEMA); + } + const torch::jit::mobile::serialization::DebugInfo *debug_info() const { + return GetPointer(VT_DEBUG_INFO); + } + torch::jit::mobile::serialization::DebugInfo *mutable_debug_info() { + return GetPointer(VT_DEBUG_INFO); + } + uint32_t class_type() const { + return GetField(VT_CLASS_TYPE, 0); + } + bool mutate_class_type(uint32_t _class_type = 0) { + return SetField(VT_CLASS_TYPE, _class_type, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_QN) && + verifier.VerifyString(qn()) && + VerifyOffset(verifier, VT_INSTRUCTIONS) && + verifier.VerifyVector(instructions()) && + VerifyOffset(verifier, VT_OPERATORS) && + verifier.VerifyVector(operators()) && + verifier.VerifyVectorOfTables(operators()) && + VerifyOffset(verifier, VT_CONSTANTS) && + verifier.VerifyVector(constants()) && + VerifyOffset(verifier, VT_TYPE_ANNOTATIONS) && + verifier.VerifyVector(type_annotations()) && + verifier.VerifyVectorOfStrings(type_annotations()) && + VerifyField(verifier, VT_REGISTER_SIZE, 4) && + VerifyOffset(verifier, VT_SCHEMA) && + verifier.VerifyTable(schema()) && + VerifyOffset(verifier, VT_DEBUG_INFO) && + verifier.VerifyTable(debug_info()) && + VerifyField(verifier, VT_CLASS_TYPE, 4) && + verifier.EndTable(); + } +}; + +struct FunctionBuilder { + typedef Function Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_qn(::flatbuffers::Offset<::flatbuffers::String> qn) { + fbb_.AddOffset(Function::VT_QN, qn); + } + void add_instructions(::flatbuffers::Offset<::flatbuffers::Vector> instructions) { + fbb_.AddOffset(Function::VT_INSTRUCTIONS, instructions); + } + void add_operators(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> operators) { + fbb_.AddOffset(Function::VT_OPERATORS, operators); + } + void add_constants(::flatbuffers::Offset<::flatbuffers::Vector> constants) { + fbb_.AddOffset(Function::VT_CONSTANTS, constants); + } + void add_type_annotations(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> type_annotations) { + fbb_.AddOffset(Function::VT_TYPE_ANNOTATIONS, type_annotations); + } + void add_register_size(int32_t register_size) { + fbb_.AddElement(Function::VT_REGISTER_SIZE, register_size, 0); + } + void add_schema(::flatbuffers::Offset schema) { + fbb_.AddOffset(Function::VT_SCHEMA, schema); + } + void add_debug_info(::flatbuffers::Offset debug_info) { + fbb_.AddOffset(Function::VT_DEBUG_INFO, debug_info); + } + void add_class_type(uint32_t class_type) { + fbb_.AddElement(Function::VT_CLASS_TYPE, class_type, 0); + } + explicit FunctionBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateFunction( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> qn = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> instructions = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> operators = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> constants = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> type_annotations = 0, + int32_t register_size = 0, + ::flatbuffers::Offset schema = 0, + ::flatbuffers::Offset debug_info = 0, + uint32_t class_type = 0) { + FunctionBuilder builder_(_fbb); + builder_.add_class_type(class_type); + builder_.add_debug_info(debug_info); + builder_.add_schema(schema); + builder_.add_register_size(register_size); + builder_.add_type_annotations(type_annotations); + builder_.add_constants(constants); + builder_.add_operators(operators); + builder_.add_instructions(instructions); + builder_.add_qn(qn); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateFunctionDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *qn = nullptr, + const std::vector *instructions = nullptr, + const std::vector<::flatbuffers::Offset> *operators = nullptr, + const std::vector *constants = nullptr, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *type_annotations = nullptr, + int32_t register_size = 0, + ::flatbuffers::Offset schema = 0, + ::flatbuffers::Offset debug_info = 0, + uint32_t class_type = 0) { + auto qn__ = qn ? _fbb.CreateString(qn) : 0; + auto instructions__ = instructions ? _fbb.CreateVectorOfStructs(*instructions) : 0; + auto operators__ = operators ? _fbb.CreateVector<::flatbuffers::Offset>(*operators) : 0; + auto constants__ = constants ? _fbb.CreateVector(*constants) : 0; + auto type_annotations__ = type_annotations ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*type_annotations) : 0; + return torch::jit::mobile::serialization::CreateFunction( + _fbb, + qn__, + instructions__, + operators__, + constants__, + type_annotations__, + register_size, + schema, + debug_info, + class_type); +} + +struct StorageData FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StorageDataBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_DATA = 4 + }; + const ::flatbuffers::Vector *data() const { + return GetPointer *>(VT_DATA); + } + ::flatbuffers::Vector *mutable_data() { + return GetPointer<::flatbuffers::Vector *>(VT_DATA); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_DATA) && + verifier.VerifyVector(data()) && + verifier.EndTable(); + } +}; + +struct StorageDataBuilder { + typedef StorageData Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_data(::flatbuffers::Offset<::flatbuffers::Vector> data) { + fbb_.AddOffset(StorageData::VT_DATA, data); + } + explicit StorageDataBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateStorageData( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> data = 0) { + StorageDataBuilder builder_(_fbb); + builder_.add_data(data); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateStorageDataDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *data = nullptr) { + if (data) { _fbb.ForceVectorAlignment(data->size(), sizeof(uint8_t), 16); } + auto data__ = data ? _fbb.CreateVector(*data) : 0; + return torch::jit::mobile::serialization::CreateStorageData( + _fbb, + data__); +} + +struct IValue FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef IValueBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_VAL_TYPE = 4, + VT_VAL = 6 + }; + torch::jit::mobile::serialization::IValueUnion val_type() const { + return static_cast(GetField(VT_VAL_TYPE, 0)); + } + const void *val() const { + return GetPointer(VT_VAL); + } + template const T *val_as() const; + const torch::jit::mobile::serialization::Int *val_as_Int() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Int ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Bool *val_as_Bool() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Bool ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Double *val_as_Double() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Double ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::ComplexDouble *val_as_ComplexDouble() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::ComplexDouble ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::TensorMetadata *val_as_TensorMetadata() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::TensorMetadata ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::String *val_as_String() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::String ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::List *val_as_List() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::List ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Tuple *val_as_Tuple() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Tuple ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Dict *val_as_Dict() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Dict ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Object *val_as_Object() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Object ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::IntList *val_as_IntList() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::IntList ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::DoubleList *val_as_DoubleList() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::DoubleList ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::BoolList *val_as_BoolList() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::BoolList ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Device *val_as_Device() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Device ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::EnumValue *val_as_EnumValue() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::EnumValue ? static_cast(val()) : nullptr; + } + const torch::jit::mobile::serialization::Function *val_as_Function() const { + return val_type() == torch::jit::mobile::serialization::IValueUnion::Function ? static_cast(val()) : nullptr; + } + void *mutable_val() { + return GetPointer(VT_VAL); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_VAL_TYPE, 1) && + VerifyOffset(verifier, VT_VAL) && + VerifyIValueUnion(verifier, val(), val_type()) && + verifier.EndTable(); + } +}; + +template<> inline const torch::jit::mobile::serialization::Int *IValue::val_as() const { + return val_as_Int(); +} + +template<> inline const torch::jit::mobile::serialization::Bool *IValue::val_as() const { + return val_as_Bool(); +} + +template<> inline const torch::jit::mobile::serialization::Double *IValue::val_as() const { + return val_as_Double(); +} + +template<> inline const torch::jit::mobile::serialization::ComplexDouble *IValue::val_as() const { + return val_as_ComplexDouble(); +} + +template<> inline const torch::jit::mobile::serialization::TensorMetadata *IValue::val_as() const { + return val_as_TensorMetadata(); +} + +template<> inline const torch::jit::mobile::serialization::String *IValue::val_as() const { + return val_as_String(); +} + +template<> inline const torch::jit::mobile::serialization::List *IValue::val_as() const { + return val_as_List(); +} + +template<> inline const torch::jit::mobile::serialization::Tuple *IValue::val_as() const { + return val_as_Tuple(); +} + +template<> inline const torch::jit::mobile::serialization::Dict *IValue::val_as() const { + return val_as_Dict(); +} + +template<> inline const torch::jit::mobile::serialization::Object *IValue::val_as() const { + return val_as_Object(); +} + +template<> inline const torch::jit::mobile::serialization::IntList *IValue::val_as() const { + return val_as_IntList(); +} + +template<> inline const torch::jit::mobile::serialization::DoubleList *IValue::val_as() const { + return val_as_DoubleList(); +} + +template<> inline const torch::jit::mobile::serialization::BoolList *IValue::val_as() const { + return val_as_BoolList(); +} + +template<> inline const torch::jit::mobile::serialization::Device *IValue::val_as() const { + return val_as_Device(); +} + +template<> inline const torch::jit::mobile::serialization::EnumValue *IValue::val_as() const { + return val_as_EnumValue(); +} + +template<> inline const torch::jit::mobile::serialization::Function *IValue::val_as() const { + return val_as_Function(); +} + +struct IValueBuilder { + typedef IValue Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_val_type(torch::jit::mobile::serialization::IValueUnion val_type) { + fbb_.AddElement(IValue::VT_VAL_TYPE, static_cast(val_type), 0); + } + void add_val(::flatbuffers::Offset val) { + fbb_.AddOffset(IValue::VT_VAL, val); + } + explicit IValueBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateIValue( + ::flatbuffers::FlatBufferBuilder &_fbb, + torch::jit::mobile::serialization::IValueUnion val_type = torch::jit::mobile::serialization::IValueUnion::NONE, + ::flatbuffers::Offset val = 0) { + IValueBuilder builder_(_fbb); + builder_.add_val(val); + builder_.add_val_type(val_type); + return builder_.Finish(); +} + +struct ExtraFile FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ExtraFileBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_NAME = 4, + VT_CONTENT = 6 + }; + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + const ::flatbuffers::String *content() const { + return GetPointer(VT_CONTENT); + } + ::flatbuffers::String *mutable_content() { + return GetPointer<::flatbuffers::String *>(VT_CONTENT); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_CONTENT) && + verifier.VerifyString(content()) && + verifier.EndTable(); + } +}; + +struct ExtraFileBuilder { + typedef ExtraFile Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(ExtraFile::VT_NAME, name); + } + void add_content(::flatbuffers::Offset<::flatbuffers::String> content) { + fbb_.AddOffset(ExtraFile::VT_CONTENT, content); + } + explicit ExtraFileBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateExtraFile( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::String> content = 0) { + ExtraFileBuilder builder_(_fbb); + builder_.add_content(content); + builder_.add_name(name); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateExtraFileDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *name = nullptr, + const char *content = nullptr) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto content__ = content ? _fbb.CreateString(content) : 0; + return torch::jit::mobile::serialization::CreateExtraFile( + _fbb, + name__, + content__); +} + +struct Module FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ModuleBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_BYTECODE_VERSION = 4, + VT_EXTRA_FILES = 6, + VT_METHODS = 8, + VT_STATE_OBJ = 10, + VT_IVALUES = 12, + VT_STORAGE_DATA_SIZE = 14, + VT_STORAGE_DATA = 16, + VT_OBJECT_TYPES = 18, + VT_JIT_SOURCES = 20, + VT_JIT_CONSTANTS = 22, + VT_OPERATOR_VERSION = 24, + VT_MOBILE_IVALUE_SIZE = 26 + }; + uint32_t bytecode_version() const { + return GetField(VT_BYTECODE_VERSION, 0); + } + bool mutate_bytecode_version(uint32_t _bytecode_version = 0) { + return SetField(VT_BYTECODE_VERSION, _bytecode_version, 0); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *extra_files() const { + return GetPointer> *>(VT_EXTRA_FILES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_extra_files() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_EXTRA_FILES); + } + const ::flatbuffers::Vector *methods() const { + return GetPointer *>(VT_METHODS); + } + ::flatbuffers::Vector *mutable_methods() { + return GetPointer<::flatbuffers::Vector *>(VT_METHODS); + } + uint32_t state_obj() const { + return GetField(VT_STATE_OBJ, 0); + } + bool mutate_state_obj(uint32_t _state_obj = 0) { + return SetField(VT_STATE_OBJ, _state_obj, 0); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *ivalues() const { + return GetPointer> *>(VT_IVALUES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_ivalues() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_IVALUES); + } + int32_t storage_data_size() const { + return GetField(VT_STORAGE_DATA_SIZE, 0); + } + bool mutate_storage_data_size(int32_t _storage_data_size = 0) { + return SetField(VT_STORAGE_DATA_SIZE, _storage_data_size, 0); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *storage_data() const { + return GetPointer> *>(VT_STORAGE_DATA); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_storage_data() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_STORAGE_DATA); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *object_types() const { + return GetPointer> *>(VT_OBJECT_TYPES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_object_types() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_OBJECT_TYPES); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *jit_sources() const { + return GetPointer> *>(VT_JIT_SOURCES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_jit_sources() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_JIT_SOURCES); + } + const ::flatbuffers::Vector *jit_constants() const { + return GetPointer *>(VT_JIT_CONSTANTS); + } + ::flatbuffers::Vector *mutable_jit_constants() { + return GetPointer<::flatbuffers::Vector *>(VT_JIT_CONSTANTS); + } + uint32_t operator_version() const { + return GetField(VT_OPERATOR_VERSION, 0); + } + bool mutate_operator_version(uint32_t _operator_version = 0) { + return SetField(VT_OPERATOR_VERSION, _operator_version, 0); + } + uint32_t mobile_ivalue_size() const { + return GetField(VT_MOBILE_IVALUE_SIZE, 0); + } + bool mutate_mobile_ivalue_size(uint32_t _mobile_ivalue_size = 0) { + return SetField(VT_MOBILE_IVALUE_SIZE, _mobile_ivalue_size, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_BYTECODE_VERSION, 4) && + VerifyOffset(verifier, VT_EXTRA_FILES) && + verifier.VerifyVector(extra_files()) && + verifier.VerifyVectorOfTables(extra_files()) && + VerifyOffset(verifier, VT_METHODS) && + verifier.VerifyVector(methods()) && + VerifyField(verifier, VT_STATE_OBJ, 4) && + VerifyOffset(verifier, VT_IVALUES) && + verifier.VerifyVector(ivalues()) && + verifier.VerifyVectorOfTables(ivalues()) && + VerifyField(verifier, VT_STORAGE_DATA_SIZE, 4) && + VerifyOffset(verifier, VT_STORAGE_DATA) && + verifier.VerifyVector(storage_data()) && + verifier.VerifyVectorOfTables(storage_data()) && + VerifyOffset(verifier, VT_OBJECT_TYPES) && + verifier.VerifyVector(object_types()) && + verifier.VerifyVectorOfTables(object_types()) && + VerifyOffset(verifier, VT_JIT_SOURCES) && + verifier.VerifyVector(jit_sources()) && + verifier.VerifyVectorOfTables(jit_sources()) && + VerifyOffset(verifier, VT_JIT_CONSTANTS) && + verifier.VerifyVector(jit_constants()) && + VerifyField(verifier, VT_OPERATOR_VERSION, 4) && + VerifyField(verifier, VT_MOBILE_IVALUE_SIZE, 4) && + verifier.EndTable(); + } +}; + +struct ModuleBuilder { + typedef Module Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_bytecode_version(uint32_t bytecode_version) { + fbb_.AddElement(Module::VT_BYTECODE_VERSION, bytecode_version, 0); + } + void add_extra_files(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> extra_files) { + fbb_.AddOffset(Module::VT_EXTRA_FILES, extra_files); + } + void add_methods(::flatbuffers::Offset<::flatbuffers::Vector> methods) { + fbb_.AddOffset(Module::VT_METHODS, methods); + } + void add_state_obj(uint32_t state_obj) { + fbb_.AddElement(Module::VT_STATE_OBJ, state_obj, 0); + } + void add_ivalues(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> ivalues) { + fbb_.AddOffset(Module::VT_IVALUES, ivalues); + } + void add_storage_data_size(int32_t storage_data_size) { + fbb_.AddElement(Module::VT_STORAGE_DATA_SIZE, storage_data_size, 0); + } + void add_storage_data(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> storage_data) { + fbb_.AddOffset(Module::VT_STORAGE_DATA, storage_data); + } + void add_object_types(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> object_types) { + fbb_.AddOffset(Module::VT_OBJECT_TYPES, object_types); + } + void add_jit_sources(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> jit_sources) { + fbb_.AddOffset(Module::VT_JIT_SOURCES, jit_sources); + } + void add_jit_constants(::flatbuffers::Offset<::flatbuffers::Vector> jit_constants) { + fbb_.AddOffset(Module::VT_JIT_CONSTANTS, jit_constants); + } + void add_operator_version(uint32_t operator_version) { + fbb_.AddElement(Module::VT_OPERATOR_VERSION, operator_version, 0); + } + void add_mobile_ivalue_size(uint32_t mobile_ivalue_size) { + fbb_.AddElement(Module::VT_MOBILE_IVALUE_SIZE, mobile_ivalue_size, 0); + } + explicit ModuleBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateModule( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t bytecode_version = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> extra_files = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> methods = 0, + uint32_t state_obj = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> ivalues = 0, + int32_t storage_data_size = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> storage_data = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> object_types = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> jit_sources = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> jit_constants = 0, + uint32_t operator_version = 0, + uint32_t mobile_ivalue_size = 0) { + ModuleBuilder builder_(_fbb); + builder_.add_mobile_ivalue_size(mobile_ivalue_size); + builder_.add_operator_version(operator_version); + builder_.add_jit_constants(jit_constants); + builder_.add_jit_sources(jit_sources); + builder_.add_object_types(object_types); + builder_.add_storage_data(storage_data); + builder_.add_storage_data_size(storage_data_size); + builder_.add_ivalues(ivalues); + builder_.add_state_obj(state_obj); + builder_.add_methods(methods); + builder_.add_extra_files(extra_files); + builder_.add_bytecode_version(bytecode_version); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateModuleDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint32_t bytecode_version = 0, + const std::vector<::flatbuffers::Offset> *extra_files = nullptr, + const std::vector *methods = nullptr, + uint32_t state_obj = 0, + const std::vector<::flatbuffers::Offset> *ivalues = nullptr, + int32_t storage_data_size = 0, + const std::vector<::flatbuffers::Offset> *storage_data = nullptr, + const std::vector<::flatbuffers::Offset> *object_types = nullptr, + const std::vector<::flatbuffers::Offset> *jit_sources = nullptr, + const std::vector *jit_constants = nullptr, + uint32_t operator_version = 0, + uint32_t mobile_ivalue_size = 0) { + auto extra_files__ = extra_files ? _fbb.CreateVector<::flatbuffers::Offset>(*extra_files) : 0; + auto methods__ = methods ? _fbb.CreateVector(*methods) : 0; + auto ivalues__ = ivalues ? _fbb.CreateVector<::flatbuffers::Offset>(*ivalues) : 0; + auto storage_data__ = storage_data ? _fbb.CreateVector<::flatbuffers::Offset>(*storage_data) : 0; + auto object_types__ = object_types ? _fbb.CreateVector<::flatbuffers::Offset>(*object_types) : 0; + auto jit_sources__ = jit_sources ? _fbb.CreateVector<::flatbuffers::Offset>(*jit_sources) : 0; + auto jit_constants__ = jit_constants ? _fbb.CreateVector(*jit_constants) : 0; + return torch::jit::mobile::serialization::CreateModule( + _fbb, + bytecode_version, + extra_files__, + methods__, + state_obj, + ivalues__, + storage_data_size, + storage_data__, + object_types__, + jit_sources__, + jit_constants__, + operator_version, + mobile_ivalue_size); +} + +inline bool VerifyIValueUnion(::flatbuffers::Verifier &verifier, const void *obj, IValueUnion type) { + switch (type) { + case IValueUnion::NONE: { + return true; + } + case IValueUnion::Int: { + return verifier.VerifyField(static_cast(obj), 0, 8); + } + case IValueUnion::Bool: { + return verifier.VerifyField(static_cast(obj), 0, 1); + } + case IValueUnion::Double: { + return verifier.VerifyField(static_cast(obj), 0, 8); + } + case IValueUnion::ComplexDouble: { + return verifier.VerifyField(static_cast(obj), 0, 8); + } + case IValueUnion::TensorMetadata: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::String: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::List: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::Tuple: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::Dict: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::Object: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::IntList: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::DoubleList: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::BoolList: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::Device: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::EnumValue: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case IValueUnion::Function: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyIValueUnionVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyIValueUnion( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline const torch::jit::mobile::serialization::Module *GetModule(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const torch::jit::mobile::serialization::Module *GetSizePrefixedModule(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline Module *GetMutableModule(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline torch::jit::mobile::serialization::Module *GetMutableSizePrefixedModule(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *ModuleIdentifier() { + return "PTMF"; +} + +inline bool ModuleBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, ModuleIdentifier()); +} + +inline bool SizePrefixedModuleBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, ModuleIdentifier(), true); +} + +inline bool VerifyModuleBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(ModuleIdentifier()); +} + +inline bool VerifySizePrefixedModuleBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(ModuleIdentifier()); +} + +inline void FinishModuleBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, ModuleIdentifier()); +} + +inline void FinishSizePrefixedModuleBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, ModuleIdentifier()); +} + +} // namespace serialization +} // namespace mobile +} // namespace jit +} // namespace torch + +#endif // FLATBUFFERS_GENERATED_MOBILEBYTECODE_TORCH_JIT_MOBILE_SERIALIZATION_H_ diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/onnx.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/onnx.h new file mode 100644 index 0000000000000000000000000000000000000000..e9886690406605a5d576b232a514204cb9f2fee4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/onnx.h @@ -0,0 +1,18 @@ +#pragma once + +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED( + "-Winconsistent-missing-destructor-override") +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED("-Wsuggest-override") +C10_DIAGNOSTIC_PUSH_AND_IGNORED_IF_DEFINED( + "-Wdeprecated-dynamic-exception-spec") +#include +C10_DIAGNOSTIC_POP() +C10_DIAGNOSTIC_POP() +C10_DIAGNOSTIC_POP() +#include + +namespace torch::jit { + +TORCH_API std::string prettyPrint(const ::ONNX_NAMESPACE::ModelProto& model); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickle.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickle.h new file mode 100644 index 0000000000000000000000000000000000000000..7a8538ab270f7757360240255d648e1daef358c8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickle.h @@ -0,0 +1,140 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +/// Pickle an IValue by calling a function to handle writing the data. +/// +/// `writer` is a function that takes in a pointer to a chunk of memory and its +/// size and consumes it. +/// +/// See `jit::pickle` for more details. +TORCH_API void pickle( + std::function writer, + const IValue& ivalue, + std::vector* tensor_table = nullptr); + +/// Save a `torch::IValue` in a format compatible with Python's `pickle` module +/// +/// If present, `tensor_table` is a pointer to a table in which tensors that +/// are contained within `ivalue` are stored, and the bytes returned by the +/// pickler will only include references to these tensors in the table. This can +/// be used to keep the binary blob size small. +/// If not provided, tensors are stored in the same byte stream as the pickle +/// data, similar to `torch.save()` in eager Python. +/// +/// Pickled values can be loaded in Python and C++: +/// \rst +/// .. code-block:: cpp +/// +/// torch::IValue float_value(2.3); +/// +/// // TODO: when tensors are stored in the pickle, delete this +/// std::vector tensor_table; +/// auto data = torch::jit::pickle(float_value, &tensor_table); +/// +/// std::vector ivalues = +/// torch::jit::unpickle(data.data(), data.size()); +/// +/// .. code-block:: python +/// +/// values = torch.load('data.pkl') +/// print(values) +/// +/// \endrst +TORCH_API std::vector pickle( + const IValue& ivalue, + std::vector* tensor_table = nullptr); + +/// Save a `torch::IValue` in a format that can be loaded by both +/// `torch::pickle_load` in C++ and `torch.load` in Python. +TORCH_API std::vector pickle_save(const IValue& ivalue); + +/// Deserialize a `torch::IValue` from bytes produced by either +/// `torch::pickle_save` in C++ or `torch.save` in Python +TORCH_API IValue pickle_load(const std::vector& data); + +/// Deserialize a `torch::IValue` from bytes produced by either +/// `torch::pickle_save` in C++ or `torch.save` in Python with custom object. +TORCH_API IValue pickle_load_obj(std::string_view data); + +/// `reader` is a function that takes in a size to read from some pickled +/// binary. `reader` should remember where it last read, and return +/// the number of bytes read. +/// See `torch::pickle` for details. +/// type_resolver is used to resolve any JIT type based on type str +TORCH_API IValue unpickle( + std::function reader, + TypeResolver type_resolver, + c10::ArrayRef tensor_table, + c10::TypePtr (*type_parser)(const std::string&) = + Unpickler::defaultTypeParser, + ObjLoader obj_loader = nullptr); + +/// Decode a chunk of memory containing pickled data into its `torch::IValue`s. +/// +/// If any `torch::IValue`s in the pickled data are `Object`s, then a +/// `class_resolver` function must be provided. +/// +/// See `torch::pickle` for details. +TORCH_API IValue unpickle( + const char* data, + size_t size, + TypeResolver type_resolver = nullptr, + c10::ArrayRef tensor_table = {}, + c10::TypePtr (*type_parser)(const std::string&) = + Unpickler::defaultTypeParser); + +/// Decode a chunk of memory containing pickled data into its `torch::IValue`s. +/// +/// If any `torch::IValue`s in the pickled data are `Object`s, then a +/// `class_resolver` function must be provided. +/// +/// See `torch::pickle` for details. +TORCH_API IValue unpickle( + const char* data, + size_t size, + ObjLoader obj_loader, + TypeResolver type_resolver = nullptr, + c10::ArrayRef tensor_table = {}, + c10::TypePtr (*type_parser)(const std::string&) = + Unpickler::defaultTypeParser); + +#ifndef C10_MOBILE +class VectorReader : public caffe2::serialize::ReadAdapterInterface { + public: + VectorReader(std::vector data) : data_(std::move(data)) {} + + size_t size() const override { + return data_.size(); + } + + size_t read(uint64_t pos, void* buf, size_t n, const char* what) + const override; + + private: + std::vector data_; +}; + +class StringViewReader : public caffe2::serialize::ReadAdapterInterface { + public: + StringViewReader(std::string_view data) : data_(data) {} + + size_t size() const override { + return data_.size(); + } + + size_t read(uint64_t pos, void* buf, size_t n, const char* what) + const override; + + private: + std::string_view data_; +}; +#endif +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickler.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickler.h new file mode 100644 index 0000000000000000000000000000000000000000..9be9b0fb2d8c1d5896fdc43300827caf2baacdb0 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/pickler.h @@ -0,0 +1,425 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +// See Python's pickletools.py for a detailed description of each of these codes +enum class PickleOpCode : char { + MARK = '(', + STOP = '.', + POP = '0', + POP_MARK = '1', + DUP = '2', + FLOAT = 'F', + INT = 'I', + BININT = 'J', + BININT1 = 'K', + LONG = 'L', + BININT2 = 'M', + NONE = 'N', + PERSID = 'P', + BINPERSID = 'Q', + REDUCE = 'R', + STRING = 'S', + BINSTRING = 'T', + SHORT_BINSTRING = 'U', + // NB: Avoid using UNICODE as it is a macro in the Windows API + UNICODE_ = 'V', + BINUNICODE = 'X', + APPEND = 'a', + BUILD = 'b', + GLOBAL = 'c', + DICT = 'd', + EMPTY_DICT = '}', + APPENDS = 'e', + GET = 'g', + BINGET = 'h', + INST = 'i', + LONG_BINGET = 'j', + LIST = 'l', + EMPTY_LIST = ']', + OBJ = 'o', + PUT = 'p', + BINPUT = 'q', + LONG_BINPUT = 'r', + SETITEM = 's', + TUPLE = 't', + EMPTY_TUPLE = ')', + SETITEMS = 'u', + BINFLOAT = 'G', + + // Protocol 2 + PROTO = char('\x80'), + NEWOBJ = '\x81', + EXT1 = '\x82', + EXT2 = '\x83', + EXT4 = '\x84', + TUPLE1 = '\x85', + TUPLE2 = '\x86', + TUPLE3 = '\x87', + NEWTRUE = '\x88', + NEWFALSE = '\x89', + LONG1 = '\x8a', + LONG4 = '\x8b', + + // Protocol 3 (Python 3.x) + BINBYTES = 'B', + SHORT_BINBYTES = 'C', + + // Protocol 4 + SHORT_BINUNICODE = char('\x8c'), + BINUNICODE8 = '\x8d', + BINBYTES8 = '\x8e', + EMPTY_SET = '\x8f', + ADDITEMS = '\x90', + FROZENSET = '\x91', + NEWOBJ_EX = '\x92', + STACK_GLOBAL = '\x93', + MEMOIZE = '\x94', + FRAME = '\x95' +}; + +using ::c10::IValue; + +struct WriteableTensorData { + const char* data() const { + return static_cast(tensor_.storage().data()); + } + size_t sizeInBytes() const { + return size_; + } + size_t nbytes() const { + return tensor_.storage().nbytes(); + } + bool storageHasDeleter() const { + return tensor_.storage().data_ptr().get_context() != nullptr; + } + + private: + friend TORCH_API WriteableTensorData + getWriteableTensorData(const at::Tensor& tensor, bool to_cpu); + at::Tensor tensor_; + uint64_t size_; +}; + +void setTypeTags(bool state); +bool getTypeTags(); + +class TORCH_API Pickler { + AT_DISALLOW_COPY_AND_ASSIGN(Pickler); + + public: + Pickler(std::function writer) + : Pickler(std::move(writer), nullptr, nullptr, nullptr) {} + + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + Pickler( + std::function writer, + std::vector* tensor_table, + std::function type_renamer, + std::vector* memoized_class_types, + std::function get_tensor_id = nullptr, + bool tag_aggregates = true) + : writer_(std::move(writer)), + tensor_table_(tensor_table), + type_renamer_(std::move(type_renamer)), + memoized_class_types_(memoized_class_types), + get_tensor_id_(std::move(get_tensor_id)), + tag_aggregates_(tag_aggregates) {} + ~Pickler(); + + // Push protocol onto the stack + void protocol(); + + // Push STOP PickleOpCode onto the stack + void stop(); + + void pushIValue(const IValue& ivalue); + + void startTuple(); + void endTuple(); + + const std::vector& tensorData() { + return tensor_data_; + } + + void pushEmptyDict(); + void pushDict(const IValue& ivalue); + void pushInt(int64_t value); + void pushLong(const std::string& data); + + private: + void pushIValueImpl(const IValue& ivalue); + void startTypeTag(); + void endTypeTag(const IValue& value); + void pushBool(bool value); + void pushDouble(double value); + void pushComplexDouble(const IValue& value); + void pushGenericList(const IValue& ivalue); + void pushIntList(const IValue& ivalue); + void pushList(const IValue& ivalue); + void pushTensor(const IValue& ivalue); + void pushTensorReference(const IValue& ivalue); + void pushLiteralTensor(const IValue& ivalue); + void pushLiteralSparseTensor(const at::Tensor& tensor); + void pushTuple(const IValue& ivalue); + void pushString(const std::string& string); + void pushDevice(const IValue& ivalue); +#ifdef USE_DISTRIBUTED + void pushRRef(const IValue& ivalue); +#endif + // unmemoized version + void pushStringImpl(const std::string& string); + void pushStorageOfTensor(const at::Tensor& tensor); + + void pushBinGet(uint32_t memo_id); + void pushSpecializedList( + const IValue& ivalue, + const char* list_name, + const std::function& item_pusher); + void pushGlobal(c10::string_view module_name, c10::string_view class_name); + // raw string data is appended directly to the byte stream + void pushBytes(const std::string& string); + void pushTensorData(const at::Tensor& tensor); + + // Add a BINPUT op and return the memoization id used + size_t pushNextBinPut(); + + const void* getPointer(const IValue& ivalue); + + // Caller checks that bufferPos_ > 0 + void flushNonEmpty() { + writer_(buffer_.data(), bufferPos_); + bufferPos_ = 0; + } + + void flush() { + if (bufferPos_ != 0) { + flushNonEmpty(); + } + } + + // These convert values to bytes and add them to the stack (NB: since T is to + // the left of a '::', its type cannot be deduced by the compiler so one must + // explicitly instantiate the template, i.e. push(int) works, push(int) + // does not) + static CONSTEXPR_EXCEPT_WIN_CUDA size_t kBufferSize = 256; + template + void push(std::common_type_t value) { + const char* begin = reinterpret_cast(&value); + if (bufferPos_ + sizeof(T) > buffer_.size()) { + flushNonEmpty(); + } + static_assert(sizeof(T) <= kBufferSize, "Buffer size assumption"); + memcpy(buffer_.data() + bufferPos_, begin, sizeof(T)); + bufferPos_ += sizeof(T); + } + + // Stream to write binary data to + // Code shouldn't call writer_ directly without first flushing. + std::function writer_; + + // Buffer to avoid calling a writer_ on a per-byte basis. + std::array buffer_; + size_t bufferPos_{0}; + + // Stack of opcodes/data + std::vector stack_; + + // External table of tensors to serialize. If this is missing, then tensors + // are serialized directly into the pickle + std::vector* tensor_table_; + + // TODO: only use this if necessary (add a pass to find all shared ivalues, + // and only memoize those) + uint32_t memo_id_ = 0; + + // Memoization of IValues that have been written (index in table is used for + // BINPUT opcodes) to enable shared references + c10::FastMap memoized_ivalue_map_; + + // because we de-dup ivalues based on their raw pointer address in the above + // map we need to keep all the memoized values alive during the pickle. + // Otherwise, it is possible that a raw address gets reused for another + // object, and we will alias it to the old object at that address. + std::vector memoized_ivalues_; + + std::function type_renamer_; + + // List of all the types that it wrote, inspect from the IValues it wrote. + std::vector* memoized_class_types_; + + // Function to grab next id_name for tensor storage, function is responsible + // for returning unique ids + std::function get_tensor_id_; + + // List of tensor storages to serialize in the same binary as the pickle data + // similar to ivalues, they are memoized using BINPUT + std::vector tensor_data_; + c10::FastMap memoized_storage_map_; + + c10::FastMap memoized_globals_map_; + c10::FastMap memoized_strings_map_; + c10::FastMap memoized_devices_map_; + // when true, List and Dict objects will be wrapped in a + // torch.jit._pickle.restore_type_tag call to correctly set the dynamic + // TorchScript type for the object. When true the thing unpickling must have + // torch installed. + bool tag_aggregates_; +}; + +// returns a (tensor, record_size) for a tensor, converting it to a CPU tensor +// if it was CUDA and to_cpu is True. +TORCH_API WriteableTensorData +getWriteableTensorData(const at::Tensor& tensor, bool to_cpu = true); + +// return the value of the tensor's storage pointer +uint64_t getStorageKey(const at::Tensor& tensor); + +// if the cls has __getstate__/__setstate__ +// assert they have the right schema and return true, +// otherwise return false +bool checkHasValidSetGetState(const std::shared_ptr& cls); + +// Declare BackendMeta serialization and deserialization function pointer types. +using BackendMetaPtr = std::function< + void(const at::Tensor&, std::unordered_map&)>; + +// A allowlist of device type, currently available is PrivateUse1 +inline std::unordered_set& GetBackendMetaAllowlist() { + static std::unordered_set DeviceTypeAllowlist{ + c10::DeviceType::PrivateUse1}; + return DeviceTypeAllowlist; +} + +// Dynamically obtain serialization function pairs +// that require the corresponding backend. +inline std::array< + std::optional>, + at::COMPILE_TIME_MAX_DEVICE_TYPES>& +GetBackendMetaSerialization() { + // The array to save function pointer for BackendMeta serialization. + // key is the DeviceType, value is std::pair obj. + // value.first represent get function and value.seconde represent set function + static std::array< + std::optional>, + at::COMPILE_TIME_MAX_DEVICE_TYPES> + BackendMetaSerialization; + return BackendMetaSerialization; +} + +// Register function pointer of Tensor BackendMetadata for serialization. +TORCH_API inline void TensorBackendMetaRegistry( + c10::DeviceType t, + const BackendMetaPtr& get_fptr, + const BackendMetaPtr& set_fptr) { + // allowlist verification + // Only if the devicetype is in the allowlist, + // we allow the serialization extension to be registered for backendmeta data. + const auto& DeviceTypeAllowlist = GetBackendMetaAllowlist(); + TORCH_CHECK( + DeviceTypeAllowlist.find(t) != DeviceTypeAllowlist.end(), + "It is not allowed to register the serialization method ", + "of backendMeta data for PrivateUse1. ", + "If you have related serialization requirements, ", + "please expand the allowlist"); + // Register function pointer + int device_type = static_cast(t); + auto& BackendMetaSerialization = GetBackendMetaSerialization(); + TORCH_CHECK( + !BackendMetaSerialization[device_type].has_value(), + "The tensor BackendMeta serialization function pointer for ", + t, + " has been registered."); + BackendMetaSerialization[device_type] = + std::optional>( + std::make_pair(get_fptr, set_fptr)); +} + +// Return a map of Tensor Metadata which including BackendMetaData for +// serialization. For now, it only takes care of `conj` and `neg` bit. +inline std::unordered_map getTensorMetadata( + const at::Tensor& t) { + // We don't support serializing `ZeroTensor` as it is not public + // facing yet. + TORCH_CHECK( + !t._is_zerotensor(), + "ZeroTensor is not serializable,", + " please file an issue if required."); + std::unordered_map metadata{}; + + // Only add meta-data if the value is not default. + if (t.is_conj()) { + metadata["conj"] = true; + } + if (t.is_neg()) { + metadata["neg"] = true; + } + // Only add BackendMetaData for custom backend if the function pointer is + // registered. + int device_type = static_cast(t.device().type()); + const auto& BackendMetaSerialization = GetBackendMetaSerialization(); + if (BackendMetaSerialization[device_type].has_value()) { + // Pass the tensor and metadata map references as parameters to the custom + // serialization function. + BackendMetaPtr fptr = BackendMetaSerialization[device_type].value().first; + fptr(t, metadata); + } + return metadata; +} + +// set Tensor Metadata based on the map. +// Refer: getTensorMetadata +inline void setTensorMetadata( + const at::Tensor& t, + std::unordered_map metadata) { + auto iter_end = metadata.end(); + auto iter_temp = metadata.find("conj"); + if (iter_temp != iter_end) { + t._set_conj(true); + metadata.erase(iter_temp); + } + iter_temp = metadata.find("neg"); + if (iter_temp != iter_end) { + t._set_neg(true); + metadata.erase(iter_temp); + } + // Only set BackendMetaData for custom backend if the function pointer is + // registered. + int device_type = static_cast(t.device().type()); + const auto& BackendMetaSerialization = GetBackendMetaSerialization(); + if (BackendMetaSerialization[device_type].has_value()) { + // Pass the tensor and metadata map references as parameters to the custom + // deserialization function. + BackendMetaPtr fptr = BackendMetaSerialization[device_type].value().second; + fptr(t, metadata); + } +} + +// set Tensor metadata based on the map. +// NOTE: This overload is required by unpickler.cpp +inline void setTensorMetadata( + const at::Tensor& t, + const c10::Dict& metadata_idict) { + std::unordered_map metadata; + for (auto& pair : metadata_idict) { + auto key = *pair.key().toString(); + metadata[key] = pair.value().toBool(); + } + setTensorMetadata(t, std::move(metadata)); +} + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/python_print.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/python_print.h new file mode 100644 index 0000000000000000000000000000000000000000..e877fd48a0027286dd64707cbe28355a33c85837 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/python_print.h @@ -0,0 +1,56 @@ +#pragma once +#include +#include +#include +#include + +namespace torch::jit { + +struct Method; +struct Module; +struct PythonPrintImpl; + +struct PrintDepsTable { + void add(const c10::NamedTypePtr& type); + + size_t size() const { + return table_.size(); + } + + const c10::NamedTypePtr& operator[](size_t index) const { + return table_[index]; + } + + private: + std::vector table_; + std::unordered_set non_unique_; +}; + +struct TORCH_API PythonPrint { + PythonPrint( + std::vector& constant_table, + PrintDepsTable& deps_table, + c10::TypePrinter type_printer = nullptr, + bool enforce_importable = false); + + void printNamedType(const c10::NamedTypePtr& classType); + void printFunction(const Function& callee); + void printMethod(const Function& callee); + + std::string str() const; + const SourceRangeRecords& ranges() const; + uint64_t minVersion() const; + + private: + std::shared_ptr pImpl; +}; + +TORCH_API bool printerHasSpecialCaseFor(c10::Symbol sym); + +TORCH_API void jitModuleToPythonCodeAndConstants( + const Module& module, + ExtraFilesMap* jit_sources, // output + std::vector* constants // output +); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization.h new file mode 100644 index 0000000000000000000000000000000000000000..ac6c604b8f71e1890bfe38b51ba179fbcaa10b2e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization.h @@ -0,0 +1,66 @@ +#pragma once + +#include +#include + +#include + +#include +#include + +namespace c10 { +struct IValue; +} + +namespace torch::jit { + +class Pickler; +class SourceRangeSerializer; +static constexpr size_t kByteOffsetIndex = 0; +static constexpr size_t kSourceRangeIndex = 1; +static constexpr size_t kSourceRangeTagIndex = 2; +constexpr c10::string_view kFormatWithStringTable = "FORMAT_WITH_STRING_TABLE"; + +class SourceRangePickler { + public: + SourceRangePickler(); + + std::vector pickle( + const SourceRangeRecords& ranges, + const SourceRangeTagMap& source_range_tags); + + private: + std::shared_ptr srs; +}; + +class SourceRangeDeserializer { + public: + SourceRangeDeserializer() = default; + explicit SourceRangeDeserializer(const c10::IValue& text_table) { + for (const auto& x : text_table.toTuple()->elements()) { + text_table_.emplace_back(std::make_shared(x.toStringRef())); + } + } + SourceRange deserialize(const c10::IValue& iv); + + private: + std::shared_ptr deserialize_source(const c10::IValue& iv); + std::unordered_map< + c10::intrusive_ptr, + std::shared_ptr> + cached_sources; + std::vector> text_table_; +}; + +class SourceRangeUnpickler { + public: + virtual std::optional findSourceRangeThatGenerated( + const SourceRange& range) = 0; + + virtual ~SourceRangeUnpickler() = default; +}; + +TORCH_API void setShouldUseFormatWithStringTable( + bool should_use_format_with_string_table); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization_impl.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..43903958d8f799158ba59c658f5ffcba60b56736 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization_impl.h @@ -0,0 +1,28 @@ +#pragma once + +#include + +namespace torch::jit { + +// Do this clownyness with virtual functions because of the split +// between ATen core and torch + +class ConcreteSourceRangeUnpickler : public SourceRangeUnpickler { + public: + ConcreteSourceRangeUnpickler(at::DataPtr&& data, size_t size); + + std::optional findSourceRangeThatGenerated( + const SourceRange& range) override; + + private: + at::DataPtr data; + size_t size; + + void unpickle(); + + std::mutex mutex; + std::shared_ptr deserializer; + std::shared_ptr unpickled_records; +}; + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/storage_context.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/storage_context.h new file mode 100644 index 0000000000000000000000000000000000000000..b44508107bae4e1aa065429d4bb3d449dced319a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/storage_context.h @@ -0,0 +1,83 @@ +#pragma once + +#include + +namespace torch::jit { + +// Used in torch.package and TorchScript serialization to coordinate +// sharing of storages between models. Also used to create deterministic +// naming for storages. +class TORCH_API SerializationStorageContext { + public: + explicit SerializationStorageContext() = default; + SerializationStorageContext operator=(const SerializationStorageContext&) = + delete; + SerializationStorageContext(const SerializationStorageContext&) = delete; + + uint64_t getOrAddStorage(const c10::Storage& storage) { + if (!hasStorage(storage)) { + uint64_t size = storage_id_map_.size(); + storage_id_map_[storage] = size; + } + return storage_id_map_[storage]; + } + + bool hasStorage(const c10::Storage& storage) { + return storage_id_map_.find(storage) != storage_id_map_.end(); + } + + ~SerializationStorageContext() = default; + + private: + class StorageSerializationHash { + public: + size_t operator()(const c10::Storage& storage) const { + return std::hash()( + reinterpret_cast(storage.unsafeGetStorageImpl())); + } + }; + + class StorageSerializationEqual { + public: + bool operator()(const c10::Storage& lhs, const c10::Storage& rhs) const { + return lhs.unsafeGetStorageImpl() == rhs.unsafeGetStorageImpl(); + } + }; + + std::unordered_map< + c10::Storage, + uint64_t, + StorageSerializationHash, + StorageSerializationEqual> + storage_id_map_; +}; + +// Used in torch.package and TorchScript deserialization to coordinate +// sharing of storages between models. +class TORCH_API DeserializationStorageContext { + public: + explicit DeserializationStorageContext() = default; + DeserializationStorageContext operator=( + const DeserializationStorageContext&) = delete; + DeserializationStorageContext(const DeserializationStorageContext&) = delete; + + void addStorage(std::string name, c10::Storage storage) { + TORCH_INTERNAL_ASSERT(!hasStorage(name)); + name_storage_map_.emplace(std::move(name), std::move(storage)); + } + + bool hasStorage(const std::string& name) { + return name_storage_map_.find(name) != name_storage_map_.end(); + } + + c10::Storage getStorage(const std::string& name) { + TORCH_INTERNAL_ASSERT(hasStorage(name)); + return name_storage_map_.find(name)->second; + } + ~DeserializationStorageContext() = default; + + private: + std::unordered_map name_storage_map_; +}; + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/type_name_uniquer.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/type_name_uniquer.h new file mode 100644 index 0000000000000000000000000000000000000000..78eea7755fe081a64178654f4daf624868595ce5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/type_name_uniquer.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include + +namespace torch::jit { + +/** + * class TypeNameUniquer + * + * Generates a unique name for every type `t` passed in. Types that compare + * equal with EqualType will receive the same unique name. + * + * This is used during Module::save(), to resolve type name collisions during + * serialization. + */ +class TORCH_API TypeNameUniquer { + public: + c10::QualifiedName getUniqueName(c10::ConstNamedTypePtr t); + + private: + NameMangler mangler_; + std::unordered_set used_names_; + std::unordered_map< + c10::ConstNamedTypePtr, + c10::QualifiedName, + HashType, + EqualType> + name_map_; +}; +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/unpickler.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/unpickler.h new file mode 100644 index 0000000000000000000000000000000000000000..aea91ebe80c50497bfbd079801f3201f2e9a28fd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/unpickler.h @@ -0,0 +1,201 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace torch::jit { + +using TypeResolver = + std::function; + +using ObjLoader = std::function< + c10::intrusive_ptr(const at::StrongTypePtr&, IValue)>; + +class DeserializationStorageContext; + +// [unpickler refactor] there is some cruft around PickleOpCode::BUILD, +// PickleOpCode::NEWOBJ, and the last_opcode_ member below that should be +// deleted at some point, the Pickler doesn't produce it and it's only around to +// support models saved before 1.1 +class TORCH_API Unpickler { + AT_DISALLOW_COPY_AND_ASSIGN(Unpickler); + + using TypeParserT = c10::TypePtr (*)(const std::string&); + + public: + // tensors inside the pickle are references to the tensor_table. + // class_resolver is to resolve strong class type, type_resolver_ is + // to resolve any JIT type. class_resolver and type_resolver are not merged + // here because some use cases need to get strong class type that + // type_resolver_ can not return. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + Unpickler( + std::function reader, + TypeResolver type_resolver, + c10::ArrayRef tensor_table, + TypeParserT type_parser = defaultTypeParser) + : reader_(std::move(reader)), + tensor_table_(tensor_table), + type_resolver_(std::move(type_resolver)), + use_storage_device_(false), + type_parser_(type_parser), + version_(caffe2::serialize::kProducedFileFormatVersion) {} + + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + Unpickler( + std::function reader, + TypeResolver type_resolver, + c10::ArrayRef tensor_table, + ObjLoader obj_loader, + TypeParserT type_parser = defaultTypeParser) + : reader_(std::move(reader)), + tensor_table_(tensor_table), + type_resolver_(std::move(type_resolver)), + obj_loader_(std::move(obj_loader)), + use_storage_device_(false), + type_parser_(type_parser), + version_(caffe2::serialize::kProducedFileFormatVersion) {} + + // tensors inside the pickle contain meta-data, the raw tensor + // dead is retrieved by calling `read_record`. + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-member-init) + Unpickler( + std::function reader, + TypeResolver type_resolver, + ObjLoader obj_loader, + std::function read_record, + std::optional device, + bool use_storage_device = false, + TypeParserT type_parser = defaultTypeParser, + std::shared_ptr storage_context = nullptr) + : reader_(std::move(reader)), + tensor_table_(), + type_resolver_(std::move(type_resolver)), + obj_loader_(std::move(obj_loader)), + read_record_(std::move(read_record)), + device_(device), + use_storage_device_(use_storage_device), + type_parser_(type_parser), + storage_context_(std::move(storage_context)), + version_(caffe2::serialize::kProducedFileFormatVersion) {} + + // consume the pickle stream, producing an IValue from the contents. + // Type Tags: the pickler will restore the type tags on + // List and Dict objects when possible IValue is an Object. + // Otherwise, Dict and List objects will end up with Any as their tag. + // If you know the type of the ivalue, tags can be restored with + // restoreAccurateTypeTags + IValue parse_ivalue(); + + // [type tag serialization] + // This is used to determine whether to restore type tags be recursively + // descending into the returned stack object (if version_number <= 2), or + // if version_number >= 3, to use the type strings included in the pickle + // archive for container types. By default this is set to + // `kProducedFileFormatVersion` so unless you're loading a pickle file + // from alongside a corresponding `version` file, you don't need to set + // the version manually. + void set_version(uint64_t version_number) { + version_ = version_number; + } + + static c10::TypePtr defaultTypeParser(const std::string& str) { + ScriptTypeParser parser; + return parser.parseType(str); + } + + private: + // No arguments ensures that a template argument must be specified + // so that the number of bytes read / type read is explicit + template + T read() { + T item; + if (sizeof(T) <= buffer_remaining_) { + // Fast path: entirely from buffer. + memcpy(&item, buffer_.data() + buffer_pos_, sizeof(T)); + buffer_remaining_ -= sizeof(T); + buffer_pos_ += sizeof(T); + } else { + // Don't over-template the slow path, to avoid code size bloat. + readSlowWithBuffer(reinterpret_cast(&item), sizeof(T)); + } + return item; + } + void readSlowWithBuffer(char* dest, size_t sz); + std::string readBytes(size_t num_bytes); + + double readFloat(); + void readGlobal( + const std::string& module_name, + const std::string& class_name); + void rebuildTensor(bool quantized); + void rebuildTensorFromTypeV2(); + void rebuildSparseTensor(); +#ifdef USE_DISTRIBUTED + void rebuildRRef(); +#endif + PickleOpCode readInstruction(); + PickleOpCode readOpCode() { + return static_cast(read()); + } + std::string readString(); + void readList(IValue list_ivalue); + void readListElements(IValue list_ivalue, size_t start); + void setInput(size_t memo_id); + void run(); + + // Returns the number of bytes read. This should statefully + // remember the position. Don't call reader_ directly. + std::function reader_; + // Small buffer to avoid calling reader_ on a per-byte basis. + std::array buffer_; + size_t buffer_pos_{0}; + size_t buffer_remaining_{0}; + + std::vector stack_; + + // globals are represented on the stack as IValue integer indices + // into this list + std::vector> globals_; + std::vector memo_table_; + std::vector marks_; + c10::ArrayRef tensor_table_; + + // When deserializing types on lists and dicts, cache the type here + // so we don't have to parse the same type multiple times. Strings + // are already de-duplicated and replaced with BINGETs in the + // pickler, so we can just use the actual data pointer of each string. + std::unordered_map type_cache_; + + // optionally nullptr, needs to be present for creating classes + TypeResolver type_resolver_; + ObjLoader obj_loader_; + IValue empty_tuple_; + + std::function read_record_; + std::optional device_; + // When set to true, Unpickler will ignore the pickled device and use the + // device of the DataPtr returned by the read_record_ function. The default + // value of this flag is false. + const bool use_storage_device_; + + TypeParserT type_parser_{defaultTypeParser}; + + // Used for torch.package to enable sharing of storages across + // ScriptModules and eager modules + std::shared_ptr storage_context_; + + // See [type tag serialization] + uint64_t version_; + + // See [NOTE] skip_next_read_global + uint8_t skip_next_read_global = 0; +}; + +void restoreAccurateTypeTags(const IValue& root, const c10::TypePtr& type_tag); + +} // namespace torch::jit diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/byte_order.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/byte_order.h new file mode 100644 index 0000000000000000000000000000000000000000..7fdbe4da8fe44f20c0e7507c0828800876017487 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/byte_order.h @@ -0,0 +1,216 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __FreeBSD__ +#include +#include +#define thp_bswap16(x) bswap16(x) +#define thp_bswap32(x) bswap32(x) +#define thp_bswap64(x) bswap64(x) +#elif defined(__APPLE__) +#include +#define thp_bswap16(x) OSSwapInt16(x) +#define thp_bswap32(x) OSSwapInt32(x) +#define thp_bswap64(x) OSSwapInt64(x) +#elif defined(__GNUC__) && !defined(__MINGW32__) +#include +#define thp_bswap16(x) bswap_16(x) +#define thp_bswap32(x) bswap_32(x) +#define thp_bswap64(x) bswap_64(x) +#elif defined _WIN32 || defined _WIN64 +#define thp_bswap16(x) _byteswap_ushort(x) +#define thp_bswap32(x) _byteswap_ulong(x) +#define thp_bswap64(x) _byteswap_uint64(x) +#endif + +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#define to_be16(x) thp_bswap16(x) +#define from_be16(x) thp_bswap16(x) +#define to_be32(x) thp_bswap32(x) +#define from_be32(x) thp_bswap32(x) +#define to_be64(x) thp_bswap64(x) +#define from_be64(x) thp_bswap64(x) +#define to_le16(x) (x) +#define from_le16(x) (x) +#define to_le32(x) (x) +#define from_le32(x) (x) +#define to_le64(x) (x) +#define from_le64(x) (x) +#elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +#define to_be16(x) (x) +#define from_be16(x) (x) +#define to_be32(x) (x) +#define from_be32(x) (x) +#define to_be64(x) (x) +#define from_be64(x) (x) +#define to_le16(x) thp_bswap16(x) +#define from_le16(x) thp_bswap16(x) +#define to_le32(x) thp_bswap32(x) +#define from_le32(x) thp_bswap32(x) +#define to_le64(x) thp_bswap64(x) +#define from_le64(x) thp_bswap64(x) +#else +#error Unexpected or undefined __BYTE_ORDER__ +#endif + +namespace torch::utils { + +enum THPByteOrder { THP_LITTLE_ENDIAN = 0, THP_BIG_ENDIAN = 1 }; + +TORCH_API THPByteOrder THP_nativeByteOrder(); + +TORCH_API void THP_decodeInt16Buffer( + int16_t* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeInt32Buffer( + int32_t* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeInt64Buffer( + int64_t* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeHalfBuffer( + c10::Half* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeFloatBuffer( + float* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeDoubleBuffer( + double* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeBoolBuffer(bool* dst, const uint8_t* src, size_t len); +TORCH_API void THP_decodeBFloat16Buffer( + at::BFloat16* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeComplexFloatBuffer( + c10::complex* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); +TORCH_API void THP_decodeComplexDoubleBuffer( + c10::complex* dst, + const uint8_t* src, + bool do_byte_swap, + size_t len); + +TORCH_API void THP_decodeInt16Buffer( + int16_t* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeInt32Buffer( + int32_t* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeInt64Buffer( + int64_t* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeHalfBuffer( + c10::Half* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeFloatBuffer( + float* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeDoubleBuffer( + double* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeBFloat16Buffer( + at::BFloat16* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeFloat8_e5m2Buffer( + at::Float8_e5m2* dst, + const uint8_t* src, + size_t len); +TORCH_API void THP_decodeFloat8_e4m3fnBuffer( + at::Float8_e4m3fn* dst, + const uint8_t* src, + size_t len); +TORCH_API void THP_decodeFloat8_e5m2fnuzBuffer( + at::Float8_e5m2fnuz* dst, + const uint8_t* src, + size_t len); +TORCH_API void THP_decodeFloat8_e4m3fnuzBuffer( + at::Float8_e4m3fnuz* dst, + const uint8_t* src, + size_t len); +TORCH_API void THP_decodeComplexFloatBuffer( + c10::complex* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_decodeComplexDoubleBuffer( + c10::complex* dst, + const uint8_t* src, + THPByteOrder order, + size_t len); + +TORCH_API void THP_encodeInt16Buffer( + uint8_t* dst, + const int16_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeInt32Buffer( + uint8_t* dst, + const int32_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeInt64Buffer( + uint8_t* dst, + const int64_t* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeFloatBuffer( + uint8_t* dst, + const float* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeDoubleBuffer( + uint8_t* dst, + const double* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeComplexFloatBuffer( + uint8_t* dst, + const c10::complex* src, + THPByteOrder order, + size_t len); +TORCH_API void THP_encodeComplexDoubleBuffer( + uint8_t* dst, + const c10::complex* src, + THPByteOrder order, + size_t len); + +} // namespace torch::utils diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/disable_torch_function.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/disable_torch_function.h new file mode 100644 index 0000000000000000000000000000000000000000..9331c521b18362abb38e4f8da1cc763542b9443a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/disable_torch_function.h @@ -0,0 +1,45 @@ +#pragma once +#include +#include +#include + +namespace torch { +// Sometimes we don't want infinite recursion for subclasses, +// Or a way to achieve the old behaviour. + +// This is an internal utility, not exposed to users. +bool torch_function_enabled(); +PyObject* disabled_torch_function_impl(); +PyObject* disabled_torch_dispatch_impl(); +void set_disabled_torch_function_impl(PyObject* value); +void set_disabled_torch_dispatch_impl(PyObject* value); +// Set ignore_mode to true if you're trying to collect overloaded arguments; +// using mode here will improperly cause you to add ALL objects to the +// overloaded list even if they don't actually have __torch_function__ +bool check_has_torch_function(PyObject* obj, bool ignore_mode = false); + +struct DisableTorchDispatch { + DisableTorchDispatch() + : guard_(c10::DispatchKeySet( + {c10::DispatchKey::Python, c10::DispatchKey::PreDispatch})), + guard_tls_snapshot_(c10::DispatchKey::PythonTLSSnapshot) {} + c10::impl::ExcludeDispatchKeyGuard guard_; + c10::impl::ExcludeDispatchKeyGuard guard_tls_snapshot_; +}; + +} // namespace torch + +PyObject* THPModule_isEnabledTorchFunction(PyObject* self, PyObject* unused); +PyObject* THPModule_isAllDisabledTorchFunction( + PyObject* self, + PyObject* unused); +PyObject* THPModule_DisableTorchFunctionType(); +PyObject* THPModule_DisableTorchFunctionSubclassType(); +PyObject* THPModule_disable_torch_function(PyObject* self, PyObject* args); +PyObject* THPModule_disable_torch_dispatch(PyObject* self, PyObject* args); +PyObject* THPModule_has_torch_function(PyObject*, PyObject* arg); +PyObject* THPModule_has_torch_function_unary(PyObject*, PyObject* obj); +PyObject* THPModule_has_torch_function_variadic( + PyObject*, + PyObject* const* args, + Py_ssize_t nargs); diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/schema_info.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/schema_info.h new file mode 100644 index 0000000000000000000000000000000000000000..18aaa9bc7d35fc93bbe7b0f0a3e24023c97445ea --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/schema_info.h @@ -0,0 +1,115 @@ +#pragma once + +#include +#include + +namespace torch::utils { + +using SchemaSpecialCasePair = + std::pair>; +/** + * class SchemaInfo + * + * FunctionSchema wrapper that publicizes argument value specific operator + * behavior (mutation, aliasing, special cases, etc...) + */ + +struct TORCH_API SchemaInfo { + public: + explicit SchemaInfo(c10::FunctionSchema schema) + : schema_(std::move(schema)), + alias_maps_current_(false), + has_init_(false) {} + explicit SchemaInfo(const char* signature) + : schema_(torch::jit::parseSchema(signature)), + alias_maps_current_(false), + has_init_(false) {} + + bool is_mutable(); + + bool is_mutable(const c10::SchemaArgument& argument); + + bool is_mutable(c10::string_view name); + + bool has_argument(c10::string_view name); + + bool is_nondeterministic() const; + + // Returns whether lhs and rhs may alias directly. + // This does not account for cases where lhs or rhs are a container that + // may contain elements that alias the other argument. + // Besides the checks already included in FunctionSchema::may_alias, this + // method also accounts special aliasing cases causes by aliasing argument + // values supplied from addArgumentValue. + bool may_alias( + const c10::SchemaArgument& lhs, + const c10::SchemaArgument& rhs); + + // Returns whether lhs and rhs may alias directly or whether lhs/rhs are a + // container that may contain elements that alias the other argument. Besides + // the checks already included in FunctionSchema::may_contain_alias, this + // method also accounts for special aliasing cases causes by aliasing argument + // values supplied from addArgumentValue. bidirectional = false only returns + // whether lhs may contain an alias of rhs while bidirectional = true returns + // both directions. + bool may_contain_alias( + const c10::SchemaArgument& lhs, + const c10::SchemaArgument& rhs, + bool bidirectional = true); + + void addArgumentValue(const std::string& name, const at::IValue& value); + + void addArgumentValues( + const std::vector>& value_list); + + void addArgumentValues( + const std::unordered_map& values); + + bool hasInputArgumentNamed(const std::string& name) const; + + private: + // This function enforces more conservative results when the TORCH_WARN is + // triggered from above due to duplicates in an argument list + void ensureConservativity( + const std::unordered_set& duplicates, + const std::vector& arguments_list, + c10::SchemaArgType type); + + void initSchemaInfo(); + + void generateAliasMaps(); + + bool mayContainAliasImpl( + const c10::SchemaArgument& lhs, + const c10::SchemaArgument& rhs); + + static std::vector getNonDeterministicOps(); + + static std::vector getTrainingOps(); + + const std::unordered_set& wildcardSet(); + + const std::unordered_set& containerSet(); + + // Set of all wildcard arguments + std::unordered_set wildcard_set_; + + // Set of all container arguments + std::unordered_set container_set_; + + // Map of argument IValues + std::unordered_map value_map_; + + // Alias map of inputs with each other + std::vector> input_alias_map_; + + // Alias map of outputs to inputs + std::vector> output_alias_map_; + + const c10::FunctionSchema schema_; + + bool alias_maps_current_; + + bool has_init_; +}; +} // namespace torch::utils diff --git a/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_apply.h b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_apply.h new file mode 100644 index 0000000000000000000000000000000000000000..0e721542fe69c7edbba5e5878872865489e5edba --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/torch/csrc/utils/tensor_apply.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include + +namespace torch::utils { + +const at::Tensor& apply_(const at::Tensor& self, PyObject* fn); +const at::Tensor& map_( + const at::Tensor& self, + const at::Tensor& other_, + PyObject* fn); +const at::Tensor& map2_( + const at::Tensor& self, + const at::Tensor& x_, + const at::Tensor& y_, + PyObject* fn); + +} // namespace torch::utils