diff --git a/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/INSTALLER b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/LICENSE b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..62b076cdee58ec8f34034141ba0befd9015b0c7e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/LICENSE @@ -0,0 +1,20 @@ +This package contains a modified version of ca-bundle.crt: + +ca-bundle.crt -- Bundle of CA Root Certificates + +This is a bundle of X.509 certificates of public Certificate Authorities +(CA). These were automatically extracted from Mozilla's root certificates +file (certdata.txt). This file can be found in the mozilla source tree: +https://hg.mozilla.org/mozilla-central/file/tip/security/nss/lib/ckfw/builtins/certdata.txt +It contains the certificates in PEM format and therefore +can be directly used with curl / libcurl / php_curl, or with +an Apache+mod_ssl webserver for SSL client authentication. +Just configure this file as the SSLCACertificateFile.# + +***** BEGIN LICENSE BLOCK ***** +This Source Code Form is subject to the terms of the Mozilla Public License, +v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain +one at http://mozilla.org/MPL/2.0/. + +***** END LICENSE BLOCK ***** +@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $ diff --git a/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/METADATA b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c4809863b70ece27fd21287a96f755db20cccbc0 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/METADATA @@ -0,0 +1,68 @@ +Metadata-Version: 2.1 +Name: certifi +Version: 2024.12.14 +Summary: Python package for providing Mozilla's CA Bundle. +Home-page: https://github.com/certifi/python-certifi +Author: Kenneth Reitz +Author-email: me@kennethreitz.com +License: MPL-2.0 +Project-URL: Source, https://github.com/certifi/python-certifi +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0) +Classifier: Natural Language :: English +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Requires-Python: >=3.6 +License-File: LICENSE + +Certifi: Python SSL Certificates +================================ + +Certifi provides Mozilla's carefully curated collection of Root Certificates for +validating the trustworthiness of SSL certificates while verifying the identity +of TLS hosts. It has been extracted from the `Requests`_ project. + +Installation +------------ + +``certifi`` is available on PyPI. Simply install it with ``pip``:: + + $ pip install certifi + +Usage +----- + +To reference the installed certificate authority (CA) bundle, you can use the +built-in function:: + + >>> import certifi + + >>> certifi.where() + '/usr/local/lib/python3.7/site-packages/certifi/cacert.pem' + +Or from the command line:: + + $ python -m certifi + /usr/local/lib/python3.7/site-packages/certifi/cacert.pem + +Enjoy! + +.. _`Requests`: https://requests.readthedocs.io/en/master/ + +Addition/Removal of Certificates +-------------------------------- + +Certifi does not support any addition/removal or other modification of the +CA trust store content. This project is intended to provide a reliable and +highly portable root of trust to python deployments. Look to upstream projects +for methods to use alternate trust. diff --git a/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/RECORD b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..4f31be3ef2259f7e5f5cb05bb1ecb925b50e4f2d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/RECORD @@ -0,0 +1,15 @@ +certifi-2024.12.14.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +certifi-2024.12.14.dist-info/LICENSE,sha256=6TcW2mucDVpKHfYP5pWzcPBpVgPSH2-D8FPkLPwQyvc,989 +certifi-2024.12.14.dist-info/METADATA,sha256=z71eRGTFszr4qsHenZ_vG2Fd5bV9PBWmJgShthc8IkY,2274 +certifi-2024.12.14.dist-info/RECORD,, +certifi-2024.12.14.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +certifi-2024.12.14.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91 +certifi-2024.12.14.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8 +certifi/__init__.py,sha256=LqjNcwt1sYSS3uhPXrf6jJzVCuHtNVpuirg5rb7mVm8,94 +certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243 +certifi/__pycache__/__init__.cpython-310.pyc,, +certifi/__pycache__/__main__.cpython-310.pyc,, +certifi/__pycache__/core.cpython-310.pyc,, +certifi/cacert.pem,sha256=gHiXJU84Oif0XkT0llbzeKurIUHt5DpK08JCCll90j8,294769 +certifi/core.py,sha256=qRDDFyXVJwTB_EmoGppaXU_R9qCZvhl-EzxPMuV3nTA,4426 +certifi/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/REQUESTED b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/WHEEL b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..ae527e7d64811439e61b93aa375defb30e06edfe --- /dev/null +++ b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (75.6.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/top_level.txt b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..963eac530b9bc28d704d1bc410299c68e3216d4d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/certifi-2024.12.14.dist-info/top_level.txt @@ -0,0 +1 @@ +certifi diff --git a/vllm/lib/python3.10/site-packages/llvmlite/__init__.py b/vllm/lib/python3.10/site-packages/llvmlite/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e44e9d156619faa3b3623f025a35d9e815fe4445 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/__init__.py @@ -0,0 +1,3 @@ +from ._version import get_versions +__version__ = get_versions()['version'] +del get_versions diff --git a/vllm/lib/python3.10/site-packages/llvmlite/_version.py b/vllm/lib/python3.10/site-packages/llvmlite/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..95e0f30140f5a3c2c5de0bb200e13d2a4ebf176c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/_version.py @@ -0,0 +1,11 @@ + +# This file was generated by 'versioneer.py' (0.14) from +# revision-control system data, or from the parent directory name of an +# unpacked source archive. Distribution tarballs contain a pre-generated copy +# of this file. + +version_version = '0.43.0' +version_full = '6c786059354260a0ae93f9d0144d4016ab3d63b4' +def get_versions(default={}, verbose=False): + return {'version': version_version, 'full': version_full} + diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__init__.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..efc234075c0fa46ae1b828cb82e07f85f4336e90 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/__init__.py @@ -0,0 +1,18 @@ +""" +Things that rely on the LLVM library +""" +from .dylib import * +from .executionengine import * +from .initfini import * +from .linker import * +from .module import * +from .options import * +from .passmanagers import * +from .targets import * +from .transforms import * +from .value import * +from .typeref import * +from .analysis import * +from .object_file import * +from .context import * +from .orcjit import * diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5af67986b710413f8d087fb7d6cb5255955e4c63 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/analysis.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/analysis.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa834ebd4f9e39c22f12c0e938f5b20906384e96 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/analysis.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/common.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c611eaf1b389ec54a84189bd566aa88ee0fc551 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/common.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/context.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/context.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39d75662321870c8ba0e60e53dd26b5573f680a2 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/context.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/dylib.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/dylib.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d98c887ca440c16c9e0f9fd571aad5ebb5853b2 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/dylib.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/executionengine.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/executionengine.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a2393763474c18b897d63a44ba245a39987d2c3 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/executionengine.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/ffi.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/ffi.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a875af0e66767ef329d25ba8fc331b09c7887e98 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/ffi.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/initfini.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/initfini.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4a6ca4da2ff79f4f1849e847bb1112c3637d057 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/initfini.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/linker.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/linker.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b6fe2be0afea878d6cc94dc57dbb751ef7b8cca Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/linker.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/module.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/module.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd7836a2c33dd2703124af24e07329e3cc9defc7 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/module.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/object_file.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/object_file.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b6ff4a03f6c9886d01281e5dee1237fccdd2196 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/object_file.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/options.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/options.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27d0839d4cb4a614caaafd4eb198322e8be44b02 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/options.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/orcjit.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/orcjit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c28fddb80f6f4a174b3733eac13ec56ac2d3aa46 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/orcjit.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/passmanagers.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/passmanagers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2fb071925ca2a5f9d32050c38361140b523929c2 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/passmanagers.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/targets.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/targets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a8acbe17d3dd1c0aba367c0fec3cc358d7948201 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/targets.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/transforms.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/transforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03e826760f8a1d6d57578acba143c59787ab1b0a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/transforms.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/typeref.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/typeref.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3352524e6106836433cd6e68b5747949b73660da Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/typeref.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/value.cpython-310.pyc b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/value.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df66e8fcd9947051b07121cd5e07369a51a1e391 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/llvmlite/binding/__pycache__/value.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/analysis.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..fe2692bf9c58478972ba4d2ce7f4a9c55bc0a068 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/analysis.py @@ -0,0 +1,69 @@ +""" +A collection of analysis utilities +""" + +from ctypes import POINTER, c_char_p, c_int + +from llvmlite.binding import ffi +from llvmlite.binding.module import parse_assembly + + +def get_function_cfg(func, show_inst=True): + """Return a string of the control-flow graph of the function in DOT + format. If the input `func` is not a materialized function, the module + containing the function is parsed to create an actual LLVM module. + The `show_inst` flag controls whether the instructions of each block + are printed. + """ + assert func is not None + from llvmlite import ir + if isinstance(func, ir.Function): + mod = parse_assembly(str(func.module)) + func = mod.get_function(func.name) + + # Assume func is a materialized function + with ffi.OutputString() as dotstr: + ffi.lib.LLVMPY_WriteCFG(func, dotstr, show_inst) + return str(dotstr) + + +def view_dot_graph(graph, filename=None, view=False): + """ + View the given DOT source. If view is True, the image is rendered + and viewed by the default application in the system. The file path of + the output is returned. If view is False, a graphviz.Source object is + returned. If view is False and the environment is in a IPython session, + an IPython image object is returned and can be displayed inline in the + notebook. + + This function requires the graphviz package. + + Args + ---- + - graph [str]: a DOT source code + - filename [str]: optional. if given and view is True, this specifies + the file path for the rendered output to write to. + - view [bool]: if True, opens the rendered output file. + + """ + # Optionally depends on graphviz package + import graphviz as gv + + src = gv.Source(graph) + if view: + # Returns the output file path + return src.render(filename, view=view) + else: + # Attempts to show the graph in IPython notebook + try: + __IPYTHON__ + except NameError: + return src + else: + import IPython.display as display + format = 'svg' + return display.SVG(data=src.pipe(format)) + + +# Ctypes binding +ffi.lib.LLVMPY_WriteCFG.argtypes = [ffi.LLVMValueRef, POINTER(c_char_p), c_int] diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/common.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/common.py new file mode 100644 index 0000000000000000000000000000000000000000..3f5746a5b057e76b1bf7b33c2892de1640919519 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/common.py @@ -0,0 +1,34 @@ +import atexit + + +def _encode_string(s): + encoded = s.encode('utf-8') + return encoded + + +def _decode_string(b): + return b.decode('utf-8') + + +_encode_string.__doc__ = """Encode a string for use by LLVM.""" +_decode_string.__doc__ = """Decode a LLVM character (byte)string.""" + + +_shutting_down = [False] + + +def _at_shutdown(): + _shutting_down[0] = True + + +atexit.register(_at_shutdown) + + +def _is_shutting_down(_shutting_down=_shutting_down): + """ + Whether the interpreter is currently shutting down. + For use in finalizers, __del__ methods, and similar; it is advised + to early bind this function rather than look it up when calling it, + since at shutdown module globals may be cleared. + """ + return _shutting_down[0] diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/context.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/context.py new file mode 100644 index 0000000000000000000000000000000000000000..7dffb82a71c1096490e80fb0031010a088cbcf0c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/context.py @@ -0,0 +1,29 @@ +from llvmlite.binding import ffi + + +def create_context(): + return ContextRef(ffi.lib.LLVMPY_ContextCreate()) + + +def get_global_context(): + return GlobalContextRef(ffi.lib.LLVMPY_GetGlobalContext()) + + +class ContextRef(ffi.ObjectRef): + def __init__(self, context_ptr): + super(ContextRef, self).__init__(context_ptr) + + def _dispose(self): + ffi.lib.LLVMPY_ContextDispose(self) + + +class GlobalContextRef(ContextRef): + def _dispose(self): + pass + + +ffi.lib.LLVMPY_GetGlobalContext.restype = ffi.LLVMContextRef + +ffi.lib.LLVMPY_ContextCreate.restype = ffi.LLVMContextRef + +ffi.lib.LLVMPY_ContextDispose.argtypes = [ffi.LLVMContextRef] diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/dylib.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/dylib.py new file mode 100644 index 0000000000000000000000000000000000000000..e22542c496b7baadc002333f28e14a91e63a359a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/dylib.py @@ -0,0 +1,45 @@ +from ctypes import c_void_p, c_char_p, c_bool, POINTER + +from llvmlite.binding import ffi +from llvmlite.binding.common import _encode_string + + +def address_of_symbol(name): + """ + Get the in-process address of symbol named *name*. + An integer is returned, or None if the symbol isn't found. + """ + return ffi.lib.LLVMPY_SearchAddressOfSymbol(_encode_string(name)) + + +def add_symbol(name, address): + """ + Register the *address* of global symbol *name*. This will make + it usable (e.g. callable) from LLVM-compiled functions. + """ + ffi.lib.LLVMPY_AddSymbol(_encode_string(name), c_void_p(address)) + + +def load_library_permanently(filename): + """ + Load an external library + """ + with ffi.OutputString() as outerr: + if ffi.lib.LLVMPY_LoadLibraryPermanently( + _encode_string(filename), outerr): + raise RuntimeError(str(outerr)) + +# ============================================================================ +# FFI + + +ffi.lib.LLVMPY_AddSymbol.argtypes = [ + c_char_p, + c_void_p, +] + +ffi.lib.LLVMPY_SearchAddressOfSymbol.argtypes = [c_char_p] +ffi.lib.LLVMPY_SearchAddressOfSymbol.restype = c_void_p + +ffi.lib.LLVMPY_LoadLibraryPermanently.argtypes = [c_char_p, POINTER(c_char_p)] +ffi.lib.LLVMPY_LoadLibraryPermanently.restype = c_bool diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/executionengine.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/executionengine.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba0985ef618ba3d497da8fbf2ee24c7f291c2ec --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/executionengine.py @@ -0,0 +1,330 @@ +import platform +from ctypes import (POINTER, c_char_p, c_bool, c_void_p, + c_int, c_uint64, c_size_t, CFUNCTYPE, string_at, cast, + py_object, Structure) + +from llvmlite.binding import ffi, targets, object_file + + +# Just check these weren't optimized out of the DLL. +ffi.lib.LLVMPY_LinkInMCJIT + + +def create_mcjit_compiler(module, target_machine, use_lmm=None): + """ + Create a MCJIT ExecutionEngine from the given *module* and + *target_machine*. + + *lmm* controls whether the llvmlite memory manager is used. If not supplied, + the default choice for the platform will be used (``True`` on 64-bit ARM + systems, ``False`` otherwise). + """ + if use_lmm is None: + use_lmm = platform.machine() in ('arm64', 'aarch64') + + with ffi.OutputString() as outerr: + engine = ffi.lib.LLVMPY_CreateMCJITCompiler( + module, target_machine, use_lmm, outerr) + if not engine: + raise RuntimeError(str(outerr)) + + target_machine._owned = True + return ExecutionEngine(engine, module=module) + + +def check_jit_execution(): + """ + Check the system allows execution of in-memory JITted functions. + An exception is raised otherwise. + """ + errno = ffi.lib.LLVMPY_TryAllocateExecutableMemory() + if errno != 0: + raise OSError(errno, + "cannot allocate executable memory. " + "This may be due to security restrictions on your " + "system, such as SELinux or similar mechanisms." + ) + + +class ExecutionEngine(ffi.ObjectRef): + """An ExecutionEngine owns all Modules associated with it. + Deleting the engine will remove all associated modules. + It is an error to delete the associated modules. + """ + _object_cache = None + + def __init__(self, ptr, module): + """ + Module ownership is transferred to the EE + """ + self._modules = set([module]) + self._td = None + module._owned = True + ffi.ObjectRef.__init__(self, ptr) + + def get_function_address(self, name): + """ + Return the address of the function named *name* as an integer. + + It's a fatal error in LLVM if the symbol of *name* doesn't exist. + """ + return ffi.lib.LLVMPY_GetFunctionAddress(self, name.encode("ascii")) + + def get_global_value_address(self, name): + """ + Return the address of the global value named *name* as an integer. + + It's a fatal error in LLVM if the symbol of *name* doesn't exist. + """ + return ffi.lib.LLVMPY_GetGlobalValueAddress(self, name.encode("ascii")) + + def add_global_mapping(self, gv, addr): + ffi.lib.LLVMPY_AddGlobalMapping(self, gv, addr) + + def add_module(self, module): + """ + Ownership of module is transferred to the execution engine + """ + if module in self._modules: + raise KeyError("module already added to this engine") + ffi.lib.LLVMPY_AddModule(self, module) + module._owned = True + self._modules.add(module) + + def finalize_object(self): + """ + Make sure all modules owned by the execution engine are fully processed + and "usable" for execution. + """ + ffi.lib.LLVMPY_FinalizeObject(self) + + def run_static_constructors(self): + """ + Run static constructors which initialize module-level static objects. + """ + ffi.lib.LLVMPY_RunStaticConstructors(self) + + def run_static_destructors(self): + """ + Run static destructors which perform module-level cleanup of static + resources. + """ + ffi.lib.LLVMPY_RunStaticDestructors(self) + + def remove_module(self, module): + """ + Ownership of module is returned + """ + with ffi.OutputString() as outerr: + if ffi.lib.LLVMPY_RemoveModule(self, module, outerr): + raise RuntimeError(str(outerr)) + self._modules.remove(module) + module._owned = False + + @property + def target_data(self): + """ + The TargetData for this execution engine. + """ + if self._td is not None: + return self._td + ptr = ffi.lib.LLVMPY_GetExecutionEngineTargetData(self) + self._td = targets.TargetData(ptr) + self._td._owned = True + return self._td + + def enable_jit_events(self): + """ + Enable JIT events for profiling of generated code. + Return value indicates whether connection to profiling tool + was successful. + """ + ret = ffi.lib.LLVMPY_EnableJITEvents(self) + return ret + + def _find_module_ptr(self, module_ptr): + """ + Find the ModuleRef corresponding to the given pointer. + """ + ptr = cast(module_ptr, c_void_p).value + for module in self._modules: + if cast(module._ptr, c_void_p).value == ptr: + return module + return None + + def add_object_file(self, obj_file): + """ + Add object file to the jit. object_file can be instance of + :class:ObjectFile or a string representing file system path + """ + if isinstance(obj_file, str): + obj_file = object_file.ObjectFileRef.from_path(obj_file) + + ffi.lib.LLVMPY_MCJITAddObjectFile(self, obj_file) + + def set_object_cache(self, notify_func=None, getbuffer_func=None): + """ + Set the object cache "notifyObjectCompiled" and "getBuffer" + callbacks to the given Python functions. + """ + self._object_cache_notify = notify_func + self._object_cache_getbuffer = getbuffer_func + # Lifetime of the object cache is managed by us. + self._object_cache = _ObjectCacheRef(self) + # Note this doesn't keep a reference to self, to avoid reference + # cycles. + ffi.lib.LLVMPY_SetObjectCache(self, self._object_cache) + + def _raw_object_cache_notify(self, data): + """ + Low-level notify hook. + """ + if self._object_cache_notify is None: + return + module_ptr = data.contents.module_ptr + buf_ptr = data.contents.buf_ptr + buf_len = data.contents.buf_len + buf = string_at(buf_ptr, buf_len) + module = self._find_module_ptr(module_ptr) + if module is None: + # The LLVM EE should only give notifications for modules + # known by us. + raise RuntimeError("object compilation notification " + "for unknown module %s" % (module_ptr,)) + self._object_cache_notify(module, buf) + + def _raw_object_cache_getbuffer(self, data): + """ + Low-level getbuffer hook. + """ + if self._object_cache_getbuffer is None: + return + module_ptr = data.contents.module_ptr + module = self._find_module_ptr(module_ptr) + if module is None: + # The LLVM EE should only give notifications for modules + # known by us. + raise RuntimeError("object compilation notification " + "for unknown module %s" % (module_ptr,)) + + buf = self._object_cache_getbuffer(module) + if buf is not None: + # Create a copy, which will be freed by the caller + data[0].buf_ptr = ffi.lib.LLVMPY_CreateByteString(buf, len(buf)) + data[0].buf_len = len(buf) + + def _dispose(self): + # The modules will be cleaned up by the EE + for mod in self._modules: + mod.detach() + if self._td is not None: + self._td.detach() + self._modules.clear() + self._object_cache = None + self._capi.LLVMPY_DisposeExecutionEngine(self) + + +class _ObjectCacheRef(ffi.ObjectRef): + """ + Internal: an ObjectCache instance for use within an ExecutionEngine. + """ + + def __init__(self, obj): + ptr = ffi.lib.LLVMPY_CreateObjectCache(_notify_c_hook, + _getbuffer_c_hook, + obj) + ffi.ObjectRef.__init__(self, ptr) + + def _dispose(self): + self._capi.LLVMPY_DisposeObjectCache(self) + + +# ============================================================================ +# FFI + + +ffi.lib.LLVMPY_CreateMCJITCompiler.argtypes = [ + ffi.LLVMModuleRef, + ffi.LLVMTargetMachineRef, + c_bool, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_CreateMCJITCompiler.restype = ffi.LLVMExecutionEngineRef + +ffi.lib.LLVMPY_RemoveModule.argtypes = [ + ffi.LLVMExecutionEngineRef, + ffi.LLVMModuleRef, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_RemoveModule.restype = c_bool + +ffi.lib.LLVMPY_AddModule.argtypes = [ + ffi.LLVMExecutionEngineRef, + ffi.LLVMModuleRef +] + +ffi.lib.LLVMPY_AddGlobalMapping.argtypes = [ffi.LLVMExecutionEngineRef, + ffi.LLVMValueRef, + c_void_p] + +ffi.lib.LLVMPY_FinalizeObject.argtypes = [ffi.LLVMExecutionEngineRef] + +ffi.lib.LLVMPY_GetExecutionEngineTargetData.argtypes = [ + ffi.LLVMExecutionEngineRef +] +ffi.lib.LLVMPY_GetExecutionEngineTargetData.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_TryAllocateExecutableMemory.argtypes = [] +ffi.lib.LLVMPY_TryAllocateExecutableMemory.restype = c_int + +ffi.lib.LLVMPY_GetFunctionAddress.argtypes = [ + ffi.LLVMExecutionEngineRef, + c_char_p +] +ffi.lib.LLVMPY_GetFunctionAddress.restype = c_uint64 + +ffi.lib.LLVMPY_GetGlobalValueAddress.argtypes = [ + ffi.LLVMExecutionEngineRef, + c_char_p +] +ffi.lib.LLVMPY_GetGlobalValueAddress.restype = c_uint64 + +ffi.lib.LLVMPY_MCJITAddObjectFile.argtypes = [ + ffi.LLVMExecutionEngineRef, + ffi.LLVMObjectFileRef +] + + +class _ObjectCacheData(Structure): + _fields_ = [ + ('module_ptr', ffi.LLVMModuleRef), + ('buf_ptr', c_void_p), + ('buf_len', c_size_t), + ] + + +_ObjectCacheNotifyFunc = CFUNCTYPE(None, py_object, + POINTER(_ObjectCacheData)) +_ObjectCacheGetBufferFunc = CFUNCTYPE(None, py_object, + POINTER(_ObjectCacheData)) + +# XXX The ctypes function wrappers are created at the top-level, otherwise +# there are issues when creating CFUNCTYPEs in child processes on CentOS 5 +# 32 bits. +_notify_c_hook = _ObjectCacheNotifyFunc( + ExecutionEngine._raw_object_cache_notify) +_getbuffer_c_hook = _ObjectCacheGetBufferFunc( + ExecutionEngine._raw_object_cache_getbuffer) + +ffi.lib.LLVMPY_CreateObjectCache.argtypes = [_ObjectCacheNotifyFunc, + _ObjectCacheGetBufferFunc, + py_object] +ffi.lib.LLVMPY_CreateObjectCache.restype = ffi.LLVMObjectCacheRef + +ffi.lib.LLVMPY_DisposeObjectCache.argtypes = [ffi.LLVMObjectCacheRef] + +ffi.lib.LLVMPY_SetObjectCache.argtypes = [ffi.LLVMExecutionEngineRef, + ffi.LLVMObjectCacheRef] + +ffi.lib.LLVMPY_CreateByteString.restype = c_void_p +ffi.lib.LLVMPY_CreateByteString.argtypes = [c_void_p, c_size_t] diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/ffi.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/ffi.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f55f9a9a2fd3f5cfc42abb959fbe6458fdf08a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/ffi.py @@ -0,0 +1,390 @@ +import sys +import ctypes +import threading +import importlib.resources as _impres + +from llvmlite.binding.common import _decode_string, _is_shutting_down +from llvmlite.utils import get_library_name + + +def _make_opaque_ref(name): + newcls = type(name, (ctypes.Structure,), {}) + return ctypes.POINTER(newcls) + + +LLVMContextRef = _make_opaque_ref("LLVMContext") +LLVMModuleRef = _make_opaque_ref("LLVMModule") +LLVMValueRef = _make_opaque_ref("LLVMValue") +LLVMTypeRef = _make_opaque_ref("LLVMType") +LLVMExecutionEngineRef = _make_opaque_ref("LLVMExecutionEngine") +LLVMPassManagerBuilderRef = _make_opaque_ref("LLVMPassManagerBuilder") +LLVMPassManagerRef = _make_opaque_ref("LLVMPassManager") +LLVMTargetDataRef = _make_opaque_ref("LLVMTargetData") +LLVMTargetLibraryInfoRef = _make_opaque_ref("LLVMTargetLibraryInfo") +LLVMTargetRef = _make_opaque_ref("LLVMTarget") +LLVMTargetMachineRef = _make_opaque_ref("LLVMTargetMachine") +LLVMMemoryBufferRef = _make_opaque_ref("LLVMMemoryBuffer") +LLVMAttributeListIterator = _make_opaque_ref("LLVMAttributeListIterator") +LLVMElementIterator = _make_opaque_ref("LLVMElementIterator") +LLVMAttributeSetIterator = _make_opaque_ref("LLVMAttributeSetIterator") +LLVMGlobalsIterator = _make_opaque_ref("LLVMGlobalsIterator") +LLVMFunctionsIterator = _make_opaque_ref("LLVMFunctionsIterator") +LLVMBlocksIterator = _make_opaque_ref("LLVMBlocksIterator") +LLVMArgumentsIterator = _make_opaque_ref("LLVMArgumentsIterator") +LLVMInstructionsIterator = _make_opaque_ref("LLVMInstructionsIterator") +LLVMOperandsIterator = _make_opaque_ref("LLVMOperandsIterator") +LLVMIncomingBlocksIterator = _make_opaque_ref("LLVMIncomingBlocksIterator") +LLVMTypesIterator = _make_opaque_ref("LLVMTypesIterator") +LLVMObjectCacheRef = _make_opaque_ref("LLVMObjectCache") +LLVMObjectFileRef = _make_opaque_ref("LLVMObjectFile") +LLVMSectionIteratorRef = _make_opaque_ref("LLVMSectionIterator") +LLVMOrcLLJITRef = _make_opaque_ref("LLVMOrcLLJITRef") +LLVMOrcDylibTrackerRef = _make_opaque_ref("LLVMOrcDylibTrackerRef") + + +class _LLVMLock: + """A Lock to guarantee thread-safety for the LLVM C-API. + + This class implements __enter__ and __exit__ for acquiring and releasing + the lock as a context manager. + + Also, callbacks can be attached so that every time the lock is acquired + and released the corresponding callbacks will be invoked. + """ + def __init__(self): + # The reentrant lock is needed for callbacks that re-enter + # the Python interpreter. + self._lock = threading.RLock() + self._cblist = [] + + def register(self, acq_fn, rel_fn): + """Register callbacks that are invoked immediately after the lock is + acquired (``acq_fn()``) and immediately before the lock is released + (``rel_fn()``). + """ + self._cblist.append((acq_fn, rel_fn)) + + def unregister(self, acq_fn, rel_fn): + """Remove the registered callbacks. + """ + self._cblist.remove((acq_fn, rel_fn)) + + def __enter__(self): + self._lock.acquire() + # Invoke all callbacks + for acq_fn, rel_fn in self._cblist: + acq_fn() + + def __exit__(self, *exc_details): + # Invoke all callbacks + for acq_fn, rel_fn in self._cblist: + rel_fn() + self._lock.release() + + +class _suppress_cleanup_errors: + def __init__(self, context): + self._context = context + + def __enter__(self): + return self._context.__enter__() + + def __exit__(self, exc_type, exc_value, traceback): + try: + return self._context.__exit__(exc_type, exc_value, traceback) + except PermissionError: + pass # Resource dylibs can't be deleted on Windows. + + +class _lib_wrapper(object): + """Wrap libllvmlite with a lock such that only one thread may access it at + a time. + + This class duck-types a CDLL. + """ + __slots__ = ['_lib_handle', '_fntab', '_lock'] + + def __init__(self): + self._lib_handle = None + self._fntab = {} + self._lock = _LLVMLock() + + def _load_lib(self): + try: + with _suppress_cleanup_errors(_importlib_resources_path( + __name__.rpartition(".")[0], + get_library_name())) as lib_path: + self._lib_handle = ctypes.CDLL(str(lib_path)) + # Check that we can look up expected symbols. + _ = self._lib_handle.LLVMPY_GetVersionInfo() + except (OSError, AttributeError) as e: + # OSError may be raised if the file cannot be opened, or is not + # a shared library. + # AttributeError is raised if LLVMPY_GetVersionInfo does not + # exist. + raise OSError("Could not find/load shared object file") from e + + @property + def _lib(self): + # Not threadsafe. + if not self._lib_handle: + self._load_lib() + return self._lib_handle + + def __getattr__(self, name): + try: + return self._fntab[name] + except KeyError: + # Lazily wraps new functions as they are requested + cfn = getattr(self._lib, name) + wrapped = _lib_fn_wrapper(self._lock, cfn) + self._fntab[name] = wrapped + return wrapped + + @property + def _name(self): + """The name of the library passed in the CDLL constructor. + + For duck-typing a ctypes.CDLL + """ + return self._lib._name + + @property + def _handle(self): + """The system handle used to access the library. + + For duck-typing a ctypes.CDLL + """ + return self._lib._handle + + +class _lib_fn_wrapper(object): + """Wraps and duck-types a ctypes.CFUNCTYPE to provide + automatic locking when the wrapped function is called. + + TODO: we can add methods to mark the function as threadsafe + and remove the locking-step on call when marked. + """ + __slots__ = ['_lock', '_cfn'] + + def __init__(self, lock, cfn): + self._lock = lock + self._cfn = cfn + + @property + def argtypes(self): + return self._cfn.argtypes + + @argtypes.setter + def argtypes(self, argtypes): + self._cfn.argtypes = argtypes + + @property + def restype(self): + return self._cfn.restype + + @restype.setter + def restype(self, restype): + self._cfn.restype = restype + + def __call__(self, *args, **kwargs): + with self._lock: + return self._cfn(*args, **kwargs) + + +def _importlib_resources_path_repl(package, resource): + """Replacement implementation of `import.resources.path` to avoid + deprecation warning following code at importlib_resources/_legacy.py + as suggested by https://importlib-resources.readthedocs.io/en/latest/using.html#migrating-from-legacy + + Notes on differences from importlib.resources implementation: + + The `_common.normalize_path(resource)` call is skipped because it is an + internal API and it is unnecessary for the use here. What it does is + ensuring `resource` is a str and that it does not contain path separators. + """ # noqa E501 + return _impres.as_file(_impres.files(package) / resource) + + +_importlib_resources_path = (_importlib_resources_path_repl + if sys.version_info[:2] >= (3, 9) + else _impres.path) + + +lib = _lib_wrapper() + + +def register_lock_callback(acq_fn, rel_fn): + """Register callback functions for lock acquire and release. + *acq_fn* and *rel_fn* are callables that take no arguments. + """ + lib._lock.register(acq_fn, rel_fn) + + +def unregister_lock_callback(acq_fn, rel_fn): + """Remove the registered callback functions for lock acquire and release. + The arguments are the same as used in `register_lock_callback()`. + """ + lib._lock.unregister(acq_fn, rel_fn) + + +class _DeadPointer(object): + """ + Dummy class to make error messages more helpful. + """ + + +class OutputString(object): + """ + Object for managing the char* output of LLVM APIs. + """ + _as_parameter_ = _DeadPointer() + + @classmethod + def from_return(cls, ptr): + """Constructing from a pointer returned from the C-API. + The pointer must be allocated with LLVMPY_CreateString. + + Note + ---- + Because ctypes auto-converts *restype* of *c_char_p* into a python + string, we must use *c_void_p* to obtain the raw pointer. + """ + return cls(init=ctypes.cast(ptr, ctypes.c_char_p)) + + def __init__(self, owned=True, init=None): + self._ptr = init if init is not None else ctypes.c_char_p(None) + self._as_parameter_ = ctypes.byref(self._ptr) + self._owned = owned + + def close(self): + if self._ptr is not None: + if self._owned: + lib.LLVMPY_DisposeString(self._ptr) + self._ptr = None + del self._as_parameter_ + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def __del__(self, _is_shutting_down=_is_shutting_down): + # Avoid errors trying to rely on globals and modules at interpreter + # shutdown. + if not _is_shutting_down(): + if self.close is not None: + self.close() + + def __str__(self): + if self._ptr is None: + return "" + s = self._ptr.value + assert s is not None + return _decode_string(s) + + def __bool__(self): + return bool(self._ptr) + + __nonzero__ = __bool__ + + @property + def bytes(self): + """Get the raw bytes of content of the char pointer. + """ + return self._ptr.value + + +def ret_string(ptr): + """To wrap string return-value from C-API. + """ + if ptr is not None: + return str(OutputString.from_return(ptr)) + + +def ret_bytes(ptr): + """To wrap bytes return-value from C-API. + """ + if ptr is not None: + return OutputString.from_return(ptr).bytes + + +class ObjectRef(object): + """ + A wrapper around a ctypes pointer to a LLVM object ("resource"). + """ + _closed = False + _as_parameter_ = _DeadPointer() + # Whether this object pointer is owned by another one. + _owned = False + + def __init__(self, ptr): + if ptr is None: + raise ValueError("NULL pointer") + self._ptr = ptr + self._as_parameter_ = ptr + self._capi = lib + + def close(self): + """ + Close this object and do any required clean-up actions. + """ + try: + if not self._closed and not self._owned: + self._dispose() + finally: + self.detach() + + def detach(self): + """ + Detach the underlying LLVM resource without disposing of it. + """ + if not self._closed: + del self._as_parameter_ + self._closed = True + self._ptr = None + + def _dispose(self): + """ + Dispose of the underlying LLVM resource. Should be overriden + by subclasses. Automatically called by close(), __del__() and + __exit__() (unless the resource has been detached). + """ + + @property + def closed(self): + """ + Whether this object has been closed. A closed object can't + be used anymore. + """ + return self._closed + + def __enter__(self): + assert hasattr(self, "close") + if self._closed: + raise RuntimeError("%s instance already closed" % (self.__class__,)) + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + + def __del__(self, _is_shutting_down=_is_shutting_down): + if not _is_shutting_down(): + if self.close is not None: + self.close() + + def __bool__(self): + return bool(self._ptr) + + def __eq__(self, other): + if not hasattr(other, "_ptr"): + return False + return ctypes.addressof(self._ptr[0]) == \ + ctypes.addressof(other._ptr[0]) + + __nonzero__ = __bool__ + + # XXX useful? + def __hash__(self): + return hash(ctypes.cast(self._ptr, ctypes.c_void_p).value) diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/initfini.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/initfini.py new file mode 100644 index 0000000000000000000000000000000000000000..4466d9da2f2c131b750a2a8ff61ed7381acb7363 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/initfini.py @@ -0,0 +1,73 @@ +from ctypes import c_uint + +from llvmlite.binding import ffi + + +def initialize(): + """ + Initialize the LLVM core. + """ + ffi.lib.LLVMPY_InitializeCore() + + +def initialize_all_targets(): + """ + Initialize all targets. Necessary before targets can be looked up + via the :class:`Target` class. + """ + ffi.lib.LLVMPY_InitializeAllTargetInfos() + ffi.lib.LLVMPY_InitializeAllTargets() + ffi.lib.LLVMPY_InitializeAllTargetMCs() + + +def initialize_all_asmprinters(): + """ + Initialize all code generators. Necessary before generating + any assembly or machine code via the :meth:`TargetMachine.emit_object` + and :meth:`TargetMachine.emit_assembly` methods. + """ + ffi.lib.LLVMPY_InitializeAllAsmPrinters() + + +def initialize_native_target(): + """ + Initialize the native (host) target. Necessary before doing any + code generation. + """ + ffi.lib.LLVMPY_InitializeNativeTarget() + + +def initialize_native_asmprinter(): + """ + Initialize the native ASM printer. + """ + ffi.lib.LLVMPY_InitializeNativeAsmPrinter() + + +def initialize_native_asmparser(): + """ + Initialize the native ASM parser. + """ + ffi.lib.LLVMPY_InitializeNativeAsmParser() + + +def shutdown(): + ffi.lib.LLVMPY_Shutdown() + + +# ============================================================================= +# Set function FFI + +ffi.lib.LLVMPY_GetVersionInfo.restype = c_uint + + +def _version_info(): + v = [] + x = ffi.lib.LLVMPY_GetVersionInfo() + while x: + v.append(x & 0xff) + x >>= 8 + return tuple(reversed(v)) + + +llvm_version_info = _version_info() diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/linker.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/linker.py new file mode 100644 index 0000000000000000000000000000000000000000..31d1e26ffb99763af367d07c30fd77770103dc79 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/linker.py @@ -0,0 +1,20 @@ +from ctypes import c_int, c_char_p, POINTER +from llvmlite.binding import ffi + + +def link_modules(dst, src): + with ffi.OutputString() as outerr: + err = ffi.lib.LLVMPY_LinkModules(dst, src, outerr) + # The underlying module was destroyed + src.detach() + if err: + raise RuntimeError(str(outerr)) + + +ffi.lib.LLVMPY_LinkModules.argtypes = [ + ffi.LLVMModuleRef, + ffi.LLVMModuleRef, + POINTER(c_char_p), +] + +ffi.lib.LLVMPY_LinkModules.restype = c_int diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/module.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/module.py new file mode 100644 index 0000000000000000000000000000000000000000..dcbb1faa6545718f9226133ccef42b03a098fd37 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/module.py @@ -0,0 +1,349 @@ +from ctypes import (c_char_p, byref, POINTER, c_bool, create_string_buffer, + c_size_t, string_at) + +from llvmlite.binding import ffi +from llvmlite.binding.linker import link_modules +from llvmlite.binding.common import _decode_string, _encode_string +from llvmlite.binding.value import ValueRef, TypeRef +from llvmlite.binding.context import get_global_context + + +def parse_assembly(llvmir, context=None): + """ + Create Module from a LLVM IR string + """ + if context is None: + context = get_global_context() + llvmir = _encode_string(llvmir) + strbuf = c_char_p(llvmir) + with ffi.OutputString() as errmsg: + mod = ModuleRef( + ffi.lib.LLVMPY_ParseAssembly(context, strbuf, errmsg), + context) + if errmsg: + mod.close() + raise RuntimeError("LLVM IR parsing error\n{0}".format(errmsg)) + return mod + + +def parse_bitcode(bitcode, context=None): + """ + Create Module from a LLVM *bitcode* (a bytes object). + """ + if context is None: + context = get_global_context() + buf = c_char_p(bitcode) + bufsize = len(bitcode) + with ffi.OutputString() as errmsg: + mod = ModuleRef(ffi.lib.LLVMPY_ParseBitcode( + context, buf, bufsize, errmsg), context) + if errmsg: + mod.close() + raise RuntimeError( + "LLVM bitcode parsing error\n{0}".format(errmsg)) + return mod + + +class ModuleRef(ffi.ObjectRef): + """ + A reference to a LLVM module. + """ + + def __init__(self, module_ptr, context): + super(ModuleRef, self).__init__(module_ptr) + self._context = context + + def __str__(self): + with ffi.OutputString() as outstr: + ffi.lib.LLVMPY_PrintModuleToString(self, outstr) + return str(outstr) + + def as_bitcode(self): + """ + Return the module's LLVM bitcode, as a bytes object. + """ + ptr = c_char_p(None) + size = c_size_t(-1) + ffi.lib.LLVMPY_WriteBitcodeToString(self, byref(ptr), byref(size)) + if not ptr: + raise MemoryError + try: + assert size.value >= 0 + return string_at(ptr, size.value) + finally: + ffi.lib.LLVMPY_DisposeString(ptr) + + def _dispose(self): + self._capi.LLVMPY_DisposeModule(self) + + def get_function(self, name): + """ + Get a ValueRef pointing to the function named *name*. + NameError is raised if the symbol isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedFunction(self, _encode_string(name)) + if not p: + raise NameError(name) + return ValueRef(p, 'function', dict(module=self)) + + def get_global_variable(self, name): + """ + Get a ValueRef pointing to the global variable named *name*. + NameError is raised if the symbol isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedGlobalVariable(self, _encode_string(name)) + if not p: + raise NameError(name) + return ValueRef(p, 'global', dict(module=self)) + + def get_struct_type(self, name): + """ + Get a TypeRef pointing to a structure type named *name*. + NameError is raised if the struct type isn't found. + """ + p = ffi.lib.LLVMPY_GetNamedStructType(self, _encode_string(name)) + if not p: + raise NameError(name) + return TypeRef(p) + + def verify(self): + """ + Verify the module IR's correctness. RuntimeError is raised on error. + """ + with ffi.OutputString() as outmsg: + if ffi.lib.LLVMPY_VerifyModule(self, outmsg): + raise RuntimeError(str(outmsg)) + + @property + def name(self): + """ + The module's identifier. + """ + return _decode_string(ffi.lib.LLVMPY_GetModuleName(self)) + + @name.setter + def name(self, value): + ffi.lib.LLVMPY_SetModuleName(self, _encode_string(value)) + + @property + def source_file(self): + """ + The module's original source file name + """ + return _decode_string(ffi.lib.LLVMPY_GetModuleSourceFileName(self)) + + @property + def data_layout(self): + """ + This module's data layout specification, as a string. + """ + # LLVMGetDataLayout() points inside a std::string managed by LLVM. + with ffi.OutputString(owned=False) as outmsg: + ffi.lib.LLVMPY_GetDataLayout(self, outmsg) + return str(outmsg) + + @data_layout.setter + def data_layout(self, strrep): + ffi.lib.LLVMPY_SetDataLayout(self, + create_string_buffer( + strrep.encode('utf8'))) + + @property + def triple(self): + """ + This module's target "triple" specification, as a string. + """ + # LLVMGetTarget() points inside a std::string managed by LLVM. + with ffi.OutputString(owned=False) as outmsg: + ffi.lib.LLVMPY_GetTarget(self, outmsg) + return str(outmsg) + + @triple.setter + def triple(self, strrep): + ffi.lib.LLVMPY_SetTarget(self, + create_string_buffer( + strrep.encode('utf8'))) + + def link_in(self, other, preserve=False): + """ + Link the *other* module into this one. The *other* module will + be destroyed unless *preserve* is true. + """ + if preserve: + other = other.clone() + link_modules(self, other) + + @property + def global_variables(self): + """ + Return an iterator over this module's global variables. + The iterator will yield a ValueRef for each global variable. + + Note that global variables don't include functions + (a function is a "global value" but not a "global variable" in + LLVM parlance) + """ + it = ffi.lib.LLVMPY_ModuleGlobalsIter(self) + return _GlobalsIterator(it, dict(module=self)) + + @property + def functions(self): + """ + Return an iterator over this module's functions. + The iterator will yield a ValueRef for each function. + """ + it = ffi.lib.LLVMPY_ModuleFunctionsIter(self) + return _FunctionsIterator(it, dict(module=self)) + + @property + def struct_types(self): + """ + Return an iterator over the struct types defined in + the module. The iterator will yield a TypeRef. + """ + it = ffi.lib.LLVMPY_ModuleTypesIter(self) + return _TypesIterator(it, dict(module=self)) + + def clone(self): + return ModuleRef(ffi.lib.LLVMPY_CloneModule(self), self._context) + + +class _Iterator(ffi.ObjectRef): + + kind = None + + def __init__(self, ptr, parents): + ffi.ObjectRef.__init__(self, ptr) + self._parents = parents + assert self.kind is not None + + def __next__(self): + vp = self._next() + if vp: + return ValueRef(vp, self.kind, self._parents) + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _GlobalsIterator(_Iterator): + + kind = 'global' + + def _dispose(self): + self._capi.LLVMPY_DisposeGlobalsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_GlobalsIterNext(self) + + +class _FunctionsIterator(_Iterator): + + kind = 'function' + + def _dispose(self): + self._capi.LLVMPY_DisposeFunctionsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_FunctionsIterNext(self) + + +class _TypesIterator(_Iterator): + + kind = 'type' + + def _dispose(self): + self._capi.LLVMPY_DisposeTypesIter(self) + + def __next__(self): + vp = self._next() + if vp: + return TypeRef(vp) + else: + raise StopIteration + + def _next(self): + return ffi.lib.LLVMPY_TypesIterNext(self) + + next = __next__ + + +# ============================================================================= +# Set function FFI + +ffi.lib.LLVMPY_ParseAssembly.argtypes = [ffi.LLVMContextRef, + c_char_p, + POINTER(c_char_p)] +ffi.lib.LLVMPY_ParseAssembly.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_ParseBitcode.argtypes = [ffi.LLVMContextRef, + c_char_p, c_size_t, + POINTER(c_char_p)] +ffi.lib.LLVMPY_ParseBitcode.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_DisposeModule.argtypes = [ffi.LLVMModuleRef] + +ffi.lib.LLVMPY_PrintModuleToString.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p)] +ffi.lib.LLVMPY_WriteBitcodeToString.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p), + POINTER(c_size_t)] + +ffi.lib.LLVMPY_GetNamedFunction.argtypes = [ffi.LLVMModuleRef, + c_char_p] +ffi.lib.LLVMPY_GetNamedFunction.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_VerifyModule.argtypes = [ffi.LLVMModuleRef, + POINTER(c_char_p)] +ffi.lib.LLVMPY_VerifyModule.restype = c_bool + +ffi.lib.LLVMPY_GetDataLayout.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)] +ffi.lib.LLVMPY_SetDataLayout.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetTarget.argtypes = [ffi.LLVMModuleRef, POINTER(c_char_p)] +ffi.lib.LLVMPY_SetTarget.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetNamedGlobalVariable.argtypes = [ffi.LLVMModuleRef, c_char_p] +ffi.lib.LLVMPY_GetNamedGlobalVariable.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_GetNamedStructType.argtypes = [ffi.LLVMModuleRef, c_char_p] +ffi.lib.LLVMPY_GetNamedStructType.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_ModuleGlobalsIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleGlobalsIter.restype = ffi.LLVMGlobalsIterator + +ffi.lib.LLVMPY_DisposeGlobalsIter.argtypes = [ffi.LLVMGlobalsIterator] + +ffi.lib.LLVMPY_GlobalsIterNext.argtypes = [ffi.LLVMGlobalsIterator] +ffi.lib.LLVMPY_GlobalsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_ModuleFunctionsIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleFunctionsIter.restype = ffi.LLVMFunctionsIterator + +ffi.lib.LLVMPY_ModuleTypesIter.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_ModuleTypesIter.restype = ffi.LLVMTypesIterator + +ffi.lib.LLVMPY_DisposeFunctionsIter.argtypes = [ffi.LLVMFunctionsIterator] + +ffi.lib.LLVMPY_DisposeTypesIter.argtypes = [ffi.LLVMTypesIterator] + +ffi.lib.LLVMPY_FunctionsIterNext.argtypes = [ffi.LLVMFunctionsIterator] +ffi.lib.LLVMPY_FunctionsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_TypesIterNext.argtypes = [ffi.LLVMTypesIterator] +ffi.lib.LLVMPY_TypesIterNext.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_CloneModule.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_CloneModule.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_GetModuleName.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_GetModuleName.restype = c_char_p + +ffi.lib.LLVMPY_SetModuleName.argtypes = [ffi.LLVMModuleRef, c_char_p] + +ffi.lib.LLVMPY_GetModuleSourceFileName.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_GetModuleSourceFileName.restype = c_char_p diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/object_file.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/object_file.py new file mode 100644 index 0000000000000000000000000000000000000000..e5961b079ef87393347436a8fd8e70fb0525b39d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/object_file.py @@ -0,0 +1,82 @@ +from llvmlite.binding import ffi +from ctypes import (c_bool, c_char_p, c_char, c_size_t, string_at, c_uint64, + POINTER) + + +class SectionIteratorRef(ffi.ObjectRef): + def name(self): + return ffi.lib.LLVMPY_GetSectionName(self) + + def is_text(self): + return ffi.lib.LLVMPY_IsSectionText(self) + + def size(self): + return ffi.lib.LLVMPY_GetSectionSize(self) + + def address(self): + return ffi.lib.LLVMPY_GetSectionAddress(self) + + def data(self): + return string_at(ffi.lib.LLVMPY_GetSectionContents(self), self.size()) + + def is_end(self, object_file): + return ffi.lib.LLVMPY_IsSectionIteratorAtEnd(object_file, self) + + def next(self): + ffi.lib.LLVMPY_MoveToNextSection(self) + + def _dispose(self): + ffi.lib.LLVMPY_DisposeSectionIterator(self) + + +class ObjectFileRef(ffi.ObjectRef): + @classmethod + def from_data(cls, data): + return cls(ffi.lib.LLVMPY_CreateObjectFile(data, len(data))) + + @classmethod + def from_path(cls, path): + with open(path, 'rb') as f: + data = f.read() + return cls(ffi.lib.LLVMPY_CreateObjectFile(data, len(data))) + + def sections(self): + it = SectionIteratorRef(ffi.lib.LLVMPY_GetSections(self)) + while not it.is_end(self): + yield it + it.next() + + def _dispose(self): + ffi.lib.LLVMPY_DisposeObjectFile(self) + + +ffi.lib.LLVMPY_CreateObjectFile.argtypes = [c_char_p, c_size_t] +ffi.lib.LLVMPY_CreateObjectFile.restype = ffi.LLVMObjectFileRef + +ffi.lib.LLVMPY_DisposeObjectFile.argtypes = [ffi.LLVMObjectFileRef] + +ffi.lib.LLVMPY_GetSections.argtypes = [ffi.LLVMObjectFileRef] +ffi.lib.LLVMPY_GetSections.restype = ffi.LLVMSectionIteratorRef + +ffi.lib.LLVMPY_DisposeSectionIterator.argtypes = [ffi.LLVMSectionIteratorRef] + +ffi.lib.LLVMPY_MoveToNextSection.argtypes = [ffi.LLVMSectionIteratorRef] + +ffi.lib.LLVMPY_IsSectionIteratorAtEnd.argtypes = [ + ffi.LLVMObjectFileRef, ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_IsSectionIteratorAtEnd.restype = c_bool + +ffi.lib.LLVMPY_GetSectionName.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionName.restype = c_char_p + +ffi.lib.LLVMPY_GetSectionSize.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionSize.restype = c_uint64 + +ffi.lib.LLVMPY_GetSectionAddress.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionAddress.restype = c_uint64 + +ffi.lib.LLVMPY_GetSectionContents.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_GetSectionContents.restype = POINTER(c_char) + +ffi.lib.LLVMPY_IsSectionText.argtypes = [ffi.LLVMSectionIteratorRef] +ffi.lib.LLVMPY_IsSectionText.restype = c_bool diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/options.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/options.py new file mode 100644 index 0000000000000000000000000000000000000000..15eedfaaf476938c97abcd7e75131e9590f34203 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/options.py @@ -0,0 +1,17 @@ +from llvmlite.binding import ffi +from llvmlite.binding.common import _encode_string +from ctypes import c_char_p + + +def set_option(name, option): + """ + Set the given LLVM "command-line" option. + + For example set_option("test", "-debug-pass=Structure") would display + all optimization passes when generating code. + """ + ffi.lib.LLVMPY_SetCommandLine(_encode_string(name), + _encode_string(option)) + + +ffi.lib.LLVMPY_SetCommandLine.argtypes = [c_char_p, c_char_p] diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/orcjit.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/orcjit.py new file mode 100644 index 0000000000000000000000000000000000000000..82996f586bf688bce389db15d29b0c294f5cba67 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/orcjit.py @@ -0,0 +1,342 @@ +import ctypes +from ctypes import POINTER, c_bool, c_char_p, c_uint8, c_uint64, c_size_t + +from llvmlite.binding import ffi, targets + + +class _LinkElement(ctypes.Structure): + _fields_ = [("element_kind", c_uint8), + ("value", c_char_p), + ("value_len", c_size_t)] + + +class _SymbolAddress(ctypes.Structure): + _fields_ = [("name", c_char_p), ("address", c_uint64)] + + +class JITLibraryBuilder: + """ + Create a library for linking by OrcJIT + + OrcJIT operates like a linker: a number of compilation units and + dependencies are collected together and linked into a single dynamic library + that can export functions to other libraries or to be consumed directly as + entry points into JITted code. The native OrcJIT has a lot of memory + management complications so this API is designed to work well with Python's + garbage collection. + + The creation of a new library is a bit like a linker command line where + compilation units, mostly as LLVM IR, and previously constructed libraries + are linked together, then loaded into memory, and the addresses of exported + symbols are extracted. Any static initializers are run and the exported + addresses and a resource tracker is produced. As long as the resource + tracker is referenced somewhere in Python, the exported addresses will be + valid. Once the resource tracker is garbage collected, the static + destructors will run and library will be unloaded from memory. + """ + def __init__(self): + self.__entries = [] + self.__exports = set() + self.__imports = {} + + def add_ir(self, llvmir): + """ + Adds a compilation unit to the library using LLVM IR as the input + format. + + This takes a string or an object that can be converted to a string, + including IRBuilder, that contains LLVM IR. + """ + self.__entries.append((0, str(llvmir).encode('utf-8'))) + return self + + def add_native_assembly(self, asm): + """ + Adds a compilation unit to the library using native assembly as the + input format. + + This takes a string or an object that can be converted to a string that + contains native assembly, which will be + parsed by LLVM. + """ + self.__entries.append((1, str(asm).encode('utf-8'))) + return self + + def add_object_img(self, data): + """ + Adds a compilation unit to the library using pre-compiled object code. + + This takes the bytes of the contents of an object artifact which will be + loaded by LLVM. + """ + self.__entries.append((2, bytes(data))) + return self + + def add_object_file(self, file_path): + """ + Adds a compilation unit to the library using pre-compiled object file. + + This takes a string or path-like object that references an object file + which will be loaded by LLVM. + """ + with open(file_path, "rb") as f: + self.__entries.append((2, f.read())) + return self + + def add_jit_library(self, name): + """ + Adds an existing JIT library as prerequisite. + + The name of the library must match the one provided in a previous link + command. + """ + self.__entries.append((3, str(name).encode('utf-8'))) + return self + + def add_current_process(self): + """ + Allows the JITted library to access symbols in the current binary. + + That is, it allows exporting the current binary's symbols, including + loaded libraries, as imports to the JITted + library. + """ + self.__entries.append((3, b'')) + return self + + def import_symbol(self, name, address): + """ + Register the *address* of global symbol *name*. This will make + it usable (e.g. callable) from LLVM-compiled functions. + """ + self.__imports[str(name)] = c_uint64(address) + return self + + def export_symbol(self, name): + """ + During linking, extract the address of a symbol that was defined in one + of the compilation units. + + This allows getting symbols, functions or global variables, out of the + JIT linked library. The addresses will be + available when the link method is called. + """ + self.__exports.add(str(name)) + return self + + def link(self, lljit, library_name): + """ + Link all the current compilation units into a JITted library and extract + the address of exported symbols. + + An instance of the OrcJIT instance must be provided and this will be the + scope that is used to find other JITted libraries that are dependencies + and also be the place where this library will be defined. + + After linking, the method will return a resource tracker that keeps the + library alive. This tracker also knows the addresses of any exported + symbols that were requested. + + The addresses will be valid as long as the resource tracker is + referenced. + + When the resource tracker is destroyed, the library will be cleaned up, + however, the name of the library cannot be reused. + """ + assert not lljit.closed, "Cannot add to closed JIT" + encoded_library_name = str(library_name).encode('utf-8') + assert len(encoded_library_name) > 0, "Library cannot be empty" + elements = (_LinkElement * len(self.__entries))() + for idx, (kind, value) in enumerate(self.__entries): + elements[idx].element_kind = c_uint8(kind) + elements[idx].value = c_char_p(value) + elements[idx].value_len = c_size_t(len(value)) + exports = (_SymbolAddress * len(self.__exports))() + for idx, name in enumerate(self.__exports): + exports[idx].name = name.encode('utf-8') + + imports = (_SymbolAddress * len(self.__imports))() + for idx, (name, addr) in enumerate(self.__imports.items()): + imports[idx].name = name.encode('utf-8') + imports[idx].address = addr + + with ffi.OutputString() as outerr: + tracker = lljit._capi.LLVMPY_LLJIT_Link( + lljit._ptr, + encoded_library_name, + elements, + len(self.__entries), + imports, + len(self.__imports), + exports, + len(self.__exports), + outerr) + if not tracker: + raise RuntimeError(str(outerr)) + return ResourceTracker(tracker, + library_name, + {name: exports[idx].address + for idx, name in enumerate(self.__exports)}) + + +class ResourceTracker(ffi.ObjectRef): + """ + A resource tracker is created for each loaded JIT library and keeps the + module alive. + + OrcJIT supports unloading libraries that are no longer used. This resource + tracker should be stored in any object that reference functions or constants + for a JITted library. When all references to the resource tracker are + dropped, this will trigger LLVM to unload the library and destroy any + functions. + + Failure to keep resource trackers while calling a function or accessing a + symbol can result in crashes or memory corruption. + + LLVM internally tracks references between different libraries, so only + "leaf" libraries need to be tracked. + """ + def __init__(self, ptr, name, addresses): + self.__addresses = addresses + self.__name = name + ffi.ObjectRef.__init__(self, ptr) + + def __getitem__(self, item): + """ + Get the address of an exported symbol as an integer + """ + return self.__addresses[item] + + @property + def name(self): + return self.__name + + def _dispose(self): + with ffi.OutputString() as outerr: + if self._capi.LLVMPY_LLJIT_Dylib_Tracker_Dispose(self, outerr): + raise RuntimeError(str(outerr)) + + +class LLJIT(ffi.ObjectRef): + """ + A OrcJIT-based LLVM JIT engine that can compile and run LLVM IR as a + collection of JITted dynamic libraries + + The C++ OrcJIT API has a lot of memory ownership patterns that do not work + with Python. This API attempts to provide ones that are safe at the expense + of some features. Each LLJIT instance is a collection of JIT-compiled + libraries. In the C++ API, there is a "main" library; this API does not + provide access to the main library. Use the JITLibraryBuilder to create a + new named library instead. + """ + def __init__(self, ptr): + self._td = None + ffi.ObjectRef.__init__(self, ptr) + + def lookup(self, dylib, fn): + """ + Find a function in this dynamic library and construct a new tracking + object for it + + If the library or function do not exist, an exception will occur. + + Parameters + ---------- + dylib : str or None + the name of the library containing the symbol + fn : str + the name of the function to get + """ + assert not self.closed, "Cannot lookup in closed JIT" + address = ctypes.c_uint64() + with ffi.OutputString() as outerr: + tracker = ffi.lib.LLVMPY_LLJITLookup(self, + dylib.encode("utf-8"), + fn.encode("utf-8"), + ctypes.byref(address), + outerr) + if not tracker: + raise RuntimeError(str(outerr)) + + return ResourceTracker(tracker, dylib, {fn: address.value}) + + @property + def target_data(self): + """ + The TargetData for this LLJIT instance. + """ + if self._td is not None: + return self._td + ptr = ffi.lib.LLVMPY_LLJITGetDataLayout(self) + self._td = targets.TargetData(ptr) + self._td._owned = True + return self._td + + def _dispose(self): + if self._td is not None: + self._td.detach() + self._capi.LLVMPY_LLJITDispose(self) + + +def create_lljit_compiler(target_machine=None, *, + use_jit_link=False, + suppress_errors=False): + """ + Create an LLJIT instance + """ + with ffi.OutputString() as outerr: + lljit = ffi.lib.LLVMPY_CreateLLJITCompiler(target_machine, + suppress_errors, + use_jit_link, + outerr) + if not lljit: + raise RuntimeError(str(outerr)) + + return LLJIT(lljit) + + +ffi.lib.LLVMPY_LLJITLookup.argtypes = [ + ffi.LLVMOrcLLJITRef, + c_char_p, + c_char_p, + POINTER(c_uint64), + POINTER(c_char_p), +] +ffi.lib.LLVMPY_LLJITLookup.restype = ffi.LLVMOrcDylibTrackerRef + +ffi.lib.LLVMPY_LLJITGetDataLayout.argtypes = [ + ffi.LLVMOrcLLJITRef, +] +ffi.lib.LLVMPY_LLJITGetDataLayout.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_CreateLLJITCompiler.argtypes = [ + ffi.LLVMTargetMachineRef, + c_bool, + c_bool, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_CreateLLJITCompiler.restype = ffi.LLVMOrcLLJITRef + +ffi.lib.LLVMPY_LLJITDispose.argtypes = [ + ffi.LLVMOrcLLJITRef, +] + + +ffi.lib.LLVMPY_LLJIT_Link.argtypes = [ + ffi.LLVMOrcLLJITRef, + c_char_p, + POINTER(_LinkElement), + c_size_t, + POINTER(_SymbolAddress), + c_size_t, + POINTER(_SymbolAddress), + c_size_t, + POINTER(c_char_p) +] +ffi.lib.LLVMPY_LLJIT_Link.restype = ffi.LLVMOrcDylibTrackerRef + +ffi.lib.LLVMPY_LLJIT_Dylib_Tracker_Dispose.argtypes = [ + ffi.LLVMOrcDylibTrackerRef, + POINTER(c_char_p) +] +ffi.lib.LLVMPY_LLJIT_Dylib_Tracker_Dispose.restype = c_bool diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/passmanagers.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/passmanagers.py new file mode 100644 index 0000000000000000000000000000000000000000..af6152f630552aba97c35f62c5707d038437a8a0 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/passmanagers.py @@ -0,0 +1,939 @@ +from ctypes import (c_bool, c_char_p, c_int, c_size_t, c_uint, Structure, byref, + POINTER) +from collections import namedtuple +from enum import IntFlag +from llvmlite.binding import ffi +from llvmlite.binding.initfini import llvm_version_info +import os +from tempfile import mkstemp +from llvmlite.binding.common import _encode_string + +_prunestats = namedtuple('PruneStats', + ('basicblock diamond fanout fanout_raise')) + +llvm_version_major = llvm_version_info[0] + + +class PruneStats(_prunestats): + """ Holds statistics from reference count pruning. + """ + + def __add__(self, other): + if not isinstance(other, PruneStats): + msg = 'PruneStats can only be added to another PruneStats, got {}.' + raise TypeError(msg.format(type(other))) + return PruneStats(self.basicblock + other.basicblock, + self.diamond + other.diamond, + self.fanout + other.fanout, + self.fanout_raise + other.fanout_raise) + + def __sub__(self, other): + if not isinstance(other, PruneStats): + msg = ('PruneStats can only be subtracted from another PruneStats, ' + 'got {}.') + raise TypeError(msg.format(type(other))) + return PruneStats(self.basicblock - other.basicblock, + self.diamond - other.diamond, + self.fanout - other.fanout, + self.fanout_raise - other.fanout_raise) + + +class _c_PruneStats(Structure): + _fields_ = [ + ('basicblock', c_size_t), + ('diamond', c_size_t), + ('fanout', c_size_t), + ('fanout_raise', c_size_t)] + + +def dump_refprune_stats(printout=False): + """ Returns a namedtuple containing the current values for the refop pruning + statistics. If kwarg `printout` is True the stats are printed to stderr, + default is False. + """ + + stats = _c_PruneStats(0, 0, 0, 0) + do_print = c_bool(printout) + + ffi.lib.LLVMPY_DumpRefPruneStats(byref(stats), do_print) + return PruneStats(stats.basicblock, stats.diamond, stats.fanout, + stats.fanout_raise) + + +def set_time_passes(enable): + """Enable or disable the pass timers. + + Parameters + ---------- + enable : bool + Set to True to enable the pass timers. + Set to False to disable the pass timers. + """ + ffi.lib.LLVMPY_SetTimePasses(c_bool(enable)) + + +def report_and_reset_timings(): + """Returns the pass timings report and resets the LLVM internal timers. + + Pass timers are enabled by ``set_time_passes()``. If the timers are not + enabled, this function will return an empty string. + + Returns + ------- + res : str + LLVM generated timing report. + """ + with ffi.OutputString() as buf: + ffi.lib.LLVMPY_ReportAndResetTimings(buf) + return str(buf) + + +def create_module_pass_manager(): + return ModulePassManager() + + +def create_function_pass_manager(module): + return FunctionPassManager(module) + + +class RefPruneSubpasses(IntFlag): + PER_BB = 0b0001 # noqa: E221 + DIAMOND = 0b0010 # noqa: E221 + FANOUT = 0b0100 # noqa: E221 + FANOUT_RAISE = 0b1000 + ALL = PER_BB | DIAMOND | FANOUT | FANOUT_RAISE + + +class PassManager(ffi.ObjectRef): + """PassManager + """ + + def _dispose(self): + self._capi.LLVMPY_DisposePassManager(self) + + def add_aa_eval_pass(self): + """ + See https://llvm.org/docs/Passes.html#aa-eval-exhaustive-alias-analysis-precision-evaluator + + LLVM 14: `llvm::createAAEvalPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddAAEvalPass(self) + + def add_basic_aa_pass(self): + """ + See https://llvm.org/docs/Passes.html#basic-aa-basic-alias-analysis-stateless-aa-impl + + LLVM 14: `llvm::createBasicAAWrapperPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddBasicAAWrapperPass(self) + + def add_constant_merge_pass(self): + """ + See http://llvm.org/docs/Passes.html#constmerge-merge-duplicate-global-constants + + LLVM 14: `LLVMAddConstantMergePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddConstantMergePass(self) + + def add_dead_arg_elimination_pass(self): + """ + See http://llvm.org/docs/Passes.html#deadargelim-dead-argument-elimination + + LLVM 14: `LLVMAddDeadArgEliminationPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDeadArgEliminationPass(self) + + def add_dependence_analysis_pass(self): + """ + See https://llvm.org/docs/Passes.html#da-dependence-analysis + + LLVM 14: `llvm::createDependenceAnalysisWrapperPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDependenceAnalysisPass(self) + + def add_dot_call_graph_pass(self): + """ + See https://llvm.org/docs/Passes.html#dot-callgraph-print-call-graph-to-dot-file + + LLVM 14: `llvm::createCallGraphDOTPrinterPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddCallGraphDOTPrinterPass(self) + + def add_dot_cfg_printer_pass(self): + """ + See https://llvm.org/docs/Passes.html#dot-cfg-print-cfg-of-function-to-dot-file + + LLVM 14: `llvm::createCFGPrinterLegacyPassPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddCFGPrinterPass(self) + + def add_dot_dom_printer_pass(self, show_body=False): + """ + See https://llvm.org/docs/Passes.html#dot-dom-print-dominance-tree-of-function-to-dot-file + + LLVM 14: `llvm::createDomPrinterPass` and `llvm::createDomOnlyPrinterPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDotDomPrinterPass(self, show_body) + + def add_dot_postdom_printer_pass(self, show_body=False): + """ + See https://llvm.org/docs/Passes.html#dot-postdom-print-postdominance-tree-of-function-to-dot-file + + LLVM 14: `llvm::createPostDomPrinterPass` and `llvm::createPostDomOnlyPrinterPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDotPostDomPrinterPass(self, show_body) + + def add_globals_mod_ref_aa_pass(self): + """ + See https://llvm.org/docs/Passes.html#globalsmodref-aa-simple-mod-ref-analysis-for-globals + + LLVM 14: `llvm::createGlobalsAAWrapperPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddGlobalsModRefAAPass(self) + + def add_iv_users_pass(self): + """ + See https://llvm.org/docs/Passes.html#iv-users-induction-variable-users + + LLVM 14: `llvm::createIVUsersPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddIVUsersPass(self) + + def add_lint_pass(self): + """ + See https://llvm.org/docs/Passes.html#lint-statically-lint-checks-llvm-ir + + LLVM 14: `llvm::createLintLegacyPassPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLintPass(self) + + def add_lazy_value_info_pass(self): + """ + See https://llvm.org/docs/Passes.html#lazy-value-info-lazy-value-information-analysis + + LLVM 14: `llvm::createLazyValueInfoPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLazyValueInfoPass(self) + + def add_module_debug_info_pass(self): + """ + See https://llvm.org/docs/Passes.html#module-debuginfo-decodes-module-level-debug-info + + LLVM 14: `llvm::createModuleDebugInfoPrinterPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddModuleDebugInfoPrinterPass(self) + + def add_region_info_pass(self): + """ + See https://llvm.org/docs/Passes.html#regions-detect-single-entry-single-exit-regions + + LLVM 14: `llvm::createRegionInfoPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddRegionInfoPass(self) + + def add_scalar_evolution_aa_pass(self): + """ + See https://llvm.org/docs/Passes.html#scev-aa-scalarevolution-based-alias-analysis + + LLVM 14: `llvm::createSCEVAAWrapperPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddScalarEvolutionAAPass(self) + + def add_aggressive_dead_code_elimination_pass(self): + """ + See https://llvm.org/docs/Passes.html#adce-aggressive-dead-code-elimination + + LLVM 14: `llvm::createAggressiveDCEPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddAggressiveDCEPass(self) + + def add_always_inliner_pass(self, insert_lifetime=True): + """ + See https://llvm.org/docs/Passes.html#always-inline-inliner-for-always-inline-functions + + LLVM 14: `llvm::createAlwaysInlinerLegacyPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddAlwaysInlinerPass(self, insert_lifetime) + + def add_arg_promotion_pass(self, max_elements=3): + """ + See https://llvm.org/docs/Passes.html#argpromotion-promote-by-reference-arguments-to-scalars + + LLVM 14: `llvm::createArgumentPromotionPass` + """ # noqa E501 + if llvm_version_major > 14: + raise RuntimeError('ArgumentPromotionPass unavailable in LLVM > 14') + ffi.lib.LLVMPY_AddArgPromotionPass(self, max_elements) + + def add_break_critical_edges_pass(self): + """ + See https://llvm.org/docs/Passes.html#break-crit-edges-break-critical-edges-in-cfg + + LLVM 14: `llvm::createBreakCriticalEdgesPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddBreakCriticalEdgesPass(self) + + def add_dead_store_elimination_pass(self): + """ + See https://llvm.org/docs/Passes.html#dse-dead-store-elimination + + LLVM 14: `llvm::createDeadStoreEliminationPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDeadStoreEliminationPass(self) + + def add_reverse_post_order_function_attrs_pass(self): + """ + See https://llvm.org/docs/Passes.html#function-attrs-deduce-function-attributes + + LLVM 14: `llvm::createReversePostOrderFunctionAttrsPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddReversePostOrderFunctionAttrsPass(self) + + def add_function_attrs_pass(self): + """ + See http://llvm.org/docs/Passes.html#functionattrs-deduce-function-attributes + + LLVM 14: `LLVMAddFunctionAttrsPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddFunctionAttrsPass(self) + + def add_function_inlining_pass(self, threshold): + """ + See http://llvm.org/docs/Passes.html#inline-function-integration-inlining + + LLVM 14: `createFunctionInliningPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddFunctionInliningPass(self, threshold) + + def add_global_dce_pass(self): + """ + See http://llvm.org/docs/Passes.html#globaldce-dead-global-elimination + + LLVM 14: `LLVMAddGlobalDCEPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddGlobalDCEPass(self) + + def add_global_optimizer_pass(self): + """ + See http://llvm.org/docs/Passes.html#globalopt-global-variable-optimizer + + LLVM 14: `LLVMAddGlobalOptimizerPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddGlobalOptimizerPass(self) + + def add_ipsccp_pass(self): + """ + See http://llvm.org/docs/Passes.html#ipsccp-interprocedural-sparse-conditional-constant-propagation + + LLVM 14: `LLVMAddIPSCCPPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddIPSCCPPass(self) + + def add_dead_code_elimination_pass(self): + """ + See http://llvm.org/docs/Passes.html#dce-dead-code-elimination + LLVM 14: `llvm::createDeadCodeEliminationPass` + """ + ffi.lib.LLVMPY_AddDeadCodeEliminationPass(self) + + def add_aggressive_instruction_combining_pass(self): + """ + See https://llvm.org/docs/Passes.html#aggressive-instcombine-combine-expression-patterns + + LLVM 14: `llvm::createAggressiveInstCombinerPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddAggressiveInstructionCombiningPass(self) + + def add_internalize_pass(self): + """ + See https://llvm.org/docs/Passes.html#internalize-internalize-global-symbols + + LLVM 14: `llvm::createInternalizePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddInternalizePass(self) + + def add_cfg_simplification_pass(self): + """ + See http://llvm.org/docs/Passes.html#simplifycfg-simplify-the-cfg + + LLVM 14: `LLVMAddCFGSimplificationPass` + """ + ffi.lib.LLVMPY_AddCFGSimplificationPass(self) + + def add_jump_threading_pass(self, threshold=-1): + """ + See https://llvm.org/docs/Passes.html#jump-threading-jump-threading + + LLVM 14: `llvm::createJumpThreadingPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddJumpThreadingPass(self, threshold) + + def add_lcssa_pass(self): + """ + See https://llvm.org/docs/Passes.html#lcssa-loop-closed-ssa-form-pass + + LLVM 14: `llvm::createLCSSAPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLCSSAPass(self) + + def add_gvn_pass(self): + """ + See http://llvm.org/docs/Passes.html#gvn-global-value-numbering + + LLVM 14: `LLVMAddGVNPass` + """ + ffi.lib.LLVMPY_AddGVNPass(self) + + def add_instruction_combining_pass(self): + """ + See http://llvm.org/docs/Passes.html#passes-instcombine + + LLVM 14: `LLVMAddInstructionCombiningPass` + """ + ffi.lib.LLVMPY_AddInstructionCombiningPass(self) + + def add_licm_pass(self): + """ + See http://llvm.org/docs/Passes.html#licm-loop-invariant-code-motion + + LLVM 14: `LLVMAddLICMPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLICMPass(self) + + def add_loop_deletion_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-deletion-delete-dead-loops + + LLVM 14: `llvm::createLoopDeletionPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopDeletionPass(self) + + def add_loop_extractor_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-extract-extract-loops-into-new-functions + + LLVM 14: `llvm::createLoopExtractorPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopExtractorPass(self) + + def add_single_loop_extractor_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-extract-single-extract-at-most-one-loop-into-a-new-function + + LLVM 14: `llvm::createSingleLoopExtractorPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddSingleLoopExtractorPass(self) + + def add_sccp_pass(self): + """ + See http://llvm.org/docs/Passes.html#sccp-sparse-conditional-constant-propagation + + LLVM 14: `LLVMAddSCCPPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddSCCPPass(self) + + def add_loop_strength_reduce_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-reduce-loop-strength-reduction + + LLVM 14: `llvm::createLoopStrengthReducePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopStrengthReducePass(self) + + def add_loop_simplification_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-simplify-canonicalize-natural-loops + + LLVM 14: `llvm::createLoopSimplifyPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopSimplificationPass(self) + + def add_loop_unroll_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-unroll-unroll-loops + + LLVM 14: `LLVMAddLoopUnrollPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopUnrollPass(self) + + def add_loop_unroll_and_jam_pass(self): + """ + See https://llvm.org/docs/Passes.html#loop-unroll-and-jam-unroll-and-jam-loops + + LLVM 14: `LLVMAddLoopUnrollAndJamPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopUnrollAndJamPass(self) + + def add_loop_unswitch_pass(self, + optimize_for_size=False, + has_branch_divergence=False): + """ + See https://llvm.org/docs/Passes.html#loop-unswitch-unswitch-loops + + LLVM 14: `llvm::createLoopUnswitchPass` + LLVM 15: `llvm::createSimpleLoopUnswitchLegacyPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLoopUnswitchPass(self, optimize_for_size, + has_branch_divergence) + + def add_lower_atomic_pass(self): + """ + See https://llvm.org/docs/Passes.html#loweratomic-lower-atomic-intrinsics-to-non-atomic-form + + LLVM 14: `llvm::createLowerAtomicPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLowerAtomicPass(self) + + def add_lower_invoke_pass(self): + """ + See https://llvm.org/docs/Passes.html#lowerinvoke-lower-invokes-to-calls-for-unwindless-code-generators + + LLVM 14: `llvm::createLowerInvokePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLowerInvokePass(self) + + def add_lower_switch_pass(self): + """ + See https://llvm.org/docs/Passes.html#lowerswitch-lower-switchinsts-to-branches + + LLVM 14: `llvm::createLowerSwitchPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddLowerSwitchPass(self) + + def add_memcpy_optimization_pass(self): + """ + See https://llvm.org/docs/Passes.html#memcpyopt-memcpy-optimization + + LLVM 14: `llvm::createMemCpyOptPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddMemCpyOptimizationPass(self) + + def add_merge_functions_pass(self): + """ + See https://llvm.org/docs/Passes.html#mergefunc-merge-functions + + LLVM 14: `llvm::createMergeFunctionsPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddMergeFunctionsPass(self) + + def add_merge_returns_pass(self): + """ + See https://llvm.org/docs/Passes.html#mergereturn-unify-function-exit-nodes + + LLVM 14: `llvm::createUnifyFunctionExitNodesPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddMergeReturnsPass(self) + + def add_partial_inlining_pass(self): + """ + See https://llvm.org/docs/Passes.html#partial-inliner-partial-inliner + + LLVM 14: `llvm::createPartialInliningPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddPartialInliningPass(self) + + def add_prune_exception_handling_pass(self): + """ + See https://llvm.org/docs/Passes.html#prune-eh-remove-unused-exception-handling-info + + LLVM 14: `llvm::createPruneEHPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddPruneExceptionHandlingPass(self) + + def add_reassociate_expressions_pass(self): + """ + See https://llvm.org/docs/Passes.html#reassociate-reassociate-expressions + + LLVM 14: `llvm::createReassociatePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddReassociatePass(self) + + def add_demote_register_to_memory_pass(self): + """ + See https://llvm.org/docs/Passes.html#rel-lookup-table-converter-relative-lookup-table-converter + + LLVM 14: `llvm::createDemoteRegisterToMemoryPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddDemoteRegisterToMemoryPass(self) + + def add_sroa_pass(self): + """ + See http://llvm.org/docs/Passes.html#scalarrepl-scalar-replacement-of-aggregates-dt + Note that this pass corresponds to the ``opt -sroa`` command-line option, + despite the link above. + + LLVM 14: `llvm::createSROAPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddSROAPass(self) + + def add_sink_pass(self): + """ + See https://llvm.org/docs/Passes.html#sink-code-sinking + + LLVM 14: `llvm::createSinkingPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddSinkPass(self) + + def add_strip_symbols_pass(self, only_debug=False): + """ + See https://llvm.org/docs/Passes.html#strip-strip-all-symbols-from-a-module + + LLVM 14: `llvm::createStripSymbolsPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddStripSymbolsPass(self, only_debug) + + def add_strip_dead_debug_info_pass(self): + """ + See https://llvm.org/docs/Passes.html#strip-dead-debug-info-strip-debug-info-for-unused-symbols + + LLVM 14: `llvm::createStripDeadDebugInfoPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddStripDeadDebugInfoPass(self) + + def add_strip_dead_prototypes_pass(self): + """ + See https://llvm.org/docs/Passes.html#strip-dead-prototypes-strip-unused-function-prototypes + + LLVM 14: `llvm::createStripDeadPrototypesPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddStripDeadPrototypesPass(self) + + def add_strip_debug_declare_pass(self): + """ + See https://llvm.org/docs/Passes.html#strip-debug-declare-strip-all-llvm-dbg-declare-intrinsics + + LLVM 14: `llvm::createStripDebugDeclarePass` + """ # noqa E501 + ffi.lib.LLVMPY_AddStripDebugDeclarePrototypesPass(self) + + def add_strip_nondebug_symbols_pass(self): + """ + See https://llvm.org/docs/Passes.html#strip-nondebug-strip-all-symbols-except-dbg-symbols-from-a-module + + LLVM 14: `llvm::createStripNonDebugSymbolsPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddStripNondebugSymbolsPass(self) + + def add_tail_call_elimination_pass(self): + """ + See https://llvm.org/docs/Passes.html#tailcallelim-tail-call-elimination + + LLVM 14: `llvm::createTailCallEliminationPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddTailCallEliminationPass(self) + + def add_type_based_alias_analysis_pass(self): + """ + LLVM 14: `LLVMAddTypeBasedAliasAnalysisPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddTypeBasedAliasAnalysisPass(self) + + def add_basic_alias_analysis_pass(self): + """ + See http://llvm.org/docs/AliasAnalysis.html#the-basicaa-pass + + LLVM 14: `LLVMAddBasicAliasAnalysisPass` + """ + ffi.lib.LLVMPY_AddBasicAliasAnalysisPass(self) + + def add_loop_rotate_pass(self): + """http://llvm.org/docs/Passes.html#loop-rotate-rotate-loops.""" + ffi.lib.LLVMPY_LLVMAddLoopRotatePass(self) + + def add_target_library_info(self, triple): + ffi.lib.LLVMPY_AddTargetLibraryInfoPass(self, _encode_string(triple)) + + def add_instruction_namer_pass(self): + """ + See https://llvm.org/docs/Passes.html#instnamer-assign-names-to-anonymous-instructions. + + LLVM 14: `llvm::createInstructionNamerPass` + """ # noqa E501 + ffi.lib.LLVMPY_AddInstructionNamerPass(self) + + # Non-standard LLVM passes + + def add_refprune_pass(self, subpasses_flags=RefPruneSubpasses.ALL, + subgraph_limit=1000): + """Add Numba specific Reference count pruning pass. + + Parameters + ---------- + subpasses_flags : RefPruneSubpasses + A bitmask to control the subpasses to be enabled. + subgraph_limit : int + Limit the fanout pruners to working on a subgraph no bigger than + this number of basic-blocks to avoid spending too much time in very + large graphs. Default is 1000. Subject to change in future + versions. + """ + iflags = RefPruneSubpasses(subpasses_flags) + ffi.lib.LLVMPY_AddRefPrunePass(self, iflags, subgraph_limit) + + +class ModulePassManager(PassManager): + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_CreatePassManager() + PassManager.__init__(self, ptr) + + def run(self, module, remarks_file=None, remarks_format='yaml', + remarks_filter=''): + """ + Run optimization passes on the given module. + + Parameters + ---------- + module : llvmlite.binding.ModuleRef + The module to be optimized inplace + remarks_file : str; optional + If not `None`, it is the file to store the optimization remarks. + remarks_format : str; optional + The format to write; YAML is default + remarks_filter : str; optional + The filter that should be applied to the remarks output. + """ + if remarks_file is None: + return ffi.lib.LLVMPY_RunPassManager(self, module) + else: + r = ffi.lib.LLVMPY_RunPassManagerWithRemarks( + self, module, _encode_string(remarks_format), + _encode_string(remarks_filter), + _encode_string(remarks_file)) + if r == -1: + raise IOError("Failed to initialize remarks file.") + return r > 0 + + def run_with_remarks(self, module, remarks_format='yaml', + remarks_filter=''): + """ + Run optimization passes on the given module and returns the result and + the remarks data. + + Parameters + ---------- + module : llvmlite.binding.ModuleRef + The module to be optimized + remarks_format : str + The remarks output; YAML is the default + remarks_filter : str; optional + The filter that should be applied to the remarks output. + """ + remarkdesc, remarkfile = mkstemp() + try: + with os.fdopen(remarkdesc, 'r'): + pass + r = self.run(module, remarkfile, remarks_format, remarks_filter) + if r == -1: + raise IOError("Failed to initialize remarks file.") + with open(remarkfile) as f: + return bool(r), f.read() + finally: + os.unlink(remarkfile) + + +class FunctionPassManager(PassManager): + + def __init__(self, module): + ptr = ffi.lib.LLVMPY_CreateFunctionPassManager(module) + self._module = module + module._owned = True + PassManager.__init__(self, ptr) + + def initialize(self): + """ + Initialize the FunctionPassManager. Returns True if it produced + any changes (?). + """ + return ffi.lib.LLVMPY_InitializeFunctionPassManager(self) + + def finalize(self): + """ + Finalize the FunctionPassManager. Returns True if it produced + any changes (?). + """ + return ffi.lib.LLVMPY_FinalizeFunctionPassManager(self) + + def run(self, function, remarks_file=None, remarks_format='yaml', + remarks_filter=''): + """ + Run optimization passes on the given function. + + Parameters + ---------- + function : llvmlite.binding.FunctionRef + The function to be optimized inplace + remarks_file : str; optional + If not `None`, it is the file to store the optimization remarks. + remarks_format : str; optional + The format of the remarks file; the default is YAML + remarks_filter : str; optional + The filter that should be applied to the remarks output. + """ + if remarks_file is None: + return ffi.lib.LLVMPY_RunFunctionPassManager(self, function) + else: + r = ffi.lib.LLVMPY_RunFunctionPassManagerWithRemarks( + self, function, _encode_string(remarks_format), + _encode_string(remarks_filter), + _encode_string(remarks_file)) + if r == -1: + raise IOError("Failed to initialize remarks file.") + return bool(r) + + def run_with_remarks(self, function, remarks_format='yaml', + remarks_filter=''): + """ + Run optimization passes on the given function and returns the result + and the remarks data. + + Parameters + ---------- + function : llvmlite.binding.FunctionRef + The function to be optimized inplace + remarks_format : str; optional + The format of the remarks file; the default is YAML + remarks_filter : str; optional + The filter that should be applied to the remarks output. + """ + # LLVM is going to need to close this file and then reopen it, so we + # can't use an unlinked temporary file. + remarkdesc, remarkfile = mkstemp() + try: + # We get an open handle, but we need LLVM to write first, so close + # it. + with os.fdopen(remarkdesc, 'r'): + pass + r = self.run(function, remarkfile, remarks_format, remarks_filter) + if r == -1: + raise IOError("Failed to initialize remarks file.") + with open(remarkfile) as f: + return bool(r), f.read() + finally: + os.unlink(remarkfile) + + +# ============================================================================ +# FFI + +ffi.lib.LLVMPY_CreatePassManager.restype = ffi.LLVMPassManagerRef + +ffi.lib.LLVMPY_CreateFunctionPassManager.argtypes = [ffi.LLVMModuleRef] +ffi.lib.LLVMPY_CreateFunctionPassManager.restype = ffi.LLVMPassManagerRef + +ffi.lib.LLVMPY_DisposePassManager.argtypes = [ffi.LLVMPassManagerRef] + +ffi.lib.LLVMPY_RunPassManager.argtypes = [ffi.LLVMPassManagerRef, + ffi.LLVMModuleRef] +ffi.lib.LLVMPY_RunPassManager.restype = c_bool + +ffi.lib.LLVMPY_RunPassManagerWithRemarks.argtypes = [ffi.LLVMPassManagerRef, + ffi.LLVMModuleRef, + c_char_p, + c_char_p, + c_char_p] +ffi.lib.LLVMPY_RunPassManagerWithRemarks.restype = c_int + +ffi.lib.LLVMPY_InitializeFunctionPassManager.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_InitializeFunctionPassManager.restype = c_bool + +ffi.lib.LLVMPY_FinalizeFunctionPassManager.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_FinalizeFunctionPassManager.restype = c_bool + +ffi.lib.LLVMPY_RunFunctionPassManager.argtypes = [ffi.LLVMPassManagerRef, + ffi.LLVMValueRef] +ffi.lib.LLVMPY_RunFunctionPassManager.restype = c_bool + +ffi.lib.LLVMPY_RunFunctionPassManagerWithRemarks.argtypes = [ + ffi.LLVMPassManagerRef, ffi.LLVMValueRef, c_char_p, c_char_p, c_char_p +] +ffi.lib.LLVMPY_RunFunctionPassManagerWithRemarks.restype = c_int + +ffi.lib.LLVMPY_AddAAEvalPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddBasicAAWrapperPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddConstantMergePass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddDeadArgEliminationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddDependenceAnalysisPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddCallGraphDOTPrinterPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddCFGPrinterPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddDotDomPrinterPass.argtypes = [ffi.LLVMPassManagerRef, c_bool] +ffi.lib.LLVMPY_AddDotPostDomPrinterPass.argtypes = [ + ffi.LLVMPassManagerRef, + c_bool] +ffi.lib.LLVMPY_AddGlobalsModRefAAPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddInstructionCountPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddIVUsersPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLazyValueInfoPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLintPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddModuleDebugInfoPrinterPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddRegionInfoPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddScalarEvolutionAAPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddAggressiveDCEPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddAlwaysInlinerPass.argtypes = [ffi.LLVMPassManagerRef, c_bool] + +if llvm_version_major < 15: + ffi.lib.LLVMPY_AddArgPromotionPass.argtypes = [ + ffi.LLVMPassManagerRef, c_uint] + +ffi.lib.LLVMPY_AddBreakCriticalEdgesPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddDeadStoreEliminationPass.argtypes = [ + ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddReversePostOrderFunctionAttrsPass.argtypes = [ + ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddAggressiveInstructionCombiningPass.argtypes = [ + ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddInternalizePass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLCSSAPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopDeletionPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopExtractorPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddSingleLoopExtractorPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopStrengthReducePass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopSimplificationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopUnrollPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopUnrollAndJamPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLoopUnswitchPass.argtypes = [ffi.LLVMPassManagerRef, c_bool, + c_bool] +ffi.lib.LLVMPY_AddLowerAtomicPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLowerInvokePass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLowerSwitchPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddMemCpyOptimizationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddMergeFunctionsPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddMergeReturnsPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddPartialInliningPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddPruneExceptionHandlingPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddReassociatePass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddDemoteRegisterToMemoryPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddSinkPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddStripSymbolsPass.argtypes = [ffi.LLVMPassManagerRef, c_bool] +ffi.lib.LLVMPY_AddStripDeadDebugInfoPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddStripDeadPrototypesPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddStripDebugDeclarePrototypesPass.argtypes = [ + ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddStripNondebugSymbolsPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddTailCallEliminationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddJumpThreadingPass.argtypes = [ffi.LLVMPassManagerRef, c_int] +ffi.lib.LLVMPY_AddFunctionAttrsPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddFunctionInliningPass.argtypes = [ + ffi.LLVMPassManagerRef, c_int] +ffi.lib.LLVMPY_AddGlobalDCEPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddGlobalOptimizerPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddIPSCCPPass.argtypes = [ffi.LLVMPassManagerRef] + +ffi.lib.LLVMPY_AddDeadCodeEliminationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddCFGSimplificationPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddGVNPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddInstructionCombiningPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddLICMPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddSCCPPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddSROAPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddTypeBasedAliasAnalysisPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddBasicAliasAnalysisPass.argtypes = [ffi.LLVMPassManagerRef] +ffi.lib.LLVMPY_AddTargetLibraryInfoPass.argtypes = [ffi.LLVMPassManagerRef, + c_char_p] +ffi.lib.LLVMPY_AddInstructionNamerPass.argtypes = [ffi.LLVMPassManagerRef] + +ffi.lib.LLVMPY_AddRefPrunePass.argtypes = [ffi.LLVMPassManagerRef, c_int, + c_size_t] + +ffi.lib.LLVMPY_DumpRefPruneStats.argtypes = [POINTER(_c_PruneStats), c_bool] diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/targets.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/targets.py new file mode 100644 index 0000000000000000000000000000000000000000..a7e6ffdc3e51e2d668f944ff6ca4f75fc5c6c612 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/targets.py @@ -0,0 +1,450 @@ +import os +from ctypes import (POINTER, c_char_p, c_longlong, c_int, c_size_t, + c_void_p, string_at) + +from llvmlite.binding import ffi +from llvmlite.binding.common import _decode_string, _encode_string + + +def get_process_triple(): + """ + Return a target triple suitable for generating code for the current process. + An example when the default triple from ``get_default_triple()`` is not be + suitable is when LLVM is compiled for 32-bit but the process is executing + in 64-bit mode. + """ + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetProcessTriple(out) + return str(out) + + +class FeatureMap(dict): + """ + Maps feature name to a boolean indicating the availability of the feature. + Extends ``dict`` to add `.flatten()` method. + """ + + def flatten(self, sort=True): + """ + Args + ---- + sort: bool + Optional. If True, the features are sorted by name; otherwise, + the ordering is unstable between python session due to hash + randomization. Defaults to True. + + Returns a string suitable for use as the ``features`` argument to + ``Target.create_target_machine()``. + + """ + iterator = sorted(self.items()) if sort else iter(self.items()) + flag_map = {True: '+', False: '-'} + return ','.join('{0}{1}'.format(flag_map[v], k) + for k, v in iterator) + + +def get_host_cpu_features(): + """ + Returns a dictionary-like object indicating the CPU features for current + architecture and whether they are enabled for this CPU. The key-value pairs + are the feature name as string and a boolean indicating whether the feature + is available. The returned value is an instance of ``FeatureMap`` class, + which adds a new method ``.flatten()`` for returning a string suitable for + use as the "features" argument to ``Target.create_target_machine()``. + + If LLVM has not implemented this feature or it fails to get the information, + this function will raise a RuntimeError exception. + """ + with ffi.OutputString() as out: + outdict = FeatureMap() + if not ffi.lib.LLVMPY_GetHostCPUFeatures(out): + return outdict + flag_map = {'+': True, '-': False} + content = str(out) + if content: # protect against empty string + for feat in content.split(','): + if feat: # protect against empty feature + outdict[feat[1:]] = flag_map[feat[0]] + return outdict + + +def get_default_triple(): + """ + Return the default target triple LLVM is configured to produce code for. + """ + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetDefaultTargetTriple(out) + return str(out) + + +def get_host_cpu_name(): + """ + Get the name of the host's CPU, suitable for using with + :meth:`Target.create_target_machine()`. + """ + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetHostCPUName(out) + return str(out) + + +_object_formats = { + 1: "COFF", + 2: "ELF", + 3: "MachO", +} + + +def get_object_format(triple=None): + """ + Get the object format for the given *triple* string (or the default + triple if omitted). + A string is returned + """ + if triple is None: + triple = get_default_triple() + res = ffi.lib.LLVMPY_GetTripleObjectFormat(_encode_string(triple)) + return _object_formats[res] + + +def create_target_data(layout): + """ + Create a TargetData instance for the given *layout* string. + """ + return TargetData(ffi.lib.LLVMPY_CreateTargetData(_encode_string(layout))) + + +class TargetData(ffi.ObjectRef): + """ + A TargetData provides structured access to a data layout. + Use :func:`create_target_data` to create instances. + """ + + def __str__(self): + if self._closed: + return "" + with ffi.OutputString() as out: + ffi.lib.LLVMPY_CopyStringRepOfTargetData(self, out) + return str(out) + + def _dispose(self): + self._capi.LLVMPY_DisposeTargetData(self) + + def get_abi_size(self, ty): + """ + Get ABI size of LLVM type *ty*. + """ + return ffi.lib.LLVMPY_ABISizeOfType(self, ty) + + def get_element_offset(self, ty, position): + """ + Get byte offset of type's ty element at the given position + """ + + offset = ffi.lib.LLVMPY_OffsetOfElement(self, ty, position) + if offset == -1: + raise ValueError("Could not determined offset of {}th " + "element of the type '{}'. Is it a struct" + "type?".format(position, str(ty))) + return offset + + def get_pointee_abi_size(self, ty): + """ + Get ABI size of pointee type of LLVM pointer type *ty*. + """ + size = ffi.lib.LLVMPY_ABISizeOfElementType(self, ty) + if size == -1: + raise RuntimeError("Not a pointer type: %s" % (ty,)) + return size + + def get_pointee_abi_alignment(self, ty): + """ + Get minimum ABI alignment of pointee type of LLVM pointer type *ty*. + """ + size = ffi.lib.LLVMPY_ABIAlignmentOfElementType(self, ty) + if size == -1: + raise RuntimeError("Not a pointer type: %s" % (ty,)) + return size + + +RELOC = frozenset(['default', 'static', 'pic', 'dynamicnopic']) +CODEMODEL = frozenset(['default', 'jitdefault', 'small', 'kernel', 'medium', + 'large']) + + +class Target(ffi.ObjectRef): + _triple = '' + + # No _dispose() method since LLVMGetTargetFromTriple() returns a + # persistent object. + + @classmethod + def from_default_triple(cls): + """ + Create a Target instance for the default triple. + """ + triple = get_default_triple() + return cls.from_triple(triple) + + @classmethod + def from_triple(cls, triple): + """ + Create a Target instance for the given triple (a string). + """ + with ffi.OutputString() as outerr: + target = ffi.lib.LLVMPY_GetTargetFromTriple(triple.encode('utf8'), + outerr) + if not target: + raise RuntimeError(str(outerr)) + target = cls(target) + target._triple = triple + return target + + @property + def name(self): + s = ffi.lib.LLVMPY_GetTargetName(self) + return _decode_string(s) + + @property + def description(self): + s = ffi.lib.LLVMPY_GetTargetDescription(self) + return _decode_string(s) + + @property + def triple(self): + return self._triple + + def __str__(self): + return "".format(self.name, self.description) + + def create_target_machine(self, cpu='', features='', + opt=2, reloc='default', codemodel='jitdefault', + printmc=False, jit=False, abiname=''): + """ + Create a new TargetMachine for this target and the given options. + + Specifying codemodel='default' will result in the use of the "small" + code model. Specifying codemodel='jitdefault' will result in the code + model being picked based on platform bitness (32="small", 64="large"). + + The `printmc` option corresponds to llvm's `-print-machineinstrs`. + + The `jit` option should be set when the target-machine is to be used + in a JIT engine. + + The `abiname` option specifies the ABI. RISC-V targets with hard-float + needs to pass the ABI name to LLVM. + """ + assert 0 <= opt <= 3 + assert reloc in RELOC + assert codemodel in CODEMODEL + triple = self._triple + # MCJIT under Windows only supports ELF objects, see + # http://lists.llvm.org/pipermail/llvm-dev/2013-December/068341.html + # Note we still want to produce regular COFF files in AOT mode. + if os.name == 'nt' and codemodel == 'jitdefault': + triple += '-elf' + tm = ffi.lib.LLVMPY_CreateTargetMachine(self, + _encode_string(triple), + _encode_string(cpu), + _encode_string(features), + opt, + _encode_string(reloc), + _encode_string(codemodel), + int(printmc), + int(jit), + _encode_string(abiname), + ) + if tm: + return TargetMachine(tm) + else: + raise RuntimeError("Cannot create target machine") + + +class TargetMachine(ffi.ObjectRef): + + def _dispose(self): + self._capi.LLVMPY_DisposeTargetMachine(self) + + def add_analysis_passes(self, pm): + """ + Register analysis passes for this target machine with a pass manager. + """ + ffi.lib.LLVMPY_AddAnalysisPasses(self, pm) + + def set_asm_verbosity(self, verbose): + """ + Set whether this target machine will emit assembly with human-readable + comments describing control flow, debug information, and so on. + """ + ffi.lib.LLVMPY_SetTargetMachineAsmVerbosity(self, verbose) + + def emit_object(self, module): + """ + Represent the module as a code object, suitable for use with + the platform's linker. Returns a byte string. + """ + return self._emit_to_memory(module, use_object=True) + + def emit_assembly(self, module): + """ + Return the raw assembler of the module, as a string. + + llvm.initialize_native_asmprinter() must have been called first. + """ + return _decode_string(self._emit_to_memory(module, use_object=False)) + + def _emit_to_memory(self, module, use_object=False): + """Returns bytes of object code of the module. + + Args + ---- + use_object : bool + Emit object code or (if False) emit assembly code. + """ + with ffi.OutputString() as outerr: + mb = ffi.lib.LLVMPY_TargetMachineEmitToMemory(self, module, + int(use_object), + outerr) + if not mb: + raise RuntimeError(str(outerr)) + + bufptr = ffi.lib.LLVMPY_GetBufferStart(mb) + bufsz = ffi.lib.LLVMPY_GetBufferSize(mb) + try: + return string_at(bufptr, bufsz) + finally: + ffi.lib.LLVMPY_DisposeMemoryBuffer(mb) + + @property + def target_data(self): + return TargetData(ffi.lib.LLVMPY_CreateTargetMachineData(self)) + + @property + def triple(self): + with ffi.OutputString() as out: + ffi.lib.LLVMPY_GetTargetMachineTriple(self, out) + return str(out) + + +def has_svml(): + """ + Returns True if SVML was enabled at FFI support compile time. + """ + if ffi.lib.LLVMPY_HasSVMLSupport() == 0: + return False + else: + return True + + +# ============================================================================ +# FFI + +ffi.lib.LLVMPY_GetProcessTriple.argtypes = [POINTER(c_char_p)] + +ffi.lib.LLVMPY_GetHostCPUFeatures.argtypes = [POINTER(c_char_p)] +ffi.lib.LLVMPY_GetHostCPUFeatures.restype = c_int + +ffi.lib.LLVMPY_GetDefaultTargetTriple.argtypes = [POINTER(c_char_p)] + +ffi.lib.LLVMPY_GetHostCPUName.argtypes = [POINTER(c_char_p)] + +ffi.lib.LLVMPY_GetTripleObjectFormat.argtypes = [c_char_p] +ffi.lib.LLVMPY_GetTripleObjectFormat.restype = c_int + +ffi.lib.LLVMPY_CreateTargetData.argtypes = [c_char_p] +ffi.lib.LLVMPY_CreateTargetData.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_CopyStringRepOfTargetData.argtypes = [ + ffi.LLVMTargetDataRef, + POINTER(c_char_p), +] + +ffi.lib.LLVMPY_DisposeTargetData.argtypes = [ + ffi.LLVMTargetDataRef, +] + +ffi.lib.LLVMPY_ABISizeOfType.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ABISizeOfType.restype = c_longlong + +ffi.lib.LLVMPY_OffsetOfElement.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef, + c_int] +ffi.lib.LLVMPY_OffsetOfElement.restype = c_longlong + +ffi.lib.LLVMPY_ABISizeOfElementType.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ABISizeOfElementType.restype = c_longlong + +ffi.lib.LLVMPY_ABIAlignmentOfElementType.argtypes = [ffi.LLVMTargetDataRef, + ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ABIAlignmentOfElementType.restype = c_longlong + +ffi.lib.LLVMPY_GetTargetFromTriple.argtypes = [c_char_p, POINTER(c_char_p)] +ffi.lib.LLVMPY_GetTargetFromTriple.restype = ffi.LLVMTargetRef + +ffi.lib.LLVMPY_GetTargetName.argtypes = [ffi.LLVMTargetRef] +ffi.lib.LLVMPY_GetTargetName.restype = c_char_p + +ffi.lib.LLVMPY_GetTargetDescription.argtypes = [ffi.LLVMTargetRef] +ffi.lib.LLVMPY_GetTargetDescription.restype = c_char_p + +ffi.lib.LLVMPY_CreateTargetMachine.argtypes = [ + ffi.LLVMTargetRef, + # Triple + c_char_p, + # CPU + c_char_p, + # Features + c_char_p, + # OptLevel + c_int, + # Reloc + c_char_p, + # CodeModel + c_char_p, + # PrintMC + c_int, + # JIT + c_int, + # ABIName + c_char_p, +] +ffi.lib.LLVMPY_CreateTargetMachine.restype = ffi.LLVMTargetMachineRef + +ffi.lib.LLVMPY_DisposeTargetMachine.argtypes = [ffi.LLVMTargetMachineRef] + +ffi.lib.LLVMPY_GetTargetMachineTriple.argtypes = [ffi.LLVMTargetMachineRef, + POINTER(c_char_p)] + +ffi.lib.LLVMPY_SetTargetMachineAsmVerbosity.argtypes = [ + ffi.LLVMTargetMachineRef, c_int] + +ffi.lib.LLVMPY_AddAnalysisPasses.argtypes = [ + ffi.LLVMTargetMachineRef, + ffi.LLVMPassManagerRef, +] + +ffi.lib.LLVMPY_TargetMachineEmitToMemory.argtypes = [ + ffi.LLVMTargetMachineRef, + ffi.LLVMModuleRef, + c_int, + POINTER(c_char_p), +] +ffi.lib.LLVMPY_TargetMachineEmitToMemory.restype = ffi.LLVMMemoryBufferRef + +ffi.lib.LLVMPY_GetBufferStart.argtypes = [ffi.LLVMMemoryBufferRef] +ffi.lib.LLVMPY_GetBufferStart.restype = c_void_p + +ffi.lib.LLVMPY_GetBufferSize.argtypes = [ffi.LLVMMemoryBufferRef] +ffi.lib.LLVMPY_GetBufferSize.restype = c_size_t + +ffi.lib.LLVMPY_DisposeMemoryBuffer.argtypes = [ffi.LLVMMemoryBufferRef] + +ffi.lib.LLVMPY_CreateTargetMachineData.argtypes = [ + ffi.LLVMTargetMachineRef, +] +ffi.lib.LLVMPY_CreateTargetMachineData.restype = ffi.LLVMTargetDataRef + +ffi.lib.LLVMPY_HasSVMLSupport.argtypes = [] +ffi.lib.LLVMPY_HasSVMLSupport.restype = c_int diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/transforms.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..82c5dc157a54d7cb1730dadb9b453cc684640cbf --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/transforms.py @@ -0,0 +1,151 @@ +from ctypes import c_uint, c_bool +from llvmlite.binding import ffi +from llvmlite.binding import passmanagers + + +def create_pass_manager_builder(): + return PassManagerBuilder() + + +class PassManagerBuilder(ffi.ObjectRef): + __slots__ = () + + def __init__(self, ptr=None): + if ptr is None: + ptr = ffi.lib.LLVMPY_PassManagerBuilderCreate() + ffi.ObjectRef.__init__(self, ptr) + + @property + def opt_level(self): + """ + The general optimization level as an integer between 0 and 3. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetOptLevel(self) + + @opt_level.setter + def opt_level(self, level): + ffi.lib.LLVMPY_PassManagerBuilderSetOptLevel(self, level) + + @property + def size_level(self): + """ + Whether and how much to optimize for size. An integer between 0 and 2. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetSizeLevel(self) + + @size_level.setter + def size_level(self, size): + ffi.lib.LLVMPY_PassManagerBuilderSetSizeLevel(self, size) + + @property + def inlining_threshold(self): + """ + The integer threshold for inlining a function into another. The higher, + the more likely inlining a function is. This attribute is write-only. + """ + raise NotImplementedError("inlining_threshold is write-only") + + @inlining_threshold.setter + def inlining_threshold(self, threshold): + ffi.lib.LLVMPY_PassManagerBuilderUseInlinerWithThreshold( + self, threshold) + + @property + def disable_unroll_loops(self): + """ + If true, disable loop unrolling. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetDisableUnrollLoops(self) + + @disable_unroll_loops.setter + def disable_unroll_loops(self, disable=True): + ffi.lib.LLVMPY_PassManagerBuilderSetDisableUnrollLoops(self, disable) + + @property + def loop_vectorize(self): + """ + If true, allow vectorizing loops. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetLoopVectorize(self) + + @loop_vectorize.setter + def loop_vectorize(self, enable=True): + return ffi.lib.LLVMPY_PassManagerBuilderSetLoopVectorize(self, enable) + + @property + def slp_vectorize(self): + """ + If true, enable the "SLP vectorizer", which uses a different algorithm + from the loop vectorizer. Both may be enabled at the same time. + """ + return ffi.lib.LLVMPY_PassManagerBuilderGetSLPVectorize(self) + + @slp_vectorize.setter + def slp_vectorize(self, enable=True): + return ffi.lib.LLVMPY_PassManagerBuilderSetSLPVectorize(self, enable) + + def _populate_module_pm(self, pm): + ffi.lib.LLVMPY_PassManagerBuilderPopulateModulePassManager(self, pm) + + def _populate_function_pm(self, pm): + ffi.lib.LLVMPY_PassManagerBuilderPopulateFunctionPassManager(self, pm) + + def populate(self, pm): + if isinstance(pm, passmanagers.ModulePassManager): + self._populate_module_pm(pm) + elif isinstance(pm, passmanagers.FunctionPassManager): + self._populate_function_pm(pm) + else: + raise TypeError(pm) + + def _dispose(self): + self._capi.LLVMPY_PassManagerBuilderDispose(self) + + +# ============================================================================ +# FFI + +ffi.lib.LLVMPY_PassManagerBuilderCreate.restype = ffi.LLVMPassManagerBuilderRef + +ffi.lib.LLVMPY_PassManagerBuilderDispose.argtypes = [ + ffi.LLVMPassManagerBuilderRef, +] + +ffi.lib.LLVMPY_PassManagerBuilderPopulateModulePassManager.argtypes = [ + ffi.LLVMPassManagerBuilderRef, + ffi.LLVMPassManagerRef, +] + +ffi.lib.LLVMPY_PassManagerBuilderPopulateFunctionPassManager.argtypes = [ + ffi.LLVMPassManagerBuilderRef, + ffi.LLVMPassManagerRef, +] + +# Unsigned int PassManagerBuilder properties + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderSetOptLevel, + ffi.lib.LLVMPY_PassManagerBuilderSetSizeLevel, + ffi.lib.LLVMPY_PassManagerBuilderUseInlinerWithThreshold, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef, c_uint] + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderGetOptLevel, + ffi.lib.LLVMPY_PassManagerBuilderGetSizeLevel, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef] + _func.restype = c_uint + +# Boolean PassManagerBuilder properties + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderSetDisableUnrollLoops, + ffi.lib.LLVMPY_PassManagerBuilderSetLoopVectorize, + ffi.lib.LLVMPY_PassManagerBuilderSetSLPVectorize, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef, c_bool] + +for _func in (ffi.lib.LLVMPY_PassManagerBuilderGetDisableUnrollLoops, + ffi.lib.LLVMPY_PassManagerBuilderGetLoopVectorize, + ffi.lib.LLVMPY_PassManagerBuilderGetSLPVectorize, + ): + _func.argtypes = [ffi.LLVMPassManagerBuilderRef] + _func.restype = c_bool diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/typeref.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/typeref.py new file mode 100644 index 0000000000000000000000000000000000000000..994db263dde162ada0b835468dcad4519ae47a36 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/typeref.py @@ -0,0 +1,198 @@ +from ctypes import c_int, c_bool, c_void_p, c_uint64 +import enum + +from llvmlite.binding import ffi + + +class TypeKind(enum.IntEnum): + # The LLVMTypeKind enum from llvm-c/Core.h + + void = 0 + half = 1 + float = 2 + double = 3 + x86_fp80 = 4 + fp128 = 5 + ppc_fp128 = 6 + label = 7 + integer = 8 + function = 9 + struct = 10 + array = 11 + pointer = 12 + vector = 13 + metadata = 14 + x86_mmx = 15 + token = 16 + scalable_vector = 17 + bfloat = 18 + x86_amx = 19 + + +class TypeRef(ffi.ObjectRef): + """A weak reference to a LLVM type + """ + @property + def name(self): + """ + Get type name + """ + return ffi.ret_string(ffi.lib.LLVMPY_GetTypeName(self)) + + @property + def is_struct(self): + """ + Returns true if the type is a struct type. + """ + return ffi.lib.LLVMPY_TypeIsStruct(self) + + @property + def is_pointer(self): + """ + Returns true if the type is a pointer type. + """ + return ffi.lib.LLVMPY_TypeIsPointer(self) + + @property + def is_array(self): + """ + Returns true if the type is an array type. + """ + return ffi.lib.LLVMPY_TypeIsArray(self) + + @property + def is_vector(self): + """ + Returns true if the type is a vector type. + """ + return ffi.lib.LLVMPY_TypeIsVector(self) + + @property + def is_function_vararg(self): + """ + Returns true if a function type accepts a variable number of arguments. + When the type is not a function, raises exception. + """ + if self.type_kind != TypeKind.function: + raise ValueError("Type {} is not a function".format(self)) + return ffi.lib.LLVMPY_IsFunctionVararg(self) + + @property + def elements(self): + """ + Returns iterator over enclosing types + """ + return _TypeListIterator(ffi.lib.LLVMPY_ElementIter(self)) + + @property + def element_type(self): + """ + Returns the pointed-to type. When the type is not a pointer, + raises exception. + """ + if not self.is_pointer: + raise ValueError("Type {} is not a pointer".format(self)) + return TypeRef(ffi.lib.LLVMPY_GetElementType(self)) + + @property + def element_count(self): + """ + Returns the number of elements in an array or a vector. For scalable + vectors, returns minimum number of elements. When the type is neither + an array nor a vector, raises exception. + """ + if not self.is_array and not self.is_vector: + raise ValueError("Type {} is not an array nor vector".format(self)) + return ffi.lib.LLVMPY_GetTypeElementCount(self) + + @property + def type_width(self): + """ + Return the basic size of this type if it is a primitive type. These are + fixed by LLVM and are not target-dependent. + This will return zero if the type does not have a size or is not a + primitive type. + + If this is a scalable vector type, the scalable property will be set and + the runtime size will be a positive integer multiple of the base size. + + Note that this may not reflect the size of memory allocated for an + instance of the type or the number of bytes that are written when an + instance of the type is stored to memory. + """ + return ffi.lib.LLVMPY_GetTypeBitWidth(self) + + @property + def type_kind(self): + """ + Returns the LLVMTypeKind enumeration of this type. + """ + return TypeKind(ffi.lib.LLVMPY_GetTypeKind(self)) + + def __str__(self): + return ffi.ret_string(ffi.lib.LLVMPY_PrintType(self)) + + +class _TypeIterator(ffi.ObjectRef): + + def __next__(self): + vp = self._next() + if vp: + return TypeRef(vp) + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _TypeListIterator(_TypeIterator): + + def _dispose(self): + self._capi.LLVMPY_DisposeElementIter(self) + + def _next(self): + return ffi.lib.LLVMPY_ElementIterNext(self) + + +# FFI + +ffi.lib.LLVMPY_PrintType.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_PrintType.restype = c_void_p + +ffi.lib.LLVMPY_GetElementType.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetElementType.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_TypeIsPointer.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsPointer.restype = c_bool + +ffi.lib.LLVMPY_TypeIsArray.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsArray.restype = c_bool + +ffi.lib.LLVMPY_TypeIsVector.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsVector.restype = c_bool + +ffi.lib.LLVMPY_TypeIsStruct.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_TypeIsStruct.restype = c_bool + +ffi.lib.LLVMPY_IsFunctionVararg.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_IsFunctionVararg.restype = c_bool + +ffi.lib.LLVMPY_GetTypeKind.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeKind.restype = c_int + +ffi.lib.LLVMPY_GetTypeElementCount.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeElementCount.restype = c_int + +ffi.lib.LLVMPY_GetTypeBitWidth.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeBitWidth.restype = c_uint64 + +ffi.lib.LLVMPY_ElementIter.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_ElementIter.restype = ffi.LLVMElementIterator + +ffi.lib.LLVMPY_ElementIterNext.argtypes = [ffi.LLVMElementIterator] +ffi.lib.LLVMPY_ElementIterNext.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_DisposeElementIter.argtypes = [ffi.LLVMElementIterator] diff --git a/vllm/lib/python3.10/site-packages/llvmlite/binding/value.py b/vllm/lib/python3.10/site-packages/llvmlite/binding/value.py new file mode 100644 index 0000000000000000000000000000000000000000..288c3e4807c9ce795714b2ebf226da36b6866736 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/binding/value.py @@ -0,0 +1,618 @@ +from ctypes import (POINTER, byref, cast, c_char_p, c_double, c_int, c_size_t, + c_uint, c_uint64, c_bool, c_void_p) +import enum + +from llvmlite.binding import ffi +from llvmlite.binding.common import _decode_string, _encode_string +from llvmlite.binding.typeref import TypeRef + + +class Linkage(enum.IntEnum): + # The LLVMLinkage enum from llvm-c/Core.h + + external = 0 + available_externally = 1 + linkonce_any = 2 + linkonce_odr = 3 + linkonce_odr_autohide = 4 + weak_any = 5 + weak_odr = 6 + appending = 7 + internal = 8 + private = 9 + dllimport = 10 + dllexport = 11 + external_weak = 12 + ghost = 13 + common = 14 + linker_private = 15 + linker_private_weak = 16 + + +class Visibility(enum.IntEnum): + # The LLVMVisibility enum from llvm-c/Core.h + + default = 0 + hidden = 1 + protected = 2 + + +class StorageClass(enum.IntEnum): + # The LLVMDLLStorageClass enum from llvm-c/Core.h + + default = 0 + dllimport = 1 + dllexport = 2 + + +class ValueKind(enum.IntEnum): + # The LLVMValueKind enum from llvm-c/Core.h + + argument = 0 + basic_block = 1 + memory_use = 2 + memory_def = 3 + memory_phi = 4 + + function = 5 + global_alias = 6 + global_ifunc = 7 + global_variable = 8 + block_address = 9 + constant_expr = 10 + constant_array = 11 + constant_struct = 12 + constant_vector = 13 + + undef_value = 14 + constant_aggregate_zero = 15 + constant_data_array = 16 + constant_data_vector = 17 + constant_int = 18 + constant_fp = 19 + constant_pointer_null = 20 + constant_token_none = 21 + + metadata_as_value = 22 + inline_asm = 23 + + instruction = 24 + poison_value = 25 + + +class ValueRef(ffi.ObjectRef): + """A weak reference to a LLVM value. + """ + + def __init__(self, ptr, kind, parents): + self._kind = kind + self._parents = parents + ffi.ObjectRef.__init__(self, ptr) + + def __str__(self): + with ffi.OutputString() as outstr: + ffi.lib.LLVMPY_PrintValueToString(self, outstr) + return str(outstr) + + @property + def module(self): + """ + The module this function or global variable value was obtained from. + """ + return self._parents.get('module') + + @property + def function(self): + """ + The function this argument or basic block value was obtained from. + """ + return self._parents.get('function') + + @property + def block(self): + """ + The block this instruction value was obtained from. + """ + return self._parents.get('block') + + @property + def instruction(self): + """ + The instruction this operand value was obtained from. + """ + return self._parents.get('instruction') + + @property + def is_global(self): + return self._kind == 'global' + + @property + def is_function(self): + return self._kind == 'function' + + @property + def is_block(self): + return self._kind == 'block' + + @property + def is_argument(self): + return self._kind == 'argument' + + @property + def is_instruction(self): + return self._kind == 'instruction' + + @property + def is_operand(self): + return self._kind == 'operand' + + @property + def is_constant(self): + return bool(ffi.lib.LLVMPY_IsConstant(self)) + + @property + def value_kind(self): + return ValueKind(ffi.lib.LLVMPY_GetValueKind(self)) + + @property + def name(self): + return _decode_string(ffi.lib.LLVMPY_GetValueName(self)) + + @name.setter + def name(self, val): + ffi.lib.LLVMPY_SetValueName(self, _encode_string(val)) + + @property + def linkage(self): + return Linkage(ffi.lib.LLVMPY_GetLinkage(self)) + + @linkage.setter + def linkage(self, value): + if not isinstance(value, Linkage): + value = Linkage[value] + ffi.lib.LLVMPY_SetLinkage(self, value) + + @property + def visibility(self): + return Visibility(ffi.lib.LLVMPY_GetVisibility(self)) + + @visibility.setter + def visibility(self, value): + if not isinstance(value, Visibility): + value = Visibility[value] + ffi.lib.LLVMPY_SetVisibility(self, value) + + @property + def storage_class(self): + return StorageClass(ffi.lib.LLVMPY_GetDLLStorageClass(self)) + + @storage_class.setter + def storage_class(self, value): + if not isinstance(value, StorageClass): + value = StorageClass[value] + ffi.lib.LLVMPY_SetDLLStorageClass(self, value) + + def add_function_attribute(self, attr): + """Only works on function value + + Parameters + ----------- + attr : str + attribute name + """ + if not self.is_function: + raise ValueError('expected function value, got %s' % (self._kind,)) + attrname = str(attr) + attrval = ffi.lib.LLVMPY_GetEnumAttributeKindForName( + _encode_string(attrname), len(attrname)) + if attrval == 0: + raise ValueError('no such attribute {!r}'.format(attrname)) + ffi.lib.LLVMPY_AddFunctionAttr(self, attrval) + + @property + def type(self): + """ + This value's LLVM type. + """ + # XXX what does this return? + return TypeRef(ffi.lib.LLVMPY_TypeOf(self)) + + @property + def is_declaration(self): + """ + Whether this value (presumably global) is defined in the current + module. + """ + if not (self.is_global or self.is_function): + raise ValueError('expected global or function value, got %s' + % (self._kind,)) + return ffi.lib.LLVMPY_IsDeclaration(self) + + @property + def attributes(self): + """ + Return an iterator over this value's attributes. + The iterator will yield a string for each attribute. + """ + itr = iter(()) + if self.is_function: + it = ffi.lib.LLVMPY_FunctionAttributesIter(self) + itr = _AttributeListIterator(it) + elif self.is_instruction: + if self.opcode == 'call': + it = ffi.lib.LLVMPY_CallInstAttributesIter(self) + itr = _AttributeListIterator(it) + elif self.opcode == 'invoke': + it = ffi.lib.LLVMPY_InvokeInstAttributesIter(self) + itr = _AttributeListIterator(it) + elif self.is_global: + it = ffi.lib.LLVMPY_GlobalAttributesIter(self) + itr = _AttributeSetIterator(it) + elif self.is_argument: + it = ffi.lib.LLVMPY_ArgumentAttributesIter(self) + itr = _AttributeSetIterator(it) + return itr + + @property + def blocks(self): + """ + Return an iterator over this function's blocks. + The iterator will yield a ValueRef for each block. + """ + if not self.is_function: + raise ValueError('expected function value, got %s' % (self._kind,)) + it = ffi.lib.LLVMPY_FunctionBlocksIter(self) + parents = self._parents.copy() + parents.update(function=self) + return _BlocksIterator(it, parents) + + @property + def arguments(self): + """ + Return an iterator over this function's arguments. + The iterator will yield a ValueRef for each argument. + """ + if not self.is_function: + raise ValueError('expected function value, got %s' % (self._kind,)) + it = ffi.lib.LLVMPY_FunctionArgumentsIter(self) + parents = self._parents.copy() + parents.update(function=self) + return _ArgumentsIterator(it, parents) + + @property + def instructions(self): + """ + Return an iterator over this block's instructions. + The iterator will yield a ValueRef for each instruction. + """ + if not self.is_block: + raise ValueError('expected block value, got %s' % (self._kind,)) + it = ffi.lib.LLVMPY_BlockInstructionsIter(self) + parents = self._parents.copy() + parents.update(block=self) + return _InstructionsIterator(it, parents) + + @property + def operands(self): + """ + Return an iterator over this instruction's operands. + The iterator will yield a ValueRef for each operand. + """ + if not self.is_instruction: + raise ValueError('expected instruction value, got %s' + % (self._kind,)) + it = ffi.lib.LLVMPY_InstructionOperandsIter(self) + parents = self._parents.copy() + parents.update(instruction=self) + return _OperandsIterator(it, parents) + + @property + def opcode(self): + if not self.is_instruction: + raise ValueError('expected instruction value, got %s' + % (self._kind,)) + return ffi.ret_string(ffi.lib.LLVMPY_GetOpcodeName(self)) + + @property + def incoming_blocks(self): + """ + Return an iterator over this phi instruction's incoming blocks. + The iterator will yield a ValueRef for each block. + """ + if not self.is_instruction or self.opcode != 'phi': + raise ValueError('expected phi instruction value, got %s' + % (self._kind,)) + it = ffi.lib.LLVMPY_PhiIncomingBlocksIter(self) + parents = self._parents.copy() + parents.update(instruction=self) + return _IncomingBlocksIterator(it, parents) + + def get_constant_value(self, signed_int=False, round_fp=False): + """ + Return the constant value, either as a literal (when supported) + or as a string. + + Parameters + ----------- + signed_int : bool + if True and the constant is an integer, returns a signed version + round_fp : bool + if True and the constant is a floating point value, rounds the + result upon accuracy loss (e.g., when querying an fp128 value). + By default, raises an exception on accuracy loss + """ + if not self.is_constant: + raise ValueError('expected constant value, got %s' + % (self._kind,)) + + if self.value_kind == ValueKind.constant_int: + # Python integers are also arbitrary-precision + little_endian = c_bool(False) + words = ffi.lib.LLVMPY_GetConstantIntNumWords(self) + ptr = ffi.lib.LLVMPY_GetConstantIntRawValue( + self, byref(little_endian)) + asbytes = bytes(cast(ptr, POINTER(c_uint64 * words)).contents) + return int.from_bytes( + asbytes, + ('little' if little_endian.value else 'big'), + signed=signed_int, + ) + elif self.value_kind == ValueKind.constant_fp: + # Convert floating-point values to double-precision (Python float) + accuracy_loss = c_bool(False) + value = ffi.lib.LLVMPY_GetConstantFPValue(self, + byref(accuracy_loss)) + if accuracy_loss.value and not round_fp: + raise ValueError( + 'Accuracy loss encountered in conversion of constant ' + f'value {str(self)}') + + return value + + # Otherwise, return the IR string + return str(self) + + +class _ValueIterator(ffi.ObjectRef): + + kind = None # derived classes must specify the Value kind value + # as class attribute + + def __init__(self, ptr, parents): + ffi.ObjectRef.__init__(self, ptr) + # Keep parent objects (module, function, etc) alive + self._parents = parents + if self.kind is None: + raise NotImplementedError('%s must specify kind attribute' + % (type(self).__name__,)) + + def __next__(self): + vp = self._next() + if vp: + return ValueRef(vp, self.kind, self._parents) + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _AttributeIterator(ffi.ObjectRef): + + def __next__(self): + vp = self._next() + if vp: + return vp + else: + raise StopIteration + + next = __next__ + + def __iter__(self): + return self + + +class _AttributeListIterator(_AttributeIterator): + + def _dispose(self): + self._capi.LLVMPY_DisposeAttributeListIter(self) + + def _next(self): + return ffi.ret_bytes(ffi.lib.LLVMPY_AttributeListIterNext(self)) + + +class _AttributeSetIterator(_AttributeIterator): + + def _dispose(self): + self._capi.LLVMPY_DisposeAttributeSetIter(self) + + def _next(self): + return ffi.ret_bytes(ffi.lib.LLVMPY_AttributeSetIterNext(self)) + + +class _BlocksIterator(_ValueIterator): + + kind = 'block' + + def _dispose(self): + self._capi.LLVMPY_DisposeBlocksIter(self) + + def _next(self): + return ffi.lib.LLVMPY_BlocksIterNext(self) + + +class _ArgumentsIterator(_ValueIterator): + + kind = 'argument' + + def _dispose(self): + self._capi.LLVMPY_DisposeArgumentsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_ArgumentsIterNext(self) + + +class _InstructionsIterator(_ValueIterator): + + kind = 'instruction' + + def _dispose(self): + self._capi.LLVMPY_DisposeInstructionsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_InstructionsIterNext(self) + + +class _OperandsIterator(_ValueIterator): + + kind = 'operand' + + def _dispose(self): + self._capi.LLVMPY_DisposeOperandsIter(self) + + def _next(self): + return ffi.lib.LLVMPY_OperandsIterNext(self) + + +class _IncomingBlocksIterator(_ValueIterator): + + kind = 'block' + + def _dispose(self): + self._capi.LLVMPY_DisposeIncomingBlocksIter(self) + + def _next(self): + return ffi.lib.LLVMPY_IncomingBlocksIterNext(self) + + +# FFI + +ffi.lib.LLVMPY_PrintValueToString.argtypes = [ + ffi.LLVMValueRef, + POINTER(c_char_p) +] + +ffi.lib.LLVMPY_GetGlobalParent.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetGlobalParent.restype = ffi.LLVMModuleRef + +ffi.lib.LLVMPY_GetValueName.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetValueName.restype = c_char_p + +ffi.lib.LLVMPY_SetValueName.argtypes = [ffi.LLVMValueRef, c_char_p] + +ffi.lib.LLVMPY_TypeOf.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_TypeOf.restype = ffi.LLVMTypeRef + +ffi.lib.LLVMPY_GetTypeName.argtypes = [ffi.LLVMTypeRef] +ffi.lib.LLVMPY_GetTypeName.restype = c_void_p + +ffi.lib.LLVMPY_GetLinkage.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetLinkage.restype = c_int + +ffi.lib.LLVMPY_SetLinkage.argtypes = [ffi.LLVMValueRef, c_int] + +ffi.lib.LLVMPY_GetVisibility.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetVisibility.restype = c_int + +ffi.lib.LLVMPY_SetVisibility.argtypes = [ffi.LLVMValueRef, c_int] + +ffi.lib.LLVMPY_GetDLLStorageClass.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetDLLStorageClass.restype = c_int + +ffi.lib.LLVMPY_SetDLLStorageClass.argtypes = [ffi.LLVMValueRef, c_int] + +ffi.lib.LLVMPY_GetEnumAttributeKindForName.argtypes = [c_char_p, c_size_t] +ffi.lib.LLVMPY_GetEnumAttributeKindForName.restype = c_uint + +ffi.lib.LLVMPY_AddFunctionAttr.argtypes = [ffi.LLVMValueRef, c_uint] + +ffi.lib.LLVMPY_IsDeclaration.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_IsDeclaration.restype = c_int + +ffi.lib.LLVMPY_FunctionAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_FunctionAttributesIter.restype = ffi.LLVMAttributeListIterator + +ffi.lib.LLVMPY_CallInstAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_CallInstAttributesIter.restype = ffi.LLVMAttributeListIterator + +ffi.lib.LLVMPY_InvokeInstAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_InvokeInstAttributesIter.restype = ffi.LLVMAttributeListIterator + +ffi.lib.LLVMPY_GlobalAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GlobalAttributesIter.restype = ffi.LLVMAttributeSetIterator + +ffi.lib.LLVMPY_ArgumentAttributesIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_ArgumentAttributesIter.restype = ffi.LLVMAttributeSetIterator + +ffi.lib.LLVMPY_FunctionBlocksIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_FunctionBlocksIter.restype = ffi.LLVMBlocksIterator + +ffi.lib.LLVMPY_FunctionArgumentsIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_FunctionArgumentsIter.restype = ffi.LLVMArgumentsIterator + +ffi.lib.LLVMPY_BlockInstructionsIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_BlockInstructionsIter.restype = ffi.LLVMInstructionsIterator + +ffi.lib.LLVMPY_InstructionOperandsIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_InstructionOperandsIter.restype = ffi.LLVMOperandsIterator + +ffi.lib.LLVMPY_PhiIncomingBlocksIter.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_PhiIncomingBlocksIter.restype = ffi.LLVMIncomingBlocksIterator + +ffi.lib.LLVMPY_DisposeAttributeListIter.argtypes = [ + ffi.LLVMAttributeListIterator] + +ffi.lib.LLVMPY_DisposeAttributeSetIter.argtypes = [ffi.LLVMAttributeSetIterator] + +ffi.lib.LLVMPY_DisposeBlocksIter.argtypes = [ffi.LLVMBlocksIterator] + +ffi.lib.LLVMPY_DisposeInstructionsIter.argtypes = [ffi.LLVMInstructionsIterator] + +ffi.lib.LLVMPY_DisposeOperandsIter.argtypes = [ffi.LLVMOperandsIterator] + +ffi.lib.LLVMPY_DisposeIncomingBlocksIter.argtypes = [ + ffi.LLVMIncomingBlocksIterator] + +ffi.lib.LLVMPY_AttributeListIterNext.argtypes = [ffi.LLVMAttributeListIterator] +ffi.lib.LLVMPY_AttributeListIterNext.restype = c_void_p + +ffi.lib.LLVMPY_AttributeSetIterNext.argtypes = [ffi.LLVMAttributeSetIterator] +ffi.lib.LLVMPY_AttributeSetIterNext.restype = c_void_p + +ffi.lib.LLVMPY_BlocksIterNext.argtypes = [ffi.LLVMBlocksIterator] +ffi.lib.LLVMPY_BlocksIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_ArgumentsIterNext.argtypes = [ffi.LLVMArgumentsIterator] +ffi.lib.LLVMPY_ArgumentsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_InstructionsIterNext.argtypes = [ffi.LLVMInstructionsIterator] +ffi.lib.LLVMPY_InstructionsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_OperandsIterNext.argtypes = [ffi.LLVMOperandsIterator] +ffi.lib.LLVMPY_OperandsIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_IncomingBlocksIterNext.argtypes = [ + ffi.LLVMIncomingBlocksIterator] +ffi.lib.LLVMPY_IncomingBlocksIterNext.restype = ffi.LLVMValueRef + +ffi.lib.LLVMPY_GetOpcodeName.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetOpcodeName.restype = c_void_p + +ffi.lib.LLVMPY_IsConstant.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_IsConstant.restype = c_bool + +ffi.lib.LLVMPY_GetValueKind.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetValueKind.restype = c_int + +ffi.lib.LLVMPY_GetConstantIntRawValue.argtypes = [ffi.LLVMValueRef, + POINTER(c_bool)] +ffi.lib.LLVMPY_GetConstantIntRawValue.restype = POINTER(c_uint64) + +ffi.lib.LLVMPY_GetConstantIntNumWords.argtypes = [ffi.LLVMValueRef] +ffi.lib.LLVMPY_GetConstantIntNumWords.restype = c_uint + +ffi.lib.LLVMPY_GetConstantFPValue.argtypes = [ffi.LLVMValueRef, + POINTER(c_bool)] +ffi.lib.LLVMPY_GetConstantFPValue.restype = c_double diff --git a/vllm/lib/python3.10/site-packages/llvmlite/tests/__init__.py b/vllm/lib/python3.10/site-packages/llvmlite/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7f2b3b082d2722e587263fb4ce5307287715a1d5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/tests/__init__.py @@ -0,0 +1,57 @@ +import sys + +import unittest +from unittest import TestCase + +import faulthandler + + +try: + # May fail in IPython Notebook with UnsupportedOperation + faulthandler.enable() +except BaseException as e: + msg = "Failed to enable faulthandler due to:\n{err}" + warnings.warn(msg.format(err=e)) + + +# Try to inject Numba's unittest customizations. +from llvmlite.tests import customize + + +def discover_tests(startdir): + """Discover test under a directory + """ + # Avoid importing unittest + loader = unittest.TestLoader() + suite = loader.discover(startdir) + return suite + + +def run_tests(suite=None, xmloutput=None, verbosity=1): + """ + args + ---- + - suite [TestSuite] + A suite of all tests to run + - xmloutput [str or None] + Path of XML output directory (optional) + - verbosity [int] + Verbosity level of tests output + + Returns the TestResult object after running the test *suite*. + """ + if suite is None: + suite = discover_tests("llvmlite.tests") + if xmloutput is not None: + import xmlrunner + runner = xmlrunner.XMLTestRunner(output=xmloutput) + else: + runner = None + prog = unittest.main(suite=suite, testRunner=runner, exit=False, + verbosity=verbosity) + return prog.result + + +def main(): + res = run_tests() + sys.exit(0 if res.wasSuccessful() else 1) diff --git a/vllm/lib/python3.10/site-packages/llvmlite/tests/__main__.py b/vllm/lib/python3.10/site-packages/llvmlite/tests/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..97563d18687da90316eef738c8aa3ffbacec4007 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/tests/__main__.py @@ -0,0 +1,3 @@ +from llvmlite.tests import main + +main() diff --git a/vllm/lib/python3.10/site-packages/llvmlite/tests/customize.py b/vllm/lib/python3.10/site-packages/llvmlite/tests/customize.py new file mode 100644 index 0000000000000000000000000000000000000000..7d747a3ca4343a7cb94911fa1283dbfbc35e0577 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/tests/customize.py @@ -0,0 +1,407 @@ +# XXX Ripped off from numba.tests; we should factor it out somewhere? + +import collections +import contextlib +import cProfile +from io import StringIO +import gc +import os +import multiprocessing +import sys +import time +import unittest +import warnings +from unittest import result, runner, signals + + +# "unittest.main" is really the TestProgram class! +# (defined in a module named itself "unittest.main"...) + +class NumbaTestProgram(unittest.main): + """ + A TestProgram subclass adding the following options: + * a -R option to enable reference leak detection + * a --profile option to enable profiling of the test run + + Currently the options are only added in 3.4+. + """ + + refleak = False + profile = False + multiprocess = False + + def __init__(self, *args, **kwargs): + self.discovered_suite = kwargs.pop('suite', None) + # HACK to force unittest not to change warning display options + # (so that NumbaWarnings don't appear all over the place) + sys.warnoptions.append(':x') + super(NumbaTestProgram, self).__init__(*args, **kwargs) + + def createTests(self): + if self.discovered_suite is not None: + self.test = self.discovered_suite + else: + super(NumbaTestProgram, self).createTests() + + def _getParentArgParser(self): + # NOTE: this hook only exists on Python 3.4+. The options won't be + # added in earlier versions (which use optparse - 3.3 - or getopt() + # - 2.x). + parser = super(NumbaTestProgram, self)._getParentArgParser() + if self.testRunner is None: + parser.add_argument('-R', '--refleak', dest='refleak', + action='store_true', + help='Detect reference / memory leaks') + parser.add_argument('-m', '--multiprocess', dest='multiprocess', + action='store_true', + help='Parallelize tests') + parser.add_argument('--profile', dest='profile', + action='store_true', + help='Profile the test run') + return parser + + def parseArgs(self, argv): + if sys.version_info < (3, 4): + # We want these options to work on all versions, emulate them. + if '-R' in argv: + argv.remove('-R') + self.refleak = True + if '-m' in argv: + argv.remove('-m') + self.multiprocess = True + super(NumbaTestProgram, self).parseArgs(argv) + if self.verbosity <= 0: + # We aren't interested in informational messages / warnings when + # running with '-q'. + self.buffer = True + + def runTests(self): + if self.refleak: + self.testRunner = RefleakTestRunner + + if not hasattr(sys, "gettotalrefcount"): + warnings.warn("detecting reference leaks requires a debug " + "build of Python, only memory leaks will be " + "detected") + + elif self.testRunner is None: + self.testRunner = unittest.TextTestRunner + + if self.multiprocess: + self.testRunner = ParallelTestRunner(self.testRunner, + verbosity=self.verbosity, + failfast=self.failfast, + buffer=self.buffer) + + def run_tests_real(): + super(NumbaTestProgram, self).runTests() + + if self.profile: + filename = os.path.splitext( + os.path.basename(sys.modules['__main__'].__file__) + )[0] + '.prof' + p = cProfile.Profile(timer=time.perf_counter) # 3.3+ + p.enable() + try: + p.runcall(run_tests_real) + finally: + p.disable() + print("Writing test profile data into %r" % (filename,)) + p.dump_stats(filename) + else: + run_tests_real() + + +# Monkey-patch unittest so that individual test modules get our custom +# options for free. +unittest.main = NumbaTestProgram + + +# The reference leak detection code is liberally taken and adapted from +# Python's own Lib/test/regrtest.py. + +def _refleak_cleanup(): + # Collect cyclic trash and read memory statistics immediately after. + try: + func1 = sys.getallocatedblocks + except AttributeError: + def func1(): + return 42 + try: + func2 = sys.gettotalrefcount + except AttributeError: + def func2(): + return 42 + + # Flush standard output, so that buffered data is sent to the OS and + # associated Python objects are reclaimed. + for stream in (sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__): + if stream is not None: + stream.flush() + + sys._clear_type_cache() + # This also clears the various internal CPython freelists. + gc.collect() + return func1(), func2() + + +class ReferenceLeakError(RuntimeError): + pass + + +class IntPool(collections.defaultdict): + + def __missing__(self, key): + return key + + +class RefleakTestResult(runner.TextTestResult): + + warmup = 3 + repetitions = 6 + + def _huntLeaks(self, test): + self.stream.flush() + + repcount = self.repetitions + nwarmup = self.warmup + rc_deltas = [0] * (repcount - nwarmup) + alloc_deltas = [0] * (repcount - nwarmup) + # Preallocate ints likely to be stored in rc_deltas and alloc_deltas, + # to make sys.getallocatedblocks() less flaky. + _int_pool = IntPool() + for i in range(-200, 200): + _int_pool[i] + + alloc_before = rc_before = 0 + for i in range(repcount): + # Use a pristine, silent result object to avoid recursion + res = result.TestResult() + test.run(res) + # Poorly-written tests may fail when run several times. + # In this case, abort the refleak run and report the failure. + if not res.wasSuccessful(): + self.failures.extend(res.failures) + self.errors.extend(res.errors) + raise AssertionError + del res + alloc_after, rc_after = _refleak_cleanup() + if i >= nwarmup: + rc_deltas[i - nwarmup] = _int_pool[rc_after - rc_before] + alloc_deltas[i - + nwarmup] = _int_pool[alloc_after - + alloc_before] + alloc_before, rc_before = alloc_after, rc_after + return rc_deltas, alloc_deltas + + def addSuccess(self, test): + try: + rc_deltas, alloc_deltas = self._huntLeaks(test) + except AssertionError: + # Test failed when repeated + assert not self.wasSuccessful() + return + + # These checkers return False on success, True on failure + def check_rc_deltas(deltas): + return any(deltas) + + def check_alloc_deltas(deltas): + # At least 1/3rd of 0s + if 3 * deltas.count(0) < len(deltas): + return True + # Nothing else than 1s, 0s and -1s + if not set(deltas) <= set((1, 0, -1)): + return True + return False + + failed = False + + for deltas, item_name, checker in [ + (rc_deltas, 'references', check_rc_deltas), + (alloc_deltas, 'memory blocks', check_alloc_deltas)]: + if checker(deltas): + msg = '%s leaked %s %s, sum=%s' % ( + test, deltas, item_name, sum(deltas)) + failed = True + try: + raise ReferenceLeakError(msg) + except Exception: + exc_info = sys.exc_info() + if self.showAll: + self.stream.write("%s = %r " % (item_name, deltas)) + self.addFailure(test, exc_info) + + if not failed: + super(RefleakTestResult, self).addSuccess(test) + + +class RefleakTestRunner(runner.TextTestRunner): + resultclass = RefleakTestResult + + +def _flatten_suite(test): + """Expand suite into list of tests + """ + if isinstance(test, unittest.TestSuite): + tests = [] + for x in test: + tests.extend(_flatten_suite(x)) + return tests + else: + return [test] + + +class ParallelTestResult(runner.TextTestResult): + """ + A TestResult able to inject results from other results. + """ + + def add_results(self, result): + """ + Add the results from the other *result* to this result. + """ + self.stream.write(result.stream.getvalue()) + self.stream.flush() + self.testsRun += result.testsRun + self.failures.extend(result.failures) + self.errors.extend(result.errors) + self.skipped.extend(result.skipped) + self.expectedFailures.extend(result.expectedFailures) + self.unexpectedSuccesses.extend(result.unexpectedSuccesses) + + +class _MinimalResult(object): + """ + A minimal, picklable TestResult-alike object. + """ + + __slots__ = ( + 'failures', 'errors', 'skipped', 'expectedFailures', + 'unexpectedSuccesses', 'stream', 'shouldStop', 'testsRun') + + def fixup_case(self, case): + """ + Remove any unpicklable attributes from TestCase instance *case*. + """ + # Python 3.3 doesn't reset this one. + case._outcomeForDoCleanups = None + + def __init__(self, original_result): + for attr in self.__slots__: + setattr(self, attr, getattr(original_result, attr)) + for case, _ in self.expectedFailures: + self.fixup_case(case) + for case, _ in self.errors: + self.fixup_case(case) + for case, _ in self.failures: + self.fixup_case(case) + + +class _FakeStringIO(object): + """ + A trivial picklable StringIO-alike for Python 2. + """ + + def __init__(self, value): + self._value = value + + def getvalue(self): + return self._value + + +class _MinimalRunner(object): + """ + A minimal picklable object able to instantiate a runner in a + child process and run a test case with it. + """ + + def __init__(self, runner_cls, runner_args): + self.runner_cls = runner_cls + self.runner_args = runner_args + + # Python 2 doesn't know how to pickle instance methods, so we use __call__ + # instead. + + def __call__(self, test): + # Executed in child process + kwargs = self.runner_args + # Force recording of output in a buffer (it will be printed out + # by the parent). + kwargs['stream'] = StringIO() + runner = self.runner_cls(**kwargs) + result = runner._makeResult() + # Avoid child tracebacks when Ctrl-C is pressed. + signals.installHandler() + signals.registerResult(result) + result.failfast = runner.failfast + result.buffer = runner.buffer + with self.cleanup_object(test): + test(result) + # HACK as cStringIO.StringIO isn't picklable in 2.x + result.stream = _FakeStringIO(result.stream.getvalue()) + return _MinimalResult(result) + + @contextlib.contextmanager + def cleanup_object(self, test): + """ + A context manager which cleans up unwanted attributes on a test case + (or any other object). + """ + vanilla_attrs = set(test.__dict__) + try: + yield test + finally: + spurious_attrs = set(test.__dict__) - vanilla_attrs + for name in spurious_attrs: + del test.__dict__[name] + + +class ParallelTestRunner(runner.TextTestRunner): + """ + A test runner which delegates the actual running to a pool of child + processes. + """ + + resultclass = ParallelTestResult + + def __init__(self, runner_cls, **kwargs): + runner.TextTestRunner.__init__(self, **kwargs) + self.runner_cls = runner_cls + self.runner_args = kwargs + + def _run_inner(self, result): + # We hijack TextTestRunner.run()'s inner logic by passing this + # method as if it were a test case. + child_runner = _MinimalRunner(self.runner_cls, self.runner_args) + pool = multiprocessing.Pool() + imap = pool.imap_unordered + try: + for child_result in imap(child_runner, self._test_list): + result.add_results(child_result) + if child_result.shouldStop: + break + return result + finally: + # Kill the still active workers + pool.terminate() + pool.join() + + def run(self, test): + self._test_list = _flatten_suite(test) + # This will call self._run_inner() on the created result object, + # and print out the detailed test results at the end. + return super(ParallelTestRunner, self).run(self._run_inner) + + +try: + import faulthandler +except ImportError: + pass +else: + try: + # May fail in IPython Notebook with UnsupportedOperation + faulthandler.enable() + except BaseException as e: + msg = "Failed to enable faulthandler due to:\n{err}" + warnings.warn(msg.format(err=e)) diff --git a/vllm/lib/python3.10/site-packages/llvmlite/tests/test_valuerepr.py b/vllm/lib/python3.10/site-packages/llvmlite/tests/test_valuerepr.py new file mode 100644 index 0000000000000000000000000000000000000000..f8d7e4b2c073ecdfd5ae8c985ebd9108245bd78f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/tests/test_valuerepr.py @@ -0,0 +1,60 @@ +import math +import sys +import unittest + +from llvmlite.ir import ( + Constant, FloatType, DoubleType, LiteralStructType, IntType, + ArrayType, HalfType) +from llvmlite.tests import TestCase + + +int8 = IntType(8) +int16 = IntType(16) + + +PY36_OR_LATER = sys.version_info[:2] >= (3, 6) + + +class TestValueRepr(TestCase): + + def test_double_repr(self): + def check_repr(val, expected): + c = Constant(DoubleType(), val) + self.assertEqual(str(c), expected) + check_repr(math.pi, "double 0x400921fb54442d18") + check_repr(float('inf'), "double 0x7ff0000000000000") + check_repr(float('-inf'), "double 0xfff0000000000000") + + def test_float_repr(self): + def check_repr(val, expected): + c = Constant(FloatType(), val) + self.assertEqual(str(c), expected) + check_repr(math.pi, "float 0x400921fb60000000") + check_repr(float('inf'), "float 0x7ff0000000000000") + check_repr(float('-inf'), "float 0xfff0000000000000") + + @unittest.skipUnless(PY36_OR_LATER, 'py36+ only') + def test_half_repr(self): + def check_repr(val, expected): + c = Constant(HalfType(), val) + self.assertEqual(str(c), expected) + check_repr(math.pi, "half 0x4009200000000000") + check_repr(float('inf'), "half 0x7ff0000000000000") + check_repr(float('-inf'), "half 0xfff0000000000000") + + def test_struct_repr(self): + tp = LiteralStructType([int8, int16]) + c = Constant(tp, (Constant(int8, 100), Constant(int16, 1000))) + self.assertEqual(str(c), "{i8, i16} {i8 100, i16 1000}") + + def test_array_repr(self): + tp = ArrayType(int8, 3) + values = [Constant(int8, x) for x in (5, 10, -15)] + c = Constant(tp, values) + self.assertEqual(str(c), "[3 x i8] [i8 5, i8 10, i8 -15]") + c = Constant(tp, bytearray(b"\x01\x02\x03")) + self.assertEqual(str(c), '[3 x i8] c"\\01\\02\\03"') + + +if __name__ == "__main__": + unittest.main() diff --git a/vllm/lib/python3.10/site-packages/llvmlite/utils.py b/vllm/lib/python3.10/site-packages/llvmlite/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e07ecd370f45b3af0fe67f9a0ac6ea1cee16db3f --- /dev/null +++ b/vllm/lib/python3.10/site-packages/llvmlite/utils.py @@ -0,0 +1,29 @@ +import os +import sys + + +# This module must be importable without loading the binding, to avoid +# bootstrapping issues in setup.py. + +def get_library_name(): + """ + Return the name of the llvmlite shared library file. + """ + if os.name == 'posix': + if sys.platform == 'darwin': + return 'libllvmlite.dylib' + else: + return 'libllvmlite.so' + else: + assert os.name == 'nt' + return 'llvmlite.dll' + + +def get_library_files(): + """ + Return the names of shared library files needed for this platform. + """ + files = [get_library_name()] + if os.name == 'nt': + files.extend(['msvcr120.dll', 'msvcp120.dll']) + return files diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9d499340c5a673e01cf56a8e3502330f2b0af4c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/__pycache__/conditionset.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d7522f0f6732acbaa6903c365d8a917b1da0faa Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/__pycache__/contains.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85abd4b4bea21d49f5f5908619c98706d0a39d03 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/__pycache__/powerset.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afdf271c0eacb413737c7c1fd44b4c0b7c91e8bc Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/add.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/add.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c5deefe63216f9d48f2b6420af6da404ae64797 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/add.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9b30ee7c38992a7b1ec635326c982298f3e9023 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/comparison.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/functions.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/functions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..699fbeb11c7eac2196aa44fc68a4dea5f9c4ba98 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/functions.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/intersection.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/intersection.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c261417f2c09e65e17dd09dcd91bba4b7289013a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/intersection.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/issubset.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/issubset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61eb70ad1f003c8f5095dd3d154ca6e9db99f62a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/issubset.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/mul.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/mul.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..178ac693a80ad2fa0441fac3ed6a1a5d5c35b027 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/mul.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/power.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/power.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f3a078e95832d883ca8120ed0639101836ef79c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/power.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/union.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/union.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c716bada61e2bdcc529bb3fe41858b01f68a52a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/__pycache__/union.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/add.py b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/add.py new file mode 100644 index 0000000000000000000000000000000000000000..8c07b25ed19d21febffd6b23a92b34b787179f44 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/add.py @@ -0,0 +1,79 @@ +from sympy.core.numbers import oo, Infinity, NegativeInfinity +from sympy.core.singleton import S +from sympy.core import Basic, Expr +from sympy.multipledispatch import Dispatcher +from sympy.sets import Interval, FiniteSet + + + +# XXX: The functions in this module are clearly not tested and are broken in a +# number of ways. + +_set_add = Dispatcher('_set_add') +_set_sub = Dispatcher('_set_sub') + + +@_set_add.register(Basic, Basic) +def _(x, y): + return None + + +@_set_add.register(Expr, Expr) +def _(x, y): + return x+y + + +@_set_add.register(Interval, Interval) +def _(x, y): + """ + Additions in interval arithmetic + https://en.wikipedia.org/wiki/Interval_arithmetic + """ + return Interval(x.start + y.start, x.end + y.end, + x.left_open or y.left_open, x.right_open or y.right_open) + + +@_set_add.register(Interval, Infinity) +def _(x, y): + if x.start is S.NegativeInfinity: + return Interval(-oo, oo) + return FiniteSet({S.Infinity}) + +@_set_add.register(Interval, NegativeInfinity) +def _(x, y): + if x.end is S.Infinity: + return Interval(-oo, oo) + return FiniteSet({S.NegativeInfinity}) + + +@_set_sub.register(Basic, Basic) +def _(x, y): + return None + + +@_set_sub.register(Expr, Expr) +def _(x, y): + return x-y + + +@_set_sub.register(Interval, Interval) +def _(x, y): + """ + Subtractions in interval arithmetic + https://en.wikipedia.org/wiki/Interval_arithmetic + """ + return Interval(x.start - y.end, x.end - y.start, + x.left_open or y.right_open, x.right_open or y.left_open) + + +@_set_sub.register(Interval, Infinity) +def _(x, y): + if x.start is S.NegativeInfinity: + return Interval(-oo, oo) + return FiniteSet(-oo) + +@_set_sub.register(Interval, NegativeInfinity) +def _(x, y): + if x.start is S.NegativeInfinity: + return Interval(-oo, oo) + return FiniteSet(-oo) diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py new file mode 100644 index 0000000000000000000000000000000000000000..b64d1a2a22e15d09f6f10fb4fef730163d468d45 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/comparison.py @@ -0,0 +1,53 @@ +from sympy.core.relational import Eq, is_eq +from sympy.core.basic import Basic +from sympy.core.logic import fuzzy_and, fuzzy_bool +from sympy.logic.boolalg import And +from sympy.multipledispatch import dispatch +from sympy.sets.sets import tfn, ProductSet, Interval, FiniteSet, Set + + +@dispatch(Interval, FiniteSet) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + return False + + +@dispatch(FiniteSet, Interval) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + return False + + +@dispatch(Interval, Interval) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + return And(Eq(lhs.left, rhs.left), + Eq(lhs.right, rhs.right), + lhs.left_open == rhs.left_open, + lhs.right_open == rhs.right_open) + +@dispatch(FiniteSet, FiniteSet) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + def all_in_both(): + s_set = set(lhs.args) + o_set = set(rhs.args) + yield fuzzy_and(lhs._contains(e) for e in o_set - s_set) + yield fuzzy_and(rhs._contains(e) for e in s_set - o_set) + + return tfn[fuzzy_and(all_in_both())] + + +@dispatch(ProductSet, ProductSet) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + if len(lhs.sets) != len(rhs.sets): + return False + + eqs = (is_eq(x, y) for x, y in zip(lhs.sets, rhs.sets)) + return tfn[fuzzy_and(map(fuzzy_bool, eqs))] + + +@dispatch(Set, Basic) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + return False + + +@dispatch(Set, Set) # type:ignore +def _eval_is_eq(lhs, rhs): # noqa: F811 + return tfn[fuzzy_and(a.is_subset(b) for a, b in [(lhs, rhs), (rhs, lhs)])] diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/functions.py b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/functions.py new file mode 100644 index 0000000000000000000000000000000000000000..2529dbfd458451d7d09e91c717b170df77b1d9fe --- /dev/null +++ b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/functions.py @@ -0,0 +1,262 @@ +from sympy.core.singleton import S +from sympy.sets.sets import Set +from sympy.calculus.singularities import singularities +from sympy.core import Expr, Add +from sympy.core.function import Lambda, FunctionClass, diff, expand_mul +from sympy.core.numbers import Float, oo +from sympy.core.symbol import Dummy, symbols, Wild +from sympy.functions.elementary.exponential import exp, log +from sympy.functions.elementary.miscellaneous import Min, Max +from sympy.logic.boolalg import true +from sympy.multipledispatch import Dispatcher +from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet, + Intersection, Range, Complement) +from sympy.sets.sets import EmptySet, is_function_invertible_in_set +from sympy.sets.fancysets import Integers, Naturals, Reals +from sympy.functions.elementary.exponential import match_real_imag + + +_x, _y = symbols("x y") + +FunctionUnion = (FunctionClass, Lambda) + +_set_function = Dispatcher('_set_function') + + +@_set_function.register(FunctionClass, Set) +def _(f, x): + return None + +@_set_function.register(FunctionUnion, FiniteSet) +def _(f, x): + return FiniteSet(*map(f, x)) + +@_set_function.register(Lambda, Interval) +def _(f, x): + from sympy.solvers.solveset import solveset + from sympy.series import limit + # TODO: handle functions with infinitely many solutions (eg, sin, tan) + # TODO: handle multivariate functions + + expr = f.expr + if len(expr.free_symbols) > 1 or len(f.variables) != 1: + return + var = f.variables[0] + if not var.is_real: + if expr.subs(var, Dummy(real=True)).is_real is False: + return + + if expr.is_Piecewise: + result = S.EmptySet + domain_set = x + for (p_expr, p_cond) in expr.args: + if p_cond is true: + intrvl = domain_set + else: + intrvl = p_cond.as_set() + intrvl = Intersection(domain_set, intrvl) + + if p_expr.is_Number: + image = FiniteSet(p_expr) + else: + image = imageset(Lambda(var, p_expr), intrvl) + result = Union(result, image) + + # remove the part which has been `imaged` + domain_set = Complement(domain_set, intrvl) + if domain_set is S.EmptySet: + break + return result + + if not x.start.is_comparable or not x.end.is_comparable: + return + + try: + from sympy.polys.polyutils import _nsort + sing = list(singularities(expr, var, x)) + if len(sing) > 1: + sing = _nsort(sing) + except NotImplementedError: + return + + if x.left_open: + _start = limit(expr, var, x.start, dir="+") + elif x.start not in sing: + _start = f(x.start) + if x.right_open: + _end = limit(expr, var, x.end, dir="-") + elif x.end not in sing: + _end = f(x.end) + + if len(sing) == 0: + soln_expr = solveset(diff(expr, var), var) + if not (isinstance(soln_expr, FiniteSet) + or soln_expr is S.EmptySet): + return + solns = list(soln_expr) + + extr = [_start, _end] + [f(i) for i in solns + if i.is_real and i in x] + start, end = Min(*extr), Max(*extr) + + left_open, right_open = False, False + if _start <= _end: + # the minimum or maximum value can occur simultaneously + # on both the edge of the interval and in some interior + # point + if start == _start and start not in solns: + left_open = x.left_open + if end == _end and end not in solns: + right_open = x.right_open + else: + if start == _end and start not in solns: + left_open = x.right_open + if end == _start and end not in solns: + right_open = x.left_open + + return Interval(start, end, left_open, right_open) + else: + return imageset(f, Interval(x.start, sing[0], + x.left_open, True)) + \ + Union(*[imageset(f, Interval(sing[i], sing[i + 1], True, True)) + for i in range(0, len(sing) - 1)]) + \ + imageset(f, Interval(sing[-1], x.end, True, x.right_open)) + +@_set_function.register(FunctionClass, Interval) +def _(f, x): + if f == exp: + return Interval(exp(x.start), exp(x.end), x.left_open, x.right_open) + elif f == log: + return Interval(log(x.start), log(x.end), x.left_open, x.right_open) + return ImageSet(Lambda(_x, f(_x)), x) + +@_set_function.register(FunctionUnion, Union) +def _(f, x): + return Union(*(imageset(f, arg) for arg in x.args)) + +@_set_function.register(FunctionUnion, Intersection) +def _(f, x): + # If the function is invertible, intersect the maps of the sets. + if is_function_invertible_in_set(f, x): + return Intersection(*(imageset(f, arg) for arg in x.args)) + else: + return ImageSet(Lambda(_x, f(_x)), x) + +@_set_function.register(FunctionUnion, EmptySet) +def _(f, x): + return x + +@_set_function.register(FunctionUnion, Set) +def _(f, x): + return ImageSet(Lambda(_x, f(_x)), x) + +@_set_function.register(FunctionUnion, Range) +def _(f, self): + if not self: + return S.EmptySet + if not isinstance(f.expr, Expr): + return + if self.size == 1: + return FiniteSet(f(self[0])) + if f is S.IdentityFunction: + return self + + x = f.variables[0] + expr = f.expr + # handle f that is linear in f's variable + if x not in expr.free_symbols or x in expr.diff(x).free_symbols: + return + if self.start.is_finite: + F = f(self.step*x + self.start) # for i in range(len(self)) + else: + F = f(-self.step*x + self[-1]) + F = expand_mul(F) + if F != expr: + return imageset(x, F, Range(self.size)) + +@_set_function.register(FunctionUnion, Integers) +def _(f, self): + expr = f.expr + if not isinstance(expr, Expr): + return + + n = f.variables[0] + if expr == abs(n): + return S.Naturals0 + + # f(x) + c and f(-x) + c cover the same integers + # so choose the form that has the fewest negatives + c = f(0) + fx = f(n) - c + f_x = f(-n) - c + neg_count = lambda e: sum(_.could_extract_minus_sign() + for _ in Add.make_args(e)) + if neg_count(f_x) < neg_count(fx): + expr = f_x + c + + a = Wild('a', exclude=[n]) + b = Wild('b', exclude=[n]) + match = expr.match(a*n + b) + if match and match[a] and ( + not match[a].atoms(Float) and + not match[b].atoms(Float)): + # canonical shift + a, b = match[a], match[b] + if a in [1, -1]: + # drop integer addends in b + nonint = [] + for bi in Add.make_args(b): + if not bi.is_integer: + nonint.append(bi) + b = Add(*nonint) + if b.is_number and a.is_real: + # avoid Mod for complex numbers, #11391 + br, bi = match_real_imag(b) + if br and br.is_comparable and a.is_comparable: + br %= a + b = br + S.ImaginaryUnit*bi + elif b.is_number and a.is_imaginary: + br, bi = match_real_imag(b) + ai = a/S.ImaginaryUnit + if bi and bi.is_comparable and ai.is_comparable: + bi %= ai + b = br + S.ImaginaryUnit*bi + expr = a*n + b + + if expr != f.expr: + return ImageSet(Lambda(n, expr), S.Integers) + + +@_set_function.register(FunctionUnion, Naturals) +def _(f, self): + expr = f.expr + if not isinstance(expr, Expr): + return + + x = f.variables[0] + if not expr.free_symbols - {x}: + if expr == abs(x): + if self is S.Naturals: + return self + return S.Naturals0 + step = expr.coeff(x) + c = expr.subs(x, 0) + if c.is_Integer and step.is_Integer and expr == step*x + c: + if self is S.Naturals: + c += step + if step > 0: + if step == 1: + if c == 0: + return S.Naturals0 + elif c == 1: + return S.Naturals + return Range(c, oo, step) + return Range(c, -oo, step) + + +@_set_function.register(FunctionUnion, Reals) +def _(f, self): + expr = f.expr + if not isinstance(expr, Expr): + return + return _set_function(f, Interval(-oo, oo)) diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/power.py b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/power.py new file mode 100644 index 0000000000000000000000000000000000000000..3cad4ee49ab27770143bc121d1fbcd024bf01548 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/power.py @@ -0,0 +1,107 @@ +from sympy.core import Basic, Expr +from sympy.core.function import Lambda +from sympy.core.numbers import oo, Infinity, NegativeInfinity, Zero, Integer +from sympy.core.singleton import S +from sympy.core.symbol import symbols +from sympy.functions.elementary.miscellaneous import (Max, Min) +from sympy.sets.fancysets import ImageSet +from sympy.sets.setexpr import set_div +from sympy.sets.sets import Set, Interval, FiniteSet, Union +from sympy.multipledispatch import Dispatcher + + +_x, _y = symbols("x y") + + +_set_pow = Dispatcher('_set_pow') + + +@_set_pow.register(Basic, Basic) +def _(x, y): + return None + +@_set_pow.register(Set, Set) +def _(x, y): + return ImageSet(Lambda((_x, _y), (_x ** _y)), x, y) + +@_set_pow.register(Expr, Expr) +def _(x, y): + return x**y + +@_set_pow.register(Interval, Zero) +def _(x, z): + return FiniteSet(S.One) + +@_set_pow.register(Interval, Integer) +def _(x, exponent): + """ + Powers in interval arithmetic + https://en.wikipedia.org/wiki/Interval_arithmetic + """ + s1 = x.start**exponent + s2 = x.end**exponent + if ((s2 > s1) if exponent > 0 else (x.end > -x.start)) == True: + left_open = x.left_open + right_open = x.right_open + # TODO: handle unevaluated condition. + sleft = s2 + else: + # TODO: `s2 > s1` could be unevaluated. + left_open = x.right_open + right_open = x.left_open + sleft = s1 + + if x.start.is_positive: + return Interval( + Min(s1, s2), + Max(s1, s2), left_open, right_open) + elif x.end.is_negative: + return Interval( + Min(s1, s2), + Max(s1, s2), left_open, right_open) + + # Case where x.start < 0 and x.end > 0: + if exponent.is_odd: + if exponent.is_negative: + if x.start.is_zero: + return Interval(s2, oo, x.right_open) + if x.end.is_zero: + return Interval(-oo, s1, True, x.left_open) + return Union(Interval(-oo, s1, True, x.left_open), Interval(s2, oo, x.right_open)) + else: + return Interval(s1, s2, x.left_open, x.right_open) + elif exponent.is_even: + if exponent.is_negative: + if x.start.is_zero: + return Interval(s2, oo, x.right_open) + if x.end.is_zero: + return Interval(s1, oo, x.left_open) + return Interval(0, oo) + else: + return Interval(S.Zero, sleft, S.Zero not in x, left_open) + +@_set_pow.register(Interval, Infinity) +def _(b, e): + # TODO: add logic for open intervals? + if b.start.is_nonnegative: + if b.end < 1: + return FiniteSet(S.Zero) + if b.start > 1: + return FiniteSet(S.Infinity) + return Interval(0, oo) + elif b.end.is_negative: + if b.start > -1: + return FiniteSet(S.Zero) + if b.end < -1: + return FiniteSet(-oo, oo) + return Interval(-oo, oo) + else: + if b.start > -1: + if b.end < 1: + return FiniteSet(S.Zero) + return Interval(0, oo) + return Interval(-oo, oo) + +@_set_pow.register(Interval, NegativeInfinity) +def _(b, e): + return _set_pow(set_div(S.One, b), oo) diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/handlers/union.py b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/union.py new file mode 100644 index 0000000000000000000000000000000000000000..75d867b49969ae2aeea76155dbaae7e05c1a6847 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/sympy/sets/handlers/union.py @@ -0,0 +1,147 @@ +from sympy.core.singleton import S +from sympy.core.sympify import sympify +from sympy.functions.elementary.miscellaneous import Min, Max +from sympy.sets.sets import (EmptySet, FiniteSet, Intersection, + Interval, ProductSet, Set, Union, UniversalSet) +from sympy.sets.fancysets import (ComplexRegion, Naturals, Naturals0, + Integers, Rationals, Reals) +from sympy.multipledispatch import Dispatcher + + +union_sets = Dispatcher('union_sets') + + +@union_sets.register(Naturals0, Naturals) +def _(a, b): + return a + +@union_sets.register(Rationals, Naturals) +def _(a, b): + return a + +@union_sets.register(Rationals, Naturals0) +def _(a, b): + return a + +@union_sets.register(Reals, Naturals) +def _(a, b): + return a + +@union_sets.register(Reals, Naturals0) +def _(a, b): + return a + +@union_sets.register(Reals, Rationals) +def _(a, b): + return a + +@union_sets.register(Integers, Set) +def _(a, b): + intersect = Intersection(a, b) + if intersect == a: + return b + elif intersect == b: + return a + +@union_sets.register(ComplexRegion, Set) +def _(a, b): + if b.is_subset(S.Reals): + # treat a subset of reals as a complex region + b = ComplexRegion.from_real(b) + + if b.is_ComplexRegion: + # a in rectangular form + if (not a.polar) and (not b.polar): + return ComplexRegion(Union(a.sets, b.sets)) + # a in polar form + elif a.polar and b.polar: + return ComplexRegion(Union(a.sets, b.sets), polar=True) + return None + +@union_sets.register(EmptySet, Set) +def _(a, b): + return b + + +@union_sets.register(UniversalSet, Set) +def _(a, b): + return a + +@union_sets.register(ProductSet, ProductSet) +def _(a, b): + if b.is_subset(a): + return a + if len(b.sets) != len(a.sets): + return None + if len(a.sets) == 2: + a1, a2 = a.sets + b1, b2 = b.sets + if a1 == b1: + return a1 * Union(a2, b2) + if a2 == b2: + return Union(a1, b1) * a2 + return None + +@union_sets.register(ProductSet, Set) +def _(a, b): + if b.is_subset(a): + return a + return None + +@union_sets.register(Interval, Interval) +def _(a, b): + if a._is_comparable(b): + # Non-overlapping intervals + end = Min(a.end, b.end) + start = Max(a.start, b.start) + if (end < start or + (end == start and (end not in a and end not in b))): + return None + else: + start = Min(a.start, b.start) + end = Max(a.end, b.end) + + left_open = ((a.start != start or a.left_open) and + (b.start != start or b.left_open)) + right_open = ((a.end != end or a.right_open) and + (b.end != end or b.right_open)) + return Interval(start, end, left_open, right_open) + +@union_sets.register(Interval, UniversalSet) +def _(a, b): + return S.UniversalSet + +@union_sets.register(Interval, Set) +def _(a, b): + # If I have open end points and these endpoints are contained in b + # But only in case, when endpoints are finite. Because + # interval does not contain oo or -oo. + open_left_in_b_and_finite = (a.left_open and + sympify(b.contains(a.start)) is S.true and + a.start.is_finite) + open_right_in_b_and_finite = (a.right_open and + sympify(b.contains(a.end)) is S.true and + a.end.is_finite) + if open_left_in_b_and_finite or open_right_in_b_and_finite: + # Fill in my end points and return + open_left = a.left_open and a.start not in b + open_right = a.right_open and a.end not in b + new_a = Interval(a.start, a.end, open_left, open_right) + return {new_a, b} + return None + +@union_sets.register(FiniteSet, FiniteSet) +def _(a, b): + return FiniteSet(*(a._elements | b._elements)) + +@union_sets.register(FiniteSet, Set) +def _(a, b): + # If `b` set contains one of my elements, remove it from `a` + if any(b.contains(x) == True for x in a): + return { + FiniteSet(*[x for x in a if b.contains(x) != True]), b} + return None + +@union_sets.register(Set, Set) +def _(a, b): + return None diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..143af7c1d9152075e4cf4a7d53f22e7fe6243e4d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_conditionset.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_conditionset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c7e1f392befba68fa166b9f01ea756e594eab2f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_conditionset.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_ordinals.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_ordinals.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ffa411caa382e7b6dc810b90e6f442014a1a5c6 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_ordinals.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_powerset.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_powerset.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f20eeca6fdbbdb927cafa5162cf08db6c7bcb01a Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_powerset.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_setexpr.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_setexpr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da4d642a99bb85cca22b5ab2e03176f0ecb42dd8 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_setexpr.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_sets.cpython-310.pyc b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_sets.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d98be4fe2b4d73d64158f340f31a4c0f763a061 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/sympy/sets/tests/__pycache__/test_sets.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/sympy/sets/tests/test_conditionset.py b/vllm/lib/python3.10/site-packages/sympy/sets/tests/test_conditionset.py new file mode 100644 index 0000000000000000000000000000000000000000..4818246f306afd46a09a2cbea1faab858a9e7806 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/sympy/sets/tests/test_conditionset.py @@ -0,0 +1,294 @@ +from sympy.core.expr import unchanged +from sympy.sets import (ConditionSet, Intersection, FiniteSet, + EmptySet, Union, Contains, ImageSet) +from sympy.sets.sets import SetKind +from sympy.core.function import (Function, Lambda) +from sympy.core.mod import Mod +from sympy.core.kind import NumberKind +from sympy.core.numbers import (oo, pi) +from sympy.core.relational import (Eq, Ne) +from sympy.core.singleton import S +from sympy.core.symbol import (Symbol, symbols) +from sympy.functions.elementary.complexes import Abs +from sympy.functions.elementary.trigonometric import (asin, sin) +from sympy.logic.boolalg import And +from sympy.matrices.dense import Matrix +from sympy.matrices.expressions.matexpr import MatrixSymbol +from sympy.sets.sets import Interval +from sympy.testing.pytest import raises, warns_deprecated_sympy + + +w = Symbol('w') +x = Symbol('x') +y = Symbol('y') +z = Symbol('z') +f = Function('f') + + +def test_CondSet(): + sin_sols_principal = ConditionSet(x, Eq(sin(x), 0), + Interval(0, 2*pi, False, True)) + assert pi in sin_sols_principal + assert pi/2 not in sin_sols_principal + assert 3*pi not in sin_sols_principal + assert oo not in sin_sols_principal + assert 5 in ConditionSet(x, x**2 > 4, S.Reals) + assert 1 not in ConditionSet(x, x**2 > 4, S.Reals) + # in this case, 0 is not part of the base set so + # it can't be in any subset selected by the condition + assert 0 not in ConditionSet(x, y > 5, Interval(1, 7)) + # since 'in' requires a true/false, the following raises + # an error because the given value provides no information + # for the condition to evaluate (since the condition does + # not depend on the dummy symbol): the result is `y > 5`. + # In this case, ConditionSet is just acting like + # Piecewise((Interval(1, 7), y > 5), (S.EmptySet, True)). + raises(TypeError, lambda: 6 in ConditionSet(x, y > 5, + Interval(1, 7))) + + X = MatrixSymbol('X', 2, 2) + matrix_set = ConditionSet(X, Eq(X*Matrix([[1, 1], [1, 1]]), X)) + Y = Matrix([[0, 0], [0, 0]]) + assert matrix_set.contains(Y).doit() is S.true + Z = Matrix([[1, 2], [3, 4]]) + assert matrix_set.contains(Z).doit() is S.false + + assert isinstance(ConditionSet(x, x < 1, {x, y}).base_set, + FiniteSet) + raises(TypeError, lambda: ConditionSet(x, x + 1, {x, y})) + raises(TypeError, lambda: ConditionSet(x, x, 1)) + + I = S.Integers + U = S.UniversalSet + C = ConditionSet + assert C(x, False, I) is S.EmptySet + assert C(x, True, I) is I + assert C(x, x < 1, C(x, x < 2, I) + ) == C(x, (x < 1) & (x < 2), I) + assert C(y, y < 1, C(x, y < 2, I) + ) == C(x, (x < 1) & (y < 2), I), C(y, y < 1, C(x, y < 2, I)) + assert C(y, y < 1, C(x, x < 2, I) + ) == C(y, (y < 1) & (y < 2), I) + assert C(y, y < 1, C(x, y < x, I) + ) == C(x, (x < 1) & (y < x), I) + assert unchanged(C, y, x < 1, C(x, y < x, I)) + assert ConditionSet(x, x < 1).base_set is U + # arg checking is not done at instantiation but this + # will raise an error when containment is tested + assert ConditionSet((x,), x < 1).base_set is U + + c = ConditionSet((x, y), x < y, I**2) + assert (1, 2) in c + assert (1, pi) not in c + + raises(TypeError, lambda: C(x, x > 1, C((x, y), x > 1, I**2))) + # signature mismatch since only 3 args are accepted + raises(TypeError, lambda: C((x, y), x + y < 2, U, U)) + + +def test_CondSet_intersect(): + input_conditionset = ConditionSet(x, x**2 > 4, Interval(1, 4, False, + False)) + other_domain = Interval(0, 3, False, False) + output_conditionset = ConditionSet(x, x**2 > 4, Interval( + 1, 3, False, False)) + assert Intersection(input_conditionset, other_domain + ) == output_conditionset + + +def test_issue_9849(): + assert ConditionSet(x, Eq(x, x), S.Naturals + ) is S.Naturals + assert ConditionSet(x, Eq(Abs(sin(x)), -1), S.Naturals + ) == S.EmptySet + + +def test_simplified_FiniteSet_in_CondSet(): + assert ConditionSet(x, And(x < 1, x > -3), FiniteSet(0, 1, 2) + ) == FiniteSet(0) + assert ConditionSet(x, x < 0, FiniteSet(0, 1, 2)) == EmptySet + assert ConditionSet(x, And(x < -3), EmptySet) == EmptySet + y = Symbol('y') + assert (ConditionSet(x, And(x > 0), FiniteSet(-1, 0, 1, y)) == + Union(FiniteSet(1), ConditionSet(x, And(x > 0), FiniteSet(y)))) + assert (ConditionSet(x, Eq(Mod(x, 3), 1), FiniteSet(1, 4, 2, y)) == + Union(FiniteSet(1, 4), ConditionSet(x, Eq(Mod(x, 3), 1), + FiniteSet(y)))) + + +def test_free_symbols(): + assert ConditionSet(x, Eq(y, 0), FiniteSet(z) + ).free_symbols == {y, z} + assert ConditionSet(x, Eq(x, 0), FiniteSet(z) + ).free_symbols == {z} + assert ConditionSet(x, Eq(x, 0), FiniteSet(x, z) + ).free_symbols == {x, z} + assert ConditionSet(x, Eq(x, 0), ImageSet(Lambda(y, y**2), + S.Integers)).free_symbols == set() + + +def test_bound_symbols(): + assert ConditionSet(x, Eq(y, 0), FiniteSet(z) + ).bound_symbols == [x] + assert ConditionSet(x, Eq(x, 0), FiniteSet(x, y) + ).bound_symbols == [x] + assert ConditionSet(x, x < 10, ImageSet(Lambda(y, y**2), S.Integers) + ).bound_symbols == [x] + assert ConditionSet(x, x < 10, ConditionSet(y, y > 1, S.Integers) + ).bound_symbols == [x] + + +def test_as_dummy(): + _0, _1 = symbols('_0 _1') + assert ConditionSet(x, x < 1, Interval(y, oo) + ).as_dummy() == ConditionSet(_0, _0 < 1, Interval(y, oo)) + assert ConditionSet(x, x < 1, Interval(x, oo) + ).as_dummy() == ConditionSet(_0, _0 < 1, Interval(x, oo)) + assert ConditionSet(x, x < 1, ImageSet(Lambda(y, y**2), S.Integers) + ).as_dummy() == ConditionSet( + _0, _0 < 1, ImageSet(Lambda(_0, _0**2), S.Integers)) + e = ConditionSet((x, y), x <= y, S.Reals**2) + assert e.bound_symbols == [x, y] + assert e.as_dummy() == ConditionSet((_0, _1), _0 <= _1, S.Reals**2) + assert e.as_dummy() == ConditionSet((y, x), y <= x, S.Reals**2 + ).as_dummy() + + +def test_subs_CondSet(): + s = FiniteSet(z, y) + c = ConditionSet(x, x < 2, s) + assert c.subs(x, y) == c + assert c.subs(z, y) == ConditionSet(x, x < 2, FiniteSet(y)) + assert c.xreplace({x: y}) == ConditionSet(y, y < 2, s) + + assert ConditionSet(x, x < y, s + ).subs(y, w) == ConditionSet(x, x < w, s.subs(y, w)) + # if the user uses assumptions that cause the condition + # to evaluate, that can't be helped from SymPy's end + n = Symbol('n', negative=True) + assert ConditionSet(n, 0 < n, S.Integers) is S.EmptySet + p = Symbol('p', positive=True) + assert ConditionSet(n, n < y, S.Integers + ).subs(n, x) == ConditionSet(n, n < y, S.Integers) + raises(ValueError, lambda: ConditionSet( + x + 1, x < 1, S.Integers)) + assert ConditionSet( + p, n < x, Interval(-5, 5)).subs(x, p) == Interval(-5, 5), ConditionSet( + p, n < x, Interval(-5, 5)).subs(x, p) + assert ConditionSet( + n, n < x, Interval(-oo, 0)).subs(x, p + ) == Interval(-oo, 0) + + assert ConditionSet(f(x), f(x) < 1, {w, z} + ).subs(f(x), y) == ConditionSet(f(x), f(x) < 1, {w, z}) + + # issue 17341 + k = Symbol('k') + img1 = ImageSet(Lambda(k, 2*k*pi + asin(y)), S.Integers) + img2 = ImageSet(Lambda(k, 2*k*pi + asin(S.One/3)), S.Integers) + assert ConditionSet(x, Contains( + y, Interval(-1,1)), img1).subs(y, S.One/3).dummy_eq(img2) + + assert (0, 1) in ConditionSet((x, y), x + y < 3, S.Integers**2) + + raises(TypeError, lambda: ConditionSet(n, n < -10, Interval(0, 10))) + + +def test_subs_CondSet_tebr(): + with warns_deprecated_sympy(): + assert ConditionSet((x, y), {x + 1, x + y}, S.Reals**2) == \ + ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2) + + +def test_dummy_eq(): + C = ConditionSet + I = S.Integers + c = C(x, x < 1, I) + assert c.dummy_eq(C(y, y < 1, I)) + assert c.dummy_eq(1) == False + assert c.dummy_eq(C(x, x < 1, S.Reals)) == False + + c1 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2) + c2 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals**2) + c3 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Complexes**2) + assert c1.dummy_eq(c2) + assert c1.dummy_eq(c3) is False + assert c.dummy_eq(c1) is False + assert c1.dummy_eq(c) is False + + # issue 19496 + m = Symbol('m') + n = Symbol('n') + a = Symbol('a') + d1 = ImageSet(Lambda(m, m*pi), S.Integers) + d2 = ImageSet(Lambda(n, n*pi), S.Integers) + c1 = ConditionSet(x, Ne(a, 0), d1) + c2 = ConditionSet(x, Ne(a, 0), d2) + assert c1.dummy_eq(c2) + + +def test_contains(): + assert 6 in ConditionSet(x, x > 5, Interval(1, 7)) + assert (8 in ConditionSet(x, y > 5, Interval(1, 7))) is False + # `in` should give True or False; in this case there is not + # enough information for that result + raises(TypeError, + lambda: 6 in ConditionSet(x, y > 5, Interval(1, 7))) + # here, there is enough information but the comparison is + # not defined + raises(TypeError, lambda: 0 in ConditionSet(x, 1/x >= 0, S.Reals)) + assert ConditionSet(x, y > 5, Interval(1, 7) + ).contains(6) == (y > 5) + assert ConditionSet(x, y > 5, Interval(1, 7) + ).contains(8) is S.false + assert ConditionSet(x, y > 5, Interval(1, 7) + ).contains(w) == And(Contains(w, Interval(1, 7)), y > 5) + # This returns an unevaluated Contains object + # because 1/0 should not be defined for 1 and 0 in the context of + # reals. + assert ConditionSet(x, 1/x >= 0, S.Reals).contains(0) == \ + Contains(0, ConditionSet(x, 1/x >= 0, S.Reals), evaluate=False) + c = ConditionSet((x, y), x + y > 1, S.Integers**2) + assert not c.contains(1) + assert c.contains((2, 1)) + assert not c.contains((0, 1)) + c = ConditionSet((w, (x, y)), w + x + y > 1, S.Integers*S.Integers**2) + assert not c.contains(1) + assert not c.contains((1, 2)) + assert not c.contains(((1, 2), 3)) + assert not c.contains(((1, 2), (3, 4))) + assert c.contains((1, (3, 4))) + + +def test_as_relational(): + assert ConditionSet((x, y), x > 1, S.Integers**2).as_relational((x, y) + ) == (x > 1) & Contains(x, S.Integers) & Contains(y, S.Integers) + assert ConditionSet(x, x > 1, S.Integers).as_relational(x + ) == Contains(x, S.Integers) & (x > 1) + + +def test_flatten(): + """Tests whether there is basic denesting functionality""" + inner = ConditionSet(x, sin(x) + x > 0) + outer = ConditionSet(x, Contains(x, inner), S.Reals) + assert outer == ConditionSet(x, sin(x) + x > 0, S.Reals) + + inner = ConditionSet(y, sin(y) + y > 0) + outer = ConditionSet(x, Contains(y, inner), S.Reals) + assert outer != ConditionSet(x, sin(x) + x > 0, S.Reals) + + inner = ConditionSet(x, sin(x) + x > 0).intersect(Interval(-1, 1)) + outer = ConditionSet(x, Contains(x, inner), S.Reals) + assert outer == ConditionSet(x, sin(x) + x > 0, Interval(-1, 1)) + + +def test_duplicate(): + from sympy.core.function import BadSignatureError + # test coverage for line 95 in conditionset.py, check for duplicates in symbols + dup = symbols('a,a') + raises(BadSignatureError, lambda: ConditionSet(dup, x < 0)) + + +def test_SetKind_ConditionSet(): + assert ConditionSet(x, Eq(sin(x), 0), Interval(0, 2*pi)).kind is SetKind(NumberKind) + assert ConditionSet(x, x < 0).kind is SetKind(NumberKind)