diff --git a/parrot/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d392b3134abc708c7540a2c5d08f316199277827 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_bunch.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_bunch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..178c16a080d2567e9f98305791e3f3fbb5daa8e6 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_bunch.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py b/parrot/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py new file mode 100644 index 0000000000000000000000000000000000000000..82021775c294c7b881b9458b57d16deaac483cc7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py @@ -0,0 +1,204 @@ +from numpy.testing import assert_equal, assert_ +from pytest import raises as assert_raises + +import time +import pytest +import ctypes +import threading +from scipy._lib import _ccallback_c as _test_ccallback_cython +from scipy._lib import _test_ccallback +from scipy._lib._ccallback import LowLevelCallable + +try: + import cffi + HAVE_CFFI = True +except ImportError: + HAVE_CFFI = False + + +ERROR_VALUE = 2.0 + + +def callback_python(a, user_data=None): + if a == ERROR_VALUE: + raise ValueError("bad value") + + if user_data is None: + return a + 1 + else: + return a + user_data + +def _get_cffi_func(base, signature): + if not HAVE_CFFI: + pytest.skip("cffi not installed") + + # Get function address + voidp = ctypes.cast(base, ctypes.c_void_p) + address = voidp.value + + # Create corresponding cffi handle + ffi = cffi.FFI() + func = ffi.cast(signature, address) + return func + + +def _get_ctypes_data(): + value = ctypes.c_double(2.0) + return ctypes.cast(ctypes.pointer(value), ctypes.c_voidp) + + +def _get_cffi_data(): + if not HAVE_CFFI: + pytest.skip("cffi not installed") + ffi = cffi.FFI() + return ffi.new('double *', 2.0) + + +CALLERS = { + 'simple': _test_ccallback.test_call_simple, + 'nodata': _test_ccallback.test_call_nodata, + 'nonlocal': _test_ccallback.test_call_nonlocal, + 'cython': _test_ccallback_cython.test_call_cython, +} + +# These functions have signatures known to the callers +FUNCS = { + 'python': lambda: callback_python, + 'capsule': lambda: _test_ccallback.test_get_plus1_capsule(), + 'cython': lambda: LowLevelCallable.from_cython(_test_ccallback_cython, + "plus1_cython"), + 'ctypes': lambda: _test_ccallback_cython.plus1_ctypes, + 'cffi': lambda: _get_cffi_func(_test_ccallback_cython.plus1_ctypes, + 'double (*)(double, int *, void *)'), + 'capsule_b': lambda: _test_ccallback.test_get_plus1b_capsule(), + 'cython_b': lambda: LowLevelCallable.from_cython(_test_ccallback_cython, + "plus1b_cython"), + 'ctypes_b': lambda: _test_ccallback_cython.plus1b_ctypes, + 'cffi_b': lambda: _get_cffi_func(_test_ccallback_cython.plus1b_ctypes, + 'double (*)(double, double, int *, void *)'), +} + +# These functions have signatures the callers don't know +BAD_FUNCS = { + 'capsule_bc': lambda: _test_ccallback.test_get_plus1bc_capsule(), + 'cython_bc': lambda: LowLevelCallable.from_cython(_test_ccallback_cython, + "plus1bc_cython"), + 'ctypes_bc': lambda: _test_ccallback_cython.plus1bc_ctypes, + 'cffi_bc': lambda: _get_cffi_func( + _test_ccallback_cython.plus1bc_ctypes, + 'double (*)(double, double, double, int *, void *)' + ), +} + +USER_DATAS = { + 'ctypes': _get_ctypes_data, + 'cffi': _get_cffi_data, + 'capsule': _test_ccallback.test_get_data_capsule, +} + + +def test_callbacks(): + def check(caller, func, user_data): + caller = CALLERS[caller] + func = FUNCS[func]() + user_data = USER_DATAS[user_data]() + + if func is callback_python: + def func2(x): + return func(x, 2.0) + else: + func2 = LowLevelCallable(func, user_data) + func = LowLevelCallable(func) + + # Test basic call + assert_equal(caller(func, 1.0), 2.0) + + # Test 'bad' value resulting to an error + assert_raises(ValueError, caller, func, ERROR_VALUE) + + # Test passing in user_data + assert_equal(caller(func2, 1.0), 3.0) + + for caller in sorted(CALLERS.keys()): + for func in sorted(FUNCS.keys()): + for user_data in sorted(USER_DATAS.keys()): + check(caller, func, user_data) + + +def test_bad_callbacks(): + def check(caller, func, user_data): + caller = CALLERS[caller] + user_data = USER_DATAS[user_data]() + func = BAD_FUNCS[func]() + + if func is callback_python: + def func2(x): + return func(x, 2.0) + else: + func2 = LowLevelCallable(func, user_data) + func = LowLevelCallable(func) + + # Test that basic call fails + assert_raises(ValueError, caller, LowLevelCallable(func), 1.0) + + # Test that passing in user_data also fails + assert_raises(ValueError, caller, func2, 1.0) + + # Test error message + llfunc = LowLevelCallable(func) + try: + caller(llfunc, 1.0) + except ValueError as err: + msg = str(err) + assert_(llfunc.signature in msg, msg) + assert_('double (double, double, int *, void *)' in msg, msg) + + for caller in sorted(CALLERS.keys()): + for func in sorted(BAD_FUNCS.keys()): + for user_data in sorted(USER_DATAS.keys()): + check(caller, func, user_data) + + +def test_signature_override(): + caller = _test_ccallback.test_call_simple + func = _test_ccallback.test_get_plus1_capsule() + + llcallable = LowLevelCallable(func, signature="bad signature") + assert_equal(llcallable.signature, "bad signature") + assert_raises(ValueError, caller, llcallable, 3) + + llcallable = LowLevelCallable(func, signature="double (double, int *, void *)") + assert_equal(llcallable.signature, "double (double, int *, void *)") + assert_equal(caller(llcallable, 3), 4) + + +def test_threadsafety(): + def callback(a, caller): + if a <= 0: + return 1 + else: + res = caller(lambda x: callback(x, caller), a - 1) + return 2*res + + def check(caller): + caller = CALLERS[caller] + + results = [] + + count = 10 + + def run(): + time.sleep(0.01) + r = caller(lambda x: callback(x, caller), count) + results.append(r) + + threads = [threading.Thread(target=run) for j in range(20)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert_equal(results, [2.0**count]*len(threads)) + + for caller in CALLERS.keys(): + check(caller) diff --git a/parrot/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py b/parrot/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py new file mode 100644 index 0000000000000000000000000000000000000000..0e789f9ccb33f3f78ea5d61a8a46fdc26a57e367 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py @@ -0,0 +1,496 @@ +""" +This test script is adopted from: + https://github.com/numpy/numpy/blob/main/numpy/tests/test_public_api.py +""" + +import pkgutil +import types +import importlib +import warnings +from importlib import import_module + +import pytest + +import scipy + +from scipy.conftest import xp_available_backends + + +def test_dir_testing(): + """Assert that output of dir has only one "testing/tester" + attribute without duplicate""" + assert len(dir(scipy)) == len(set(dir(scipy))) + + +# Historically SciPy has not used leading underscores for private submodules +# much. This has resulted in lots of things that look like public modules +# (i.e. things that can be imported as `import scipy.somesubmodule.somefile`), +# but were never intended to be public. The PUBLIC_MODULES list contains +# modules that are either public because they were meant to be, or because they +# contain public functions/objects that aren't present in any other namespace +# for whatever reason and therefore should be treated as public. +PUBLIC_MODULES = ["scipy." + s for s in [ + "cluster", + "cluster.vq", + "cluster.hierarchy", + "constants", + "datasets", + "fft", + "fftpack", + "integrate", + "interpolate", + "io", + "io.arff", + "io.matlab", + "io.wavfile", + "linalg", + "linalg.blas", + "linalg.cython_blas", + "linalg.lapack", + "linalg.cython_lapack", + "linalg.interpolative", + "misc", + "ndimage", + "odr", + "optimize", + "signal", + "signal.windows", + "sparse", + "sparse.linalg", + "sparse.csgraph", + "spatial", + "spatial.distance", + "spatial.transform", + "special", + "stats", + "stats.contingency", + "stats.distributions", + "stats.mstats", + "stats.qmc", + "stats.sampling" +]] + +# The PRIVATE_BUT_PRESENT_MODULES list contains modules that lacked underscores +# in their name and hence looked public, but weren't meant to be. All these +# namespace were deprecated in the 1.8.0 release - see "clear split between +# public and private API" in the 1.8.0 release notes. +# These private modules support will be removed in SciPy v2.0.0, as the +# deprecation messages emitted by each of these modules say. +PRIVATE_BUT_PRESENT_MODULES = [ + 'scipy.constants.codata', + 'scipy.constants.constants', + 'scipy.fftpack.basic', + 'scipy.fftpack.convolve', + 'scipy.fftpack.helper', + 'scipy.fftpack.pseudo_diffs', + 'scipy.fftpack.realtransforms', + 'scipy.integrate.dop', + 'scipy.integrate.lsoda', + 'scipy.integrate.odepack', + 'scipy.integrate.quadpack', + 'scipy.integrate.vode', + 'scipy.interpolate.dfitpack', + 'scipy.interpolate.fitpack', + 'scipy.interpolate.fitpack2', + 'scipy.interpolate.interpnd', + 'scipy.interpolate.interpolate', + 'scipy.interpolate.ndgriddata', + 'scipy.interpolate.polyint', + 'scipy.interpolate.rbf', + 'scipy.io.arff.arffread', + 'scipy.io.harwell_boeing', + 'scipy.io.idl', + 'scipy.io.matlab.byteordercodes', + 'scipy.io.matlab.mio', + 'scipy.io.matlab.mio4', + 'scipy.io.matlab.mio5', + 'scipy.io.matlab.mio5_params', + 'scipy.io.matlab.mio5_utils', + 'scipy.io.matlab.mio_utils', + 'scipy.io.matlab.miobase', + 'scipy.io.matlab.streams', + 'scipy.io.mmio', + 'scipy.io.netcdf', + 'scipy.linalg.basic', + 'scipy.linalg.decomp', + 'scipy.linalg.decomp_cholesky', + 'scipy.linalg.decomp_lu', + 'scipy.linalg.decomp_qr', + 'scipy.linalg.decomp_schur', + 'scipy.linalg.decomp_svd', + 'scipy.linalg.matfuncs', + 'scipy.linalg.misc', + 'scipy.linalg.special_matrices', + 'scipy.misc.common', + 'scipy.misc.doccer', + 'scipy.ndimage.filters', + 'scipy.ndimage.fourier', + 'scipy.ndimage.interpolation', + 'scipy.ndimage.measurements', + 'scipy.ndimage.morphology', + 'scipy.odr.models', + 'scipy.odr.odrpack', + 'scipy.optimize.cobyla', + 'scipy.optimize.cython_optimize', + 'scipy.optimize.lbfgsb', + 'scipy.optimize.linesearch', + 'scipy.optimize.minpack', + 'scipy.optimize.minpack2', + 'scipy.optimize.moduleTNC', + 'scipy.optimize.nonlin', + 'scipy.optimize.optimize', + 'scipy.optimize.slsqp', + 'scipy.optimize.tnc', + 'scipy.optimize.zeros', + 'scipy.signal.bsplines', + 'scipy.signal.filter_design', + 'scipy.signal.fir_filter_design', + 'scipy.signal.lti_conversion', + 'scipy.signal.ltisys', + 'scipy.signal.signaltools', + 'scipy.signal.spectral', + 'scipy.signal.spline', + 'scipy.signal.waveforms', + 'scipy.signal.wavelets', + 'scipy.signal.windows.windows', + 'scipy.sparse.base', + 'scipy.sparse.bsr', + 'scipy.sparse.compressed', + 'scipy.sparse.construct', + 'scipy.sparse.coo', + 'scipy.sparse.csc', + 'scipy.sparse.csr', + 'scipy.sparse.data', + 'scipy.sparse.dia', + 'scipy.sparse.dok', + 'scipy.sparse.extract', + 'scipy.sparse.lil', + 'scipy.sparse.linalg.dsolve', + 'scipy.sparse.linalg.eigen', + 'scipy.sparse.linalg.interface', + 'scipy.sparse.linalg.isolve', + 'scipy.sparse.linalg.matfuncs', + 'scipy.sparse.sparsetools', + 'scipy.sparse.spfuncs', + 'scipy.sparse.sputils', + 'scipy.spatial.ckdtree', + 'scipy.spatial.kdtree', + 'scipy.spatial.qhull', + 'scipy.spatial.transform.rotation', + 'scipy.special.add_newdocs', + 'scipy.special.basic', + 'scipy.special.cython_special', + 'scipy.special.orthogonal', + 'scipy.special.sf_error', + 'scipy.special.specfun', + 'scipy.special.spfun_stats', + 'scipy.stats.biasedurn', + 'scipy.stats.kde', + 'scipy.stats.morestats', + 'scipy.stats.mstats_basic', + 'scipy.stats.mstats_extras', + 'scipy.stats.mvn', + 'scipy.stats.stats', +] + + +def is_unexpected(name): + """Check if this needs to be considered.""" + if '._' in name or '.tests' in name or '.setup' in name: + return False + + if name in PUBLIC_MODULES: + return False + + if name in PRIVATE_BUT_PRESENT_MODULES: + return False + + return True + + +SKIP_LIST = [ + 'scipy.conftest', + 'scipy.version', + 'scipy.special.libsf_error_state' +] + + +# XXX: this test does more than it says on the tin - in using `pkgutil.walk_packages`, +# it will raise if it encounters any exceptions which are not handled by `ignore_errors` +# while attempting to import each discovered package. +# For now, `ignore_errors` only ignores what is necessary, but this could be expanded - +# for example, to all errors from private modules or git subpackages - if desired. +def test_all_modules_are_expected(): + """ + Test that we don't add anything that looks like a new public module by + accident. Check is based on filenames. + """ + + def ignore_errors(name): + # if versions of other array libraries are installed which are incompatible + # with the installed NumPy version, there can be errors on importing + # `array_api_compat`. This should only raise if SciPy is configured with + # that library as an available backend. + backends = {'cupy': 'cupy', + 'pytorch': 'torch', + 'dask.array': 'dask.array'} + for backend, dir_name in backends.items(): + path = f'array_api_compat.{dir_name}' + if path in name and backend not in xp_available_backends: + return + raise + + modnames = [] + + for _, modname, _ in pkgutil.walk_packages(path=scipy.__path__, + prefix=scipy.__name__ + '.', + onerror=ignore_errors): + if is_unexpected(modname) and modname not in SKIP_LIST: + # We have a name that is new. If that's on purpose, add it to + # PUBLIC_MODULES. We don't expect to have to add anything to + # PRIVATE_BUT_PRESENT_MODULES. Use an underscore in the name! + modnames.append(modname) + + if modnames: + raise AssertionError(f'Found unexpected modules: {modnames}') + + +# Stuff that clearly shouldn't be in the API and is detected by the next test +# below +SKIP_LIST_2 = [ + 'scipy.char', + 'scipy.rec', + 'scipy.emath', + 'scipy.math', + 'scipy.random', + 'scipy.ctypeslib', + 'scipy.ma' +] + + +def test_all_modules_are_expected_2(): + """ + Method checking all objects. The pkgutil-based method in + `test_all_modules_are_expected` does not catch imports into a namespace, + only filenames. + """ + + def find_unexpected_members(mod_name): + members = [] + module = importlib.import_module(mod_name) + if hasattr(module, '__all__'): + objnames = module.__all__ + else: + objnames = dir(module) + + for objname in objnames: + if not objname.startswith('_'): + fullobjname = mod_name + '.' + objname + if isinstance(getattr(module, objname), types.ModuleType): + if is_unexpected(fullobjname) and fullobjname not in SKIP_LIST_2: + members.append(fullobjname) + + return members + + unexpected_members = find_unexpected_members("scipy") + for modname in PUBLIC_MODULES: + unexpected_members.extend(find_unexpected_members(modname)) + + if unexpected_members: + raise AssertionError("Found unexpected object(s) that look like " + f"modules: {unexpected_members}") + + +def test_api_importable(): + """ + Check that all submodules listed higher up in this file can be imported + Note that if a PRIVATE_BUT_PRESENT_MODULES entry goes missing, it may + simply need to be removed from the list (deprecation may or may not be + needed - apply common sense). + """ + def check_importable(module_name): + try: + importlib.import_module(module_name) + except (ImportError, AttributeError): + return False + + return True + + module_names = [] + for module_name in PUBLIC_MODULES: + if not check_importable(module_name): + module_names.append(module_name) + + if module_names: + raise AssertionError("Modules in the public API that cannot be " + f"imported: {module_names}") + + with warnings.catch_warnings(record=True): + warnings.filterwarnings('always', category=DeprecationWarning) + warnings.filterwarnings('always', category=ImportWarning) + for module_name in PRIVATE_BUT_PRESENT_MODULES: + if not check_importable(module_name): + module_names.append(module_name) + + if module_names: + raise AssertionError("Modules that are not really public but looked " + "public and can not be imported: " + f"{module_names}") + + +@pytest.mark.parametrize(("module_name", "correct_module"), + [('scipy.constants.codata', None), + ('scipy.constants.constants', None), + ('scipy.fftpack.basic', None), + ('scipy.fftpack.helper', None), + ('scipy.fftpack.pseudo_diffs', None), + ('scipy.fftpack.realtransforms', None), + ('scipy.integrate.dop', None), + ('scipy.integrate.lsoda', None), + ('scipy.integrate.odepack', None), + ('scipy.integrate.quadpack', None), + ('scipy.integrate.vode', None), + ('scipy.interpolate.fitpack', None), + ('scipy.interpolate.fitpack2', None), + ('scipy.interpolate.interpolate', None), + ('scipy.interpolate.ndgriddata', None), + ('scipy.interpolate.polyint', None), + ('scipy.interpolate.rbf', None), + ('scipy.io.harwell_boeing', None), + ('scipy.io.idl', None), + ('scipy.io.mmio', None), + ('scipy.io.netcdf', None), + ('scipy.io.arff.arffread', 'arff'), + ('scipy.io.matlab.byteordercodes', 'matlab'), + ('scipy.io.matlab.mio_utils', 'matlab'), + ('scipy.io.matlab.mio', 'matlab'), + ('scipy.io.matlab.mio4', 'matlab'), + ('scipy.io.matlab.mio5_params', 'matlab'), + ('scipy.io.matlab.mio5_utils', 'matlab'), + ('scipy.io.matlab.mio5', 'matlab'), + ('scipy.io.matlab.miobase', 'matlab'), + ('scipy.io.matlab.streams', 'matlab'), + ('scipy.linalg.basic', None), + ('scipy.linalg.decomp', None), + ('scipy.linalg.decomp_cholesky', None), + ('scipy.linalg.decomp_lu', None), + ('scipy.linalg.decomp_qr', None), + ('scipy.linalg.decomp_schur', None), + ('scipy.linalg.decomp_svd', None), + ('scipy.linalg.matfuncs', None), + ('scipy.linalg.misc', None), + ('scipy.linalg.special_matrices', None), + ('scipy.misc.common', None), + ('scipy.ndimage.filters', None), + ('scipy.ndimage.fourier', None), + ('scipy.ndimage.interpolation', None), + ('scipy.ndimage.measurements', None), + ('scipy.ndimage.morphology', None), + ('scipy.odr.models', None), + ('scipy.odr.odrpack', None), + ('scipy.optimize.cobyla', None), + ('scipy.optimize.lbfgsb', None), + ('scipy.optimize.linesearch', None), + ('scipy.optimize.minpack', None), + ('scipy.optimize.minpack2', None), + ('scipy.optimize.moduleTNC', None), + ('scipy.optimize.nonlin', None), + ('scipy.optimize.optimize', None), + ('scipy.optimize.slsqp', None), + ('scipy.optimize.tnc', None), + ('scipy.optimize.zeros', None), + ('scipy.signal.bsplines', None), + ('scipy.signal.filter_design', None), + ('scipy.signal.fir_filter_design', None), + ('scipy.signal.lti_conversion', None), + ('scipy.signal.ltisys', None), + ('scipy.signal.signaltools', None), + ('scipy.signal.spectral', None), + ('scipy.signal.waveforms', None), + ('scipy.signal.wavelets', None), + ('scipy.signal.windows.windows', 'windows'), + ('scipy.sparse.lil', None), + ('scipy.sparse.linalg.dsolve', 'linalg'), + ('scipy.sparse.linalg.eigen', 'linalg'), + ('scipy.sparse.linalg.interface', 'linalg'), + ('scipy.sparse.linalg.isolve', 'linalg'), + ('scipy.sparse.linalg.matfuncs', 'linalg'), + ('scipy.sparse.sparsetools', None), + ('scipy.sparse.spfuncs', None), + ('scipy.sparse.sputils', None), + ('scipy.spatial.ckdtree', None), + ('scipy.spatial.kdtree', None), + ('scipy.spatial.qhull', None), + ('scipy.spatial.transform.rotation', 'transform'), + ('scipy.special.add_newdocs', None), + ('scipy.special.basic', None), + ('scipy.special.orthogonal', None), + ('scipy.special.sf_error', None), + ('scipy.special.specfun', None), + ('scipy.special.spfun_stats', None), + ('scipy.stats.biasedurn', None), + ('scipy.stats.kde', None), + ('scipy.stats.morestats', None), + ('scipy.stats.mstats_basic', 'mstats'), + ('scipy.stats.mstats_extras', 'mstats'), + ('scipy.stats.mvn', None), + ('scipy.stats.stats', None)]) +def test_private_but_present_deprecation(module_name, correct_module): + # gh-18279, gh-17572, gh-17771 noted that deprecation warnings + # for imports from private modules + # were misleading. Check that this is resolved. + module = import_module(module_name) + if correct_module is None: + import_name = f'scipy.{module_name.split(".")[1]}' + else: + import_name = f'scipy.{module_name.split(".")[1]}.{correct_module}' + + correct_import = import_module(import_name) + + # Attributes that were formerly in `module_name` can still be imported from + # `module_name`, albeit with a deprecation warning. + for attr_name in module.__all__: + if attr_name == "varmats_from_mat": + # defer handling this case, see + # https://github.com/scipy/scipy/issues/19223 + continue + # ensure attribute is present where the warning is pointing + assert getattr(correct_import, attr_name, None) is not None + message = f"Please import `{attr_name}` from the `{import_name}`..." + with pytest.deprecated_call(match=message): + getattr(module, attr_name) + + # Attributes that were not in `module_name` get an error notifying the user + # that the attribute is not in `module_name` and that `module_name` is deprecated. + message = f"`{module_name}` is deprecated..." + with pytest.raises(AttributeError, match=message): + getattr(module, "ekki") + + +def test_misc_doccer_deprecation(): + # gh-18279, gh-17572, gh-17771 noted that deprecation warnings + # for imports from private modules were misleading. + # Check that this is resolved. + # `test_private_but_present_deprecation` cannot be used since `correct_import` + # is a different subpackage (`_lib` instead of `misc`). + module = import_module('scipy.misc.doccer') + correct_import = import_module('scipy._lib.doccer') + + # Attributes that were formerly in `scipy.misc.doccer` can still be imported from + # `scipy.misc.doccer`, albeit with a deprecation warning. The specific message + # depends on whether the attribute is in `scipy._lib.doccer` or not. + for attr_name in module.__all__: + attr = getattr(correct_import, attr_name, None) + if attr is None: + message = f"`scipy.misc.{attr_name}` is deprecated..." + else: + message = f"Please import `{attr_name}` from the `scipy._lib.doccer`..." + with pytest.deprecated_call(match=message): + getattr(module, attr_name) + + # Attributes that were not in `scipy.misc.doccer` get an error + # notifying the user that the attribute is not in `scipy.misc.doccer` + # and that `scipy.misc.doccer` is deprecated. + message = "`scipy.misc.doccer` is deprecated..." + with pytest.raises(AttributeError, match=message): + getattr(module, "ekki") diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_amp_update_scale_compositeexplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_amp_update_scale_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..1b740f5d433d49e009215021779cfc8a15f8a1a3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_amp_update_scale_compositeexplicitautograd_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::tuple _amp_update_scale(const at::Tensor & self, const at::Tensor & growth_tracker, const at::Tensor & found_inf, double scale_growth_factor, double scale_backoff_factor, int64_t growth_interval); +TORCH_API at::Tensor & _amp_update_scale_out(at::Tensor & out, const at::Tensor & self, at::Tensor & growth_tracker, const at::Tensor & found_inf, double scale_growth_factor, double scale_backoff_factor, int64_t growth_interval); +TORCH_API at::Tensor & _amp_update_scale_outf(const at::Tensor & self, at::Tensor & growth_tracker, const at::Tensor & found_inf, double scale_growth_factor, double scale_backoff_factor, int64_t growth_interval, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_coalesce_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_coalesce_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..26c3d1b66de0495df5eb2b63dff8901a0a9b8e29 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_coalesce_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _coalesce { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_coalesce") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_coalesce(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API _coalesce_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_coalesce") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_coalesce.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_mkldnn_reshape_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_mkldnn_reshape_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..8d7b091eb044d7b4805a1d4317044dbe734bf666 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_mkldnn_reshape_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _mkldnn_reshape { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_mkldnn_reshape") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_mkldnn_reshape(Tensor self, int[] shape) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::IntArrayRef shape); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef shape); +}; + +struct TORCH_API _mkldnn_reshape_out { + using schema = at::Tensor & (const at::Tensor &, at::IntArrayRef, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_mkldnn_reshape") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_mkldnn_reshape.out(Tensor self, int[] shape, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::IntArrayRef shape, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef shape, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_csr_sum_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_csr_sum_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..3a99a33974f6e9ac22bc287dafa38230f3d24ffd --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_csr_sum_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _sparse_csr_sum_dim_dtype { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, bool, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_csr_sum") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim_dtype") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_csr_sum.dim_dtype(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, c10::optional dtype); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, bool keepdim, c10::optional dtype); +}; + +struct TORCH_API _sparse_csr_sum_dim_dtype_out { + using schema = at::Tensor & (const at::Tensor &, at::IntArrayRef, bool, c10::optional, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_csr_sum") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim_dtype_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_csr_sum.dim_dtype_out(Tensor self, int[1] dim, bool keepdim=False, *, ScalarType? dtype=None, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, c10::optional dtype, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, bool keepdim, c10::optional dtype, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..7f9dcd4e1ed0ddf5157fc17f67554ef0cf9a6d69 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_test_autograd_multiple_dispatch_view_copy_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _test_autograd_multiple_dispatch_view_copy { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_test_autograd_multiple_dispatch_view_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_test_autograd_multiple_dispatch_view_copy(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API _test_autograd_multiple_dispatch_view_copy_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_test_autograd_multiple_dispatch_view_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_test_autograd_multiple_dispatch_view_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_to_dense_compositeexplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_to_dense_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..7896e26f7f8ea5190502f37d493f61564fad3c76 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_to_dense_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _to_dense_out(at::Tensor & out, const at::Tensor & self, c10::optional dtype=c10::nullopt, c10::optional masked_grad=c10::nullopt); +TORCH_API at::Tensor & _to_dense_outf(const at::Tensor & self, c10::optional dtype, c10::optional masked_grad, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/abs_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/abs_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..fb0a3bcf28c239d269e2cef4acbc1b20c1fe81b2 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/abs_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API abs { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::abs") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "abs(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API abs_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::abs_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "abs_(Tensor(a!) self) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API abs_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::abs") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "abs.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/argmin_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/argmin_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..5dcb3d7a1ff8e9862527ecf83b1b38bfd2297d15 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/argmin_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API argmin { + using schema = at::Tensor (const at::Tensor &, c10::optional, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::argmin") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "argmin(Tensor self, int? dim=None, bool keepdim=False) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::optional dim, bool keepdim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional dim, bool keepdim); +}; + +struct TORCH_API argmin_out { + using schema = at::Tensor & (const at::Tensor &, c10::optional, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::argmin") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "argmin.out(Tensor self, int? dim=None, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, c10::optional dim, bool keepdim, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional dim, bool keepdim, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_grid_sampler_backward.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_grid_sampler_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..b1ea045ac23fa7c2a65499f951ab5a33750d1bac --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_grid_sampler_backward.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::cudnn_grid_sampler_backward(Tensor self, Tensor grid, Tensor grad_output) -> (Tensor grad_self, Tensor grad_grid) +inline ::std::tuple cudnn_grid_sampler_backward(const at::Tensor & self, const at::Tensor & grid, const at::Tensor & grad_output) { + return at::_ops::cudnn_grid_sampler_backward::call(self, grid, grad_output); +} + +// aten::cudnn_grid_sampler_backward.out(Tensor self, Tensor grid, Tensor grad_output, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple cudnn_grid_sampler_backward_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & self, const at::Tensor & grid, const at::Tensor & grad_output) { + return at::_ops::cudnn_grid_sampler_backward_out::call(self, grid, grad_output, out0, out1); +} +// aten::cudnn_grid_sampler_backward.out(Tensor self, Tensor grid, Tensor grad_output, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple cudnn_grid_sampler_backward_outf(const at::Tensor & self, const at::Tensor & grid, const at::Tensor & grad_output, at::Tensor & out0, at::Tensor & out1) { + return at::_ops::cudnn_grid_sampler_backward_out::call(self, grid, grad_output, out0, out1); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/frobenius_norm_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/frobenius_norm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..75a9fed675d8c191464e5d3d0ccf742309e189e8 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/frobenius_norm_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API frobenius_norm_dim { + using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::frobenius_norm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "dim") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "frobenius_norm.dim(Tensor self, int[1] dim, bool keepdim=False) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::IntArrayRef dim, bool keepdim); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, bool keepdim); +}; + +struct TORCH_API frobenius_norm_out { + using schema = at::Tensor & (const at::Tensor &, at::IntArrayRef, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::frobenius_norm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "frobenius_norm.out(Tensor self, int[1] dim, bool keepdim=False, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::IntArrayRef dim, bool keepdim, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef dim, bool keepdim, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/hspmm.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/hspmm.h new file mode 100644 index 0000000000000000000000000000000000000000..90d058110c9fac32d089ba905acf632afeed7d03 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/hspmm.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::hspmm.out(Tensor mat1, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hspmm_out(at::Tensor & out, const at::Tensor & mat1, const at::Tensor & mat2) { + return at::_ops::hspmm_out::call(mat1, mat2, out); +} +// aten::hspmm.out(Tensor mat1, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & hspmm_outf(const at::Tensor & mat1, const at::Tensor & mat2, at::Tensor & out) { + return at::_ops::hspmm_out::call(mat1, mat2, out); +} + +// aten::hspmm(Tensor mat1, Tensor mat2) -> Tensor +inline at::Tensor hspmm(const at::Tensor & mat1, const at::Tensor & mat2) { + return at::_ops::hspmm::call(mat1, mat2); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/igammac_compositeexplicitautogradnonfunctional_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/igammac_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f379585d85c7eaec55415268b0dd5ba7cbdfbf83 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/igammac_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor igammac(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & igammac_(at::Tensor & self, const at::Tensor & other); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/item.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/item.h new file mode 100644 index 0000000000000000000000000000000000000000..3151cecd136d4ef627a0d39016e6c817a05ad0a7 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/item.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/kthvalue_compositeexplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/kthvalue_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..45b01801bf0d1523a53e1b7dd92f8537f629d224 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/kthvalue_compositeexplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API ::std::tuple kthvalue(const at::Tensor & self, int64_t k, int64_t dim=-1, bool keepdim=false); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/mse_loss_compositeexplicitautogradnonfunctional_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/mse_loss_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..aa5b6f69bc7fb09fcef585ac3fddba47c80ada34 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/mse_loss_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor mse_loss(const at::Tensor & self, const at::Tensor & target, int64_t reduction=at::Reduction::Mean); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/orgqr_compositeimplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/orgqr_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..ce06d57632bcd494ad3d410680059e6379e7f7c8 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/orgqr_compositeimplicitautograd_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor orgqr(const at::Tensor & self, const at::Tensor & input2); +TORCH_API at::Tensor & orgqr_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & input2); +TORCH_API at::Tensor & orgqr_outf(const at::Tensor & self, const at::Tensor & input2, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/ormqr.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/ormqr.h new file mode 100644 index 0000000000000000000000000000000000000000..85d20d27aa0c9e9e76a783316dfdeec33b9f9f12 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/ormqr.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::ormqr.out(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & ormqr_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & input2, const at::Tensor & input3, bool left=true, bool transpose=false) { + return at::_ops::ormqr_out::call(self, input2, input3, left, transpose, out); +} +// aten::ormqr.out(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & ormqr_outf(const at::Tensor & self, const at::Tensor & input2, const at::Tensor & input3, bool left, bool transpose, at::Tensor & out) { + return at::_ops::ormqr_out::call(self, input2, input3, left, transpose, out); +} + +// aten::ormqr(Tensor self, Tensor input2, Tensor input3, bool left=True, bool transpose=False) -> Tensor +inline at::Tensor ormqr(const at::Tensor & self, const at::Tensor & input2, const at::Tensor & input3, bool left=true, bool transpose=false) { + return at::_ops::ormqr::call(self, input2, input3, left, transpose); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/pad_sequence_native.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/pad_sequence_native.h new file mode 100644 index 0000000000000000000000000000000000000000..ea46e18e84d79fddb4273506f23daeeecc575d56 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/pad_sequence_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor pad_sequence(at::TensorList sequences, bool batch_first=false, double padding_value=0.0); +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/permute_copy_compositeexplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/permute_copy_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2a144c8454ef80f54b0d9d1fb1e315c461ca76b8 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/permute_copy_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & permute_copy_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef dims); +TORCH_API at::Tensor & permute_copy_outf(const at::Tensor & self, at::IntArrayRef dims, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/rshift_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/rshift_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..8c86b0fb012f89ab90fc0f28952705ec38065bef --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/rshift_ops.h @@ -0,0 +1,83 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API __rshift___Scalar { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__rshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__rshift__.Scalar(Tensor self, Scalar other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API __rshift___Tensor { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__rshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__rshift__.Tensor(Tensor self, Tensor other) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & other); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API __irshift___Scalar { + using schema = at::Tensor & (at::Tensor &, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__irshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__irshift__.Scalar(Tensor(a!) self, Scalar other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & other); +}; + +struct TORCH_API __irshift___Tensor { + using schema = at::Tensor & (at::Tensor &, const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__irshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__irshift__.Tensor(Tensor(a!) self, Tensor other) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Tensor & other); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Tensor & other); +}; + +struct TORCH_API __rshift___Scalar_out { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__rshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__rshift__.Scalar_out(Tensor self, Scalar other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & other, at::Tensor & out); +}; + +struct TORCH_API __rshift___Tensor_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::__rshift__") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "__rshift__.Tensor_out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/slow_conv_transpose2d.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/slow_conv_transpose2d.h new file mode 100644 index 0000000000000000000000000000000000000000..a04cbedd321675434cf7530ae7b6bb88ec13ad68 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/slow_conv_transpose2d.h @@ -0,0 +1,91 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::slow_conv_transpose2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & slow_conv_transpose2d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1) { + return at::_ops::slow_conv_transpose2d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation), out); +} +namespace symint { + template ::value>> + at::Tensor & slow_conv_transpose2d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1) { + return at::_ops::slow_conv_transpose2d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation), out); + } +} + +// aten::slow_conv_transpose2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & slow_conv_transpose2d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef dilation, at::Tensor & out) { + return at::_ops::slow_conv_transpose2d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation), out); +} +namespace symint { + template ::value>> + at::Tensor & slow_conv_transpose2d_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef dilation, at::Tensor & out) { + return at::_ops::slow_conv_transpose2d_out::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation), out); + } +} + +// aten::slow_conv_transpose2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & slow_conv_transpose2d_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)) { + return at::_ops::slow_conv_transpose2d_out::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation, out); +} +namespace symint { + template ::value>> + at::Tensor & slow_conv_transpose2d_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)) { + return at::_ops::slow_conv_transpose2d_out::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation, out); + } +} + +// aten::slow_conv_transpose2d.out(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & slow_conv_transpose2d_symint_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef dilation, at::Tensor & out) { + return at::_ops::slow_conv_transpose2d_out::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation, out); +} +namespace symint { + template ::value>> + at::Tensor & slow_conv_transpose2d_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias, c10::SymIntArrayRef stride, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef dilation, at::Tensor & out) { + return at::_ops::slow_conv_transpose2d_out::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation, out); + } +} + +// aten::slow_conv_transpose2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1) -> Tensor +inline at::Tensor slow_conv_transpose2d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1) { + return at::_ops::slow_conv_transpose2d::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation)); +} +namespace symint { + template ::value>> + at::Tensor slow_conv_transpose2d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const c10::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef output_padding=0, at::IntArrayRef dilation=1) { + return at::_ops::slow_conv_transpose2d::call(self, weight, c10::fromIntArrayRefSlow(kernel_size), bias, c10::fromIntArrayRefSlow(stride), c10::fromIntArrayRefSlow(padding), c10::fromIntArrayRefSlow(output_padding), c10::fromIntArrayRefSlow(dilation)); + } +} + +// aten::slow_conv_transpose2d(Tensor self, Tensor weight, SymInt[2] kernel_size, Tensor? bias=None, SymInt[2] stride=1, SymInt[2] padding=0, SymInt[2] output_padding=0, SymInt[2] dilation=1) -> Tensor +inline at::Tensor slow_conv_transpose2d_symint(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)) { + return at::_ops::slow_conv_transpose2d::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation); +} +namespace symint { + template ::value>> + at::Tensor slow_conv_transpose2d(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const c10::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef output_padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)) { + return at::_ops::slow_conv_transpose2d::call(self, weight, kernel_size, bias, stride, padding, output_padding, dilation); + } +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_bessel_y0_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_bessel_y0_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..55e11d5a9bdb8706d75c9e9f5d07ec913645ef3b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_bessel_y0_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API special_bessel_y0 { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_bessel_y0") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_bessel_y0(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API special_bessel_y0_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::special_bessel_y0") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_bessel_y0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_u.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_u.h new file mode 100644 index 0000000000000000000000000000000000000000..f94f163864fbb7e5f487735084a1fb984dfbd1d0 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_chebyshev_polynomial_u.h @@ -0,0 +1,67 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::special_chebyshev_polynomial_u(Tensor x, Tensor n) -> Tensor +inline at::Tensor special_chebyshev_polynomial_u(const at::Tensor & x, const at::Tensor & n) { + return at::_ops::special_chebyshev_polynomial_u::call(x, n); +} + +// aten::special_chebyshev_polynomial_u.x_scalar(Scalar x, Tensor n) -> Tensor +inline at::Tensor special_chebyshev_polynomial_u(const at::Scalar & x, const at::Tensor & n) { + return at::_ops::special_chebyshev_polynomial_u_x_scalar::call(x, n); +} + +// aten::special_chebyshev_polynomial_u.n_scalar(Tensor x, Scalar n) -> Tensor +inline at::Tensor special_chebyshev_polynomial_u(const at::Tensor & x, const at::Scalar & n) { + return at::_ops::special_chebyshev_polynomial_u_n_scalar::call(x, n); +} + +// aten::special_chebyshev_polynomial_u.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_chebyshev_polynomial_u_out(at::Tensor & out, const at::Tensor & x, const at::Tensor & n) { + return at::_ops::special_chebyshev_polynomial_u_out::call(x, n, out); +} +// aten::special_chebyshev_polynomial_u.out(Tensor x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_chebyshev_polynomial_u_outf(const at::Tensor & x, const at::Tensor & n, at::Tensor & out) { + return at::_ops::special_chebyshev_polynomial_u_out::call(x, n, out); +} + +// aten::special_chebyshev_polynomial_u.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_chebyshev_polynomial_u_out(at::Tensor & out, const at::Scalar & x, const at::Tensor & n) { + return at::_ops::special_chebyshev_polynomial_u_x_scalar_out::call(x, n, out); +} +// aten::special_chebyshev_polynomial_u.x_scalar_out(Scalar x, Tensor n, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_chebyshev_polynomial_u_outf(const at::Scalar & x, const at::Tensor & n, at::Tensor & out) { + return at::_ops::special_chebyshev_polynomial_u_x_scalar_out::call(x, n, out); +} + +// aten::special_chebyshev_polynomial_u.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_chebyshev_polynomial_u_out(at::Tensor & out, const at::Tensor & x, const at::Scalar & n) { + return at::_ops::special_chebyshev_polynomial_u_n_scalar_out::call(x, n, out); +} +// aten::special_chebyshev_polynomial_u.n_scalar_out(Tensor x, Scalar n, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_chebyshev_polynomial_u_outf(const at::Tensor & x, const at::Scalar & n, at::Tensor & out) { + return at::_ops::special_chebyshev_polynomial_u_n_scalar_out::call(x, n, out); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_modified_bessel_i0_cuda_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_modified_bessel_i0_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..7146ca6a736b1bd7c5df0541272b1135786ede8b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_modified_bessel_i0_cuda_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor special_modified_bessel_i0(const at::Tensor & self); +TORCH_API at::Tensor & special_modified_bessel_i0_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & special_modified_bessel_i0_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/to_compositeimplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/to_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..cb96bb7d172d60956a09f917d6fc59392b883683 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/to_compositeimplicitautograd_dispatch.h @@ -0,0 +1,27 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor to(const at::Tensor & self, at::TensorOptions options={}, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor to(const at::Tensor & self, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory, bool non_blocking, bool copy, c10::optional memory_format); +TORCH_API at::Tensor to(const at::Tensor & self, at::Device device, at::ScalarType dtype, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor to(const at::Tensor & self, at::ScalarType dtype, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt); +TORCH_API at::Tensor to(const at::Tensor & self, const at::Tensor & other, bool non_blocking=false, bool copy=false, c10::optional memory_format=c10::nullopt); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_trilinear3d_meta_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_trilinear3d_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6dd6d5ef77f09264b9814fbce99264f442bf2251 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_trilinear3d_meta_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor upsample_trilinear3d(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor upsample_trilinear3d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & upsample_trilinear3d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & upsample_trilinear3d_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, c10::optional scales_d, c10::optional scales_h, c10::optional scales_w, at::Tensor & out); +TORCH_API at::Tensor & upsample_trilinear3d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_d=c10::nullopt, c10::optional scales_h=c10::nullopt, c10::optional scales_w=c10::nullopt); +TORCH_API at::Tensor & upsample_trilinear3d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, c10::optional scales_d, c10::optional scales_h, c10::optional scales_w, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/vander_compositeimplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/vander_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..023ec2ab3df69325aed529e87568ed4576a63492 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/vander_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor vander(const at::Tensor & x, c10::optional N=c10::nullopt, bool increasing=false); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/view_as.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/view_as.h new file mode 100644 index 0000000000000000000000000000000000000000..ac38603e7604e9f7aceee8e46629f874d5261fbd --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/view_as.h @@ -0,0 +1,26 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/view_cuda_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/view_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..0b3f3cd53a586a6dbd1954b2b0a2aaed364277ab --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/view_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor view(const at::Tensor & self, at::IntArrayRef size); +TORCH_API at::Tensor view_symint(const at::Tensor & self, c10::SymIntArrayRef size); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0039381506db0099b90b168990f3e3213a38c6e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_fft.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_fft.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4098caa30e06bece4082658284d430748851b118 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_fft.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_fftlog.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_fftlog.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..063027d5489999906e4ffb2f07f20e0a3b14fe65 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_fftlog.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_helper.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_helper.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78aa333068c5f37e51b656cf594dfef1774cb169 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_helper.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2dc90538a8157750ed00a997cad56418061256d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/__pycache__/_realtransforms.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/_fft.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/_fft.py new file mode 100644 index 0000000000000000000000000000000000000000..e6aa0e4c1dec753e0d49c7da9d9b1ab10af144c2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/_fft.py @@ -0,0 +1,683 @@ +from numbers import Number +import warnings + +import numpy as np + +import cupy + +from cupy.fft._fft import (_fft, _default_fft_func, hfft as _hfft, + ihfft as _ihfft, _swap_direction) + +_scipy_150 = False +_scipy_160 = False +try: + import scipy + import scipy.fft as _scipy_fft +except ImportError: + class _DummyModule: + def __getattr__(self, name): + return None + + _scipy_fft = _DummyModule() +else: + from numpy.lib import NumpyVersion as Version + _scipy_150 = Version(scipy.__version__) >= Version('1.5.0') + _scipy_160 = Version(scipy.__version__) >= Version('1.6.0') + del Version + del scipy + +# Backend support for scipy.fft + +__ua_domain__ = 'numpy.scipy.fft' +_implemented: dict = {} + + +def __ua_convert__(dispatchables, coerce): + if coerce: + try: + replaced = [ + cupy.asarray(d.value) if d.coercible and d.type is np.ndarray + else d.value for d in dispatchables] + except TypeError: + return NotImplemented + else: + replaced = [d.value for d in dispatchables] + + if not all(d.type is not np.ndarray or isinstance(r, cupy.ndarray) + for r, d in zip(replaced, dispatchables)): + return NotImplemented + + return replaced + + +def __ua_function__(method, args, kwargs): + fn = _implemented.get(method, None) + if fn is None: + return NotImplemented + if 'plan' in kwargs and not _scipy_150: + warnings.warn('The \'plan\' argument is supported in SciPy v1.5.0+') + return fn(*args, **kwargs) + + +def _implements(scipy_func): + """Decorator adds function to the dictionary of implemented functions""" + def inner(func): + _implemented[scipy_func] = func + return func + + return inner + + +def _assequence(x): + """Convert scalars to a sequence, otherwise pass through ``x`` unchanged""" + if isinstance(x, Number): + return (x,) + return x + + +@_implements(_scipy_fft.fft) +def fft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): + """Compute the one-dimensional FFT. + + Args: + x (cupy.ndarray): Array to be transformed. + n (None or int): Length of the transformed axis of the output. If ``n`` + is not given, the length of the input along the axis specified by + ``axis`` is used. + axis (int): Axis over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for + transforming ``x`` over ``axis``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, n, axis) + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``n`` and type + will convert to complex if that of the input is another. + + .. seealso:: :func:`scipy.fft.fft` + """ + from cupy.cuda import cufft + return _fft(x, (n,), (axis,), norm, cufft.CUFFT_FORWARD, + overwrite_x=overwrite_x, plan=plan) + + +@_implements(_scipy_fft.ifft) +def ifft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): + """Compute the one-dimensional inverse FFT. + + Args: + x (cupy.ndarray): Array to be transformed. + n (None or int): Length of the transformed axis of the output. If ``n`` + is not given, the length of the input along the axis specified by + ``axis`` is used. + axis (int): Axis over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for + transforming ``x`` over ``axis``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, n, axis) + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``n`` and type + will convert to complex if that of the input is another. + + .. seealso:: :func:`scipy.fft.ifft` + """ + from cupy.cuda import cufft + return _fft(x, (n,), (axis,), norm, cufft.CUFFT_INVERSE, + overwrite_x=overwrite_x, plan=plan) + + +@_implements(_scipy_fft.fft2) +def fft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, *, plan=None): + """Compute the two-dimensional FFT. + + Args: + x (cupy.ndarray): Array to be transformed. + s (None or tuple of ints): Shape of the transformed axes of the + output. If ``s`` is not given, the lengths of the input along + the axes specified by ``axes`` are used. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for + transforming ``x`` over ``axes``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes) + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``s`` and + type will convert to complex if that of the input is another. + + .. seealso:: :func:`scipy.fft.fft2` + """ + return fftn(x, s, axes, norm, overwrite_x, plan=plan) + + +@_implements(_scipy_fft.ifft2) +def ifft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, *, + plan=None): + """Compute the two-dimensional inverse FFT. + + Args: + x (cupy.ndarray): Array to be transformed. + s (None or tuple of ints): Shape of the transformed axes of the + output. If ``s`` is not given, the lengths of the input along + the axes specified by ``axes`` are used. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for + transforming ``x`` over ``axes``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes) + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``s`` and + type will convert to complex if that of the input is another. + + .. seealso:: :func:`scipy.fft.ifft2` + """ + return ifftn(x, s, axes, norm, overwrite_x, plan=plan) + + +@_implements(_scipy_fft.fftn) +def fftn(x, s=None, axes=None, norm=None, overwrite_x=False, *, plan=None): + """Compute the N-dimensional FFT. + + Args: + x (cupy.ndarray): Array to be transformed. + s (None or tuple of ints): Shape of the transformed axes of the + output. If ``s`` is not given, the lengths of the input along + the axes specified by ``axes`` are used. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for + transforming ``x`` over ``axes``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes) + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``s`` and + type will convert to complex if that of the input is another. + + .. seealso:: :func:`scipy.fft.fftn` + """ + from cupy.cuda import cufft + + s = _assequence(s) + axes = _assequence(axes) + func = _default_fft_func(x, s, axes) + return func(x, s, axes, norm, cufft.CUFFT_FORWARD, overwrite_x=overwrite_x, + plan=plan) + + +@_implements(_scipy_fft.ifftn) +def ifftn(x, s=None, axes=None, norm=None, overwrite_x=False, *, plan=None): + """Compute the N-dimensional inverse FFT. + + Args: + x (cupy.ndarray): Array to be transformed. + s (None or tuple of ints): Shape of the transformed axes of the + output. If ``s`` is not given, the lengths of the input along + the axes specified by ``axes`` are used. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for + transforming ``x`` over ``axes``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes) + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``s`` and + type will convert to complex if that of the input is another. + + .. seealso:: :func:`scipy.fft.ifftn` + """ + from cupy.cuda import cufft + + s = _assequence(s) + axes = _assequence(axes) + func = _default_fft_func(x, s, axes) + return func(x, s, axes, norm, cufft.CUFFT_INVERSE, overwrite_x=overwrite_x, + plan=plan) + + +@_implements(_scipy_fft.rfft) +def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): + """Compute the one-dimensional FFT for real input. + + The returned array contains the positive frequency components of the + corresponding :func:`fft`, up to and including the Nyquist frequency. + + Args: + x (cupy.ndarray): Array to be transformed. + n (None or int): Length of the transformed axis of the output. If ``n`` + is not given, the length of the input along the axis specified by + ``axis`` is used. + axis (int): Axis over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for + transforming ``x`` over ``axis``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, n, axis, + value_type='R2C') + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array. + + .. seealso:: :func:`scipy.fft.rfft` + + """ + from cupy.cuda import cufft + + return _fft(x, (n,), (axis,), norm, cufft.CUFFT_FORWARD, 'R2C', + overwrite_x=overwrite_x, plan=plan) + + +@_implements(_scipy_fft.irfft) +def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): + """Compute the one-dimensional inverse FFT for real input. + + Args: + x (cupy.ndarray): Array to be transformed. + n (None or int): Length of the transformed axis of the output. If ``n`` + is not given, the length of the input along the axis specified by + ``axis`` is used. + axis (int): Axis over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.Plan1d` or ``None``): a cuFFT plan for + transforming ``x`` over ``axis``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, n, axis, + value_type='C2R') + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array. + + .. seealso:: :func:`scipy.fft.irfft` + """ + from cupy.cuda import cufft + return _fft(x, (n,), (axis,), norm, cufft.CUFFT_INVERSE, 'C2R', + overwrite_x=overwrite_x, plan=plan) + + +@_implements(_scipy_fft.rfft2) +def rfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, *, + plan=None): + """Compute the two-dimensional FFT for real input. + + Args: + a (cupy.ndarray): Array to be transform. + s (None or tuple of ints): Shape to use from the input. If ``s`` is not + given, the lengths of the input along the axes specified by + ``axes`` are used. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for + transforming ``x`` over ``axes``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes, + value_type='R2C') + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``s`` and type + will convert to complex if the input is other. The length of the + last axis transformed will be ``s[-1]//2+1``. + + .. seealso:: :func:`scipy.fft.rfft2` + """ + return rfftn(x, s, axes, norm, overwrite_x, plan=plan) + + +@_implements(_scipy_fft.irfft2) +def irfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, *, + plan=None): + """Compute the two-dimensional inverse FFT for real input. + + Args: + a (cupy.ndarray): Array to be transform. + s (None or tuple of ints): Shape of the output. If ``s`` is not given, + they are determined from the lengths of the input along the axes + specified by ``axes``. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for + transforming ``x`` over ``axes``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes, + value_type='C2R') + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``s`` and type + will convert to complex if the input is other. If ``s`` is not + given, the length of final transformed axis of output will be + `2*(m-1)` where `m` is the length of the final transformed axis of + the input. + + .. seealso:: :func:`scipy.fft.irfft2` + """ + return irfftn(x, s, axes, norm, overwrite_x, plan=plan) + + +@_implements(_scipy_fft.rfftn) +def rfftn(x, s=None, axes=None, norm=None, overwrite_x=False, *, plan=None): + """Compute the N-dimensional FFT for real input. + + Args: + a (cupy.ndarray): Array to be transform. + s (None or tuple of ints): Shape to use from the input. If ``s`` is not + given, the lengths of the input along the axes specified by + ``axes`` are used. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for + transforming ``x`` over ``axes``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes, + value_type='R2C') + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``s`` and type + will convert to complex if the input is other. The length of the + last axis transformed will be ``s[-1]//2+1``. + + .. seealso:: :func:`scipy.fft.rfftn` + """ + from cupy.cuda import cufft + + s = _assequence(s) + axes = _assequence(axes) + func = _default_fft_func(x, s, axes, value_type='R2C') + return func(x, s, axes, norm, cufft.CUFFT_FORWARD, 'R2C', + overwrite_x=overwrite_x, plan=plan) + + +@_implements(_scipy_fft.irfftn) +def irfftn(x, s=None, axes=None, norm=None, overwrite_x=False, *, plan=None): + """Compute the N-dimensional inverse FFT for real input. + + Args: + a (cupy.ndarray): Array to be transform. + s (None or tuple of ints): Shape of the output. If ``s`` is not given, + they are determined from the lengths of the input along the axes + specified by ``axes``. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (:class:`cupy.cuda.cufft.PlanNd` or ``None``): a cuFFT plan for + transforming ``x`` over ``axes``, which can be obtained using:: + + plan = cupyx.scipy.fftpack.get_fft_plan(x, s, axes, + value_type='C2R') + + Note that ``plan`` is defaulted to ``None``, meaning CuPy will use + an auto-generated plan behind the scene. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``s`` and type + will convert to complex if the input is other. If ``s`` is not + given, the length of final transformed axis of output will be + ``2*(m-1)`` where `m` is the length of the final transformed axis + of the input. + + .. seealso:: :func:`scipy.fft.irfftn` + """ + from cupy.cuda import cufft + + s = _assequence(s) + axes = _assequence(axes) + func = _default_fft_func(x, s, axes, value_type='C2R') + return func(x, s, axes, norm, cufft.CUFFT_INVERSE, 'C2R', + overwrite_x=overwrite_x, plan=plan) + + +@_implements(_scipy_fft.hfft) +def hfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): + """Compute the FFT of a signal that has Hermitian symmetry. + + Args: + a (cupy.ndarray): Array to be transform. + n (None or int): Length of the transformed axis of the output. For + ``n`` output points, ``n//2+1`` input points are necessary. If + ``n`` is not given, it is determined from the length of the input + along the axis specified by ``axis``. + axis (int): Axis over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (None): This argument is currently not supported. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``n`` and type + will convert to complex if the input is other. If ``n`` is not + given, the length of the transformed axis is ``2*(m-1)`` where `m` + is the length of the transformed axis of the input. + + .. seealso:: :func:`scipy.fft.hfft` + """ + # TODO(leofang): support R2C & C2R plans + if plan is not None: + raise NotImplementedError('hfft plan is currently not yet supported') + return _hfft(x, n, axis, norm) + + +@_implements(_scipy_fft.ihfft) +def ihfft(x, n=None, axis=-1, norm=None, overwrite_x=False, *, plan=None): + """Compute the FFT of a signal that has Hermitian symmetry. + + Args: + a (cupy.ndarray): Array to be transform. + n (None or int): Number of points along transformation axis in the + input to use. If ``n`` is not given, the length of the input along + the axis specified by ``axis`` is used. + axis (int): Axis over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + plan (None): This argument is currently not supported. + + Returns: + cupy.ndarray: + The transformed array which shape is specified by ``n`` and type + will convert to complex if the input is other. The length of the + transformed axis is ``n//2+1``. + + .. seealso:: :func:`scipy.fft.ihfft` + """ + # TODO(leofang): support R2C & C2R plans + if plan is not None: + raise NotImplementedError('ihfft plan is currently not yet supported') + return _ihfft(x, n, axis, norm) + + +@_implements(_scipy_fft.hfft2) +def hfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, *, + plan=None): + """Compute the FFT of a two-dimensional signal that has Hermitian symmetry. + + Args: + x (cupy.ndarray): Array to be transformed. + s (None or tuple of ints): Shape of the real output. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + (This argument is currently not supported) + plan (None): This argument is currently not supported. + + Returns: + cupy.ndarray: + The real result of the 2-D Hermitian complex real FFT. + + .. seealso:: :func:`scipy.fft.hfft2` + """ + if plan is not None: + raise NotImplementedError('hfft2 plan is currently not yet supported') + return irfft2(x.conj(), s, axes, _swap_direction(norm)) + + +@_implements(_scipy_fft.ihfft2) +def ihfft2(x, s=None, axes=(-2, -1), norm=None, overwrite_x=False, *, + plan=None): + """Compute the Inverse FFT of a two-dimensional signal that has Hermitian + symmetry. + + Args: + x (cupy.ndarray): Array to be transformed. + s (None or tuple of ints): Shape of the real output. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + (This argument is currently not supported) + plan (None): This argument is currently not supported. + + Returns: + cupy.ndarray: + The real result of the 2-D Hermitian inverse complex real FFT. + + .. seealso:: :func:`scipy.fft.ihfft2` + """ + if plan is not None: + raise NotImplementedError('ihfft2 plan is currently not yet supported') + return rfft2(x, s, axes, _swap_direction(norm)).conj() + + +@_implements(_scipy_fft.hfftn) +def hfftn(x, s=None, axes=None, norm=None, overwrite_x=False, *, + plan=None): + """Compute the FFT of a N-dimensional signal that has Hermitian symmetry. + + Args: + x (cupy.ndarray): Array to be transformed. + s (None or tuple of ints): Shape of the real output. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + (This argument is currently not supported) + plan (None): This argument is currently not supported. + + Returns: + cupy.ndarray: + The real result of the N-D Hermitian complex real FFT. + + .. seealso:: :func:`scipy.fft.hfftn` + """ + if plan is not None: + raise NotImplementedError('hfftn plan is currently not yet supported') + return irfftn(x.conj(), s, axes, _swap_direction(norm)) + + +@_implements(_scipy_fft.ihfftn) +def ihfftn(x, s=None, axes=None, norm=None, overwrite_x=False, *, + plan=None): + """Compute the Inverse FFT of a N-dimensional signal that has Hermitian + symmetry. + + Args: + x (cupy.ndarray): Array to be transformed. + s (None or tuple of ints): Shape of the real output. + axes (tuple of ints): Axes over which to compute the FFT. + norm (``"backward"``, ``"ortho"``, or ``"forward"``): Optional keyword + to specify the normalization mode. Default is ``None``, which is + an alias of ``"backward"``. + overwrite_x (bool): If True, the contents of ``x`` can be destroyed. + (This argument is currently not supported) + plan (None): This argument is currently not supported. + + Returns: + cupy.ndarray: + The real result of the N-D Hermitian inverse complex real FFT. + + .. seealso:: :func:`scipy.fft.ihfftn` + """ + if plan is not None: + raise NotImplementedError('ihfftn plan is currently not yet supported') + return rfftn(x, s, axes, _swap_direction(norm)).conj() diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/_helper.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..f6d7b623f8c6c35036566bbe08307928b1434c26 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/_helper.py @@ -0,0 +1,51 @@ +from typing import Dict, List, Tuple + +import math + + +_next_fast_len_cache: Dict[Tuple[int, List[int]], int] = {} + + +def _next_fast_len_impl(n, primes): + if len(primes) == 0: + return math.inf + result = _next_fast_len_cache.get((n, primes), None) + if result is None: + if n == 1: + result = 1 + else: + p = primes[0] + result = min( + _next_fast_len_impl((n + p - 1) // p, primes) * p, + _next_fast_len_impl(n, primes[1:])) + _next_fast_len_cache[(n, primes)] = result + return result + + +def next_fast_len(target, real=False): + """Find the next fast size to ``fft``. + + Args: + target (int): The size of input array. + real (bool): ``True`` if the FFT involves real input or output. + This parameter is of no use, and only for compatibility to + SciPy's interface. + + Returns: + int: The smallest fast length greater than or equal to the input value. + + .. seealso:: :func:`scipy.fft.next_fast_len` + + .. note:: + It may return a different value to :func:`scipy.fft.next_fast_len` + as pocketfft's prime factors are different from cuFFT's factors. + For details, see the `cuFFT documentation`_. + + .. _cuFFT documentation: + https://docs.nvidia.com/cuda/cufft/index.html#accuracy-and-performance + """ + if target == 0: + return 0 + + primes = (2, 3, 5, 7) + return _next_fast_len_impl(target, primes) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/_realtransforms.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/_realtransforms.py new file mode 100644 index 0000000000000000000000000000000000000000..70718ebe3729c588c6b317b592aa332d43a2a843 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/fft/_realtransforms.py @@ -0,0 +1,922 @@ +"""Real-to-real transforms + +cuFFT does not implement real-to-real FFTs. This module implements forward +and inverse DCT-II and DCT-III transforms using FFTs. + +A length N DCT can be computed using a length N FFT and some additional +multiplications and reordering of entries. + +The approach taken here is based on the work in [1]_, [2]_ and is discussed in +the freely-available online resources [3]_, [4]_. + +The implementation here follows that approach with only minor modification to +match the normalization conventions in SciPy. + +The modifications to turn a type II or III DCT to a DST were implemented as +described in [5]_. + +.. [1] J. Makhoul, "A fast cosine transform in one and two dimensions," in + IEEE Transactions on Acoustics, Speech, and Signal Processing, vol. 28, + no. 1, pp. 27-34, February 1980. + +.. [2] M.J. Narasimha and A.M. Peterson, “On the computation of the discrete + cosine transform,” IEEE Trans. Commun., vol. 26, no. 6, pp. 934–936, 1978. + +.. [3] http://fourier.eng.hmc.edu/e161/lectures/dct/node2.html + +.. [4] https://dsp.stackexchange.com/questions/2807/fast-cosine-transform-via-fft + +.. [5] X. Shao, S. G. Johnson. Type-II/III DCT/DST algorithms with reduced + number of arithmetic operations, Signal Processing, Volume 88, Issue 6, + pp. 1553-1564, 2008. +""" + +import math +import numbers +import operator + +import cupy +from cupy import _core +from cupy.fft._fft import _cook_shape +from cupyx.scipy.fft import _fft +from cupy.exceptions import AxisError + +__all__ = ['dct', 'dctn', 'dst', 'dstn', 'idct', 'idctn', 'idst', 'idstn'] + + +def _promote_dtype(x): + if x.dtype.kind in 'bui': + # use float64 instead of promote_types to match SciPy's behavior + float_dtype = cupy.float64 + else: + float_dtype = cupy.promote_types(x.dtype, cupy.float32) + return x.astype(float_dtype, copy=False) + + +def _get_dct_norm_factor(n, inorm, dct_type=2): + """Normalization factors for DCT/DST I-IV. + + Parameters + ---------- + n : int + Data size. + inorm : {'none', 'sqrt', 'full'} + When `inorm` is 'none', the scaling factor is 1.0 (unnormalized). When + `inorm` is 1, scaling by ``1/sqrt(d)`` as needed for an orthogonal + transform is used. When `inorm` is 2, normalization by ``1/d`` is + applied. The value of ``d`` depends on both `n` and the `dct_type`. + dct_type : {1, 2, 3, 4} + Which type of DCT or DST is being normalized?. + + Returns + ------- + fct : float + The normalization factor. + """ + if inorm == 'none': + return 1 + delta = -1 if dct_type == 1 else 0 + d = 2 * (n + delta) + if inorm == 'full': + fct = 1 / d + elif inorm == 'sqrt': + fct = 1 / math.sqrt(d) + else: + raise ValueError('expected inorm = "none", "sqrt" or "full"') + return fct + + +def _reshuffle_dct2(x, n, axis, dst=False): + """Reorder entries to allow computation of DCT/DST-II via FFT.""" + sl_even = [slice(None)] * x.ndim + sl_even[axis] = slice(0, None, 2) + sl_even = tuple(sl_even) + sl_odd = [slice(None)] * x.ndim + if n % 2: + sl_odd[axis] = slice(-2, None, -2) + sl_odd = tuple(sl_odd) + else: + sl_odd[axis] = slice(None, None, -2) + sl_odd = tuple(sl_odd) + if dst: + x = cupy.concatenate((x[sl_even], -x[sl_odd]), axis=axis) + else: + x = cupy.concatenate((x[sl_even], x[sl_odd]), axis=axis) + return x + + +_mult_factor_dct2 = _core.ElementwiseKernel( + in_params='R xr, int32 N, R norm_factor', + out_params='C y', + operation=""" + C j(0., -1.); + y = (R)2.0 * norm_factor * exp(j * (R)(i * M_PI / (2 * N)));""", +) + + +def _exp_factor_dct2(x, n, axis, norm_factor, n_truncate=None): + """Twiddle & scaling factors for computation of DCT/DST-II via FFT.""" + if n_truncate is None: + n_truncate = n + tmp = cupy.empty((n_truncate,), dtype=x.dtype) + _mult_factor_dct2(tmp.real, n, norm_factor, tmp) + + if x.ndim == 1: + return tmp + tmp_shape = [1] * x.ndim + tmp_shape[axis] = n_truncate + tmp_shape = tuple(tmp_shape) + return tmp.reshape(tmp_shape) + + +def _dct_or_dst_type2( + x, n=None, axis=-1, forward=True, norm=None, dst=False, overwrite_x=False +): + """Forward DCT/DST-II (or inverse DCT/DST-III) along a single axis + + Parameters + ---------- + x : cupy.ndarray + The data to transform. + n : int + The size of the transform. If None, ``x.shape[axis]`` is used. + axis : int + Axis along which the transform is applied. + forward : bool + Set true to indicate that this is a forward DCT-II as opposed to an + inverse DCT-III (The difference between the two is only in the + normalization factor). + norm : {None, 'ortho', 'forward', 'backward'} + The normalization convention to use. + dst : bool + If True, a discrete sine transform is computed rather than the discrete + cosine transform. + overwrite_x : bool + Indicates that it is okay to overwrite x. In practice, the current + implementation never performs the transform in-place. + + Returns + ------- + y: cupy.ndarray + The transformed array. + """ + if axis < -x.ndim or axis >= x.ndim: + raise AxisError('axis out of range') + if axis < 0: + axis += x.ndim + if n is not None and n < 1: + raise ValueError( + f'invalid number of data points ({n}) specified' + ) + + x = _cook_shape(x, (n,), (axis,), 'R2R') + n = x.shape[axis] + + x = _reshuffle_dct2(x, x.shape[axis], axis, dst) + + if norm == 'ortho': + inorm = 'sqrt' + elif norm == 'forward': + inorm = 'full' if forward else 'none' + else: + inorm = 'none' if forward else 'full' + norm_factor = _get_dct_norm_factor(n, inorm=inorm, dct_type=2) + + x = _fft.fft(x, n=n, axis=axis, overwrite_x=True) + tmp = _exp_factor_dct2(x, n, axis, norm_factor) + + x *= tmp # broadcasting + x = cupy.real(x) + + if norm == 'ortho': + sl0 = [slice(None)] * x.ndim + sl0[axis] = slice(1) + x[tuple(sl0)] *= math.sqrt(2) * 0.5 + + if dst: + slrev = [slice(None)] * x.ndim + slrev[axis] = slice(None, None, -1) + x = x[tuple(slrev)] + return x + + +def _reshuffle_dct3(y, n, axis, dst): + """Reorder entries to allow computation of DCT/DST-II via FFT.""" + x = cupy.empty_like(y) + n_half = (n + 1) // 2 + + # Store first half of y in the even entries of the output + sl_even = [slice(None)] * y.ndim + sl_even[axis] = slice(0, None, 2) + sl_even = tuple(sl_even) + + sl_half = [slice(None)] * y.ndim + sl_half[axis] = slice(0, n_half) + x[sl_even] = y[tuple(sl_half)] + + # Store the second half of y in the odd entries of the output + sl_odd = [slice(None)] * y.ndim + sl_odd[axis] = slice(1, None, 2) + sl_odd = tuple(sl_odd) + + sl_half[axis] = slice(-1, n_half - 1, -1) + if dst: + x[sl_odd] = -y[tuple(sl_half)] + else: + x[sl_odd] = y[tuple(sl_half)] + return x + + +_mult_factor_dct3 = _core.ElementwiseKernel( + in_params='R xr, int32 N, R norm_factor', + out_params='C y', + operation=""" + C j(0., 1.); + y = (R)(2 * N * norm_factor) * exp(j * (R)(i * M_PI / (2 * N)));""", +) + + +def _exp_factor_dct3(x, n, axis, dtype, norm_factor): + """Twiddle & scaling factors for computation of DCT/DST-III via FFT.""" + tmp = cupy.empty((n,), dtype=dtype) + _mult_factor_dct3(tmp.real, n, norm_factor, tmp) + if x.ndim == 1: + return tmp + # prepare shape for broadcasting along non-transformed axes + tmp_shape = [1] * x.ndim + tmp_shape[axis] = n + tmp_shape = tuple(tmp_shape) + return tmp.reshape(tmp_shape) + + +def _dct_or_dst_type3( + x, n=None, axis=-1, norm=None, forward=True, dst=False, overwrite_x=False +): + """Forward DCT/DST-III (or inverse DCT/DST-II) along a single axis. + + Parameters + ---------- + x : cupy.ndarray + The data to transform. + n : int + The size of the transform. If None, ``x.shape[axis]`` is used. + axis : int + Axis along which the transform is applied. + forward : bool + Set true to indicate that this is a forward DCT-II as opposed to an + inverse DCT-III (The difference between the two is only in the + normalization factor). + norm : {None, 'ortho', 'forward', 'backward'} + The normalization convention to use. + dst : bool + If True, a discrete sine transform is computed rather than the discrete + cosine transform. + overwrite_x : bool + Indicates that it is okay to overwrite x. In practice, the current + implementation never performs the transform in-place. + + Returns + ------- + y: cupy.ndarray + The transformed array. + + """ + if axis < -x.ndim or axis >= x.ndim: + raise AxisError('axis out of range') + if axis < 0: + axis += x.ndim + if n is not None and n < 1: + raise ValueError( + f'invalid number of data points ({n}) specified' + ) + + x = _cook_shape(x, (n,), (axis,), 'R2R') + n = x.shape[axis] + + # determine normalization factor + if norm == 'ortho': + sl0_scale = 0.5 * math.sqrt(2) + inorm = 'sqrt' + elif norm == 'forward': + sl0_scale = 0.5 + inorm = 'full' if forward else 'none' + elif norm == 'backward' or norm is None: + sl0_scale = 0.5 + inorm = 'none' if forward else 'full' + else: + raise ValueError(f'Invalid norm value "{norm}", should be "backward", ' + '"ortho" or "forward"') + norm_factor = _get_dct_norm_factor(n, inorm=inorm, dct_type=3) + dtype = cupy.promote_types(x, cupy.complex64) + + sl0 = [slice(None)] * x.ndim + sl0[axis] = slice(1) + + if dst: + slrev = [slice(None)] * x.ndim + slrev[axis] = slice(None, None, -1) + x = x[tuple(slrev)] + if norm == 'ortho': + float_dtype = cupy.promote_types(x.dtype, cupy.float32) + if x.dtype != float_dtype: + x = x.astype(float_dtype) + elif not overwrite_x: + x = x.copy() + x[tuple(sl0)] *= math.sqrt(2) + sl0_scale = 0.5 + + # scale by exponentials and normalization factor + tmp = _exp_factor_dct3(x, n, axis, dtype, norm_factor) + x = x * tmp # broadcasting + x[tuple(sl0)] *= sl0_scale + + # inverse fft + x = _fft.ifft(x, n=n, axis=axis, overwrite_x=True) + x = cupy.real(x) + + # reorder entries + return _reshuffle_dct3(x, n, axis, dst) + + +@_fft._implements(_fft._scipy_fft.dct) +def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False): + """Return the Discrete Cosine Transform of an array, x. + + Parameters + ---------- + x : cupy.ndarray + The input array. + type : {1, 2, 3, 4}, optional + Type of the DCT (see Notes). Default type is 2. Currently CuPy only + supports types 2 and 3. + n : int, optional: + Length of the transform. If ``n < x.shape[axis]``, `x` is + truncated. If ``n > x.shape[axis]``, `x` is zero-padded. + The default results in ``n = x.shape[axis]``. + axis : int, optional + Axis along which the dct is computed; the default is over the + last axis (i.e., ``axis=-1``). + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + + Returns + ------- + y : cupy.ndarray of real + The transformed input array. + + See Also + -------- + :func:`scipy.fft.dct` + + Notes + ----- + For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal + to MATLAB ``dct(x)``. + + For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same + overall factor in both directions. By default, the transform is also + orthogonalized which for types 1, 2 and 3 means the transform definition is + modified to give orthogonality of the DCT matrix (see below). + + For ``norm="backward"``, there is no scaling on `dct` and the `idct` is + scaled by ``1/N`` where ``N`` is the "logical" size of the DCT. For + ``norm="forward"`` the ``1/N`` normalization is applied to the forward + `dct` instead and the `idct` is unnormalized. + + CuPy currently only supports DCT types 2 and 3. 'The' DCT generally + refers to DCT type 2, and 'the' Inverse DCT generally refers to DCT + type 3 [1]_. See the :func:`scipy.fft.dct` documentation for a full + description of each type. + + References + ---------- + .. [1] Wikipedia, "Discrete cosine transform", + https://en.wikipedia.org/wiki/Discrete_cosine_transform + + """ + if x.dtype.kind == 'c': + # separable application on real and imaginary parts + out = dct(x.real, type, n, axis, norm, overwrite_x) + out = out + 1j * dct(x.imag, type, n, axis, norm, overwrite_x) + return out + + x = _promote_dtype(x) + + if type == 2: + return _dct_or_dst_type2( + x, n=n, axis=axis, norm=norm, forward=True, dst=False + ) + elif type == 3: + return _dct_or_dst_type3( + x, n=n, axis=axis, norm=norm, forward=True, dst=False + ) + elif type in [1, 4]: + raise NotImplementedError( + 'Only DCT-II and DCT-III have been implemented.' + ) + else: + raise ValueError('invalid DCT type') + + +@_fft._implements(_fft._scipy_fft.dst) +def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False): + """Return the Discrete Sine Transform of an array, x. + + Parameters + ---------- + x : cupy.ndarray + The input array. + type : {1, 2, 3, 4}, optional + Type of the DST (see Notes). Default type is 2. + n : int, optional + Length of the transform. If ``n < x.shape[axis]``, `x` is + truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The + default results in ``n = x.shape[axis]``. + axis : int, optional + Axis along which the dst is computed; the default is over the + last axis (i.e., ``axis=-1``). + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + + Returns + ------- + dst : cupy.ndarray of real + The transformed input array. + + See Also + -------- + :func:`scipy.fft.dst` + + Notes + ----- + + For ``norm="ortho"`` both the `dst` and `idst` are scaled by the same + overall factor in both directions. By default, the transform is also + orthogonalized which for types 2 and 3 means the transform definition is + modified to give orthogonality of the DST matrix (see below). + + For ``norm="backward"``, there is no scaling on the `dst` and the `idst` is + scaled by ``1/N`` where ``N`` is the "logical" size of the DST. + + See the :func:`scipy.fft.dst` documentation for a full description of each + type. CuPy currently only supports DST types 2 and 3. + """ + if x.dtype.kind == 'c': + # separable application on real and imaginary parts + out = dst(x.real, type, n, axis, norm, overwrite_x) + out = out + 1j * dst(x.imag, type, n, axis, norm, overwrite_x) + return out + + x = _promote_dtype(x) + + if type == 2: + return _dct_or_dst_type2( + x, n=n, axis=axis, norm=norm, forward=True, dst=True + ) + elif type == 3: + return _dct_or_dst_type3( + x, n=n, axis=axis, norm=norm, forward=True, dst=True + ) + elif type in [1, 4]: + raise NotImplementedError( + 'Only DST-II and DST-III have been implemented.' + ) + else: + raise ValueError('invalid DST type') + + +@_fft._implements(_fft._scipy_fft.idct) +def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False): + """Return the Inverse Discrete Cosine Transform of an array, x. + + Parameters + ---------- + x : cupy.ndarray + The input array. + type : {1, 2, 3, 4}, optional + Type of the DCT (see Notes). Default type is 2. + n : int, optional + Length of the transform. If ``n < x.shape[axis]``, `x` is + truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The + default results in ``n = x.shape[axis]``. + axis : int, optional + Axis along which the idct is computed; the default is over the + last axis (i.e., ``axis=-1``). + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + + Returns + ------- + idct : cupy.ndarray of real + The transformed input array. + + See Also + -------- + :func:`scipy.fft.idct` + + Notes + ----- + For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to + MATLAB ``idct(x)``. + + For ``norm="ortho"`` both the `dct` and `idct` are scaled by the same + overall factor in both directions. By default, the transform is also + orthogonalized which for types 1, 2 and 3 means the transform definition is + modified to give orthogonality of the IDCT matrix (see `dct` for the full + definitions). + + 'The' IDCT is the IDCT-II, which is the same as the normalized DCT-III + [1]_. See the :func:`scipy.fft.dct` documentation for a full description of + each type. CuPy currently only supports DCT types 2 and 3. + + References + ---------- + .. [1] Wikipedia, "Discrete sine transform", + https://en.wikipedia.org/wiki/Discrete_sine_transform + """ + if x.dtype.kind == 'c': + # separable application on real and imaginary parts + out = idct(x.real, type, n, axis, norm, overwrite_x) + out = out + 1j * idct(x.imag, type, n, axis, norm, overwrite_x) + return out + + x = _promote_dtype(x) + + if type == 2: + # DCT-III is the inverse of DCT-II + return _dct_or_dst_type3(x, n=n, axis=axis, norm=norm, forward=False) + elif type == 3: + # DCT-II is the inverse of DCT-III + return _dct_or_dst_type2(x, n=n, axis=axis, norm=norm, forward=False) + elif type in [1, 4]: + raise NotImplementedError( + 'Only DCT-II and DCT-III have been implemented.' + ) + else: + raise ValueError('invalid DCT type') + + +@_fft._implements(_fft._scipy_fft.idst) +def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False): + """Return the Inverse Discrete Sine Transform of an array, x. + + Parameters + ---------- + x : cupy.ndarray + The input array. + type : {1, 2, 3, 4}, optional + Type of the DST (see Notes). Default type is 2. + n : int, optional + Length of the transform. If ``n < x.shape[axis]``, `x` is + truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The + default results in ``n = x.shape[axis]``. + axis : int, optional + Axis along which the idst is computed; the default is over the + last axis (i.e., ``axis=-1``). + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + + Returns + ------- + idst : cupy.ndarray of real + The transformed input array. + + See Also + -------- + :func:`scipy.fft.idst` + + Notes + ----- + For full details of the DST types and normalization modes, as well as + references, see :func:`scipy.fft.dst`. + """ + if x.dtype.kind == 'c': + # separable application on real and imaginary parts + out = idst(x.real, type, n, axis, norm, overwrite_x) + out = out + 1j * idst(x.imag, type, n, axis, norm, overwrite_x) + return out + + x = _promote_dtype(x) + + if type == 2: + # DCT-III is the inverse of DCT-II + return _dct_or_dst_type3( + x, n=n, axis=axis, norm=norm, forward=False, dst=True + ) + elif type == 3: + # DCT-II is the inverse of DCT-III + return _dct_or_dst_type2( + x, n=n, axis=axis, norm=norm, forward=False, dst=True + ) + elif type in [1, 4]: + raise NotImplementedError( + 'Only DST-II and DST-III have been implemented.' + ) + else: + raise ValueError('invalid DST type') + + +def _iterable_of_int(x, name=None): + """Convert ``x`` to an iterable sequence of int.""" + if isinstance(x, numbers.Number): + x = (x,) + + try: + x = [operator.index(a) for a in x] + except TypeError as e: + name = name or 'value' + raise ValueError( + f'{name} must be a scalar or iterable of integers' + ) from e + + return x + + +def _init_nd_shape_and_axes(x, shape, axes): + """Handles shape and axes arguments for nd transforms.""" + noshape = shape is None + noaxes = axes is None + + if not noaxes: + axes = _iterable_of_int(axes, 'axes') + axes = [a + x.ndim if a < 0 else a for a in axes] + + if any(a >= x.ndim or a < 0 for a in axes): + raise ValueError('axes exceeds dimensionality of input') + if len(set(axes)) != len(axes): + raise ValueError('all axes must be unique') + + if not noshape: + shape = _iterable_of_int(shape, 'shape') + nshape = len(shape) + if axes and len(axes) != nshape: + raise ValueError( + 'when given, axes and shape arguments' + ' have to be of the same length' + ) + if noaxes: + if nshape > x.ndim: + raise ValueError('shape requires more axes than are present') + axes = range(x.ndim - len(shape), x.ndim) + + shape = [x.shape[a] if s == -1 else s for s, a in zip(shape, axes)] + elif noaxes: + shape = list(x.shape) + axes = range(x.ndim) + else: + shape = [x.shape[a] for a in axes] + + if any(s < 1 for s in shape): + raise ValueError( + f'invalid number of data points ({shape}) specified' + ) + + return shape, axes + + +@_fft._implements(_fft._scipy_fft.dctn) +def dctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False): + """Compute a multidimensional Discrete Cosine Transform. + + Parameters + ---------- + x : cupy.ndarray + The input array. + type : {1, 2, 3, 4}, optional + Type of the DCT (see Notes). Default type is 2. + s : int or array_like of ints or None, optional + The shape of the result. If both `s` and `axes` (see below) are None, + `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is + ``numpy.take(x.shape, axes, axis=0)``. + If ``s[i] > x.shape[i]``, the ith dimension is padded with zeros. + If ``s[i] < x.shape[i]``, the ith dimension is truncated to length + ``s[i]``. + If any element of `s` is -1, the size of the corresponding dimension of + `x` is used. + axes : int or array_like of ints or None, optional + Axes over which the DCT is computed. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + + Returns + ------- + y : cupy.ndarray of real + The transformed input array. + + See Also + -------- + :func:`scipy.fft.dctn` + + Notes + ----- + For full details of the DCT types and normalization modes, as well as + references, see `dct`. + """ + if x.dtype.kind == 'c': + # separable application on real and imaginary parts + out = dctn(x.real, type, s, axes, norm, overwrite_x) + out = out + 1j * dctn(x.imag, type, s, axes, norm, overwrite_x) + return out + + shape, axes = _init_nd_shape_and_axes(x, s, axes) + x = _promote_dtype(x) + + if len(axes) == 0: + return x + + for n, axis in zip(shape, axes): + x = dct( + x, type=type, n=n, axis=axis, norm=norm, overwrite_x=overwrite_x + ) + return x + + +@_fft._implements(_fft._scipy_fft.idctn) +def idctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False): + """Compute a multidimensional Discrete Cosine Transform. + + Parameters + ---------- + x : cupy.ndarray + The input array. + type : {1, 2, 3, 4}, optional + Type of the DCT (see Notes). Default type is 2. + s : int or array_like of ints or None, optional + The shape of the result. If both `s` and `axes` (see below) are None, + `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is + ``numpy.take(x.shape, axes, axis=0)``. + If ``s[i] > x.shape[i]``, the ith dimension is padded with zeros. + If ``s[i] < x.shape[i]``, the ith dimension is truncated to length + ``s[i]``. + If any element of `s` is -1, the size of the corresponding dimension of + `x` is used. + axes : int or array_like of ints or None, optional + Axes over which the IDCT is computed. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + + Returns + ------- + y : cupy.ndarray of real + The transformed input array. + + See Also + -------- + :func:`scipy.fft.idctn` + + Notes + ----- + For full details of the IDCT types and normalization modes, as well as + references, see :func:`scipy.fft.idct`. + """ + if x.dtype.kind == 'c': + # separable application on real and imaginary parts + out = idctn(x.real, type, s, axes, norm, overwrite_x) + out = out + 1j * idctn(x.imag, type, s, axes, norm, overwrite_x) + return out + + shape, axes = _init_nd_shape_and_axes(x, s, axes) + x = _promote_dtype(x) + + if len(axes) == 0: + return x + + for n, axis in zip(shape, axes): + x = idct( + x, type=type, n=n, axis=axis, norm=norm, overwrite_x=overwrite_x + ) + return x + + +@_fft._implements(_fft._scipy_fft.dstn) +def dstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False): + """Compute a multidimensional Discrete Sine Transform. + + Parameters + ---------- + x : cupy.ndarray + The input array. + type : {1, 2, 3, 4}, optional + Type of the DST (see Notes). Default type is 2. + s : int or array_like of ints or None, optional + The shape of the result. If both `s` and `axes` (see below) are None, + `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is + ``numpy.take(x.shape, axes, axis=0)``. + If ``s[i] > x.shape[i]``, the ith dimension is padded with zeros. + If ``s[i] < x.shape[i]``, the ith dimension is truncated to length + ``s[i]``. + If any element of `s` is -1, the size of the corresponding dimension of + `x` is used. + axes : int or array_like of ints or None, optional + Axes over which the DST is computed. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + + Returns + ------- + y : cupy.ndarray of real + The transformed input array. + + See Also + -------- + :func:`scipy.fft.dstn` + + Notes + ----- + For full details of the DST types and normalization modes, as well as + references, see :func:`scipy.fft.dst`. + """ + if x.dtype.kind == 'c': + # separable application on real and imaginary parts + out = dstn(x.real, type, s, axes, norm, overwrite_x) + out = out + 1j * dstn(x.imag, type, s, axes, norm, overwrite_x) + return out + + shape, axes = _init_nd_shape_and_axes(x, s, axes) + x = _promote_dtype(x) + + if len(axes) == 0: + return x + + for n, axis in zip(shape, axes): + x = dst( + x, type=type, n=n, axis=axis, norm=norm, overwrite_x=overwrite_x + ) + return x + + +@_fft._implements(_fft._scipy_fft.idstn) +def idstn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False): + """Compute a multidimensional Discrete Sine Transform. + + Parameters + ---------- + x : cupy.ndarray + The input array. + type : {1, 2, 3, 4}, optional + Type of the DST (see Notes). Default type is 2. + s : int or array_like of ints or None, optional + The shape of the result. If both `s` and `axes` (see below) are None, + `s` is ``x.shape``; if `s` is None but `axes` is not None, then `s` is + ``numpy.take(x.shape, axes, axis=0)``. + If ``s[i] > x.shape[i]``, the ith dimension is padded with zeros. + If ``s[i] < x.shape[i]``, the ith dimension is truncated to length + ``s[i]``. + If any element of `s` is -1, the size of the corresponding dimension of + `x` is used. + axes : int or array_like of ints or None, optional + Axes over which the IDST is computed. If not given, the last ``len(s)`` + axes are used, or all axes if `s` is also not specified. + norm : {"backward", "ortho", "forward"}, optional + Normalization mode (see Notes). Default is "backward". + overwrite_x : bool, optional + If True, the contents of `x` can be destroyed; the default is False. + + Returns + ------- + y : cupy.ndarray of real + The transformed input array. + + See Also + -------- + :func:`scipy.fft.idstn` + + Notes + ----- + For full details of the IDST types and normalization modes, as well as + references, see :func:`scipy.fft.idst`. + """ + if x.dtype.kind == 'c': + # separable application on real and imaginary parts + out = idstn(x.real, type, s, axes, norm, overwrite_x) + out = out + 1j * idstn(x.imag, type, s, axes, norm, overwrite_x) + return out + + shape, axes = _init_nd_shape_and_axes(x, s, axes) + x = _promote_dtype(x) + + if len(axes) == 0: + return x + + for n, axis in zip(shape, axes): + x = idst( + x, type=type, n=n, axis=axis, norm=norm, overwrite_x=overwrite_x + ) + return x diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__init__.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed71bd99babbe76fd525998db16735b01b8c3cc5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__init__.py @@ -0,0 +1,21 @@ +# flake8: NOQA +from cupyx.scipy.linalg._special_matrices import ( + tri, tril, triu, toeplitz, circulant, hankel, + hadamard, leslie, kron, block_diag, companion, + helmert, hilbert, dft, + fiedler, fiedler_companion, convolution_matrix +) +from cupyx.scipy.linalg._solve_triangular import solve_triangular # NOQA +from cupyx.scipy.linalg._decomp_lu import lu, lu_factor, lu_solve # NOQA + +# uarray backend support (NEP 31) +# The uarray feature for scipy.linalg is experimental. +# The interface can change in the future. +from cupyx.scipy.linalg._uarray import __ua_convert__ # NOQA +from cupyx.scipy.linalg._uarray import __ua_domain__ # NOQA +from cupyx.scipy.linalg._uarray import __ua_function__ # NOQA + +from cupyx.scipy.linalg._array_utils import bandwidth # NOQA +from cupyx.scipy.linalg._matfuncs import khatri_rao # NOQA + +from cupyx.scipy.linalg._matfuncs import expm # NOQA diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d195a00e309de4d9cc4fb6378301dd0b96341dc1 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_array_utils.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_array_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91e23772e15a73078e3dcb864c313134ccc9300e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_array_utils.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34c033b03cefbc3b1a0c59d275714c10c49b74a2 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_decomp_lu.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae51bc3192de7f7657a6597b5b8e49c434da703f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_matfuncs.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_solve_triangular.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_solve_triangular.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc3ef16c90d12829b3c45437b5dc7cc9dcb4b3f8 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_solve_triangular.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d12110f120b6379341e966bf6baba5a7e9e74fa5 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_special_matrices.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_uarray.cpython-310.pyc b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_uarray.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bd2c94ad5efb67089374c037042efaa11e0b57f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/__pycache__/_uarray.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_array_utils.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_array_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f27a6f8cc2124f3acd3b9d49f5769743a4fb61f5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_array_utils.py @@ -0,0 +1,55 @@ +import cupy +from cupy.linalg import _util + +# Find the "bandwise position" of a nonzero cell +_kernel_cupy_band_pos_c = cupy.ElementwiseKernel( + 'T A, N r, N c', + 'N out', + 'out = A != 0 ? r - c : 0', + 'cupyx_scipy_linalg_band_pos' +) + + +def bandwidth(a): + """Return the lower and upper bandwidth of a 2D numeric array. + Parameters + ---------- + a : ndarray + Input array of size (M, N) + Returns + ------- + lu : tuple + 2-tuple of ints indicating the lower and upper bandwidth. A zero + denotes no sub- or super-diagonal on that side (triangular), and, + say for M rows (M-1) means that side is full. Same example applies + to the upper triangular part with (N-1). + + .. seealso:: :func:`scipy.linalg.bandwidth` + """ + + a = cupy.asarray(a) + + if a.size == 0: + return (0, 0) + _util._assert_2d(a) + + # Create new matrix A which is C contiguous + if a.flags['F_CONTIGUOUS']: + A = a.T + else: + A = a + + # row_num and col_num contain info on the row and column number of A + m, n = A.shape + row_num, col_num = cupy.mgrid[0:m, 0:n] + bandpts = _kernel_cupy_band_pos_c(A, row_num, col_num) + + # If F contiguous, transpose + if a.flags['F_CONTIGUOUS']: + upper_band = int(cupy.amax(bandpts)) + lower_band = -int(cupy.amin(bandpts)) + else: + lower_band = int(cupy.amax(bandpts)) + upper_band = -int(cupy.amin(bandpts)) + + return lower_band, upper_band diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_decomp_lu.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_decomp_lu.py new file mode 100644 index 0000000000000000000000000000000000000000..0d3443ee4b5dc50819b330c0d1c95f5c48fc13ee --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_decomp_lu.py @@ -0,0 +1,356 @@ +from warnings import warn + +import numpy + +import cupy +from cupy.cuda import cublas +from cupy.cuda import device +from cupy.cuda import runtime +from cupy.linalg import _util +from cupyx.scipy.linalg import _uarray + + +@_uarray.implements('lu_factor') +def lu_factor(a, overwrite_a=False, check_finite=True): + """LU decomposition. + + Decompose a given two-dimensional square matrix into ``P * L * U``, + where ``P`` is a permutation matrix, ``L`` lower-triangular with + unit diagonal elements, and ``U`` upper-triangular matrix. + + Args: + a (cupy.ndarray): The input matrix with dimension ``(M, N)`` + overwrite_a (bool): Allow overwriting data in ``a`` (may enhance + performance) + check_finite (bool): Whether to check that the input matrices contain + only finite numbers. Disabling may give a performance gain, but may + result in problems (crashes, non-termination) if the inputs do + contain infinities or NaNs. + + Returns: + tuple: + ``(lu, piv)`` where ``lu`` is a :class:`cupy.ndarray` + storing ``U`` in its upper triangle, and ``L`` without + unit diagonal elements in its lower triangle, and ``piv`` is + a :class:`cupy.ndarray` storing pivot indices representing + permutation matrix ``P``. For ``0 <= i < min(M,N)``, row + ``i`` of the matrix was interchanged with row ``piv[i]`` + + .. seealso:: :func:`scipy.linalg.lu_factor` + """ + return _lu_factor(a, overwrite_a, check_finite) + + +@_uarray.implements('lu') +def lu(a, permute_l=False, overwrite_a=False, check_finite=True): + """LU decomposition. + + Decomposes a given two-dimensional matrix into ``P @ L @ U``, where ``P`` + is a permutation matrix, ``L`` is a lower triangular or trapezoidal matrix + with unit diagonal, and ``U`` is a upper triangular or trapezoidal matrix. + + Args: + a (cupy.ndarray): The input matrix with dimension ``(M, N)``. + permute_l (bool): If ``True``, perform the multiplication ``P @ L``. + overwrite_a (bool): Allow overwriting data in ``a`` (may enhance + performance) + check_finite (bool): Whether to check that the input matrices contain + only finite numbers. Disabling may give a performance gain, but may + result in problems (crashes, non-termination) if the inputs do + contain infinities or NaNs. + + Returns: + tuple: + ``(P, L, U)`` if ``permute_l == False``, otherwise ``(PL, U)``. + ``P`` is a :class:`cupy.ndarray` storing permutation matrix with + dimension ``(M, M)``. ``L`` is a :class:`cupy.ndarray` storing + lower triangular or trapezoidal matrix with unit diagonal with + dimension ``(M, K)`` where ``K = min(M, N)``. ``U`` is a + :class:`cupy.ndarray` storing upper triangular or trapezoidal + matrix with dimension ``(K, N)``. ``PL`` is a :class:`cupy.ndarray` + storing permuted ``L`` matrix with dimension ``(M, K)``. + + .. seealso:: :func:`scipy.linalg.lu` + """ + lu, piv = _lu_factor(a, overwrite_a, check_finite) + + m, n = lu.shape + k = min(m, n) + L, U = _cupy_split_lu(lu) + + if permute_l: + _cupy_laswp(L, 0, k-1, piv, -1) + return (L, U) + else: + r_dtype = numpy.float32 if lu.dtype.char in 'fF' else numpy.float64 + P = cupy.diag(cupy.ones((m,), dtype=r_dtype)) + _cupy_laswp(P, 0, k-1, piv, -1) + return (P, L, U) + + +def _lu_factor(a, overwrite_a=False, check_finite=True): + from cupy_backends.cuda.libs import cusolver + + a = cupy.asarray(a) + _util._assert_2d(a) + + dtype = a.dtype + + if dtype.char == 'f': + getrf = cusolver.sgetrf + getrf_bufferSize = cusolver.sgetrf_bufferSize + elif dtype.char == 'd': + getrf = cusolver.dgetrf + getrf_bufferSize = cusolver.dgetrf_bufferSize + elif dtype.char == 'F': + getrf = cusolver.cgetrf + getrf_bufferSize = cusolver.cgetrf_bufferSize + elif dtype.char == 'D': + getrf = cusolver.zgetrf + getrf_bufferSize = cusolver.zgetrf_bufferSize + else: + msg = 'Only float32, float64, complex64 and complex128 are supported.' + raise NotImplementedError(msg) + + a = a.astype(dtype, order='F', copy=(not overwrite_a)) + + if check_finite: + if a.dtype.kind == 'f' and not cupy.isfinite(a).all(): + raise ValueError( + 'array must not contain infs or NaNs') + + cusolver_handle = device.get_cusolver_handle() + dev_info = cupy.empty(1, dtype=numpy.int32) + + m, n = a.shape + + ipiv = cupy.empty((min(m, n),), dtype=numpy.intc) + + buffersize = getrf_bufferSize(cusolver_handle, m, n, a.data.ptr, m) + workspace = cupy.empty(buffersize, dtype=dtype) + + # LU factorization + getrf(cusolver_handle, m, n, a.data.ptr, m, workspace.data.ptr, + ipiv.data.ptr, dev_info.data.ptr) + + if not runtime.is_hip and dev_info[0] < 0: + # rocSOLVER does not inform us this info + raise ValueError('illegal value in %d-th argument of ' + 'internal getrf (lu_factor)' % -dev_info[0]) + elif dev_info[0] > 0: + warn('Diagonal number %d is exactly zero. Singular matrix.' + % dev_info[0], RuntimeWarning, stacklevel=2) + + # cuSolver uses 1-origin while SciPy uses 0-origin + ipiv -= 1 + + return (a, ipiv) + + +def _cupy_split_lu(LU, order='C'): + assert LU._f_contiguous + m, n = LU.shape + k = min(m, n) + order = 'F' if order == 'F' else 'C' + L = cupy.empty((m, k), order=order, dtype=LU.dtype) + U = cupy.empty((k, n), order=order, dtype=LU.dtype) + size = m * n + _kernel_cupy_split_lu(LU, m, n, k, L._c_contiguous, L, U, size=size) + return (L, U) + + +_device_get_index = ''' +__device__ inline int get_index(int row, int col, int num_rows, int num_cols, + bool c_contiguous) +{ + if (c_contiguous) { + return col + num_cols * row; + } else { + return row + num_rows * col; + } +} +''' + +_kernel_cupy_split_lu = cupy.ElementwiseKernel( + 'raw T LU, int32 M, int32 N, int32 K, bool C_CONTIGUOUS', + 'raw T L, raw T U', + ''' + // LU: shape: (M, N) + // L: shape: (M, K) + // U: shape: (K, N) + const T* ptr_LU = &(LU[0]); + T* ptr_L = &(L[0]); + T* ptr_U = &(U[0]); + int row, col; + if (C_CONTIGUOUS) { + row = i / N; + col = i % N; + } else { + row = i % M; + col = i / M; + } + T lu_val = ptr_LU[get_index(row, col, M, N, false)]; + T l_val, u_val; + if (row > col) { + l_val = lu_val; + u_val = static_cast(0); + } else if (row == col) { + l_val = static_cast(1); + u_val = lu_val; + } else { + l_val = static_cast(0); + u_val = lu_val; + } + if (col < K) { + ptr_L[get_index(row, col, M, K, C_CONTIGUOUS)] = l_val; + } + if (row < K) { + ptr_U[get_index(row, col, K, N, C_CONTIGUOUS)] = u_val; + } + ''', + 'cupyx_scipy_linalg_split_lu', preamble=_device_get_index +) + + +def _cupy_laswp(A, k1, k2, ipiv, incx): + m, n = A.shape + k = ipiv.shape[0] + assert 0 <= k1 and k1 <= k2 and k2 < k + assert A._c_contiguous or A._f_contiguous + _kernel_cupy_laswp(m, n, k1, k2, ipiv, incx, A._c_contiguous, A, size=n) + + +_kernel_cupy_laswp = cupy.ElementwiseKernel( + 'int32 M, int32 N, int32 K1, int32 K2, raw I IPIV, int32 INCX, ' + 'bool C_CONTIGUOUS', + 'raw T A', + ''' + // IPIV: 0-based pivot indices. shape: (K,) (*) K > K2 + // A: shape: (M, N) + T* ptr_A = &(A[0]); + if (K1 > K2) return; + int row_start, row_end, row_inc; + if (INCX > 0) { + row_start = K1; row_end = K2; row_inc = 1; + } else if (INCX < 0) { + row_start = K2; row_end = K1; row_inc = -1; + } else { + return; + } + int col = i; + int row1 = row_start; + while (1) { + int row2 = IPIV[row1]; + if (row1 != row2) { + int idx1 = get_index(row1, col, M, N, C_CONTIGUOUS); + int idx2 = get_index(row2, col, M, N, C_CONTIGUOUS); + T tmp = ptr_A[idx1]; + ptr_A[idx1] = ptr_A[idx2]; + ptr_A[idx2] = tmp; + } + if (row1 == row_end) break; + row1 += row_inc; + } + ''', + 'cupyx_scipy_linalg_laswp', preamble=_device_get_index +) + + +@_uarray.implements('lu_solve') +def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True): + """Solve an equation system, ``a * x = b``, given the LU factorization of ``a`` + + Args: + lu_and_piv (tuple): LU factorization of matrix ``a`` (``(M, M)``) + together with pivot indices. + b (cupy.ndarray): The matrix with dimension ``(M,)`` or + ``(M, N)``. + trans ({0, 1, 2}): Type of system to solve: + + ======== ========= + trans system + ======== ========= + 0 a x = b + 1 a^T x = b + 2 a^H x = b + ======== ========= + overwrite_b (bool): Allow overwriting data in b (may enhance + performance) + check_finite (bool): Whether to check that the input matrices contain + only finite numbers. Disabling may give a performance gain, but may + result in problems (crashes, non-termination) if the inputs do + contain infinities or NaNs. + + Returns: + cupy.ndarray: + The matrix with dimension ``(M,)`` or ``(M, N)``. + + .. seealso:: :func:`scipy.linalg.lu_solve` + """ # NOQA + from cupy_backends.cuda.libs import cusolver + + (lu, ipiv) = lu_and_piv + + _util._assert_cupy_array(lu) + _util._assert_2d(lu) + _util._assert_stacked_square(lu) + + m = lu.shape[0] + if m != b.shape[0]: + raise ValueError('incompatible dimensions.') + + dtype = lu.dtype + if dtype.char == 'f': + getrs = cusolver.sgetrs + elif dtype.char == 'd': + getrs = cusolver.dgetrs + elif dtype.char == 'F': + getrs = cusolver.cgetrs + elif dtype.char == 'D': + getrs = cusolver.zgetrs + else: + msg = 'Only float32, float64, complex64 and complex128 are supported.' + raise NotImplementedError(msg) + + if trans == 0: + trans = cublas.CUBLAS_OP_N + elif trans == 1: + trans = cublas.CUBLAS_OP_T + elif trans == 2: + trans = cublas.CUBLAS_OP_C + else: + raise ValueError('unknown trans') + + lu = lu.astype(dtype, order='F', copy=False) + ipiv = ipiv.astype(ipiv.dtype, order='F', copy=True) + # cuSolver uses 1-origin while SciPy uses 0-origin + ipiv += 1 + b = b.astype(dtype, order='F', copy=(not overwrite_b)) + + if check_finite: + if lu.dtype.kind == 'f' and not cupy.isfinite(lu).all(): + raise ValueError( + 'array must not contain infs or NaNs.\n' + 'Note that when a singular matrix is given, unlike ' + 'scipy.linalg.lu_factor, cupyx.scipy.linalg.lu_factor ' + 'returns an array containing NaN.') + if b.dtype.kind == 'f' and not cupy.isfinite(b).all(): + raise ValueError( + 'array must not contain infs or NaNs') + + n = 1 if b.ndim == 1 else b.shape[1] + cusolver_handle = device.get_cusolver_handle() + dev_info = cupy.empty(1, dtype=numpy.int32) + + # solve for the inverse + getrs(cusolver_handle, + trans, + m, n, lu.data.ptr, m, ipiv.data.ptr, b.data.ptr, + m, dev_info.data.ptr) + + if not runtime.is_hip and dev_info[0] < 0: + # rocSOLVER does not inform us this info + raise ValueError('illegal value in %d-th argument of ' + 'internal getrs (lu_solve)' % -dev_info[0]) + + return b diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_matfuncs.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_matfuncs.py new file mode 100644 index 0000000000000000000000000000000000000000..b9b6d96477469343b762264a9a00abe34da9120e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_matfuncs.py @@ -0,0 +1,147 @@ +import math +import cmath + +import cupy +from cupy.linalg import _util + + +def khatri_rao(a, b): + r""" + Khatri-rao product + + A column-wise Kronecker product of two matrices + + Parameters + ---------- + a : (n, k) array_like + Input array + b : (m, k) array_like + Input array + + Returns + ------- + c: (n*m, k) ndarray + Khatri-rao product of `a` and `b`. + + See Also + -------- + .. seealso:: :func:`scipy.linalg.khatri_rao` + + """ + + _util._assert_2d(a) + _util._assert_2d(b) + + if a.shape[1] != b.shape[1]: + raise ValueError("The number of columns for both arrays " + "should be equal.") + + c = a[..., :, cupy.newaxis, :] * b[..., cupy.newaxis, :, :] + return c.reshape((-1,) + c.shape[2:]) + + +# ### expm ### +b = [64764752532480000., + 32382376266240000., + 7771770303897600., + 1187353796428800., + 129060195264000., + 10559470521600., + 670442572800., + 33522128640., + 1323241920., + 40840800., + 960960., + 16380., + 182., + 1.,] + +th13 = 5.37 + + +def expm(a): + """Compute the matrix exponential. + + Parameters + ---------- + a : ndarray, 2D + + Returns + ------- + matrix exponential of `a` + + Notes + ----- + Uses (a simplified) version of Algorithm 2.3 of [1]_: + a [13 / 13] Pade approximant with scaling and squaring. + + Simplifications: + + * we always use a [13/13] approximate + * no matrix balancing + + References + ---------- + .. [1] N. Higham, SIAM J. MATRIX ANAL. APPL. Vol. 26(4), p. 1179 (2005) + https://doi.org/10.1137/04061101X + + """ + if a.size == 0: + return cupy.zeros((0, 0), dtype=a.dtype) + + n = a.shape[0] + + # follow scipy.linalg.expm dtype handling + a_dtype = a.dtype if cupy.issubdtype( + a.dtype, cupy.inexact) else cupy.float64 + + # try reducing the norm + mu = cupy.diag(a).sum() / n + A = a - cupy.eye(n, dtype=a_dtype)*mu + + # scale factor + nrmA = cupy.linalg.norm(A, ord=1).item() + + scale = nrmA > th13 + if scale: + s = int(math.ceil(math.log2(float(nrmA) / th13))) + 1 + else: + s = 1 + + A /= 2**s + + # compute [13/13] Pade approximant + A2 = A @ A + A4 = A2 @ A2 + A6 = A2 @ A4 + + E = cupy.eye(A.shape[0], dtype=a_dtype) + bb = cupy.asarray(b, dtype=a_dtype) + + u1, u2, v1, v2 = _expm_inner(E, A, A2, A4, A6, bb) + u = A @ (A6 @ u1 + u2) + v = A6 @ v1 + v2 + + r13 = cupy.linalg.solve(-u + v, u + v) + + # squaring + x = r13 + for _ in range(s): + x = x @ x + + # undo preprocessing + emu = cmath.exp(mu) if cupy.issubdtype( + mu.dtype, cupy.complexfloating) else math.exp(mu) + x *= emu + + return x + + +@cupy.fuse +def _expm_inner(E, A, A2, A4, A6, b): + u1 = b[13]*A6 + b[11]*A4 + b[9]*A2 + u2 = b[7]*A6 + b[5]*A4 + b[3]*A2 + b[1]*E + + v1 = b[12]*A6 + b[10]*A4 + b[8]*A + v2 = b[6]*A6 + b[4]*A4 + b[2]*A2 + b[0]*E + return u1, u2, v1, v2 diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_solve_triangular.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_solve_triangular.py new file mode 100644 index 0000000000000000000000000000000000000000..cdb28fb5ed615b24a39804129b89af20beb5c193 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_solve_triangular.py @@ -0,0 +1,101 @@ +import numpy + +import cupy +from cupy.cuda import cublas +from cupy.cuda import device +from cupy.linalg import _util +from cupyx.scipy.linalg import _uarray + + +@_uarray.implements('solve_triangular') +def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False, + overwrite_b=False, check_finite=False): + """Solve the equation a x = b for x, assuming a is a triangular matrix. + + Args: + a (cupy.ndarray): The matrix with dimension ``(M, M)``. + b (cupy.ndarray): The matrix with dimension ``(M,)`` or + ``(M, N)``. + lower (bool): Use only data contained in the lower triangle of ``a``. + Default is to use upper triangle. + trans (0, 1, 2, 'N', 'T' or 'C'): Type of system to solve: + + - *'0'* or *'N'* -- :math:`a x = b` + - *'1'* or *'T'* -- :math:`a^T x = b` + - *'2'* or *'C'* -- :math:`a^H x = b` + + unit_diagonal (bool): If ``True``, diagonal elements of ``a`` are + assumed to be 1 and will not be referenced. + overwrite_b (bool): Allow overwriting data in b (may enhance + performance) + check_finite (bool): Whether to check that the input matrices contain + only finite numbers. Disabling may give a performance gain, but may + result in problems (crashes, non-termination) if the inputs do + contain infinities or NaNs. + + Returns: + cupy.ndarray: + The matrix with dimension ``(M,)`` or ``(M, N)``. + + .. seealso:: :func:`scipy.linalg.solve_triangular` + """ + + _util._assert_cupy_array(a, b) + + if len(a.shape) != 2 or a.shape[0] != a.shape[1]: + raise ValueError('expected square matrix') + if len(a) != len(b): + raise ValueError('incompatible dimensions') + + # Cast to float32 or float64 + if a.dtype.char in 'fd': + dtype = a.dtype + else: + dtype = numpy.promote_types(a.dtype.char, 'f') + + a = cupy.array(a, dtype=dtype, order='F', copy=False) + b = cupy.array(b, dtype=dtype, order='F', copy=(not overwrite_b)) + + if check_finite: + if a.dtype.kind == 'f' and not cupy.isfinite(a).all(): + raise ValueError( + 'array must not contain infs or NaNs') + if b.dtype.kind == 'f' and not cupy.isfinite(b).all(): + raise ValueError( + 'array must not contain infs or NaNs') + + m, n = (b.size, 1) if b.ndim == 1 else b.shape + cublas_handle = device.get_cublas_handle() + + if dtype == 'f': + trsm = cublas.strsm + elif dtype == 'd': + trsm = cublas.dtrsm + elif dtype == 'F': + trsm = cublas.ctrsm + else: # dtype == 'D' + trsm = cublas.ztrsm + one = numpy.array(1, dtype=dtype) + + if lower: + uplo = cublas.CUBLAS_FILL_MODE_LOWER + else: + uplo = cublas.CUBLAS_FILL_MODE_UPPER + + if trans == 'N': + trans = cublas.CUBLAS_OP_N + elif trans == 'T': + trans = cublas.CUBLAS_OP_T + elif trans == 'C': + trans = cublas.CUBLAS_OP_C + + if unit_diagonal: + diag = cublas.CUBLAS_DIAG_UNIT + else: + diag = cublas.CUBLAS_DIAG_NON_UNIT + + trsm( + cublas_handle, cublas.CUBLAS_SIDE_LEFT, uplo, + trans, diag, + m, n, one.ctypes.data, a.data.ptr, m, b.data.ptr, m) + return b diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_special_matrices.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_special_matrices.py new file mode 100644 index 0000000000000000000000000000000000000000..4f3036ff41eb2839c9a4cfcf8e433e979535d5e9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_special_matrices.py @@ -0,0 +1,578 @@ +import math +import warnings + +import cupy +from cupy import _core +from cupyx.scipy.linalg import _uarray + + +@_uarray.implements('tri') +def tri(N, M=None, k=0, dtype=None): + """ Construct (``N``, ``M``) matrix filled with ones at and below the + ``k``-th diagonal. The matrix has ``A[i,j] == 1`` for ``i <= j + k``. + + Args: + N (int): The size of the first dimension of the matrix. + M (int, optional): The size of the second dimension of the matrix. If + ``M`` is None, ``M = N`` is assumed. + k (int, optional): Number of subdiagonal below which matrix is filled + with ones. ``k = 0`` is the main diagonal, ``k < 0`` subdiagonal + and ``k > 0`` superdiagonal. + dtype (dtype, optional): Data type of the matrix. + + Returns: + cupy.ndarray: Tri matrix. + + .. seealso:: :func:`scipy.linalg.tri` + """ + warnings.warn("'tri'/'tril/'triu' are deprecated", DeprecationWarning) + + if M is None: + M = N + elif isinstance(M, str): + # handle legacy interface + M, dtype = N, M + # TODO: no outer method + # m = cupy.greater_equal.outer(cupy.arange(k, N+k), cupy.arange(M)) + # return m if dtype is None else m.astype(dtype, copy=False) + return cupy.tri(N, M, k, bool if dtype is None else dtype) + + +@_uarray.implements('tril') +def tril(m, k=0): + """Make a copy of a matrix with elements above the ``k``-th diagonal + zeroed. + + Args: + m (cupy.ndarray): Matrix whose elements to return + k (int, optional): Diagonal above which to zero elements. + ``k == 0`` is the main diagonal, ``k < 0`` subdiagonal and + ``k > 0`` superdiagonal. + + Returns: + (cupy.ndarray): Return is the same shape and type as ``m``. + + .. seealso:: :func:`scipy.linalg.tril` + """ + warnings.warn("'tri'/'tril/'triu' are deprecated", DeprecationWarning) + + # this is ~2x faster than cupy.tril for a 500x500 float64 matrix + t = tri(m.shape[0], m.shape[1], k=k, dtype=m.dtype.char) + t *= m + return t + + +@_uarray.implements('triu') +def triu(m, k=0): + """Make a copy of a matrix with elements below the ``k``-th diagonal + zeroed. + + Args: + m (cupy.ndarray): Matrix whose elements to return + k (int, optional): Diagonal above which to zero elements. + ``k == 0`` is the main diagonal, ``k < 0`` subdiagonal and + ``k > 0`` superdiagonal. + + Returns: + (cupy.ndarray): Return matrix with zeroed elements below the kth + diagonal and has same shape and type as ``m``. + + .. seealso:: :func:`scipy.linalg.triu` + """ + warnings.warn("'tri'/'tril/'triu' are deprecated", DeprecationWarning) + + # this is ~25% faster than cupy.tril for a 500x500 float64 matrix + t = tri(m.shape[0], m.shape[1], k - 1, m.dtype.char) + cupy.subtract(1, t, out=t) + t *= m + return t + + +@_uarray.implements('toeplitz') +def toeplitz(c, r=None): + """Construct a Toeplitz matrix. + + The Toeplitz matrix has constant diagonals, with ``c`` as its first column + and ``r`` as its first row. If ``r`` is not given, ``r == conjugate(c)`` is + assumed. + + Args: + c (cupy.ndarray): First column of the matrix. Whatever the actual shape + of ``c``, it will be converted to a 1-D array. + r (cupy.ndarray, optional): First row of the matrix. If None, + ``r = conjugate(c)`` is assumed; in this case, if ``c[0]`` is real, + the result is a Hermitian matrix. r[0] is ignored; the first row of + the returned matrix is ``[c[0], r[1:]]``. Whatever the actual shape + of ``r``, it will be converted to a 1-D array. + + Returns: + cupy.ndarray: The Toeplitz matrix. Dtype is the same as + ``(c[0] + r[0]).dtype``. + + .. seealso:: :func:`cupyx.scipy.linalg.circulant` + .. seealso:: :func:`cupyx.scipy.linalg.hankel` + .. seealso:: :func:`cupyx.scipy.linalg.solve_toeplitz` + .. seealso:: :func:`cupyx.scipy.linalg.fiedler` + .. seealso:: :func:`scipy.linalg.toeplitz` + """ + c = c.ravel() + r = c.conjugate() if r is None else r.ravel() + return _create_toeplitz_matrix(c[::-1], r[1:]) + + +@_uarray.implements('circulant') +def circulant(c): + """Construct a circulant matrix. + + Args: + c (cupy.ndarray): 1-D array, the first column of the matrix. + + Returns: + cupy.ndarray: A circulant matrix whose first column is ``c``. + + .. seealso:: :func:`cupyx.scipy.linalg.toeplitz` + .. seealso:: :func:`cupyx.scipy.linalg.hankel` + .. seealso:: :func:`cupyx.scipy.linalg.solve_circulant` + .. seealso:: :func:`cupyx.scipy.linalg.fiedler` + .. seealso:: :func:`scipy.linalg.circulant` + """ + c = c.ravel() + return _create_toeplitz_matrix(c[::-1], c[:0:-1]) + + +@_uarray.implements('hankel') +def hankel(c, r=None): + """Construct a Hankel matrix. + + The Hankel matrix has constant anti-diagonals, with ``c`` as its first + column and ``r`` as its last row. If ``r`` is not given, then + ``r = zeros_like(c)`` is assumed. + + Args: + c (cupy.ndarray): First column of the matrix. Whatever the actual shape + of ``c``, it will be converted to a 1-D array. + r (cupy.ndarray, optional): Last row of the matrix. If None, + ``r = zeros_like(c)`` is assumed. ``r[0]`` is ignored; the last row + of the returned matrix is ``[c[-1], r[1:]]``. Whatever the actual + shape of ``r``, it will be converted to a 1-D array. + + Returns: + cupy.ndarray: The Hankel matrix. Dtype is the same as + ``(c[0] + r[0]).dtype``. + + .. seealso:: :func:`cupyx.scipy.linalg.toeplitz` + .. seealso:: :func:`cupyx.scipy.linalg.circulant` + .. seealso:: :func:`scipy.linalg.hankel` + """ + c = c.ravel() + r = cupy.zeros_like(c) if r is None else r.ravel() + return _create_toeplitz_matrix(c, r[1:], True) + + +def _create_toeplitz_matrix(c, r, hankel=False): + vals = cupy.concatenate((c, r)) + n = vals.strides[0] + return cupy.lib.stride_tricks.as_strided( + vals if hankel else vals[c.size-1:], + shape=(c.size, r.size+1), + strides=(n if hankel else -n, n)).copy() + + +@_uarray.implements('hadamard') +def hadamard(n, dtype=int): + """Construct an Hadamard matrix. + + Constructs an n-by-n Hadamard matrix, using Sylvester's construction. ``n`` + must be a power of 2. + + Args: + n (int): The order of the matrix. ``n`` must be a power of 2. + dtype (dtype, optional): The data type of the array to be constructed. + + Returns: + (cupy.ndarray): The Hadamard matrix. + + .. seealso:: :func:`scipy.linalg.hadamard` + """ + lg2 = 0 if n < 1 else (int(n).bit_length() - 1) + if 2 ** lg2 != n: + raise ValueError('n must be an positive a power of 2 integer') + H = cupy.empty((n, n), dtype) + return _hadamard_kernel(H, H) + + +_hadamard_kernel = _core.ElementwiseKernel( + 'T in', 'T out', + 'out = (__popc(_ind.get()[0] & _ind.get()[1]) & 1) ? -1 : 1;', + 'cupyx_scipy_linalg_hadamard', reduce_dims=False) + + +@_uarray.implements('leslie') +def leslie(f, s): + """Create a Leslie matrix. + + Given the length n array of fecundity coefficients ``f`` and the length n-1 + array of survival coefficients ``s``, return the associated Leslie matrix. + + Args: + f (cupy.ndarray): The "fecundity" coefficients. + s (cupy.ndarray): The "survival" coefficients, has to be 1-D. The + length of ``s`` must be one less than the length of ``f``, and it + must be at least 1. + + Returns: + cupy.ndarray: The array is zero except for the first row, which is + ``f``, and the first sub-diagonal, which is ``s``. The data-type of + the array will be the data-type of ``f[0]+s[0]``. + + .. seealso:: :func:`scipy.linalg.leslie` + """ + if f.ndim != 1: + raise ValueError('Incorrect shape for f. f must be 1D') + if s.ndim != 1: + raise ValueError('Incorrect shape for s. s must be 1D') + n = f.size + if n != s.size + 1: + raise ValueError('Length of s must be one less than length of f') + if s.size == 0: + raise ValueError('The length of s must be at least 1.') + a = cupy.zeros((n, n), dtype=cupy.result_type(f, s)) + a[0] = f + cupy.fill_diagonal(a[1:], s) + return a + + +@_uarray.implements('kron') +def kron(a, b): + """Kronecker product. + + The result is the block matrix:: + a[0,0]*b a[0,1]*b ... a[0,-1]*b + a[1,0]*b a[1,1]*b ... a[1,-1]*b + ... + a[-1,0]*b a[-1,1]*b ... a[-1,-1]*b + + Args: + a (cupy.ndarray): Input array + b (cupy.ndarray): Input array + + Returns: + cupy.ndarray: Kronecker product of ``a`` and ``b``. + + .. seealso:: :func:`scipy.linalg.kron` + """ + o = cupy.outer(a, b) + o = o.reshape(a.shape + b.shape) + return cupy.concatenate(cupy.concatenate(o, axis=1), axis=1) + + +@_uarray.implements('block_diag') +def block_diag(*arrs): + """Create a block diagonal matrix from provided arrays. + + Given the inputs ``A``, ``B``, and ``C``, the output will have these + arrays arranged on the diagonal:: + + [A, 0, 0] + [0, B, 0] + [0, 0, C] + + Args: + A, B, C, ... (cupy.ndarray): Input arrays. A 1-D array of length ``n`` + is treated as a 2-D array with shape ``(1,n)``. + + Returns: + (cupy.ndarray): Array with ``A``, ``B``, ``C``, ... on the diagonal. + Output has the same dtype as ``A``. + + .. seealso:: :func:`scipy.linalg.block_diag` + """ + if not arrs: + return cupy.empty((1, 0)) + + # Convert to 2D and check + if len(arrs) == 1: + arrs = (cupy.atleast_2d(*arrs),) + else: + arrs = cupy.atleast_2d(*arrs) + if any(a.ndim != 2 for a in arrs): + bad = [k for k in range(len(arrs)) if arrs[k].ndim != 2] + raise ValueError('arguments in the following positions have dimension ' + 'greater than 2: {}'.format(bad)) + + shapes = tuple(a.shape for a in arrs) + shape = tuple(sum(x) for x in zip(*shapes)) + out = cupy.zeros(shape, dtype=cupy.result_type(*arrs)) + r, c = 0, 0 + for arr in arrs: + rr, cc = arr.shape + out[r:r + rr, c:c + cc] = arr + r += rr + c += cc + return out + + +@_uarray.implements('companion') +def companion(a): + """Create a companion matrix. + + Create the companion matrix associated with the polynomial whose + coefficients are given in ``a``. + + Args: + a (cupy.ndarray): 1-D array of polynomial coefficients. The length of + ``a`` must be at least two, and ``a[0]`` must not be zero. + + Returns: + (cupy.ndarray): The first row of the output is ``-a[1:]/a[0]``, and the + first sub-diagonal is all ones. The data-type of the array is the + same as the data-type of ``-a[1:]/a[0]``. + + .. seealso:: :func:`cupyx.scipy.linalg.fiedler_companion` + .. seealso:: :func:`scipy.linalg.companion` + """ + n = a.size + if a.ndim != 1: + raise ValueError('`a` must be one-dimensional.') + if n < 2: + raise ValueError('The length of `a` must be at least 2.') + # Following check requires device-to-host synchronization so will we not + # raise an error this situation + # if a[0] == 0: + # raise ValueError('The first coefficient in `a` must not be zero.') + first_row = -a[1:] / a[0] + c = cupy.zeros((n - 1, n - 1), dtype=first_row.dtype) + c[0] = first_row + cupy.fill_diagonal(c[1:], 1) + return c + + +@_uarray.implements('helmert') +def helmert(n, full=False): + """Create an Helmert matrix of order ``n``. + + This has applications in statistics, compositional or simplicial analysis, + and in Aitchison geometry. + + Args: + n (int): The size of the array to create. + full (bool, optional): If True the (n, n) ndarray will be returned. + Otherwise, the default, the submatrix that does not include the + first row will be returned. + + Returns: + cupy.ndarray: The Helmert matrix. The shape is (n, n) or (n-1, n) + depending on the ``full`` argument. + + .. seealso:: :func:`scipy.linalg.helmert` + """ + d = cupy.arange(n) + H = cupy.tri(n, n, -1) + H.diagonal()[:] -= d + d *= cupy.arange(1, n+1) + H[0] = 1 + d[0] = n + H /= cupy.sqrt(d)[:, None] + return H if full else H[1:] + + +@_uarray.implements('hilbert') +def hilbert(n): + """Create a Hilbert matrix of order ``n``. + + Returns the ``n`` by ``n`` array with entries ``h[i,j] = 1 / (i + j + 1)``. + + Args: + n (int): The size of the array to create. + + Returns: + cupy.ndarray: The Hilbert matrix. + + .. seealso:: :func:`scipy.linalg.hilbert` + """ + values = cupy.arange(1, 2*n, dtype=cupy.float64) + cupy.reciprocal(values, values) + return hankel(values[:n], r=values[n-1:]) + + +# TODO: invhilbert(n, exact=False) +# TODO: pascal(n, kind='symmetric', exact=True) +# TODO: invpascal(n, kind='symmetric', exact=True) + + +@_uarray.implements('dft') +def dft(n, scale=None): + """Discrete Fourier transform matrix. + + Create the matrix that computes the discrete Fourier transform of a + sequence. The nth primitive root of unity used to generate the matrix is + exp(-2*pi*i/n), where i = sqrt(-1). + + Args: + n (int): Size the matrix to create. + scale (str, optional): Must be None, 'sqrtn', or 'n'. + If ``scale`` is 'sqrtn', the matrix is divided by ``sqrt(n)``. + If ``scale`` is 'n', the matrix is divided by ``n``. + If ``scale`` is None (default), the matrix is not normalized, and + the return value is simply the Vandermonde matrix of the roots of + unity. + + Returns: + (cupy.ndarray): The DFT matrix. + + Notes: + When ``scale`` is None, multiplying a vector by the matrix returned by + ``dft`` is mathematically equivalent to (but much less efficient than) + the calculation performed by ``scipy.fft.fft``. + + .. seealso:: :func:`scipy.linalg.dft` + """ + if scale not in (None, 'sqrtn', 'n'): + raise ValueError('scale must be None, \'sqrtn\', or \'n\'; ' + '%r is not valid.' % (scale,)) + r = cupy.arange(n, dtype='complex128') + r *= -2j*cupy.pi/n + omegas = cupy.exp(r, out=r)[:, None] + m = omegas ** cupy.arange(n) + if scale is not None: + m *= (1/math.sqrt(n)) if scale == 'sqrtn' else (1/n) + return m + + +@_uarray.implements('fiedler') +def fiedler(a): + """Returns a symmetric Fiedler matrix + + Given an sequence of numbers ``a``, Fiedler matrices have the structure + ``F[i, j] = np.abs(a[i] - a[j])``, and hence zero diagonals and nonnegative + entries. A Fiedler matrix has a dominant positive eigenvalue and other + eigenvalues are negative. Although not valid generally, for certain inputs, + the inverse and the determinant can be derived explicitly. + + Args: + a (cupy.ndarray): coefficient array + + Returns: + cupy.ndarray: the symmetric Fiedler matrix + + .. seealso:: :func:`cupyx.scipy.linalg.circulant` + .. seealso:: :func:`cupyx.scipy.linalg.toeplitz` + .. seealso:: :func:`scipy.linalg.fiedler` + """ + if a.ndim != 1: + raise ValueError('Input `a` must be a 1D array.') + if a.size == 0: + return cupy.zeros(0) + if a.size == 1: + return cupy.zeros((1, 1)) + a = a[:, None] - a + return cupy.abs(a, out=a) + + +@_uarray.implements('fiedler_companion') +def fiedler_companion(a): + """Returns a Fiedler companion matrix + + Given a polynomial coefficient array ``a``, this function forms a + pentadiagonal matrix with a special structure whose eigenvalues coincides + with the roots of ``a``. + + Args: + a (cupy.ndarray): 1-D array of polynomial coefficients in descending + order with a nonzero leading coefficient. For ``N < 2``, an empty + array is returned. + + Returns: + cupy.ndarray: Resulting companion matrix + + Notes: + Similar to ``companion`` the leading coefficient should be nonzero. In + the case the leading coefficient is not 1, other coefficients are + rescaled before the array generation. To avoid numerical issues, it is + best to provide a monic polynomial. + + .. seealso:: :func:`cupyx.scipy.linalg.companion` + .. seealso:: :func:`scipy.linalg.fiedler_companion` + """ + if a.ndim != 1: + raise ValueError('Input `a` must be a 1-D array.') + if a.size < 2: + return cupy.zeros((0,), a.dtype) + if a.size == 2: + return (-a[1]/a[0])[None, None] + # Following check requires device-to-host synchronization so will we not + # raise an error this situation + # if a[0] == 0.: + # raise ValueError('Leading coefficient is zero.') + a = a/a[0] + n = a.size - 1 + c = cupy.zeros((n, n), dtype=a.dtype) + # subdiagonals + cupy.fill_diagonal(c[3::2, 1::2], 1) + cupy.fill_diagonal(c[2::2, 1::2], -a[3::2]) + # superdiagonals + cupy.fill_diagonal(c[::2, 2::2], 1) + cupy.fill_diagonal(c[::2, 1::2], -a[2::2]) + c[0, 0] = -a[1] + c[1, 0] = 1 + return c + + +@_uarray.implements('convolution_matrix') +def convolution_matrix(a, n, mode='full'): + """Construct a convolution matrix. + + Constructs the Toeplitz matrix representing one-dimensional convolution. + + Args: + a (cupy.ndarray): The 1-D array to convolve. + n (int): The number of columns in the resulting matrix. It gives the + length of the input to be convolved with ``a``. This is analogous + to the length of ``v`` in ``numpy.convolve(a, v)``. + mode (str): This must be one of (``'full'``, ``'valid'``, ``'same'``). + This is analogous to ``mode`` in ``numpy.convolve(v, a, mode)``. + + Returns: + cupy.ndarray: The convolution matrix whose row count k depends on + ``mode``: + + =========== ========================= + ``mode`` k + =========== ========================= + ``'full'`` m + n - 1 + ``'same'`` max(m, n) + ``'valid'`` max(m, n) - min(m, n) + 1 + =========== ========================= + + .. seealso:: :func:`cupyx.scipy.linalg.toeplitz` + .. seealso:: :func:`scipy.linalg.convolution_matrix` + """ + if n <= 0: + raise ValueError('n must be a positive integer.') + if a.ndim != 1: + raise ValueError('convolution_matrix expects a one-dimensional ' + 'array as input') + if a.size == 0: + raise ValueError('len(a) must be at least 1.') + if mode not in ('full', 'valid', 'same'): + raise ValueError( + '`mode` argument must be one of (\'full\', \'valid\', \'same\')') + + # create zero padded versions of the array + az = cupy.pad(a, (0, n-1), 'constant') + raz = cupy.pad(a[::-1], (0, n-1), 'constant') + if mode == 'same': + trim = min(n, a.size) - 1 + tb = trim//2 + te = trim - tb + col0 = az[tb:az.size-te] + row0 = raz[-n-tb:raz.size-tb] + elif mode == 'valid': + tb = min(n, a.size) - 1 + te = tb + col0 = az[tb:az.size-te] + row0 = raz[-n-tb:raz.size-tb] + else: # 'full' + col0 = az + row0 = raz[-n:] + return toeplitz(col0, row0) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_uarray.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_uarray.py new file mode 100644 index 0000000000000000000000000000000000000000..aa5395e433749527ddd917dc65d07da300feea87 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/linalg/_uarray.py @@ -0,0 +1,75 @@ +import numpy as np +import cupy +import cupy.linalg as _cp_linalg + + +try: + import scipy.linalg as _scipy_linalg +except ImportError: + _scipy_linalg = None + + +# Backend support for scipy.linalg + +__ua_domain__ = 'numpy.scipy.linalg' +_implemented = {} # type: ignore +_notfound = [] # for test + + +def __ua_convert__(dispatchables, coerce): + if coerce: + try: + replaced = [ + cupy.asarray(d.value) if d.coercible and d.type is np.ndarray + else d.value for d in dispatchables] + except TypeError: + return NotImplemented + else: + replaced = [d.value for d in dispatchables] + + if not all(d.type is not np.ndarray or isinstance(r, cupy.ndarray) + for r, d in zip(replaced, dispatchables)): + return NotImplemented + + return replaced + + +def __ua_function__(method, args, kwargs): + fn = _implemented.get(method, None) + if fn is None: + return NotImplemented + return fn(*args, **kwargs) + + +def implements(scipy_func_name): + """Decorator adds function to the dictionary of implemented functions""" + def inner(func): + scipy_func = ( + _scipy_linalg and getattr(_scipy_linalg, scipy_func_name, None)) + if scipy_func: + _implemented[scipy_func] = func + else: + _notfound.append(scipy_func_name) + return func + + return inner + + +# cupy linalg functions + +_cp_linalg_functions = [ + # cupy.linalg._eigenvalue + 'eigh', 'eigvalsh', + # cupy.linalg._decomposition + 'cholesky', 'qr', 'svd', + # cupy.linalg._norms + 'norm', 'det', + # cupy.linalg._solve + 'solve', 'lstsq', 'inv', 'pinv' +] + +if _scipy_linalg: + for func_name in _cp_linalg_functions: + cp_func = getattr(_cp_linalg, func_name) + scipy_func = getattr(_scipy_linalg, func_name) + _implemented[scipy_func] = cp_func diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/__init__.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9389a4dd64b8bc1e3cc4422a5b768feb2c055466 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/__init__.py @@ -0,0 +1,118 @@ +# Bessel Functions +from cupyx.scipy.special._bessel import i0 # NOQA +from cupyx.scipy.special._bessel import i0e # NOQA +from cupyx.scipy.special._bessel import i1 # NOQA +from cupyx.scipy.special._bessel import i1e # NOQA +from cupyx.scipy.special._bessel import j0 # NOQA +from cupyx.scipy.special._bessel import j1 # NOQA +from cupyx.scipy.special._bessel import k0 # NOQA +from cupyx.scipy.special._bessel import k0e # NOQA +from cupyx.scipy.special._bessel import k1 # NOQA +from cupyx.scipy.special._bessel import k1e # NOQA +from cupyx.scipy.special._bessel import y0 # NOQA +from cupyx.scipy.special._bessel import y1 # NOQA +from cupyx.scipy.special._bessel import yn # NOQA +from cupyx.scipy.special._spherical_bessel import spherical_yn # NOQA + +# Raw statistical functions +from cupyx.scipy.special._stats_distributions import bdtr # NOQA +from cupyx.scipy.special._stats_distributions import bdtrc # NOQA +from cupyx.scipy.special._stats_distributions import bdtri # NOQA +from cupyx.scipy.special._stats_distributions import btdtr # NOQA +from cupyx.scipy.special._stats_distributions import btdtri # NOQA +from cupyx.scipy.special._stats_distributions import fdtr # NOQA +from cupyx.scipy.special._stats_distributions import fdtrc # NOQA +from cupyx.scipy.special._stats_distributions import fdtri # NOQA +from cupyx.scipy.special._stats_distributions import gdtr # NOQA +from cupyx.scipy.special._stats_distributions import gdtrc # NOQA +from cupyx.scipy.special._stats_distributions import nbdtr # NOQA +from cupyx.scipy.special._stats_distributions import nbdtrc # NOQA +from cupyx.scipy.special._stats_distributions import nbdtri # NOQA +from cupyx.scipy.special._stats_distributions import pdtr # NOQA +from cupyx.scipy.special._stats_distributions import pdtrc # NOQA +from cupyx.scipy.special._stats_distributions import pdtri # NOQA +from cupyx.scipy.special._stats_distributions import chdtr # NOQA +from cupyx.scipy.special._stats_distributions import chdtrc # NOQA +from cupyx.scipy.special._stats_distributions import chdtri # NOQA +from cupyx.scipy.special._stats_distributions import ndtr # NOQA +from cupyx.scipy.special._stats_distributions import log_ndtr # NOQA +from cupyx.scipy.special._stats_distributions import ndtri # NOQA +from cupyx.scipy.special._statistics import logit # NOQA +from cupyx.scipy.special._statistics import expit # NOQA +from cupyx.scipy.special._statistics import log_expit # NOQA +from cupyx.scipy.special._statistics import boxcox # NOQA +from cupyx.scipy.special._statistics import boxcox1p # NOQA +from cupyx.scipy.special._statistics import inv_boxcox # NOQA +from cupyx.scipy.special._statistics import inv_boxcox1p # NOQA + +# Information Theory functions +from cupyx.scipy.special._convex_analysis import entr # NOQA +from cupyx.scipy.special._convex_analysis import huber # NOQA +from cupyx.scipy.special._convex_analysis import kl_div # NOQA +from cupyx.scipy.special._convex_analysis import pseudo_huber # NOQA +from cupyx.scipy.special._convex_analysis import rel_entr # NOQA + +# Gamma and related functions +from cupyx.scipy.special._gamma import gamma # NOQA +from cupyx.scipy.special._gammaln import gammaln # NOQA +from cupyx.scipy.special._loggamma import loggamma # NOQA +from cupyx.scipy.special._gammasgn import gammasgn # NOQA +from cupyx.scipy.special._gammainc import gammainc # NOQA +from cupyx.scipy.special._gammainc import gammaincinv # NOQA +from cupyx.scipy.special._gammainc import gammaincc # NOQA +from cupyx.scipy.special._gammainc import gammainccinv # NOQA +from cupyx.scipy.special._beta import beta # NOQA +from cupyx.scipy.special._beta import betaln # NOQA +from cupyx.scipy.special._beta import betainc # NOQA +from cupyx.scipy.special._beta import betaincinv # NOQA +from cupyx.scipy.special._digamma import digamma as psi # NOQA +from cupyx.scipy.special._gamma import rgamma # NOQA +from cupyx.scipy.special._polygamma import polygamma # NOQA +from cupyx.scipy.special._gammaln import multigammaln # NOQA +from cupyx.scipy.special._digamma import digamma # NOQA +from cupyx.scipy.special._poch import poch # NOQA + +# Error function and Fresnel integrals +from cupyx.scipy.special._erf import erf # NOQA +from cupyx.scipy.special._erf import erfc # NOQA +from cupyx.scipy.special._erf import erfcx # NOQA +from cupyx.scipy.special._erf import erfinv # NOQA +from cupyx.scipy.special._erf import erfcinv # NOQA + +# Legendre functions +from cupyx.scipy.special._lpmv import lpmv # NOQA +from cupyx.scipy.special._sph_harm import sph_harm # NOQA + +# Other special functions +from cupyx.scipy.special._binom import binom # NOQA +from cupyx.scipy.special._exp1 import exp1 # NOQA +from cupyx.scipy.special._expi import expi # NOQA +from cupyx.scipy.special._expn import expn # NOQA +from cupyx.scipy.special._softmax import softmax # NOQA +from cupyx.scipy.special._logsoftmax import log_softmax # NOQA +from cupyx.scipy.special._zeta import zeta # NOQA +from cupyx.scipy.special._zetac import zetac # NOQA + +# Convenience functions +from cupyx.scipy.special._basic import cbrt # NOQA +from cupyx.scipy.special._basic import exp10 # NOQA +from cupyx.scipy.special._basic import exp2 # NOQA +from cupyx.scipy.special._basic import radian # NOQA +from cupyx.scipy.special._basic import cosdg # NOQA +from cupyx.scipy.special._basic import sindg # NOQA +from cupyx.scipy.special._basic import tandg # NOQA +from cupyx.scipy.special._basic import cotdg # NOQA +from cupyx.scipy.special._basic import log1p # NOQA +from cupyx.scipy.special._basic import expm1 # NOQA +from cupyx.scipy.special._basic import exprel # NOQA +from cupyx.scipy.special._basic import cosm1 # NOQA +from cupy._math.rounding import round # NOQA +from cupyx.scipy.special._xlogy import xlogy # NOQA +from cupyx.scipy.special._xlogy import xlog1py # NOQA +from cupyx.scipy.special._logsumexp import logsumexp # NOQA +from cupy._math.special import sinc # NOQA + +# Elliptic functions +from cupyx.scipy.special._ellip import ellipk # NOQA +from cupyx.scipy.special._ellip import ellipkm1 # NOQA +from cupyx.scipy.special._ellip import ellipj # NOQA diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_bessel.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_bessel.py new file mode 100644 index 0000000000000000000000000000000000000000..b5eb1f96433e98b4a39db42fc5f83a050e763987 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_bessel.py @@ -0,0 +1,462 @@ +# This source code contains SciPy's code. +# https://github.com/scipy/scipy/blob/master/scipy/special/cephes/k0.c +# https://github.com/scipy/scipy/blob/master/scipy/special/cephes/k1.c +# +# +# Cephes Math Library Release 2.8: June, 2000 +# Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier + +from cupy import _core +from cupyx.scipy.special._gamma import chbevl_implementation + +j0 = _core.create_ufunc( + 'cupyx_scipy_special_j0', ('f->f', 'd->d'), + 'out0 = j0(in0)', + doc='''Bessel function of the first kind of order 0. + + .. seealso:: :meth:`scipy.special.j0` + + ''') + + +j1 = _core.create_ufunc( + 'cupyx_scipy_special_j1', ('f->f', 'd->d'), + 'out0 = j1(in0)', + doc='''Bessel function of the first kind of order 1. + + .. seealso:: :meth:`scipy.special.j1` + + ''') + + +y0 = _core.create_ufunc( + 'cupyx_scipy_special_y0', ('f->f', 'd->d'), + 'out0 = y0(in0)', + doc='''Bessel function of the second kind of order 0. + + .. seealso:: :meth:`scipy.special.y0` + + ''') + + +y1 = _core.create_ufunc( + 'cupyx_scipy_special_y1', ('f->f', 'd->d'), + 'out0 = y1(in0)', + doc='''Bessel function of the second kind of order 1. + + .. seealso:: :meth:`scipy.special.y1` + + ''') + + +# Note: oddly, unlike for y0 or y1, SciPy always returns double for yn +# dd->d because SciPy will accept 2.0 +yn = _core.create_ufunc( + 'cupyx_scipy_special_yn', ('id->d', 'dd->d'), + 'out0 = yn((int)in0, in1)', + doc='''Bessel function of the second kind of order n. + + Args: + n (cupy.ndarray): order (integer) + x (cupy.ndarray): argument (float) + + Returns: + cupy.ndarray: The result. + + Notes + ----- + Unlike SciPy, no warning will be raised on unsafe casting of `order` to + 32-bit integer. + + .. seealso:: :meth:`scipy.special.yn` + ''') + + +i0 = _core.create_ufunc( + 'cupyx_scipy_special_i0', ('f->f', 'd->d'), + 'out0 = cyl_bessel_i0(in0)', + doc='''Modified Bessel function of order 0. + + .. seealso:: :meth:`scipy.special.i0` + + ''') + + +i0e = _core.create_ufunc( + 'cupyx_scipy_special_i0e', ('f->f', 'd->d'), + 'out0 = exp(-abs(in0)) * cyl_bessel_i0(in0)', + doc='''Exponentially scaled modified Bessel function of order 0. + + .. seealso:: :meth:`scipy.special.i0e` + + ''') + + +i1 = _core.create_ufunc( + 'cupyx_scipy_special_i1', ('f->f', 'd->d'), + 'out0 = cyl_bessel_i1(in0)', + doc='''Modified Bessel function of order 1. + + .. seealso:: :meth:`scipy.special.i1` + + ''') + + +i1e = _core.create_ufunc( + 'cupyx_scipy_special_i1e', ('f->f', 'd->d'), + 'out0 = exp(-abs(in0)) * cyl_bessel_i1(in0)', + doc='''Exponentially scaled modified Bessel function of order 1. + + .. seealso:: :meth:`scipy.special.i1e` + + ''') + + +k_preamble = chbevl_implementation + """ +#include + +/* Chebyshev coefficients for K0(x) + log(x/2) I0(x) + * in the interval [0,2]. The odd order coefficients are all + * zero; only the even order coefficients are listed. + * + * lim(x->0){ K0(x) + log(x/2) I0(x) } = -EUL. + */ +__device__ double k0_A[] = { + 1.37446543561352307156E-16, + 4.25981614279661018399E-14, + 1.03496952576338420167E-11, + 1.90451637722020886025E-9, + 2.53479107902614945675E-7, + 2.28621210311945178607E-5, + 1.26461541144692592338E-3, + 3.59799365153615016266E-2, + 3.44289899924628486886E-1, + -5.35327393233902768720E-1 +}; +__device__ float k0_AF[] = { + 1.37446543561352307156E-16, + 4.25981614279661018399E-14, + 1.03496952576338420167E-11, + 1.90451637722020886025E-9, + 2.53479107902614945675E-7, + 2.28621210311945178607E-5, + 1.26461541144692592338E-3, + 3.59799365153615016266E-2, + 3.44289899924628486886E-1, + -5.35327393233902768720E-1 +}; + + +/* Chebyshev coefficients for exp(x) sqrt(x) K0(x) + * in the inverted interval [2,infinity]. + * + * lim(x->inf){ exp(x) sqrt(x) K0(x) } = sqrt(pi/2). + */ +__device__ double k0_B[] = { + 5.30043377268626276149E-18, + -1.64758043015242134646E-17, + 5.21039150503902756861E-17, + -1.67823109680541210385E-16, + 5.51205597852431940784E-16, + -1.84859337734377901440E-15, + 6.34007647740507060557E-15, + -2.22751332699166985548E-14, + 8.03289077536357521100E-14, + -2.98009692317273043925E-13, + 1.14034058820847496303E-12, + -4.51459788337394416547E-12, + 1.85594911495471785253E-11, + -7.95748924447710747776E-11, + 3.57739728140030116597E-10, + -1.69753450938905987466E-9, + 8.57403401741422608519E-9, + -4.66048989768794782956E-8, + 2.76681363944501510342E-7, + -1.83175552271911948767E-6, + 1.39498137188764993662E-5, + -1.28495495816278026384E-4, + 1.56988388573005337491E-3, + -3.14481013119645005427E-2, + 2.44030308206595545468E0 +}; +__device__ float k0_BF[] = { + 5.30043377268626276149E-18, + -1.64758043015242134646E-17, + 5.21039150503902756861E-17, + -1.67823109680541210385E-16, + 5.51205597852431940784E-16, + -1.84859337734377901440E-15, + 6.34007647740507060557E-15, + -2.22751332699166985548E-14, + 8.03289077536357521100E-14, + -2.98009692317273043925E-13, + 1.14034058820847496303E-12, + -4.51459788337394416547E-12, + 1.85594911495471785253E-11, + -7.95748924447710747776E-11, + 3.57739728140030116597E-10, + -1.69753450938905987466E-9, + 8.57403401741422608519E-9, + -4.66048989768794782956E-8, + 2.76681363944501510342E-7, + -1.83175552271911948767E-6, + 1.39498137188764993662E-5, + -1.28495495816278026384E-4, + 1.56988388573005337491E-3, + -3.14481013119645005427E-2, + 2.44030308206595545468E0 +}; + + +/* Chebyshev coefficients for x(K1(x) - log(x/2) I1(x)) + * in the interval [0,2]. + * + * lim(x->0){ x(K1(x) - log(x/2) I1(x)) } = 1. + */ +__device__ static double k1_A[] = { + -7.02386347938628759343E-18, + -2.42744985051936593393E-15, + -6.66690169419932900609E-13, + -1.41148839263352776110E-10, + -2.21338763073472585583E-8, + -2.43340614156596823496E-6, + -1.73028895751305206302E-4, + -6.97572385963986435018E-3, + -1.22611180822657148235E-1, + -3.53155960776544875667E-1, + 1.52530022733894777053E0 +}; +__device__ static float k1_AF[] = { + -7.02386347938628759343E-18, + -2.42744985051936593393E-15, + -6.66690169419932900609E-13, + -1.41148839263352776110E-10, + -2.21338763073472585583E-8, + -2.43340614156596823496E-6, + -1.73028895751305206302E-4, + -6.97572385963986435018E-3, + -1.22611180822657148235E-1, + -3.53155960776544875667E-1, + 1.52530022733894777053E0 +}; + + +/* Chebyshev coefficients for exp(x) sqrt(x) K1(x) + * in the interval [2,infinity]. + * + * lim(x->inf){ exp(x) sqrt(x) K1(x) } = sqrt(pi/2). + */ +__device__ static double k1_B[] = { + -5.75674448366501715755E-18, + 1.79405087314755922667E-17, + -5.68946255844285935196E-17, + 1.83809354436663880070E-16, + -6.05704724837331885336E-16, + 2.03870316562433424052E-15, + -7.01983709041831346144E-15, + 2.47715442448130437068E-14, + -8.97670518232499435011E-14, + 3.34841966607842919884E-13, + -1.28917396095102890680E-12, + 5.13963967348173025100E-12, + -2.12996783842756842877E-11, + 9.21831518760500529508E-11, + -4.19035475934189648750E-10, + 2.01504975519703286596E-9, + -1.03457624656780970260E-8, + 5.74108412545004946722E-8, + -3.50196060308781257119E-7, + 2.40648494783721712015E-6, + -1.93619797416608296024E-5, + 1.95215518471351631108E-4, + -2.85781685962277938680E-3, + 1.03923736576817238437E-1, + 2.72062619048444266945E0 +}; +__device__ static float k1_BF[] = { + -5.75674448366501715755E-18, + 1.79405087314755922667E-17, + -5.68946255844285935196E-17, + 1.83809354436663880070E-16, + -6.05704724837331885336E-16, + 2.03870316562433424052E-15, + -7.01983709041831346144E-15, + 2.47715442448130437068E-14, + -8.97670518232499435011E-14, + 3.34841966607842919884E-13, + -1.28917396095102890680E-12, + 5.13963967348173025100E-12, + -2.12996783842756842877E-11, + 9.21831518760500529508E-11, + -4.19035475934189648750E-10, + 2.01504975519703286596E-9, + -1.03457624656780970260E-8, + 5.74108412545004946722E-8, + -3.50196060308781257119E-7, + 2.40648494783721712015E-6, + -1.93619797416608296024E-5, + 1.95215518471351631108E-4, + -2.85781685962277938680E-3, + 1.03923736576817238437E-1, + 2.72062619048444266945E0 +}; + +__device__ double k0(double x){ + if (x == 0) { + return CUDART_INF; + } + + if (x < 0) { + return CUDART_NAN; + } + + double y, z; + + if (x <= 2.0) { + y = x * x - 2.0; + y = chbevl(y, k0_A, 10) - log(0.5 * x) * cyl_bessel_i0(x); + return y; + } + + z = 8.0 / x - 2.0; + y = chbevl(z, k0_B, 25) / sqrt(x); + return y * exp(-x); +} + +__device__ float k0f(float x){ + if (x == 0) { + return CUDART_INF; + } + + if (x < 0) { + return CUDART_NAN; + } + + float y, z; + + if (x <= 2.0) { + y = x * x - 2.0; + y = chbevl(y, k0_AF, 10) - logf(0.5 * x) * cyl_bessel_i0f(x); + return y; + } + + z = 8.0 / x - 2.0; + y = chbevl(z, k0_BF, 25) / sqrtf(x); + return y * expf(-x); +} + +__device__ double k1(double x){ + if (x == 0) { + return CUDART_INF; + } + + if (x < 0) { + return CUDART_NAN; + } + + double y; + + if (x <= 2.0) { + y = x * x - 2.0; + y = log(0.5 * x) * cyl_bessel_i1(x) + chbevl(y, k1_A, 11) / x; + return y; + } + + return (exp(-x) * chbevl(8.0 / x - 2.0, k1_B, 25) / sqrt(x)); +} + +__device__ float k1f(float x){ + if (x == 0) { + return CUDART_INF; + } + + if (x < 0) { + return CUDART_NAN; + } + + float y; + float i1; + + if (x <= 2.0) { + y = x * x - 2.0; + i1 = cyl_bessel_i1f(x); + y = logf(0.5 * x) * i1 + chbevl(y, k1_AF, 11) / x; + return y; + } + + float z = 8.0 / x - 2.0; + return (expf(-x) * chbevl(z, k1_BF, 25) / sqrtf(x)); +} +""" + + +k0 = _core.create_ufunc( + 'cupyx_scipy_special_k0', + (('f->f', 'out0 = k0f(in0)'), 'd->d'), + 'out0 = k0(in0)', + preamble=k_preamble, + doc='''Modified Bessel function of the second kind of order 0. + + Args: + x (cupy.ndarray): argument (float) + + Returns: + cupy.ndarray: Value of the modified Bessel function K of order 0 at x. + + .. seealso:: :meth:`scipy.special.k0` + + ''') + + +k0e = _core.create_ufunc( + 'cupyx_scipy_special_k0e', + (('f->f', 'out0 = expf(in0) * k0f(in0)'), 'd->d'), + 'out0 = exp(in0) * k0(in0)', + preamble=k_preamble, + doc='''Exponentially scaled modified Bessel function K of order 0 + + Args: + x (cupy.ndarray): argument (float) + + Returns: + cupy.ndarray: Value at x. + + .. seealso:: :meth:`scipy.special.k0e` + + ''') + + +k1 = _core.create_ufunc( + 'cupyx_scipy_special_k1', + (('f->f', 'out0 = k1f(in0)'), 'd->d'), + 'out0 = k1(in0)', + preamble=k_preamble, + doc='''Modified Bessel function of the second kind of order 1. + + Args: + x (cupy.ndarray): argument (float) + + Returns: + cupy.ndarray: Value of the modified Bessel function K of order 1 at x. + + .. seealso:: :meth:`scipy.special.k1` + + ''') + + +k1e = _core.create_ufunc( + 'cupyx_scipy_special_k1e', + (('f->f', 'out0 = expf(in0) * k1f(in0)'), 'd->d'), + 'out0 = exp(in0) * k1(in0)', + preamble=k_preamble, + doc='''Exponentially scaled modified Bessel function K of order 1 + + Args: + x (cupy.ndarray): argument (float) + + Returns: + cupy.ndarray: Value at x. + + .. seealso:: :meth:`scipy.special.k1e` + + ''') diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_binom.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_binom.py new file mode 100644 index 0000000000000000000000000000000000000000..2c83851bf202da09558b8e38f2d6d7503c542f13 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_binom.py @@ -0,0 +1,118 @@ +""" +Implements the binom function from scipy. + +This is essentially a CUDA C++ adaptation of existing scipy code, available at: +https://github.com/scipy/scipy/blob/v1.10.1/scipy/special/orthogonal_eval.pxd +""" + +from cupy import _core +from cupyx.scipy.special._beta import ( + beta_preamble, + lbeta_symp_definition, + lgam_sgn_definition, + beta_definition, + lbeta_definition +) +from cupyx.scipy.special._digamma import polevl_definition +from cupyx.scipy.special._gamma import gamma_definition +from cupyx.scipy.special._gammainc import p1evl_definition + +binom_definition = """ +__device__ double binom(double n, double k) { + + // Check if n is negative integer + if (n < 0 && n == trunc(n)) { + return CUDART_NAN; + } + // Check if k is infinite + if (k == CUDART_INF) { + return CUDART_NAN; + } + + // k is integer and n is not very small + if (k == floor(k) && (fabs(n) > 1.0e-8 || n == 0)) { + // Reduce k by symmetry if n also integer + if (n == floor(n) && k > n/2 && n > 0) { + k = n - k; + } + // Manually multiply if k between 0, 20 + if (0 <= k && k < 20) { + double num = 1.0; + double den = 1.0; + for (int i = 1; i < k+.5; i++) { + num *= i + n - k; + den *= i; + // Resize num, den if num becomes too big + if (fabs(num) > 1.0e50) { + num /= den; + den = 1.0; + } + } + return num / den; + } + } + + if (n >= k * 1e10 && k > 0) { + // Prevent overflow + return exp(-lbeta(1 + n - k, 1 + k) - log(n + 1)); + } else if (k > 1e8 * fabs(n)) { + double num = Gamma(1 + n) / fabs(k) + Gamma(1 + n) * n / (2 * k*k); + num /= M_PI * pow(fabs(k), n); + double kfloor = floor(k); + if (k > 0) { + int sgn; + double dk; + if (int(kfloor) == kfloor) { + dk = k - kfloor; + sgn = int(kfloor) % 2 == 0 ? 1 : -1; + } else { + dk = k; + sgn = 1; + } + return num * sin((dk-n)*M_PI) * sgn; + } else { + if (int(kfloor) == kfloor) { + return 0; + } else { + return num * sin(k*M_PI); + } + } + } else { + return 1/(n + 1)/beta(1 + n - k, 1 + k); + } +} +""" + +binom = _core.create_ufunc( + "cupyx_scipy_binom", + ("ff->f", "dd->d"), + "out0 = out0_type(binom(in0, in1));", + preamble=( + gamma_definition + + beta_preamble + + p1evl_definition + + polevl_definition + + lgam_sgn_definition + + lbeta_symp_definition + + lbeta_definition + + beta_definition + + binom_definition + ), + doc="""Binomial coefficient + + Parameters + ---------- + n, k : cupy.ndarray + Real-valued parameters to nCk + out : ndarray, optional + Optional output array for the function result + + Returns + ------- + scalar or ndarray + Value of binomial coefficient + + .. seealso:: :func:`scipy.special.binom` + + """, +) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_digamma.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_digamma.py new file mode 100644 index 0000000000000000000000000000000000000000..f98a43f899f20f637dc9ad1f39b51f6ae859f7f6 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_digamma.py @@ -0,0 +1,191 @@ +# This source code contains SciPy's code. +# https://github.com/scipy/scipy/blob/master/scipy/special/cephes/psi.c +# +# +# Cephes Math Library Release 2.8: June, 2000 +# Copyright 1984, 1987, 1992, 2000 by Stephen L. Moshier +# +# +# Code for the rational approximation on [1, 2] is: +# +# (C) Copyright John Maddock 2006. +# Use, modification and distribution are subject to the +# Boost Software License, Version 1.0. (See accompanying file +# LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +from cupy import _core + + +polevl_definition = ''' +template static __device__ double polevl(double x, double coef[]) +{ + double ans; + double *p; + + p = coef; + ans = *p++; + + for (int i = 0; i < N; ++i){ + ans = ans * x + *p++; + } + + return ans; +} +''' + + +psi_definition = ''' +__constant__ double A[] = { + 8.33333333333333333333E-2, + -2.10927960927960927961E-2, + 7.57575757575757575758E-3, + -4.16666666666666666667E-3, + 3.96825396825396825397E-3, + -8.33333333333333333333E-3, + 8.33333333333333333333E-2 +}; + +__constant__ double PI = 3.141592653589793; +__constant__ double EULER = 0.5772156649015329; + +__constant__ float Y = 0.99558162689208984f; + +__constant__ double root1 = 1569415565.0 / 1073741824.0; +__constant__ double root2 = (381566830.0 / 1073741824.0) / 1073741824.0; +__constant__ double root3 = 0.9016312093258695918615325266959189453125e-19; + +__constant__ double P[] = { + -0.0020713321167745952, + -0.045251321448739056, + -0.28919126444774784, + -0.65031853770896507, + -0.32555031186804491, + 0.25479851061131551 +}; +__constant__ double Q[] = { + -0.55789841321675513e-6, + 0.0021284987017821144, + 0.054151797245674225, + 0.43593529692665969, + 1.4606242909763515, + 2.0767117023730469, + 1.0 +}; + +static __device__ double digamma_imp_1_2(double x) +{ + /* + * Rational approximation on [1, 2] taken from Boost. + * + * Now for the approximation, we use the form: + * + * digamma(x) = (x - root) * (Y + R(x-1)) + * + * Where root is the location of the positive root of digamma, + * Y is a constant, and R is optimised for low absolute error + * compared to Y. + * + * Maximum Deviation Found: 1.466e-18 + * At double precision, max error found: 2.452e-17 + */ + double r, g; + g = x - root1 - root2 - root3; + r = polevl<5>(x - 1.0, P) / polevl<6>(x - 1.0, Q); + + return g * Y + g * r; +} + + +static __device__ double psi_asy(double x) +{ + double y, z; + + if (x < 1.0e17) { + z = 1.0 / (x * x); + y = z * polevl<6>(z, A); + } + else { + y = 0.0; + } + + return log(x) - (0.5 / x) - y; +} + + +double __device__ psi(double x) +{ + double y = 0.0; + double q, r; + int i, n; + + if (isnan(x)) { + return x; + } + else if (isinf(x)){ + if(x > 0){ + return x; + }else{ + return nan(""); + } + } + else if (x == 0) { + return -1.0/0.0; + } + else if (x < 0.0) { + /* argument reduction before evaluating tan(pi * x) */ + r = modf(x, &q); + if (r == 0.0) { + return nan(""); + } + y = -PI / tan(PI * r); + x = 1.0 - x; + } + + /* check for positive integer up to 10 */ + if ((x <= 10.0) && (x == floor(x))) { + n = (int)x; + for (i = 1; i < n; i++) { + y += 1.0 / i; + } + y -= EULER; + return y; + } + + /* use the recurrence relation to move x into [1, 2] */ + if (x < 1.0) { + y -= 1.0 / x; + x += 1.0; + } + else if (x < 10.0) { + while (x > 2.0) { + x -= 1.0; + y += 1.0 / x; + } + } + if ((1.0 <= x) && (x <= 2.0)) { + y += digamma_imp_1_2(x); + return y; + } + + /* x is large, use the asymptotic series */ + y += psi_asy(x); + return y; +} +''' + + +digamma = _core.create_ufunc( + 'cupyx_scipy_special_digamma', ('f->f', 'd->d'), + 'out0 = psi(in0)', + preamble=polevl_definition+psi_definition, + doc="""The digamma function. + + Args: + x (cupy.ndarray): The input of digamma function. + + Returns: + cupy.ndarray: Computed value of digamma function. + + .. seealso:: :data:`scipy.special.digamma` + + """) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_erf.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_erf.py new file mode 100644 index 0000000000000000000000000000000000000000..7eea14adaf4657ce245401a8c20eb83d0de54864 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_erf.py @@ -0,0 +1,59 @@ +from cupy import _core + + +erf = _core.create_ufunc( + 'cupyx_scipy_special_erf', ('f->f', 'd->d'), + 'out0 = erf(in0)', + doc='''Error function. + + .. seealso:: :meth:`scipy.special.erf` + + ''') + + +erfc = _core.create_ufunc( + 'cupyx_scipy_special_erfc', ('f->f', 'd->d'), + 'out0 = erfc(in0)', + doc='''Complementary error function. + + .. seealso:: :meth:`scipy.special.erfc` + + ''') + + +erfcx = _core.create_ufunc( + 'cupyx_scipy_special_erfcx', ('f->f', 'd->d'), + 'out0 = erfcx(in0)', + doc='''Scaled complementary error function. + + .. seealso:: :meth:`scipy.special.erfcx` + + ''') + + +erfinv = _core.create_ufunc( + 'cupyx_scipy_special_erfinv', ('f->f', 'd->d'), + 'out0 = erfinv(in0);', + doc='''Inverse function of error function. + + .. seealso:: :meth:`scipy.special.erfinv` + + .. note:: + The behavior close to (and outside) the domain follows that of + SciPy v1.4.0+. + + ''') + + +erfcinv = _core.create_ufunc( + 'cupyx_scipy_special_erfcinv', ('f->f', 'd->d'), + 'out0 = erfcinv(in0);', + doc='''Inverse function of complementary error function. + + .. seealso:: :meth:`scipy.special.erfcinv` + + .. note:: + The behavior close to (and outside) the domain follows that of + SciPy v1.4.0+. + + ''') diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_exp1.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_exp1.py new file mode 100644 index 0000000000000000000000000000000000000000..ef550ba4f7c870a4c7b53f50f0bafa87a437a529 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_exp1.py @@ -0,0 +1,62 @@ +# This source code contains SciPy's code. +# https://github.com/scipy/scipy/blob/main/scipy/special/specfun/specfun.f + +from cupy import _core # NOQA + + +math_constants_and_eul = """ +#include +__constant__ double EUL = 0.5772156649015328; +""" + +exp1_definition = """ +template +static __device__ T exp1(T x) { + if (x == 0) { + return CUDART_INF; + } else if (x <= 1) { + T e1 = 1.0; + T R = 1.0; + + for (int k = 1; k <= 25; k++) { + int den = (k + 1) * (k + 1); + R = -R * k * x / den; + e1 += R; + } + return -EUL - log(x) + x * e1; + } + + int M = 20 + 80.0 / x; + T t0 = 0; + for (int k = M; k != 0; k--) { + t0 = k / (1.0 + k / (x + t0)); + } + T t = 1.0 / (x + t0); + return exp(-x) * t; +} +""" + + +exp1 = _core.create_ufunc( + 'cupyx_scipy_special_exp1', + ('f->f', 'd->d'), + 'out0 = exp1(in0)', + preamble=math_constants_and_eul + exp1_definition, + doc="""Exponential integral E1. + + Parameters + ---------- + x : cupy.ndarray + Real argument + + Returns + ------- + y : scalar or cupy.ndarray + Values of the exponential integral E1 + + See Also + -------- + :func:`scipy.special.exp1` + + """, +) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_expi.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_expi.py new file mode 100644 index 0000000000000000000000000000000000000000..02c018ce484259c568a6b3ab534a3f9e33216fbf --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_expi.py @@ -0,0 +1,60 @@ +# This source code contains SciPy's code. +# https://github.com/scipy/scipy/blob/main/scipy/special/specfun/specfun.f + +from cupy import _core # NOQA +from cupyx.scipy.special._exp1 import exp1_definition +from cupyx.scipy.special._exp1 import math_constants_and_eul + + +expi_definition = """ +template < typename T > +__device__ double expi(T x) { + T ei = 1; + T r = 1; + + if (x == 0) { + return -CUDART_INF; + } else if (x < 0) { + return -exp1(-x); + } else if (x <= 40.0) { + for (int k = 1; k <= 100; k++) { + int den = (k + 1) * (k + 1); + r = r * k * x / den; + ei += r; + } + + return EUL + x * ei + log(x); + } + + for (int k = 1; k <= 40; k++) { + r = r * k / x; + ei += r; + } + + return exp(x) / x * ei; +} +""" + +expi = _core.create_ufunc( + 'cupyx_scipy_special_expi', + ('f->f', 'd->d'), + 'out0 = expi(in0)', + preamble=math_constants_and_eul + exp1_definition + expi_definition, + doc="""Exponential integral Ei. + + Parameters + ---------- + x : cupy.ndarray + Real argument + + Returns + ------- + y : scalar or cupy.ndarray + Values of exponential integral + + See Also + -------- + :func:`scipy.special.expi` + + """, +) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_gamma.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_gamma.py new file mode 100644 index 0000000000000000000000000000000000000000..73a9caedbfaa75fab92759a6e0dbc4efd5da291c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_gamma.py @@ -0,0 +1,220 @@ +from cupy import _core +from cupyx.scipy.special._loggamma import loggamma_definition + + +_gamma_body = """ + + if (isinf(in0) && in0 < 0) { + out0 = -1.0 / 0.0; + } else if (in0 < 0. && in0 == floor(in0)) { + out0 = 1.0 / 0.0; + } else { + out0 = tgamma(in0); + } +""" + +# Also define a standalone Gamma device function for internal use in other code +# like beta, betaln, etc. +gamma_definition = f""" + +__noinline__ __device__ double Gamma(double in0) +{{ + double out0; + {_gamma_body} + return out0; +}} +""" + +cgamma_definition = loggamma_definition + """ + +// Compute Gamma(z) using loggamma. + +__device__ complex cgamma(complex z) +{ + if ((z.real() <= 0.0) && (z == floor(z.real()))){ + // Poles + return complex(CUDART_NAN, CUDART_NAN); + } + return exp(loggamma(z)); +} +""" + + +gamma = _core.create_ufunc( + 'cupyx_scipy_gamma', + ( + 'f->f', + 'd->d', + ('F->F', 'out0 = out0_type(cgamma(in0))'), + ('D->D', 'out0 = cgamma(in0)') + ), + _gamma_body, + preamble=cgamma_definition, + doc="""Gamma function. + + Args: + z (cupy.ndarray): The input of gamma function. + + Returns: + cupy.ndarray: Computed value of gamma function. + + .. seealso:: :func:`scipy.special.gamma` + + """) + +# Kernel fusion involves preambles concatenating so +# if there are several kernels that depend on the same cpp function, +# compiler throws an error because of duplicates +# ifndef allows to fixes it as compiler throw all duplicates away +chbevl_implementation = """ +#ifndef chbevl_defined +#define chbevl_defined +template +__device__ T chbevl(T x, T array[], int n) +{ + T b0, b1, b2, *p; + int i; + + p = array; + b0 = *p++; + b1 = 0.0; + i = n - 1; + + do { + b2 = b1; + b1 = b0; + b0 = x * b1 - b2 + *p++; + } + while (--i); + + return (0.5 * (b0 - b2)); +} +#endif + +""" + + +rgamma_implementation = chbevl_implementation + """ + +#include + +#define MAXLOG 7.09782712893383996732E2 +#define NPY_PI 3.141592653589793238462643383279502884 + + +/* Chebyshev coefficients for reciprocal Gamma function + * in interval 0 to 1. Function is 1/(x Gamma(x)) - 1 + */ + +__device__ double R[] = { + 3.13173458231230000000E-17, + -6.70718606477908000000E-16, + 2.20039078172259550000E-15, + 2.47691630348254132600E-13, + -6.60074100411295197440E-12, + 5.13850186324226978840E-11, + 1.08965386454418662084E-9, + -3.33964630686836942556E-8, + 2.68975996440595483619E-7, + 2.96001177518801696639E-6, + -8.04814124978471142852E-5, + 4.16609138709688864714E-4, + 5.06579864028608725080E-3, + -6.41925436109158228810E-2, + -4.98558728684003594785E-3, + 1.27546015610523951063E-1 +}; + + +/* + * Reciprocal Gamma function + */ +__device__ double rgamma(double x) +{ + double w, y, z; + int sign; + + if (x > 34.84425627277176174) { + return exp(-lgamma(x)); + } + if (x < -34.034) { + w = -x; + z = sinpi(w); + if (z == 0.0) { + return 0.0; + } + if (z < 0.0) { + sign = 1; + z = -z; + } else { + sign = -1; + } + y = log(w * z) - log(NPY_PI) + lgamma(w); + if (y < -MAXLOG) { + return sign * 0.0; + } + if (y > MAXLOG) { + return sign * CUDART_INF; + } + return sign * exp(y); + } + z = 1.0; + w = x; + while (w > 1.0) { /* Downward recurrence */ + w -= 1.0; + z *= w; + } + while (w < 0.0) { /* Upward recurrence */ + z /= w; + w += 1.0; + } + if (w == 0.0) { /* Nonpositive integer */ + return 0.0; + } + if (w == 1.0) { /* Other integer */ + return 1.0 / z; + } + y = w * (1.0 + chbevl(4.0 * w - 2.0, R, 16)) / z; + return y; +} + +""" + + +crgamma_implementation = loggamma_definition + """ + +// Compute 1/Gamma(z) using loggamma + +__device__ complex crgamma(complex z) +{ + + if ((z.real() <= 0) && (z == floor(z.real()))){ + // Zeros at 0, -1, -2, ... + return complex(0.0, 0.0); + } + return exp(-loggamma(z)); // complex exp via Thrust +} +""" + + +rgamma = _core.create_ufunc( + 'cupyx_scipy_rgamma', + ( + 'f->f', + 'd->d', + ('F->F', 'out0 = out0_type(crgamma(in0))'), + ('D->D', 'out0 = crgamma(in0)') + ), + 'out0 = out0_type(rgamma(in0))', + preamble=rgamma_implementation + crgamma_implementation, + doc="""Reciprocal gamma function. + + Args: + z (cupy.ndarray): The input to the rgamma function. + + Returns: + cupy.ndarray: Computed value of the rgamma function. + + .. seealso:: :func:`scipy.special.rgamma` + + """) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_gammainc.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_gammainc.py new file mode 100644 index 0000000000000000000000000000000000000000..f52b7732d3c73ca960756d48ec51e4a70f8afdc3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_gammainc.py @@ -0,0 +1,1144 @@ +""" +The source code here is an adaptation with minimal changes from the following +files in SciPy's bundled Cephes library: + +https://github.com/scipy/scipy/blob/master/scipy/special/cephes/const.c +https://github.com/scipy/scipy/blob/master/scipy/special/cephes/igam.c +https://github.com/scipy/scipy/blob/master/scipy/special/cephes/igam.h +https://github.com/scipy/scipy/blob/master/scipy/special/cephes/igami.c +https://github.com/scipy/scipy/blob/master/scipy/special/cephes/lanczos.c +https://github.com/scipy/scipy/blob/master/scipy/special/cephes/lanczos.h +https://github.com/scipy/scipy/blob/master/scipy/special/cephes/mconf.h +https://github.com/scipy/scipy/blob/master/scipy/special/cephes/polevl.h +https://github.com/scipy/scipy/blob/master/scipy/special/cephes/unity.c + +Cephes Math Library Release 2.0: April, 1987 +Copyright 1984, 1987 by Stephen L. Moshier +Direct inquiries to 30 Frost Street, Cambridge, MA 02140 +""" + +from cupy import _core + +from cupyx.scipy.special._digamma import polevl_definition +from cupyx.scipy.special._gamma import gamma_definition +from cupyx.scipy.special._zeta import zeta_definition + +_zeta_c = zeta_definition +# comment out duplicate MACHEP definition +_zeta_c = _zeta_c.replace( + "__constant__ double MACHEP", "// __constant__ double MACHEP" +) + + +# TODO: finish + +# See the following on error states: +# docs.scipy.org/doc/scipy/reference/generated/scipy.special.errstate.html +# scipy/special/sf_error.h + +# TODO: which value for MACHEP, MAXLOG from const.c to use? + +_misc_preamble = """ + +// include for CUDART_NAN, CUDART_INF +#include + +// defines from /scipy/special/cephes/const.c +__constant__ double MACHEP = 1.11022302462515654042E-16; +__constant__ double MAXLOG = 7.09782712893383996732E2; + +// defines from numpy/core/include/numpy/npy_math.h +#define NPY_EULER 0.577215664901532860606512090082402431 /* Euler constant */ +#define NPY_PI 3.141592653589793238462643383279502884 /* pi */ +#define NPY_SQRT2 1.414213562373095048801688724209698079 /* sqrt(2) */ +#define NPY_SQRT1_2 0.707106781186547524400844362104849039 /* 1/sqrt(2) */ + +// from /scipy/special/cephes/mconf.h +#ifdef MAXITER +#undef MAXITER +#endif + +#define MAXITER 2000 +#define IGAM 1 +#define IGAMC 0 +#define SMALL 20 +#define LARGE 200 +#define SMALLRATIO 0.3 +#define LARGERATIO 4.5 + +__constant__ double big = 4.503599627370496e15; +__constant__ double biginv = 2.22044604925031308085e-16; + +""" + + +# Note: p1evl -> followed the template style used for polevl in digamma.py +p1evl_definition = """ +template static __device__ double p1evl(double x, const double coef[]) +{ + double ans; + const double *p; + int i; + + p = coef; + ans = x + *p++; + + for (i = 0; i < N - 1; ++i){ + ans = ans * x + *p++; + } + + return ans; +} +""" + +lgam_definition = """ +// define lgam, using CUDA's lgamma as done for cupyx.scipy.special.gammaln +__device__ double lgam(double x) +{ + if (isinf(x) && x < 0) { + return -1.0 / 0.0; + } else { + return lgamma(x); + } +} +""" + +# lgam1p from unity.c +_unity_c_partial = ( + _zeta_c + + lgam_definition + + polevl_definition + + p1evl_definition + + """ +// part of cephes/unity.c + + +/* log(1 + x) - x */ +#ifdef __HIP_DEVICE_COMPILE__ +// For some reason ROCm 4.3 crashes with the noinline in this function +__device__ double log1pmx(double x) +#else +__noinline__ __device__ double log1pmx(double x) +#endif +{ + if (fabs(x) < 0.5) { + int n; + double xfac = x; + double term; + double res = 0; + + for(n = 2; n < MAXITER; n++) { + xfac *= -x; + term = xfac / n; + res += term; + if (fabs(term) < MACHEP * fabs(res)) { + break; + } + } + return res; + } + else { + return log1p(x) - x; + } +} + + +/* Compute lgam(x + 1) around x = 0 using its Taylor series. */ +__noinline__ __device__ double lgam1p_taylor(double x) +{ + int n; + double xfac, coeff, res; + + if (x == 0) { + return 0; + } + res = -NPY_EULER * x; + xfac = -x; + for (n = 2; n < 42; n++) { + xfac *= -x; + coeff = zeta(n, 1) * xfac / n; + res += coeff; + if (fabs(coeff) < MACHEP * fabs(res)) { + break; + } + } + + return res; +} + + +/* Compute lgam(x + 1). */ +__noinline__ __device__ double lgam1p(double x) +{ + if (fabs(x) <= 0.5) { + return lgam1p_taylor(x); + } else if (fabs(x - 1) < 0.5) { + return log(x) + lgam1p_taylor(x - 1); + } else { + return lgam(x + 1); + } +} + + +""" +) + +ratevl_definition = """ +// from scipy/special/cephes/polevl.h + +/* Evaluate a rational function. See [1]. */ + +static __device__ double ratevl(double x, const double num[], int M, + const double denom[], int N) +{ + int i, dir; + double y, num_ans, denom_ans; + double absx = fabs(x); + const double *p; + + if (absx > 1) { + /* Evaluate as a polynomial in 1/x. */ + dir = -1; + p = num + M; + y = 1 / x; + } else { + dir = 1; + p = num; + y = x; + } + + /* Evaluate the numerator */ + num_ans = *p; + p += dir; + for (i = 1; i <= M; i++) { + num_ans = num_ans * y + *p; + p += dir; + } + + /* Evaluate the denominator */ + if (absx > 1) { + p = denom + N; + } else { + p = denom; + } + + denom_ans = *p; + p += dir; + for (i = 1; i <= N; i++) { + denom_ans = denom_ans * y + *p; + p += dir; + } + + if (absx > 1) { + i = N - M; + return pow(x, (double)i) * num_ans / denom_ans; + } else { + return num_ans / denom_ans; + } +} +""" + +_lanczos_h = """ +// from scipy/special/cephes/lanczos.h + +__constant__ double lanczos_num[13] = { + 2.506628274631000270164908177133837338626, + 210.8242777515793458725097339207133627117, + 8071.672002365816210638002902272250613822, + 186056.2653952234950402949897160456992822, + 2876370.628935372441225409051620849613599, + 31426415.58540019438061423162831820536287, + 248874557.8620541565114603864132294232163, + 1439720407.311721673663223072794912393972, + 6039542586.35202800506429164430729792107, + 17921034426.03720969991975575445893111267, + 35711959237.35566804944018545154716670596, + 42919803642.64909876895789904700198885093, + 23531376880.41075968857200767445163675473 +}; + +__constant__ double lanczos_denom[13] = { + 1, + 66, + 1925, + 32670, + 357423, + 2637558, + 13339535, + 45995730, + 105258076, + 150917976, + 120543840, + 39916800, + 0 +}; + +__constant__ double lanczos_sum_expg_scaled_num[13] = { + 0.006061842346248906525783753964555936883222, + 0.5098416655656676188125178644804694509993, + 19.51992788247617482847860966235652136208, + 449.9445569063168119446858607650988409623, + 6955.999602515376140356310115515198987526, + 75999.29304014542649875303443598909137092, + 601859.6171681098786670226533699352302507, + 3481712.15498064590882071018964774556468, + 14605578.08768506808414169982791359218571, + 43338889.32467613834773723740590533316085, + 86363131.28813859145546927288977868422342, + 103794043.1163445451906271053616070238554, + 56906521.91347156388090791033559122686859 +}; + +__constant__ double lanczos_sum_expg_scaled_denom[13] = { + 1, + 66, + 1925, + 32670, + 357423, + 2637558, + 13339535, + 45995730, + 105258076, + 150917976, + 120543840, + 39916800, + 0 +}; + +__constant__ double lanczos_sum_near_1_d[12] = { + 0.3394643171893132535170101292240837927725e-9, + -0.2499505151487868335680273909354071938387e-8, + 0.8690926181038057039526127422002498960172e-8, + -0.1933117898880828348692541394841204288047e-7, + 0.3075580174791348492737947340039992829546e-7, + -0.2752907702903126466004207345038327818713e-7, + -0.1515973019871092388943437623825208095123e-5, + 0.004785200610085071473880915854204301886437, + -0.1993758927614728757314233026257810172008, + 1.483082862367253753040442933770164111678, + -3.327150580651624233553677113928873034916, + 2.208709979316623790862569924861841433016 +}; + +__constant__ double lanczos_sum_near_2_d[12] = { + 0.1009141566987569892221439918230042368112e-8, + -0.7430396708998719707642735577238449585822e-8, + 0.2583592566524439230844378948704262291927e-7, + -0.5746670642147041587497159649318454348117e-7, + 0.9142922068165324132060550591210267992072e-7, + -0.8183698410724358930823737982119474130069e-7, + -0.4506604409707170077136555010018549819192e-5, + 0.01422519127192419234315002746252160965831, + -0.5926941084905061794445733628891024027949, + 4.408830289125943377923077727900630927902, + -9.8907772644920670589288081640128194231, + 6.565936202082889535528455955485877361223 +}; + +__constant__ double lanczos_g = 6.024680040776729583740234375; +""" + +_lanczos_preamble = ( + ratevl_definition + + _lanczos_h + + """ + +// from scipy/special/cephes/lanczos.c + +__device__ double lanczos_sum(double x) +{ + return ratevl(x, lanczos_num, + sizeof(lanczos_num) / sizeof(lanczos_num[0]) - 1, + lanczos_denom, + sizeof(lanczos_denom) / sizeof(lanczos_denom[0]) - 1); +} + + +__device__ double lanczos_sum_expg_scaled(double x) +{ + return ratevl(x, lanczos_sum_expg_scaled_num, + sizeof(lanczos_sum_expg_scaled_num) + / sizeof(lanczos_sum_expg_scaled_num[0]) - 1, + lanczos_sum_expg_scaled_denom, + sizeof(lanczos_sum_expg_scaled_denom) + / sizeof(lanczos_sum_expg_scaled_denom[0]) - 1); +} + + +__device__ double lanczos_sum_near_1(double dx) +{ + double result = 0; + unsigned k; + + for (k = 1; + k <= sizeof(lanczos_sum_near_1_d) / sizeof(lanczos_sum_near_1_d[0]); + ++k) { + result += (-lanczos_sum_near_1_d[k-1]*dx)/(k*dx + k*k); + } + return result; +} + + +__device__ double lanczos_sum_near_2(double dx) +{ + double result = 0; + double x = dx + 2; + unsigned k; + + for(k = 1; + k <= sizeof(lanczos_sum_near_2_d) / sizeof(lanczos_sum_near_2_d[0]); + ++k) { + result += (-lanczos_sum_near_2_d[k-1]*dx)/(x + k*x + k*k - 1); + } + return result; +} + +""" +) + +# add predefined array from igam.h +_igam_h = """ + +// from scipy/special/cephes/igam.h + +#define d_K 25 +#define d_N 25 + +__device__ static const double d[d_K][d_N] = +{{-3.3333333333333333e-1, 8.3333333333333333e-2, -1.4814814814814815e-2, 1.1574074074074074e-3, 3.527336860670194e-4, -1.7875514403292181e-4, 3.9192631785224378e-5, -2.1854485106799922e-6, -1.85406221071516e-6, 8.296711340953086e-7, -1.7665952736826079e-7, 6.7078535434014986e-9, 1.0261809784240308e-8, -4.3820360184533532e-9, 9.1476995822367902e-10, -2.551419399494625e-11, -5.8307721325504251e-11, 2.4361948020667416e-11, -5.0276692801141756e-12, 1.1004392031956135e-13, 3.3717632624009854e-13, -1.3923887224181621e-13, 2.8534893807047443e-14, -5.1391118342425726e-16, -1.9752288294349443e-15}, +{-1.8518518518518519e-3, -3.4722222222222222e-3, 2.6455026455026455e-3, -9.9022633744855967e-4, 2.0576131687242798e-4, -4.0187757201646091e-7, -1.8098550334489978e-5, 7.6491609160811101e-6, -1.6120900894563446e-6, 4.6471278028074343e-9, 1.378633446915721e-7, -5.752545603517705e-8, 1.1951628599778147e-8, -1.7543241719747648e-11, -1.0091543710600413e-9, 4.1627929918425826e-10, -8.5639070264929806e-11, 6.0672151016047586e-14, 7.1624989648114854e-12, -2.9331866437714371e-12, 5.9966963656836887e-13, -2.1671786527323314e-16, -4.9783399723692616e-14, 2.0291628823713425e-14, -4.13125571381061e-15}, +{4.1335978835978836e-3, -2.6813271604938272e-3, 7.7160493827160494e-4, 2.0093878600823045e-6, -1.0736653226365161e-4, 5.2923448829120125e-5, -1.2760635188618728e-5, 3.4235787340961381e-8, 1.3721957309062933e-6, -6.298992138380055e-7, 1.4280614206064242e-7, -2.0477098421990866e-10, -1.4092529910867521e-8, 6.228974084922022e-9, -1.3670488396617113e-9, 9.4283561590146782e-13, 1.2872252400089318e-10, -5.5645956134363321e-11, 1.1975935546366981e-11, -4.1689782251838635e-15, -1.0940640427884594e-12, 4.6622399463901357e-13, -9.905105763906906e-14, 1.8931876768373515e-17, 8.8592218725911273e-15}, +{6.4943415637860082e-4, 2.2947209362139918e-4, -4.6918949439525571e-4, 2.6772063206283885e-4, -7.5618016718839764e-5, -2.3965051138672967e-7, 1.1082654115347302e-5, -5.6749528269915966e-6, 1.4230900732435884e-6, -2.7861080291528142e-11, -1.6958404091930277e-7, 8.0994649053880824e-8, -1.9111168485973654e-8, 2.3928620439808118e-12, 2.0620131815488798e-9, -9.4604966618551322e-10, 2.1541049775774908e-10, -1.388823336813903e-14, -2.1894761681963939e-11, 9.7909989511716851e-12, -2.1782191880180962e-12, 6.2088195734079014e-17, 2.126978363279737e-13, -9.3446887915174333e-14, 2.0453671226782849e-14}, +{-8.618882909167117e-4, 7.8403922172006663e-4, -2.9907248030319018e-4, -1.4638452578843418e-6, 6.6414982154651222e-5, -3.9683650471794347e-5, 1.1375726970678419e-5, 2.5074972262375328e-10, -1.6954149536558306e-6, 8.9075075322053097e-7, -2.2929348340008049e-7, 2.956794137544049e-11, 2.8865829742708784e-8, -1.4189739437803219e-8, 3.4463580499464897e-9, -2.3024517174528067e-13, -3.9409233028046405e-10, 1.8602338968504502e-10, -4.356323005056618e-11, 1.2786001016296231e-15, 4.6792750266579195e-12, -2.1492464706134829e-12, 4.9088156148096522e-13, -6.3385914848915603e-18, -5.0453320690800944e-14}, +{-3.3679855336635815e-4, -6.9728137583658578e-5, 2.7727532449593921e-4, -1.9932570516188848e-4, 6.7977804779372078e-5, 1.419062920643967e-7, -1.3594048189768693e-5, 8.0184702563342015e-6, -2.2914811765080952e-6, -3.252473551298454e-10, 3.4652846491085265e-7, -1.8447187191171343e-7, 4.8240967037894181e-8, -1.7989466721743515e-14, -6.3061945000135234e-9, 3.1624176287745679e-9, -7.8409242536974293e-10, 5.1926791652540407e-15, 9.3589442423067836e-11, -4.5134262161632782e-11, 1.0799129993116827e-11, -3.661886712685252e-17, -1.210902069055155e-12, 5.6807435849905643e-13, -1.3249659916340829e-13}, +{5.3130793646399222e-4, -5.9216643735369388e-4, 2.7087820967180448e-4, 7.9023532326603279e-7, -8.1539693675619688e-5, 5.6116827531062497e-5, -1.8329116582843376e-5, -3.0796134506033048e-9, 3.4651553688036091e-6, -2.0291327396058604e-6, 5.7887928631490037e-7, 2.338630673826657e-13, -8.8286007463304835e-8, 4.7435958880408128e-8, -1.2545415020710382e-8, 8.6496488580102925e-14, 1.6846058979264063e-9, -8.5754928235775947e-10, 2.1598224929232125e-10, -7.6132305204761539e-16, -2.6639822008536144e-11, 1.3065700536611057e-11, -3.1799163902367977e-12, 4.7109761213674315e-18, 3.6902800842763467e-13}, +{3.4436760689237767e-4, 5.1717909082605922e-5, -3.3493161081142236e-4, 2.812695154763237e-4, -1.0976582244684731e-4, -1.2741009095484485e-7, 2.7744451511563644e-5, -1.8263488805711333e-5, 5.7876949497350524e-6, 4.9387589339362704e-10, -1.0595367014026043e-6, 6.1667143761104075e-7, -1.7562973359060462e-7, -1.2974473287015439e-12, 2.695423606288966e-8, -1.4578352908731271e-8, 3.887645959386175e-9, -3.8810022510194121e-17, -5.3279941738772867e-10, 2.7437977643314845e-10, -6.9957960920705679e-11, 2.5899863874868481e-17, 8.8566890996696381e-12, -4.403168815871311e-12, 1.0865561947091654e-12}, +{-6.5262391859530942e-4, 8.3949872067208728e-4, -4.3829709854172101e-4, -6.969091458420552e-7, 1.6644846642067548e-4, -1.2783517679769219e-4, 4.6299532636913043e-5, 4.5579098679227077e-9, -1.0595271125805195e-5, 6.7833429048651666e-6, -2.1075476666258804e-6, -1.7213731432817145e-11, 3.7735877416110979e-7, -2.1867506700122867e-7, 6.2202288040189269e-8, 6.5977038267330006e-16, -9.5903864974256858e-9, 5.2132144922808078e-9, -1.3991589583935709e-9, 5.382058999060575e-16, 1.9484714275467745e-10, -1.0127287556389682e-10, 2.6077347197254926e-11, -5.0904186999932993e-18, -3.3721464474854592e-12}, +{-5.9676129019274625e-4, -7.2048954160200106e-5, 6.7823088376673284e-4, -6.4014752602627585e-4, 2.7750107634328704e-4, 1.8197008380465151e-7, -8.4795071170685032e-5, 6.105192082501531e-5, -2.1073920183404862e-5, -8.8585890141255994e-10, 4.5284535953805377e-6, -2.8427815022504408e-6, 8.7082341778646412e-7, 3.6886101871706965e-12, -1.5344695190702061e-7, 8.862466778790695e-8, -2.5184812301826817e-8, -1.0225912098215092e-14, 3.8969470758154777e-9, -2.1267304792235635e-9, 5.7370135528051385e-10, -1.887749850169741e-19, -8.0931538694657866e-11, 4.2382723283449199e-11, -1.1002224534207726e-11}, +{1.3324454494800656e-3, -1.9144384985654775e-3, 1.1089369134596637e-3, 9.932404122642299e-7, -5.0874501293093199e-4, 4.2735056665392884e-4, -1.6858853767910799e-4, -8.1301893922784998e-9, 4.5284402370562147e-5, -3.127053674781734e-5, 1.044986828530338e-5, 4.8435226265680926e-11, -2.1482565873456258e-6, 1.329369701097492e-6, -4.0295693092101029e-7, -1.7567877666323291e-13, 7.0145043163668257e-8, -4.040787734999483e-8, 1.1474026743371963e-8, 3.9642746853563325e-18, -1.7804938269892714e-9, 9.7480262548731646e-10, -2.6405338676507616e-10, 5.794875163403742e-18, 3.7647749553543836e-11}, +{1.579727660730835e-3, 1.6251626278391582e-4, -2.0633421035543276e-3, 2.1389686185689098e-3, -1.0108559391263003e-3, -3.9912705529919201e-7, 3.6235025084764691e-4, -2.8143901463712154e-4, 1.0449513336495887e-4, 2.1211418491830297e-9, -2.5779417251947842e-5, 1.7281818956040463e-5, -5.6413773872904282e-6, -1.1024320105776174e-11, 1.1223224418895175e-6, -6.8693396379526735e-7, 2.0653236975414887e-7, 4.6714772409838506e-14, -3.5609886164949055e-8, 2.0470855345905963e-8, -5.8091738633283358e-9, -1.332821287582869e-16, 9.0354604391335133e-10, -4.9598782517330834e-10, 1.3481607129399749e-10}, +{-4.0725121195140166e-3, 6.4033628338080698e-3, -4.0410161081676618e-3, -2.183732802866233e-6, 2.1740441801254639e-3, -1.9700440518418892e-3, 8.3595469747962458e-4, 1.9445447567109655e-8, -2.5779387120421696e-4, 1.9009987368139304e-4, -6.7696499937438965e-5, -1.4440629666426572e-10, 1.5712512518742269e-5, -1.0304008744776893e-5, 3.304517767401387e-6, 7.9829760242325709e-13, -6.4097794149313004e-7, 3.8894624761300056e-7, -1.1618347644948869e-7, -2.816808630596451e-15, 1.9878012911297093e-8, -1.1407719956357511e-8, 3.2355857064185555e-9, 4.1759468293455945e-20, -5.0423112718105824e-10}, +{-5.9475779383993003e-3, -5.4016476789260452e-4, 8.7910413550767898e-3, -9.8576315587856125e-3, 5.0134695031021538e-3, 1.2807521786221875e-6, -2.0626019342754683e-3, 1.7109128573523058e-3, -6.7695312714133799e-4, -6.9011545676562133e-9, 1.8855128143995902e-4, -1.3395215663491969e-4, 4.6263183033528039e-5, 4.0034230613321351e-11, -1.0255652921494033e-5, 6.612086372797651e-6, -2.0913022027253008e-6, -2.0951775649603837e-13, 3.9756029041993247e-7, -2.3956211978815887e-7, 7.1182883382145864e-8, 8.925574873053455e-16, -1.2101547235064676e-8, 6.9350618248334386e-9, -1.9661464453856102e-9}, +{1.7402027787522711e-2, -2.9527880945699121e-2, 2.0045875571402799e-2, 7.0289515966903407e-6, -1.2375421071343148e-2, 1.1976293444235254e-2, -5.4156038466518525e-3, -6.3290893396418616e-8, 1.8855118129005065e-3, -1.473473274825001e-3, 5.5515810097708387e-4, 5.2406834412550662e-10, -1.4357913535784836e-4, 9.9181293224943297e-5, -3.3460834749478311e-5, -3.5755837291098993e-12, 7.1560851960630076e-6, -4.5516802628155526e-6, 1.4236576649271475e-6, 1.8803149082089664e-14, -2.6623403898929211e-7, 1.5950642189595716e-7, -4.7187514673841102e-8, -6.5107872958755177e-17, 7.9795091026746235e-9}, +{3.0249124160905891e-2, 2.4817436002649977e-3, -4.9939134373457022e-2, 5.9915643009307869e-2, -3.2483207601623391e-2, -5.7212968652103441e-6, 1.5085251778569354e-2, -1.3261324005088445e-2, 5.5515262632426148e-3, 3.0263182257030016e-8, -1.7229548406756723e-3, 1.2893570099929637e-3, -4.6845138348319876e-4, -1.830259937893045e-10, 1.1449739014822654e-4, -7.7378565221244477e-5, 2.5625836246985201e-5, 1.0766165333192814e-12, -5.3246809282422621e-6, 3.349634863064464e-6, -1.0381253128684018e-6, -5.608909920621128e-15, 1.9150821930676591e-7, -1.1418365800203486e-7, 3.3654425209171788e-8}, +{-9.9051020880159045e-2, 1.7954011706123486e-1, -1.2989606383463778e-1, -3.1478872752284357e-5, 9.0510635276848131e-2, -9.2828824411184397e-2, 4.4412112839877808e-2, 2.7779236316835888e-7, -1.7229543805449697e-2, 1.4182925050891573e-2, -5.6214161633747336e-3, -2.39598509186381e-9, 1.6029634366079908e-3, -1.1606784674435773e-3, 4.1001337768153873e-4, 1.8365800754090661e-11, -9.5844256563655903e-5, 6.3643062337764708e-5, -2.076250624489065e-5, -1.1806020912804483e-13, 4.2131808239120649e-6, -2.6262241337012467e-6, 8.0770620494930662e-7, 6.0125912123632725e-16, -1.4729737374018841e-7}, +{-1.9994542198219728e-1, -1.5056113040026424e-2, 3.6470239469348489e-1, -4.6435192311733545e-1, 2.6640934719197893e-1, 3.4038266027147191e-5, -1.3784338709329624e-1, 1.276467178337056e-1, -5.6213828755200985e-2, -1.753150885483011e-7, 1.9235592956768113e-2, -1.5088821281095315e-2, 5.7401854451350123e-3, 1.0622382710310225e-9, -1.5335082692563998e-3, 1.0819320643228214e-3, -3.7372510193945659e-4, -6.6170909729031985e-12, 8.4263617380909628e-5, -5.5150706827483479e-5, 1.7769536448348069e-5, 3.8827923210205533e-14, -3.53513697488768e-6, 2.1865832130045269e-6, -6.6812849447625594e-7}, +{7.2438608504029431e-1, -1.3918010932653375, 1.0654143352413968, 1.876173868950258e-4, -8.2705501176152696e-1, 8.9352433347828414e-1, -4.4971003995291339e-1, -1.6107401567546652e-6, 1.9235590165271091e-1, -1.6597702160042609e-1, 6.8882222681814333e-2, 1.3910091724608687e-8, -2.146911561508663e-2, 1.6228980898865892e-2, -5.9796016172584256e-3, -1.1287469112826745e-10, 1.5167451119784857e-3, -1.0478634293553899e-3, 3.5539072889126421e-4, 8.1704322111801517e-13, -7.7773013442452395e-5, 5.0291413897007722e-5, -1.6035083867000518e-5, 1.2469354315487605e-14, 3.1369106244517615e-6}, +{1.6668949727276811, 1.165462765994632e-1, -3.3288393225018906, 4.4692325482864037, -2.6977693045875807, -2.600667859891061e-4, 1.5389017615694539, -1.4937962361134612, 6.8881964633233148e-1, 1.3077482004552385e-6, -2.5762963325596288e-1, 2.1097676102125449e-1, -8.3714408359219882e-2, -7.7920428881354753e-9, 2.4267923064833599e-2, -1.7813678334552311e-2, 6.3970330388900056e-3, 4.9430807090480523e-11, -1.5554602758465635e-3, 1.0561196919903214e-3, -3.5277184460472902e-4, 9.3002334645022459e-14, 7.5285855026557172e-5, -4.8186515569156351e-5, 1.5227271505597605e-5}, +{-6.6188298861372935, 1.3397985455142589e+1, -1.0789350606845146e+1, -1.4352254537875018e-3, 9.2333694596189809, -1.0456552819547769e+1, 5.5105526029033471, 1.2024439690716742e-5, -2.5762961164755816, 2.3207442745387179, -1.0045728797216284, -1.0207833290021914e-7, 3.3975092171169466e-1, -2.6720517450757468e-1, 1.0235252851562706e-1, 8.4329730484871625e-10, -2.7998284958442595e-2, 2.0066274144976813e-2, -7.0554368915086242e-3, 1.9402238183698188e-12, 1.6562888105449611e-3, -1.1082898580743683e-3, 3.654545161310169e-4, -5.1290032026971794e-11, -7.6340103696869031e-5}, +{-1.7112706061976095e+1, -1.1208044642899116, 3.7131966511885444e+1, -5.2298271025348962e+1, 3.3058589696624618e+1, 2.4791298976200222e-3, -2.061089403411526e+1, 2.088672775145582e+1, -1.0045703956517752e+1, -1.2238783449063012e-5, 4.0770134274221141, -3.473667358470195, 1.4329352617312006, 7.1359914411879712e-8, -4.4797257159115612e-1, 3.4112666080644461e-1, -1.2699786326594923e-1, -2.8953677269081528e-10, 3.3125776278259863e-2, -2.3274087021036101e-2, 8.0399993503648882e-3, -1.177805216235265e-9, -1.8321624891071668e-3, 1.2108282933588665e-3, -3.9479941246822517e-4}, +{7.389033153567425e+1, -1.5680141270402273e+2, 1.322177542759164e+2, 1.3692876877324546e-2, -1.2366496885920151e+2, 1.4620689391062729e+2, -8.0365587724865346e+1, -1.1259851148881298e-4, 4.0770132196179938e+1, -3.8210340013273034e+1, 1.719522294277362e+1, 9.3519707955168356e-7, -6.2716159907747034, 5.1168999071852637, -2.0319658112299095, -4.9507215582761543e-9, 5.9626397294332597e-1, -4.4220765337238094e-1, 1.6079998700166273e-1, -2.4733786203223402e-8, -4.0307574759979762e-2, 2.7849050747097869e-2, -9.4751858992054221e-3, 6.419922235909132e-6, 2.1250180774699461e-3}, +{2.1216837098382522e+2, 1.3107863022633868e+1, -4.9698285932871748e+2, 7.3121595266969204e+2, -4.8213821720890847e+2, -2.8817248692894889e-2, 3.2616720302947102e+2, -3.4389340280087117e+2, 1.7195193870816232e+2, 1.4038077378096158e-4, -7.52594195897599e+1, 6.651969984520934e+1, -2.8447519748152462e+1, -7.613702615875391e-7, 9.5402237105304373, -7.5175301113311376, 2.8943997568871961, -4.6612194999538201e-7, -8.0615149598794088e-1, 5.8483006570631029e-1, -2.0845408972964956e-1, 1.4765818959305817e-4, 5.1000433863753019e-2, -3.3066252141883665e-2, 1.5109265210467774e-2}, +{-9.8959643098322368e+2, 2.1925555360905233e+3, -1.9283586782723356e+3, -1.5925738122215253e-1, 1.9569985945919857e+3, -2.4072514765081556e+3, 1.3756149959336496e+3, 1.2920735237496668e-3, -7.525941715948055e+2, 7.3171668742208716e+2, -3.4137023466220065e+2, -9.9857390260608043e-6, 1.3356313181291573e+2, -1.1276295161252794e+2, 4.6310396098204458e+1, -7.9237387133614756e-6, -1.4510726927018646e+1, 1.1111771248100563e+1, -4.1690817945270892, 3.1008219800117808e-3, 1.1220095449981468, -7.6052379926149916e-1, 3.6262236505085254e-1, 2.216867741940747e-1, 4.8683443692930507e-1}}; + +""" + +# add functions from igam.c +_igam_preamble = ( + _misc_preamble + + _unity_c_partial + + _lanczos_preamble + + _igam_h + + """ + +// from scipy/special/cephes/igam.c + +/* Compute igam/igamc using DLMF 8.12.3/8.12.4. */ +__noinline__ __device__ double asymptotic_series(double a, double x, int func) +{ + int k, n, sgn; + int maxpow = 0; + double lambda = x / a; + double sigma = (x - a) / a; + double eta, res, ck, ckterm, term, absterm; + double absoldterm = CUDART_INF; + double etapow[d_N] = {1}; + double sum = 0; + double afac = 1; + + if (func == IGAM) { + sgn = -1; + } else { + sgn = 1; + } + + if (lambda > 1) { + eta = sqrt(-2 * log1pmx(sigma)); + } else if (lambda < 1) { + eta = -sqrt(-2 * log1pmx(sigma)); + } else { + eta = 0; + } + res = 0.5 * erfc(sgn * eta * sqrt(a / 2)); + + for (k = 0; k < d_K; k++) { + ck = d[k][0]; + for (n = 1; n < d_N; n++) { + if (n > maxpow) { + etapow[n] = eta * etapow[n-1]; + maxpow += 1; + } + ckterm = d[k][n]*etapow[n]; + ck += ckterm; + if (fabs(ckterm) < MACHEP * fabs(ck)) { + break; + } + } + term = ck * afac; + absterm = fabs(term); + if (absterm > absoldterm) { + break; + } + sum += term; + if (absterm < MACHEP * fabs(sum)) { + break; + } + absoldterm = absterm; + afac /= a; + } + res += sgn * exp(-0.5 * a * eta * eta) * sum / sqrt(2 * NPY_PI * a); + + return res; +} + + +/* Compute igamc using DLMF 8.7.3. This is related to the series in + * igam_series but extra care is taken to avoid cancellation. + */ +__noinline__ __device__ double igamc_series(double a, double x) +{ + int n; + double fac = 1; + double sum = 0; + double term, logx; + + for (n = 1; n < MAXITER; n++) { + fac *= -x / n; + term = fac / (a + n); + sum += term; + if (fabs(term) <= MACHEP * fabs(sum)) { + break; + } + } + + logx = log(x); + term = -expm1(a * logx - lgam1p(a)); + return term - exp(a * logx - lgam(a)) * sum; +} + + +/* Compute + * + * x^a * exp(-x) / gamma(a) + * + * corrected from (15) and (16) in [2] by replacing exp(x - a) with + * exp(a - x). + */ +__noinline__ __device__ double igam_fac(double a, double x) +{ + double ax, fac, res, num; + + if (fabs(a - x) > 0.4 * fabs(a)) { + ax = a * log(x) - x - lgam(a); + if (ax < -MAXLOG) { + // sf_error("igam", SF_ERROR_UNDERFLOW, NULL); + return 0.0; + } + return exp(ax); + } + + fac = a + lanczos_g - 0.5; + res = sqrt(fac / exp(1.)) / lanczos_sum_expg_scaled(a); + + if ((a < 200) && (x < 200)) { + res *= exp(a - x) * pow(x / fac, a); + } else { + num = x - a - lanczos_g + 0.5; + res *= exp(a * log1pmx(num / fac) + x * (0.5 - lanczos_g) / fac); + } + + return res; +} + + +/* Compute igamc using DLMF 8.9.2. */ +__noinline__ __device__ double igamc_continued_fraction(double a, double x) +{ + int i; + double ans, ax, c, yc, r, t, y, z; + double pk, pkm1, pkm2, qk, qkm1, qkm2; + + ax = igam_fac(a, x); + if (ax == 0.0) { + return 0.0; + } + + /* continued fraction */ + y = 1.0 - a; + z = x + y + 1.0; + c = 0.0; + pkm2 = 1.0; + qkm2 = x; + pkm1 = x + 1.0; + qkm1 = z * x; + ans = pkm1 / qkm1; + + for (i = 0; i < MAXITER; i++) { + c += 1.0; + y += 1.0; + z += 2.0; + yc = y * c; + pk = pkm1 * z - pkm2 * yc; + qk = qkm1 * z - qkm2 * yc; + if (qk != 0) { + r = pk / qk; + t = fabs((ans - r) / r); + ans = r; + } + else + t = 1.0; + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + if (fabs(pk) > big) { + pkm2 *= biginv; + pkm1 *= biginv; + qkm2 *= biginv; + qkm1 *= biginv; + } + if (t <= MACHEP) { + break; + } + } + + return (ans * ax); +} + + +/* Compute igam using DLMF 8.11.4. */ +__noinline__ __device__ double igam_series(double a, double x) +{ + int i; + double ans, ax, c, r; + + ax = igam_fac(a, x); + if (ax == 0.0) { + return 0.0; + } + + /* power series */ + r = a; + c = 1.0; + ans = 1.0; + + for (i = 0; i < MAXITER; i++) { + r += 1.0; + c *= x / r; + ans += c; + if (c <= MACHEP * ans) { + break; + } + } + + return (ans * ax / a); +} + +__noinline__ __device__ double igamc(double a, double x) +{ + double absxma_a; + + if (x < 0 || a < 0) { + // sf_error("gammaincc", SF_ERROR_DOMAIN, NULL); + return CUDART_NAN; + } else if (a == 0) { + if (x > 0) { + return 0; + } else { + return CUDART_NAN; + } + } else if (x == 0) { + return 1; + } else if (isinf(a)) { + if (isinf(x)) { + return CUDART_NAN; + } + return 1; + } else if (isinf(x)) { + return 0; + } + + /* Asymptotic regime where a ~ x; see [2]. */ + absxma_a = fabs(x - a) / a; + if ((a > SMALL) && (a < LARGE) && (absxma_a < SMALLRATIO)) { + return asymptotic_series(a, x, IGAMC); + } else if ((a > LARGE) && (absxma_a < LARGERATIO / sqrt(a))) { + return asymptotic_series(a, x, IGAMC); + } + + /* Everywhere else; see [2]. */ + if (x > 1.1) { + if (x < a) { + return 1.0 - igam_series(a, x); + } else { + return igamc_continued_fraction(a, x); + } + } else if (x <= 0.5) { + if (-0.4 / log(x) < a) { + return 1.0 - igam_series(a, x); + } else { + return igamc_series(a, x); + } + } else { + if (x * 1.1 < a) { + return 1.0 - igam_series(a, x); + } else { + return igamc_series(a, x); + } + } +} + + +__noinline__ __device__ double igam(double a, double x) +{ + double absxma_a; + + if (x < 0 || a < 0) { + // sf_error("gammainc", SF_ERROR_DOMAIN, NULL); + return CUDART_NAN; + } else if (a == 0) { + if (x > 0) { + return 1; + } else { + return CUDART_NAN; + } + } else if (x == 0) { + /* Zero integration limit */ + return 0; + } else if (isinf(a)) { + if (isinf(x)) { + return CUDART_NAN; + } + return 0; + } else if (isinf(x)) { + return 1; + } + + /* Asymptotic regime where a ~ x; see [2]. */ + absxma_a = fabs(x - a) / a; + if ((a > SMALL) && (a < LARGE) && (absxma_a < SMALLRATIO)) { + return asymptotic_series(a, x, IGAM); + } else if ((a > LARGE) && (absxma_a < LARGERATIO / sqrt(a))) { + return asymptotic_series(a, x, IGAM); + } + + if ((x > 1.0) && (x > a)) { + return (1.0 - igamc(a, x)); + } + + return igam_series(a, x); +} + + +""" +) + + +_igami_preamble = ( + _igam_preamble + + gamma_definition + + """ + +// from scipy/special/cephes/igami.c + +__noinline__ __device__ double igamci(double a, double q); +__noinline__ __device__ double igami(double a, double q); + +__noinline__ __device__ double find_inverse_s(double p, double q) +{ + /* + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + * + * See equation 32. + */ + double s, t; + double a[4] = {0.213623493715853, 4.28342155967104, + 11.6616720288968, 3.31125922108741}; + double b[5] = {0.3611708101884203e-1, 1.27364489782223, + 6.40691597760039, 6.61053765625462, 1}; + + if (p < 0.5) { + t = sqrt(-2 * log(p)); + } + else { + t = sqrt(-2 * log(q)); + } + s = t - polevl<3>(t, a) / polevl<4>(t, b); + if(p < 0.5) + s = -s; + return s; +} + + +__noinline__ __device__ double didonato_SN(double a, double x, unsigned N, double tolerance) +{ + /* + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + * + * See equation 34. + */ + double sum = 1.0; + + if (N >= 1) { + unsigned i; + double partial = x / (a + 1); + + sum += partial; + for(i = 2; i <= N; ++i) { + partial *= x / (a + i); + sum += partial; + if(partial < tolerance) { + break; + } + } + } + return sum; +} + + +__noinline__ __device__ double find_inverse_gamma(double a, double p, double q) +{ + /* + * In order to understand what's going on here, you will + * need to refer to: + * + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + */ + double result; + + if (a == 1) { + if (q > 0.9) { + result = -log1p(-p); + } + else { + result = -log(q); + } + } + else if (a < 1) { + double g = Gamma(a); + double b = q * g; + + if ((b > 0.6) || ((b >= 0.45) && (a >= 0.3))) { + /* DiDonato & Morris Eq 21: + * + * There is a slight variation from DiDonato and Morris here: + * the first form given here is unstable when p is close to 1, + * making it impossible to compute the inverse of Q(a,x) for small + * q. Fortunately the second form works perfectly well in this case. + */ + double u; + if((b * q > 1e-8) && (q > 1e-5)) { + u = pow(p * g * a, 1 / a); + } + else { + u = exp((-q / a) - NPY_EULER); + } + result = u / (1 - (u / (a + 1))); + } + else if ((a < 0.3) && (b >= 0.35)) { + /* DiDonato & Morris Eq 22: */ + double t = exp(-NPY_EULER - b); + double u = t * exp(t); + result = t * exp(u); + } + else if ((b > 0.15) || (a >= 0.3)) { + /* DiDonato & Morris Eq 23: */ + double y = -log(b); + double u = y - (1 - a) * log(y); + result = y - (1 - a) * log(u) - log(1 + (1 - a) / (1 + u)); + } + else if (b > 0.1) { + /* DiDonato & Morris Eq 24: */ + double y = -log(b); + double u = y - (1 - a) * log(y); + result = y - (1 - a) * log(u) + - log((u * u + 2 * (3 - a) * u + (2 - a) * (3 - a)) + / (u * u + (5 - a) * u + 2)); + } + else { + /* DiDonato & Morris Eq 25: */ + double y = -log(b); + double c1 = (a - 1) * log(y); + double c1_2 = c1 * c1; + double c1_3 = c1_2 * c1; + double c1_4 = c1_2 * c1_2; + double a_2 = a * a; + double a_3 = a_2 * a; + + double c2 = (a - 1) * (1 + c1); + double c3 = (a - 1) * (-(c1_2 / 2) + + (a - 2) * c1 + + (3 * a - 5) / 2); + double c4 = (a - 1) * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + + (a_2 - 6 * a + 7) * c1 + + (11 * a_2 - 46 * a + 47) / 6); + double c5 = (a - 1) + * (-(c1_4 / 4) + + (11 * a - 17) * c1_3 / 6 + + (-3 * a_2 + 13 * a -13) * c1_2 + + (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 + + (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12); + + double y_2 = y * y; + double y_3 = y_2 * y; + double y_4 = y_2 * y_2; + result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4); + } + } + else { + /* DiDonato and Morris Eq 31: */ + double s = find_inverse_s(p, q); + + double s_2 = s * s; + double s_3 = s_2 * s; + double s_4 = s_2 * s_2; + double s_5 = s_4 * s; + double ra = sqrt(a); + + double w = a + s * ra + (s_2 - 1) / 3; + w += (s_3 - 7 * s) / (36 * ra); + w -= (3 * s_4 + 7 * s_2 - 16) / (810 * a); + w += (9 * s_5 + 256 * s_3 - 433 * s) / (38880 * a * ra); + + if ((a >= 500) && (fabs(1 - w / a) < 1e-6)) { + result = w; + } + else if (p > 0.5) { + if (w < 3 * a) { + result = w; + } + else { + double D = fmax(2, a * (a - 1)); + double lg = lgam(a); + double lb = log(q) + lg; + if (lb < -D * 2.3) { + /* DiDonato and Morris Eq 25: */ + double y = -lb; + double c1 = (a - 1) * log(y); + double c1_2 = c1 * c1; + double c1_3 = c1_2 * c1; + double c1_4 = c1_2 * c1_2; + double a_2 = a * a; + double a_3 = a_2 * a; + + double c2 = (a - 1) * (1 + c1); + double c3 = (a - 1) * (-(c1_2 / 2) + + (a - 2) * c1 + + (3 * a - 5) / 2); + double c4 = (a - 1) * ((c1_3 / 3) + - (3 * a - 5) * c1_2 / 2 + + (a_2 - 6 * a + 7) * c1 + + (11 * a_2 - 46 * a + 47) / 6); + double c5 = (a - 1) * (-(c1_4 / 4) + + (11 * a - 17) * c1_3 / 6 + + (-3 * a_2 + 13 * a -13) * c1_2 + + (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 + + (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12); + + double y_2 = y * y; + double y_3 = y_2 * y; + double y_4 = y_2 * y_2; + result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + + (c5 / y_4); + } + else { + /* DiDonato and Morris Eq 33: */ + double u = -lb + (a - 1) * log(w) + - log(1 + (1 - a) / (1 + w)); + result = -lb + (a - 1) * log(u) + - log(1 + (1 - a) / (1 + u)); + } + } + } + else { + double z = w; + double ap1 = a + 1; + double ap2 = a + 2; + if (w < 0.15 * ap1) { + /* DiDonato and Morris Eq 35: */ + double v = log(p) + lgam(ap1); + z = exp((v + w) / a); + s = log1p(z / ap1 * (1 + z / ap2)); + z = exp((v + z - s) / a); + s = log1p(z / ap1 * (1 + z / ap2)); + z = exp((v + z - s) / a); + s = log1p(z / ap1 * (1 + z / ap2 * (1 + z / (a + 3)))); + z = exp((v + z - s) / a); + } + + if ((z <= 0.01 * ap1) || (z > 0.7 * ap1)) { + result = z; + } + else { + /* DiDonato and Morris Eq 36: */ + double ls = log(didonato_SN(a, z, 100, 1e-4)); + double v = log(p) + lgam(ap1); + z = exp((v + z - ls) / a); + result = z * (1 - (a * log(z) - z - v + ls) / (a - z)); + } + } + } + return result; +} + + +__noinline__ __device__ double igamci(double a, double q) +{ + int i; + double x, fac, f_fp, fpp_fp; + + if (isnan(a) || isnan(q)) { + return CUDART_NAN; + } + else if ((a < 0.0) || (q < 0.0) || (q > 1.0)) { + // sf_error("gammainccinv", SF_ERROR_DOMAIN, NULL); + } + else if (q == 0.0) { + return CUDART_INF; + } + else if (q == 1.0) { + return 0.0; + } + else if (q > 0.9) { + return igami(a, 1 - q); + } + + x = find_inverse_gamma(a, 1 - q, q); + for (i = 0; i < 3; i++) { + fac = igam_fac(a, x); + if (fac == 0.0) { + return x; + } + f_fp = (igamc(a, x) - q) * x / (-fac); + fpp_fp = -1.0 + (a - 1) / x; + if (isinf(fpp_fp)) { + x = x - f_fp; + } + else { + x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp); + } + } + + return x; +} + + +__noinline__ __device__ double igami(double a, double p) +{ + int i; + double x, fac, f_fp, fpp_fp; + + if (isnan(a) || isnan(p)) { + return CUDART_NAN; + } + else if ((a < 0) || (p < 0) || (p > 1)) { + // sf_error("gammaincinv", SF_ERROR_DOMAIN, NULL); + } + else if (p == 0.0) { + return 0.0; + } + else if (p == 1.0) { + return CUDART_INF; + } + else if (p > 0.9) { + return igamci(a, 1 - p); + } + x = find_inverse_gamma(a, p, 1 - p); + /* Halley's method */ + for (i = 0; i < 3; i++) { + fac = igam_fac(a, x); + if (fac == 0.0) { + return x; + } + f_fp = (igam(a, x) - p) * x / fac; + // The ratio of the first and second derivatives simplifies + fpp_fp = -1.0 + (a - 1) / x; + if (isinf(fpp_fp)) { + // Resort to Newton's method in the case of overflow + x = x - f_fp; + } + else { + x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp); + } + } + + return x; +} + +""" +) + + +gammaincc = _core.create_ufunc( + "cupyx_scipy_gammaincc", + ("ff->f", "dd->d"), + "out0 = out0_type(igamc(in0, in1));", + preamble=_igam_preamble, + doc="""Elementwise function for scipy.special.gammaincc + + Regularized upper incomplete gamma function. + + .. seealso:: :meth:`scipy.special.gammaincc` + """, +) + + +gammainc = _core.create_ufunc( + "cupyx_scipy_gammainc", + ("ff->f", "dd->d"), + "out0 = out0_type(igam(in0, in1));", + preamble=_igam_preamble, + doc="""Elementwise function for scipy.special.gammainc + + Regularized lower incomplete gamma function. + + .. seealso:: :meth:`scipy.special.gammainc` + """, +) + + +gammainccinv = _core.create_ufunc( + "cupyx_scipy_gammainccinv", + ("ff->f", "dd->d"), + "out0 = out0_type(igamci(in0, in1));", + preamble=_igami_preamble, + doc="""Elementwise function for scipy.special.gammainccinv + + Inverse to gammaincc. + + .. seealso:: :meth:`scipy.special.gammainccinv` + """, +) + + +gammaincinv = _core.create_ufunc( + "cupyx_scipy_gammaincinv", + ("ff->f", "dd->d"), + "out0 = out0_type(igami(in0, in1));", + preamble=_igami_preamble, + doc="""Elementwise function for scipy.special.gammaincinv + + Inverse to gammainc. + + .. seealso:: :meth:`scipy.special.gammaincinv` + """, +) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_gammaln.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_gammaln.py new file mode 100644 index 0000000000000000000000000000000000000000..da538151bdf752290a224f564c2b2eda978507ab --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_gammaln.py @@ -0,0 +1,65 @@ +import math + +import cupy +from cupy import _core + + +gammaln = _core.create_ufunc( + 'cupyx_scipy_special_gammaln', ('f->f', 'd->d'), + ''' + if (isinf(in0) && in0 < 0) { + out0 = -1.0 / 0.0; + } else { + out0 = lgamma(in0); + } + ''', + doc="""Logarithm of the absolute value of the Gamma function. + + Args: + x (cupy.ndarray): Values on the real line at which to compute + ``gammaln``. + + Returns: + cupy.ndarray: Values of ``gammaln`` at x. + + .. seealso:: :data:`scipy.special.gammaln` + + """) + + +def multigammaln(a, d): + r"""Returns the log of multivariate gamma, also sometimes called the + generalized gamma. + + Parameters + ---------- + a : cupy.ndarray + The multivariate gamma is computed for each item of `a`. + d : int + The dimension of the space of integration. + + Returns + ------- + res : ndarray + The values of the log multivariate gamma at the given points `a`. + + See Also + -------- + :func:`scipy.special.multigammaln` + + """ + if not cupy.isscalar(d) or (math.floor(d) != d): + raise ValueError("d should be a positive integer (dimension)") + if cupy.isscalar(a): + a = cupy.asarray(a, dtype=float) + if int(cupy.any(a <= 0.5 * (d - 1))): + raise ValueError("condition a > 0.5 * (d-1) not met") + res = (d * (d - 1) * 0.25) * math.log(math.pi) + gam0 = gammaln(a) + if a.dtype.kind != 'f': + # make sure all integer dtypes do the summation with float64 + gam0 = gam0.astype(cupy.float64) + res = res + gam0 + for j in range(2, d + 1): + res += gammaln(a - (j - 1.0) / 2) + return res diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_loggamma.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_loggamma.py new file mode 100644 index 0000000000000000000000000000000000000000..0a659c3e626f5e82f14d80b7fb63d3e08661f26d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_loggamma.py @@ -0,0 +1,229 @@ +""" +The source code here is an adaptation with minimal changes from the following +SciPy files: + +https://github.com/scipy/scipy/blob/master/scipy/special/_complexstuff.pxd +https://github.com/scipy/scipy/blob/master/scipy/special/_evalpoly.pxd +https://github.com/scipy/scipy/blob/master/scipy/special/_loggamma.pxd + +""" + +from cupy import _core +from cupyx.scipy.special._complexstuff import zlog1_definition +from cupyx.scipy.special._trig import csinpi_definition + + +ceval_poly_definition = """ + +/* Evaluate polynomials. + * + * + * All of the coefficients are stored in reverse order, i.e. if the + * polynomial is + * + * u_n x^n + u_{n - 1} x^{n - 1} + ... + u_0, + * + * then coeffs[0] = u_n, coeffs[1] = u_{n - 1}, ..., coeffs[n] = u_0. + * + * References + * ---------- + * [1] Knuth, 'The Art of Computer Programming, Volume II' + * + */ + +/* Evaluate a polynomial with real coefficients at a complex point. + * Uses equation (3) in section 4.6.4 of [1]. Note that it is more + * efficient than Horner's method. + */ +__device__ complex cevalpoly(double *coeffs, int degree, + complex z) +{ + int j; + double a = coeffs[0]; + double b = coeffs[1]; + double r = 2*z.real(); + double s = z.real()*z.real() + z.imag()*z.imag(); + double tmp; + for (j=2; j<=degree; j++) + { + tmp = b; + b = fma(-s, a, coeffs[j]); + a = fma(r, a, tmp); + } + return z*a + b; +} +""" + + +loggamma_real_definition = """ + +#include + +__device__ double loggamma_real(double x) +{ + if (x < 0.0) { + return CUDART_NAN; + } else { + return lgamma(x); + } +} + +""" + + +loggamma_definition = ( + ceval_poly_definition + + zlog1_definition + + csinpi_definition + + loggamma_real_definition + + """ + +#include + +#define TWOPI 6.2831853071795864769252842 // 2*pi +#define LOGPI 1.1447298858494001741434262 // log(pi) +#define HLOG2PI 0.918938533204672742 // log(2*pi)/2 +#define SMALLX 7.0 +#define SMALLY 7.0 +#define TAYLOR_RADIUS 0.2 + +__device__ complex loggamma_recurrence(complex); +__device__ complex loggamma_stirling(complex); +__device__ complex loggamma_taylor(complex); + + +// Compute the principal branch of log-Gamma + +__noinline__ __device__ complex loggamma(complex z) +{ + double tmp; + if (isnan(z)) { + return complex(CUDART_NAN, CUDART_NAN); + } else if ((z.real() <= 0) && (z == floor(z.real()))) { + return complex(CUDART_NAN, CUDART_NAN); + } else if ((z.real() > SMALLX) || (fabs(z.imag()) > SMALLY)) { + return loggamma_stirling(z); + } else if (abs(z - 1.0) <= TAYLOR_RADIUS) { + return loggamma_taylor(z); + } else if (abs(z - 2.0) <= TAYLOR_RADIUS) { + // Recurrence relation and the Taylor series around 1 + return zlog1(z - 1.0) + loggamma_taylor(z - 1.0); + } else if (z.real() < 0.1) { + // Reflection formula; see Proposition 3.1 in [1] + tmp = copysign(TWOPI, z.imag())*floor(0.5*z.real() + 0.25); + complex ctemp(LOGPI, tmp); + return ctemp - log(csinpi(z)) - loggamma(1.0 - z); + } else if (signbit(z.imag()) == 0.0) { + // z.imag() >= 0 but is not -0.0 + return loggamma_recurrence(z); + } else { + return conj(loggamma_recurrence(conj(z))); + } +} + + +/* Backward recurrence relation. + * + * See Proposition 2.2 in [1] and the Julia implementation [2]. + */ +__noinline__ __device__ complex loggamma_recurrence(complex z) +{ + int signflips = 0; + int sb = 0; + int nsb; + complex shiftprod = z; + z += 1.0; + while(z.real() <= SMALLX) { + shiftprod *= z; + nsb = signbit(shiftprod.imag()); + if (nsb != 0 and sb == 0) { + signflips += 1; + } + sb = nsb; + z += 1.0; + } + complex ctemp(0.0, -signflips*TWOPI); + return loggamma_stirling(z) - log(shiftprod) + ctemp; +} + + +/* Stirling series for log-Gamma. + * + * The coefficients are B[2*n]/(2*n*(2*n - 1)) where B[2*n] is the + * (2*n)th Bernoulli number. See (1.1) in [1]. + */ +__device__ complex loggamma_stirling(complex z) +{ + double coeffs[] = { + -2.955065359477124183e-2, 6.4102564102564102564e-3, + -1.9175269175269175269e-3, 8.4175084175084175084e-4, + -5.952380952380952381e-4, 7.9365079365079365079e-4, + -2.7777777777777777778e-3, 8.3333333333333333333e-2 + }; + complex rz = 1.0/z; + complex rzz = rz/z; + return (z - 0.5)*log(z) - z + HLOG2PI + rz*cevalpoly(coeffs, 7, rzz); +} + + +/* Taylor series for log-Gamma around z = 1. + * + * It is + * + * loggamma(z + 1) = -gamma*z + zeta(2)*z**2/2 - zeta(3)*z**3/3 ... + * + * where gamma is the Euler-Mascheroni constant. + */ +__device__ complex loggamma_taylor(complex z) +{ + double coeffs[] = { + -4.3478266053040259361e-2, 4.5454556293204669442e-2, + -4.7619070330142227991e-2, 5.000004769810169364e-2, + -5.2631679379616660734e-2, 5.5555767627403611102e-2, + -5.8823978658684582339e-2, 6.2500955141213040742e-2, + -6.6668705882420468033e-2, 7.1432946295361336059e-2, + -7.6932516411352191473e-2, 8.3353840546109004025e-2, + -9.0954017145829042233e-2, 1.0009945751278180853e-1, + -1.1133426586956469049e-1, 1.2550966952474304242e-1, + -1.4404989676884611812e-1, 1.6955717699740818995e-1, + -2.0738555102867398527e-1, 2.7058080842778454788e-1, + -4.0068563438653142847e-1, 8.2246703342411321824e-1, + -5.7721566490153286061e-1 + }; + + z = z - 1.0; + return z*cevalpoly(coeffs, 22, z); +} + +""") + + +loggamma = _core.create_ufunc( + 'cupyx_scipy_loggamma', + ( + ('f->f', 'out0 = out0_type(loggamma_real(in0))'), + ('d->d', 'out0 = loggamma_real(in0)'), + 'F->F', + 'D->D' + ), + 'out0 = out0_type(loggamma(in0))', + preamble=loggamma_definition, + doc="""Principal branch of the logarithm of the gamma function. + + Parameters + ---------- + z : cupy.ndarray + Values in the complex plain at which to compute loggamma + out : cupy.ndarray, optional + Output array for computed values of loggamma + + Returns + ------- + cupy.ndarray + Values of loggamma at z. + + See Also + -------- + :func:`scipy.special.loggamma` + """, +) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_logsumexp.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_logsumexp.py new file mode 100644 index 0000000000000000000000000000000000000000..8477363c539be0f22aa917f108964241bc85f6d0 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_logsumexp.py @@ -0,0 +1,75 @@ +import cupy as cp + + +def logsumexp(a, axis=None, b=None, keepdims=False, return_sign=False): + """Compute the log of the sum of exponentials of input elements. + + Parameters + ---------- + a : cupy.ndarray + Input array + axis : None or int or tuple of ints, optional + Axis or axes over which the sum is taken. By default + `axis` is None, and all elements are summed + keepdims : bool, optional + If this is set to True, the axes which are reduced + are left in the result as dimensions with size one. With + this option, the result will broadcast correctly + against the original array + b : cupy.ndarray, optional + Scaling factor for exp(`a`) must be of the same shape as `a` or + broadcastable to `a`. These values may be negative in order to + implement subtraction + return_sign : bool, optional + If this is set to True, the result will be a pair containing sign + information; if False, results that are negative will be returned + as NaN. Default is False + + Returns + ------- + res : cupy.ndarray + The result, ``cp.log(cp.sum(cp.exp(a)))`` calculated + in a numerically more stable way. If `b` is given then + ``cp.log(cp.sum(b*cp.exp(a)))`` is returned + sgn : cupy.ndarray + If return_sign is True, this will be an array of floating-point + numbers matching res and +1, 0, or -1 depending on the sign of + the result. If False, only one result is returned. + + See Also + -------- + scipy.special.logsumexp + + """ + if b is not None: + a, b = cp.broadcast_arrays(a, b) + if cp.any(b == 0): + a = a + 0. # promote to at least float + a[b == 0] = -cp.inf + + a_max = cp.max(a, axis=axis, keepdims=True) + + if a_max.ndim > 0: + a_max[~cp.isfinite(a_max)] = 0 + elif not cp.isfinite(a_max): + a_max = 0 + + if b is not None: + tmp = b * cp.exp(a - a_max) + else: + tmp = cp.exp(a - a_max) + + s = cp.sum(tmp, axis=axis, keepdims=keepdims) + if return_sign: + sgn = cp.sign(s) + s *= sgn + out = cp.log(s) + + if not keepdims: + a_max = cp.squeeze(a_max, axis=axis) + out += a_max + + if return_sign: + return out, sgn + else: + return out diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_lpmv.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_lpmv.py new file mode 100644 index 0000000000000000000000000000000000000000..e2a767d7d35cc63c733d283305e945078859b693 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_lpmv.py @@ -0,0 +1,417 @@ +""" +The source code here is an adaptation with minimal changes from the following +files in SciPy: + +https://github.com/scipy/scipy/blob/master/scipy/special/specfun_wrappers.c + +Code for psi_spec, gamma2, lpmv0, lpmv was manually translated to C++ from +SciPy's Fortran-77 code located in: +https://github.com/scipy/scipy/blob/master/scipy/special/specfun/specfun.f + +The fortran code in scipy originated in the following book. + + "Computation of Special Functions", 1996, John Wiley & Sons, Inc. + + Shanjie Zhang and Jianming Jin + + Copyrighted but permission granted to use code in programs. +""" + +from cupy import _core + +# May want to use CUDART_PI instead of redefining here. +# The two seem to differ in the last didit, though. +# #define CUDART_PI 3.1415926535897931e+0 + +nan_inf = """ +// include for CUDART_NAN, CUDART_INF +#include + +""" + + +lpmv_definition = """ + +// include for CUDART_NAN, CUDART_INF +#include + +// CUDA C++ translation of code from: +// https://github.com/scipy/scipy/blob/master/scipy/special/specfun/specfun.f + +/* + * Purpose: Compute Psi function + * Input : x --- Argument of psi(x) + */ +__device__ double psi_spec(double x) +{ + double xa = fabs(x); + double PI = 3.1415926535897930; + double EL = 0.5772156649015329; // Euler-Mascheroni constant + double s = 0.; + double ps; + int n = 0; + if ((x - (int)x == 0.) && (x <= 0.)) + { + return CUDART_INF; + } else if (xa - (int)xa == 0.) { + n = (int) xa; + for (int k=1; k <= n - 1; k++) + { + s += 1.0/k; + } + ps = -EL + s; + } else if ((xa - 0.5) - (int)(xa - 0.5) == 0.) { + n = (int)(xa - 0.5); + for (int k=1; k <= n; k++) + { + s += 1.0/(2.0*k - 1.0); + } + ps = -EL + 2.0 * s - 1.386294361119891; + } else { + if (xa < 10.0) + { + n = 10 - (int)(xa); + for (int k=1; k < n; k++) + { + s += 1.0/(xa + k); + } + xa += (double)n; + } + double x2 = 1.0 / (xa*xa); + double a1 = -.8333333333333e-01; + double a2 = .83333333333333333e-02; + double a3 = -.39682539682539683e-02; + double a4 = .41666666666666667e-02; + double a5 = -.75757575757575758e-02; + double a6 = .21092796092796093e-01; + double a7 = -.83333333333333333e-01; + double a8 = .44325980392156860; + ps = log(xa) - 0.5/xa + x2*(((((((a8*x2 + a7)*x2 + + a6)*x2 + a5)*x2 + a4)*x2 + a3)*x2 + a2)*x2 + a1); + ps -= s; + } + if (x < 0.) { + ps = ps - PI*cos(PI*x)/sin(PI*x) - 1.0/x; + } + return ps; +} + + +/* + * Purpose: Compute gamma function Gamma(x) + * Input : x --- Argument of Gamma(x) + * ( x is not equal to 0,-1,-2,...) + * Output: GA --- Gamma(x) + */ +__device__ double gamma2(double x) +{ + double ga; + double G[26] = {1.0, 0.5772156649015329, + -0.6558780715202538, -0.420026350340952e-1, + 0.1665386113822915,-.421977345555443e-1, + -.96219715278770e-2, .72189432466630e-2, + -.11651675918591e-2, -.2152416741149e-3, + .1280502823882e-3, -.201348547807e-4, + -.12504934821e-5, .11330272320e-5, + -.2056338417e-6, .61160950e-8, + .50020075e-8, -.11812746e-8, + .1043427e-9, .77823e-11, + -.36968e-11, .51e-12, + -.206e-13, -.54e-14, .14e-14, .1e-15}; + double PI = 3.141592653589793; + int k; + if ((x - (int)x) == 0.) + { + if (x > 0.) + { + ga = 1.0; + for (k=2; k < x; k++) + { + ga *= k; + } + } else + { + ga = CUDART_INF; + } + } + else + { + double r = 1.0; + double z = fabs(x); + if (z > 1.0){ + int m = (int)z; + for (k=1; k<=m; k++) + { + r *= (z - k); + } + z -= m; + } else { + z = x; + } + double gr = G[24]; + for (k=25; k>=1; k--) + { + gr = gr*z + G[k]; + } + ga = 1.0 / (gr * z); + if (fabs(x) > 1.0) + { + ga *= r; + if (x < 0.0) + { + ga = -PI / (x*ga*sin(PI*x)); + } + } + } + return ga; +} + + +/* + * Purpose: Compute the associated Legendre function + * Pmv(x) with an integer order and an arbitrary + * nonnegative degree v + * Input : x --- Argument of Pm(x) ( -1 <= x <= 1 ) + * m --- Order of Pmv(x) + * v --- Degree of Pmv(x) + */ +__device__ double lpmv0(double v, double m, double x) +{ + double pmv, r; + int j, k; + + double PI = 3.141592653589793; + double EL = .5772156649015329; // Euler-Mascheroni constant + double EPS = 1.0e-14; + int nv = (int)v; + double v0 = v - nv; + if ((x == -1.0) && (v != nv)) + { + if (m == 0) + return -CUDART_INF; + else + return CUDART_INF; + } + double c0 = 1.0; + if (m != 0) + { + double rg = v*(v + m); + for (j=1; j < m; j++) + { + rg *= (v*v - j*j); + } + double xq = sqrt(1.0 - x*x); + + double r0 = 1.0; + for (j=1; j <= m; j++) + { + r0 *= 0.5*xq/j; + } + c0 = r0*rg; + } + if (v0 == 0.) + { + // DLMF 14.3.4, 14.7.17, 15.2.4 + pmv = 1.0; + r = 1.0; + for (k=1; k <= nv - m; k++) + { + r *= 0.5*(-nv + m + k - 1.0)*(nv + m + k)/(k*(k + m))*(1.0 + x); + pmv += r; + } + pmv *= c0; + if ((nv % 2) == 1) + { + pmv = -pmv; + } + } + else + { + if (x >= -0.35) + { + // DLMF 14.3.4, 15.2.1 + pmv = 1.0; + r = 1.0; + for (k = 1; k <= 100; k++) + { + r *= 0.5*(-v + m + k - 1.0)*(v + m + k)/(k*(m + k))*(1.0 - x); + pmv += r; + if ((k > 12) & (fabs(r/pmv) < EPS)){ + break; + } + + } + pmv *= c0; + if (((int)m % 2) == 1) + { + pmv = -pmv; + } + } + else + { + // DLMF 14.3.5, 15.8.10 + double vs = sin(v * PI) / PI; + double pv0 = 0.0; + double r2; + if (m != 0) + { + double qr = sqrt((1.0 - x)/(1.0 + x)); + r2 = 1.0; + for (j = 1; j <= m; j++) + { + r2 *= qr*j; + } + double s0 = 1.0; + double r1 = 1.0; + for (k = 1; k < m; k++) + { + r1=0.5*r1*(-v + k - 1)*(v + k)/(k*(k - m))*(1.0 + x); + s0 += r1; + } + pv0 = -vs*r2/m*s0; + } + double psv = psi_spec(v); + double pa = 2.0*(psv + EL) + PI/tan(PI*v) + 1.0/v; + double s1 = 0.0; + for (j = 1; j <= m; j++) + { + s1 += (j*j + v*v)/(j*(j*j - v*v)); + } + pmv = pa + s1 - 1.0/(m - v) + log(0.5*(1.0 + x)); + r = 1.0; + for (k = 1; j <= 100; k++) + { + r *= 0.5*(-v + m + k-1.0)*(v + m + k)/(k*(k + m))*(1.0 + x); + double s = 0.0; + for (j = 1; j <= m; j++) + { + double kjsq = (k + j) * (k + j); + s += (kjsq + v*v)/((k + j)*(kjsq - v*v)); + } + double s2 = 0.0; + for (j = 1; j <= k; j++) + { + s2 += 1.0/(j*(j*j - v*v)); + } + double pss = pa + s + 2.0*v*v*s2 - 1.0/(m + k - v) + + log(0.5*(1.0 + x)); + r2 = pss*r; + pmv += r2; + if (fabs(r2/pmv) < EPS) + { + break; + } + } + pmv = pv0 + pmv*vs*c0; + } + } + return pmv; +} + + +/* Purpose: Compute the associated Legendre function + * Pmv(x) with an integer order and an arbitrary + * degree v, using recursion for large degrees + * Input : x --- Argument of Pm(x) ( -1 <= x <= 1 ) + * m --- Order of Pmv(x) + * v --- Degree of Pmv(x) + * Output: PMV --- Pmv(x) + */ +__device__ double lpmv(double v, int m, double x) +{ + double pmv; + int j; + + if ((x == -1.0) && (v != (int)v)) + { + if (m == 0) + { + return -CUDART_INF; + } else + { + return CUDART_INF; + } + } + + double vx = v; + double mx = m; + // DLMF 14.9.5 + if (v < 0) + { + vx = -vx - 1; + } + int neg_m = 0; + if (m < 0) + { + if (((vx + m + 1) > 0) || (vx != (int)vx)) + { + neg_m = 1; + mx = -m; + } + else + { + // We don't handle cases where DLMF 14.9.3 doesn't help + return CUDART_NAN; + } + } + + int nv = (int)vx; + double v0 = vx - nv; + if ((nv > 2) && (nv > mx)) + { + // Up-recursion on degree, AMS 8.5.3 / DLMF 14.10.3 + double p0 = lpmv0(v0 + mx, mx, x); + double p1 = lpmv0(v0 + mx + 1, mx, x); + pmv = p1; + for (j = mx + 2; j <= nv; j++) + { + pmv = ((2*(v0 + j) - 1)*x*p1 - (v0 + j - 1 + mx)*p0) / (v0 + j - mx); + p0 = p1; + p1 = pmv; + } + } + else + { + pmv = lpmv0(vx, mx, x); + } + + if ((neg_m != 0) && (fabs(pmv) < 1.0e300)) + { + double g1 = gamma2(vx - mx + 1); + double g2 = gamma2(vx + mx + 1); + pmv = pmv * g1/g2 * pow(-1, mx); + } + return pmv; +} + + +// pmv_wrap as in +// https://github.com/scipy/scipy/blob/master/scipy/special/specfun_wrappers.c + +__device__ double pmv_wrap(double m, double v, double x){ + int int_m; + double out; + + if (m != floor(m)) + { + return CUDART_NAN; + } + int_m = (int) m; + out = lpmv(v, int_m, x); + // should raise an overflow warning here on INF + return out; +} + +""" + +lpmv = _core.create_ufunc( + "cupyx_scipy_lpmv", + ("fff->f", "ddd->d"), + "out0 = out0_type(pmv_wrap(in0, in1, in2));", + preamble=lpmv_definition, + doc="""Associated Legendre function of integer order and real degree. + + .. seealso:: :meth:`scipy.special.lpmv` + + """, +) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_softmax.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..2ecae0cf584e3a60a1071f227c441b8deb23d116 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_softmax.py @@ -0,0 +1,28 @@ +import cupy + + +def softmax(x, axis=None): + """Softmax function. + + The softmax function transforms each element of a + collection by computing the exponential of each element + divided by the sum of the exponentials of all the elements. + + Parameters + ---------- + x : array-like + The input array + axis : int or tuple of ints, optional + Axis to compute values along. Default is None + + Returns + ------- + s : cupy.ndarray + Returns an array with same shape as input. The result + will sum to 1 along the provided axis + + """ + + x_max = cupy.amax(x, axis=axis, keepdims=True) + exp_x_shifted = cupy.exp(x - x_max) + return exp_x_shifted / cupy.sum(exp_x_shifted, axis=axis, keepdims=True) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_sph_harm.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_sph_harm.py new file mode 100644 index 0000000000000000000000000000000000000000..4af131b67ec7fd50302c4ac33f6068860dbc2880 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_sph_harm.py @@ -0,0 +1,84 @@ +""" +The source code here is an adaptation with minimal changes from the following +SciPy Cython file: + +https://github.com/scipy/scipy/blob/master/scipy/special/sph_harm.pxd +""" + +from cupy import _core + +from cupyx.scipy.special._poch import poch_definition +from cupyx.scipy.special._lpmv import lpmv_definition + +sph_harmonic_definition = ( + poch_definition + + lpmv_definition + + """ + +#include + +// include for CUDART_NAN, CUDART_INF +#include + +#define NPY_PI 3.141592653589793238462643383279502884 /* pi */ + +// from scipy/special/sph_harm.pxd +__device__ complex sph_harmonic(int m, int n, double theta, double phi) +{ + double x, prefactor; + complex val; + int mp; + + x = cos(phi); + if (abs(m) > n) + { + // sf_error.error("sph_harm", sf_error.ARG, + // "m should not be greater than n") + return CUDART_NAN; + } + if (n < 0) + { + // sf_error.error("sph_harm", sf_error.ARG, "n should not be negative") + return CUDART_NAN; + } + if (m < 0) + { + mp = -m; + prefactor = poch(n + mp + 1, -2 * mp); + if ((mp % 2) == 1) + { + prefactor = -prefactor; + } + } + else + { + mp = m; + } + val = pmv_wrap(mp, n, x); + if (m < 0) + { + val *= prefactor; + } + val *= sqrt((2*n + 1) / 4.0 / NPY_PI); + val *= sqrt(poch(n + m + 1, -2 * m)); + + complex exponent(0, m * theta); + val *= exp(exponent); + + return val; +} +""" +) + + +sph_harm = _core.create_ufunc( + "cupyx_scipy_lpmv", + ("iiff->F", "iidd->D", "llff->F", "lldd->D"), + "out0 = out0_type(sph_harmonic(in0, in1, in2, in3));", + preamble=sph_harmonic_definition, + doc="""Spherical Harmonic. + + .. seealso:: :meth:`scipy.special.sph_harm` + + """, +) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_spherical_bessel.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_spherical_bessel.py new file mode 100644 index 0000000000000000000000000000000000000000..d4b7f740f04a7d326edaf7f1199104782a71d0f3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_spherical_bessel.py @@ -0,0 +1,121 @@ +import cupy +from cupy import _core + +spherical_bessel_preamble = """ +#include + +__device__ double spherical_yn_real(int n, double x) { + double s, s0, s1; + + if (isnan(x)) + return x; + if (x < 0) { + if (n % 2 == 0) + return -spherical_yn_real(n, -x); + else + return spherical_yn_real(n, -x); + } + if (isinf(x)) + return 0; + if (x == 0) + return -CUDART_INF; + + s0 = -cos(x) / x; + if (n == 0) { + return s0; + } + s1 = (s0 - sin(x)) / x; + for (int k = 2; k <= n; ++k) { + s = (2.0 * k - 1.0) * s1 / x - s0; + if (isinf(s)) { + return s; + } + s0 = s1; + s1 = s; + } + + return s1; +} + +__device__ double spherical_yn_d_real(int n, double x) { + double s, s0, s1; + + if (isnan(x)) + return x; + if (x < 0) { + if (n % 2 == 0) + return -spherical_yn_d_real(n, -x); + else + return spherical_yn_d_real(n, -x); + } + if (isinf(x)) + return 0; + if (x == 0) + return CUDART_INF; + + if (n == 1) { + return (sin(x) + cos(x) / x) / x; + } + s0 = -cos(x) / x; + s1 = (s0 - sin(x)) / x; + for (int k = 2; k <= n; ++k) { + s = (2.0 * k - 1.0) * s1 / x - s0; + if (isinf(s)) { + return s; + } + s0 = s1; + s1 = s; + } + + return s0 - (n + 1.0) * s1 / x; +} +""" + +_spherical_yn_real = _core.create_ufunc( + "cupyx_scipy_spherical_yn_real", + ("if->d", "id->d"), + "out0 = out0_type(spherical_yn_real(in0, in1))", + preamble=spherical_bessel_preamble, +) + +_spherical_dyn_real = _core.create_ufunc( + "cupyx_scipy_spherical_dyn_real", + ("if->d", "id->d"), + "out0 = out0_type(spherical_yn_d_real(in0, in1));", + preamble=spherical_bessel_preamble, +) + + +def spherical_yn(n, z, derivative=False): + """Spherical Bessel function of the second kind or its derivative. + + Parameters + ---------- + n : cupy.ndarray + Order of the Bessel function. + z : cupy.ndarray + Argument of the Bessel function. + Real-valued input. + derivative : bool, optional + If True, the value of the derivative (rather than the function + itself) is returned. + + Returns + ------- + yn : cupy.ndarray + + See Also + ------- + :func:`scipy.special.spherical_yn` + + """ + if cupy.iscomplexobj(z): + if derivative: + raise NotImplementedError + else: + raise NotImplementedError + else: + if derivative: + return _spherical_dyn_real(n, z) + else: + return _spherical_yn_real(n, z) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_statistics.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..345ad3d7e18f19160c4580b2db87492ec6cf67f7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_statistics.py @@ -0,0 +1,230 @@ +from cupy import _core + + +logit_definition = """ +template +static __device__ T logit(T x) { + x /= 1 - x; + return log(x); +} + +""" + + +logit = _core.create_ufunc( + 'cupy_logit', + ('e->f', 'f->f', 'd->d'), + 'out0 = logit(in0)', + preamble=logit_definition, + doc='''Logit function. + + Args: + x (cupy.ndarray): input data + + Returns: + cupy.ndarray: values of logit(x) + + .. seealso:: :data:`scipy.special.logit` + + ''') + + +expit_definition = """ +template +static __device__ T expit(T x) { + return 1 / (1 + exp(-x)); +} + +""" + + +expit = _core.create_ufunc( + 'cupy_expit', + ('e->f', 'f->f', 'd->d'), + 'out0 = expit(in0)', + preamble=expit_definition, + doc='''Logistic sigmoid function (expit). + + Args: + x (cupy.ndarray): input data (must be real) + + Returns: + cupy.ndarray: values of expit(x) + + .. seealso:: :data:`scipy.special.expit` + + .. note:: + expit is the inverse of logit. + + ''') + + +# log_expit implemented based on log1p as in SciPy's scipy/special/_logit.h + +log_expit_definition = """ +template +static __device__ T log_expit(T x) +{ + if (x < 0.0) { + return x - log1p(exp(x)); + } else { + return -log1p(exp(-x)); + } +} + +""" + + +log_expit = _core.create_ufunc( + 'cupy_log_expit', + ('e->f', 'f->f', 'd->d'), + 'out0 = log_expit(in0)', + preamble=log_expit_definition, + doc='''Logarithm of the logistic sigmoid function. + + Args: + x (cupy.ndarray): input data (must be real) + + Returns: + cupy.ndarray: values of log(expit(x)) + + .. seealso:: :data:`scipy.special.log_expit` + + .. note:: + The function is mathematically equivalent to ``log(expit(x))``, but + is formulated to avoid loss of precision for inputs with large + (positive or negative) magnitude. + ''') + + +boxcox_definition = """ +static __device__ double boxcox(double x, double lmbda) { + // if lmbda << 1 and log(x) < 1.0, the lmbda*log(x) product can lose + // precision, furthermore, expm1(x) == x for x < eps. + // For doubles, the range of log is -744.44 to +709.78, with eps being + // the smallest value produced. This range means that we will have + // abs(lmbda)*log(x) < eps whenever abs(lmbda) <= eps/-log(min double) + // which is ~2.98e-19. + if (fabs(lmbda) < 1e-19) { + return log(x); + } else { + return expm1(lmbda * log(x)) / lmbda; + } +} + +""" + + +boxcox = _core.create_ufunc( + 'cupy_boxcox', + ('ee->f', 'ff->f', 'dd->d'), + 'out0 = out0_type(boxcox(in0, in1))', + preamble=boxcox_definition, + doc='''Compute the Box-Cox transformation. + + Args: + x (cupy.ndarray): input data (must be real) + + Returns: + cupy.ndarray: values of boxcox(x) + + .. seealso:: :data:`scipy.special.boxcox` + + ''') + + +boxcox1p_definition = """ +static __device__ double boxcox1p(double x, double lmbda) { + // The argument given above in boxcox applies here with the modification + // that the smallest value produced by log1p is the minimum representable + // value, rather than eps. The second condition here prevents underflow + // when log1p(x) is < eps. + double lgx = log1p(x); + if ((fabs(lmbda) < 1e-19) + || ((fabs(lgx) < 1e-289) && (fabs(lmbda) < 1e273))) { + return lgx; + } else { + return expm1(lmbda * lgx) / lmbda; + } +} + +""" + + +boxcox1p = _core.create_ufunc( + 'cupy_boxcox1p', + ('ee->f', 'ff->f', 'dd->d'), + 'out0 = out0_type(boxcox1p(in0, in1))', + preamble=boxcox1p_definition, + doc='''Compute the Box-Cox transformation op 1 + `x`. + + Args: + x (cupy.ndarray): input data (must be real) + + Returns: + cupy.ndarray: values of boxcox1p(x) + + .. seealso:: :data:`scipy.special.boxcox1p` + + ''') + + +inv_boxcox_definition = """ +static __device__ double inv_boxcox(double x, double lmbda) { + if (lmbda == 0.0) { + return exp(x); + } else { + return exp(log1p(lmbda * x) / lmbda); + } +} + +""" + + +inv_boxcox = _core.create_ufunc( + 'cupy_inv_boxcox', + ('ee->f', 'ff->f', 'dd->d'), + 'out0 = out0_type(inv_boxcox(in0, in1))', + preamble=inv_boxcox_definition, + doc='''Compute the Box-Cox transformation. + + Args: + x (cupy.ndarray): input data (must be real) + + Returns: + cupy.ndarray: values of inv_boxcox(x) + + .. seealso:: :data:`scipy.special.inv_boxcox` + + ''') + + +inv_boxcox1p_definition = """ +static __device__ double inv_boxcox1p(double x, double lmbda) { + if (lmbda == 0.0) { + return expm1(x); + } else if (fabs(lmbda * x) < 1e-154) { + return x; + } else { + return expm1(log1p(lmbda * x) / lmbda); + } +} + +""" + + +inv_boxcox1p = _core.create_ufunc( + 'cupy_inv_boxcox1p', + ('ee->f', 'ff->f', 'dd->d'), + 'out0 = out0_type(inv_boxcox1p(in0, in1))', + preamble=inv_boxcox1p_definition, + doc='''Compute the Box-Cox transformation op 1 + `x`. + + Args: + x (cupy.ndarray): input data (must be real) + + Returns: + cupy.ndarray: values of inv_boxcox1p(x) + + .. seealso:: :data:`scipy.special.inv_boxcox1p` +''') diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_stats_distributions.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_stats_distributions.py new file mode 100644 index 0000000000000000000000000000000000000000..2d7d4ea040f6dd283aabb21f28d510d2ce002cf4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_stats_distributions.py @@ -0,0 +1,1125 @@ +"""Statistical distribution functions (Beta, Binomial, Poisson, etc.) + +The source code here is an adaptation with minimal changes from the following +files in SciPy's bundled Cephes library: + +https://github.com/scipy/scipy/blob/main/scipy/special/cephes/bdtr.c +https://github.com/scipy/scipy/blob/main/scipy/special/cephes/chdtr.c +https://github.com/scipy/scipy/blob/main/scipy/special/cephes/fdtr.c +https://github.com/scipy/scipy/blob/main/scipy/special/cephes/gdtr.c +https://github.com/scipy/scipy/blob/main/scipy/special/cephes/nbdtr.c +https://github.com/scipy/scipy/blob/main/scipy/special/cephes/pdtr.c + +Cephes Math Library, Release 2.3: March, 1995 +Copyright 1984, 1995 by Stephen L. Moshier +""" + +from cupy import _core +from cupyx.scipy.special._beta import incbet_preamble, incbi_preamble +from cupyx.scipy.special._gammainc import _igam_preamble, _igami_preamble + + +# Normal distribution functions + +ndtr = _core.create_ufunc( + 'cupyx_scipy_special_ndtr', + (('f->f', 'out0 = normcdff(in0)'), 'd->d'), + 'out0 = normcdf(in0)', + doc='''Cumulative distribution function of normal distribution. + + .. seealso:: :data:`scipy.special.ndtr` + + ''') + + +log_ndtr_definition = """ + +#define NPY_SQRT1_2 0.707106781186547524400844362104849039 /* 1/sqrt(2) */ + +static __device__ double log_ndtr(double x) +{ + double t = x * NPY_SQRT1_2; + if (x < -1.0) { + return log(erfcx(-t) / 2) - t * t; + } else { + return log1p(-erfc(t) / 2); + } +} + +static __device__ float log_ndtrf(float x) +{ + float t = x * NPY_SQRT1_2; + if (x < -1.0) { + return logf(erfcxf(-t) / 2) - t * t; + } else { + return log1pf(-erfcf(t) / 2); + } +} + +""" + + +log_ndtr = _core.create_ufunc( + 'cupyx_scipy_special_log_ndtr', + (('f->f', 'out0 = log_ndtrf(in0)'), 'd->d'), + 'out0 = log_ndtr(in0)', + preamble=log_ndtr_definition, + doc="""Logarithm of Gaussian cumulative distribution function. + + Returns the log of the area under the standard Gaussian probability + density function. + + Parameters + ---------- + x : array-like + The input array + + Returns + ------- + y : cupy.ndarray + The value of the log of the normal cumulative distribution + function evaluated at x + + See Also + -------- + :func:`scipy.special.log_ndtr` + + """, +) + + +ndtri = _core.create_ufunc( + 'cupyx_scipy_special_ndtri', + (('f->f', 'out0 = normcdfinvf(in0)'), 'd->d'), + 'out0 = normcdfinv(in0)', + doc='''Inverse of the cumulative distribution function of the standard + normal distribution. + + .. seealso:: :data:`scipy.special.ndtri` +''') + + +# Binomial distribution functions + +bdtr_definition = """ + +__device__ double bdtr(double k, int n, double p) +{ + double dk, dn; + double fk = floor(k); + + if (isnan(p) || isnan(k)) { + return CUDART_NAN; + } + + if (p < 0.0 || p > 1.0 || fk < 0 || n < fk) { + return CUDART_NAN; + } + + if (fk == n) { + return 1.0; + } + + dn = n - fk; + if (fk == 0) { + dk = pow(1.0 - p, dn); + } else { + dk = fk + 1.; + dk = incbet(dn, dk, 1.0 - p); + } + return dk; +} + + +__device__ double bdtr_unsafe(double k, double n, double p) +{ + if (isnan(n) || isinf(n)) { + return CUDART_NAN; + } else { + return bdtr(k, (int)n, p); + } +} + +""" + + +bdtrc_definition = """ + +__device__ double bdtrc(double k, int n, double p) +{ + double dk, dn; + double fk = floor(k); + + if (isnan(p) || isnan(k)) { + return CUDART_NAN; + } + + if (p < 0.0 || p > 1.0 || n < fk) { + return CUDART_NAN; + } + + if (fk < 0) { + return 1.0; + } + + if (fk == n) { + return 0.0; + } + + dn = n - fk; + if (k == 0) { + if (p < .01) { + dk = -expm1(dn * log1p(-p)); + } else { + dk = 1.0 - pow(1.0 - p, dn); + } + } else { + dk = fk + 1; + dk = incbet(dk, dn, p); + } + return dk; +} + +__device__ double bdtrc_unsafe(double k, double n, double p) +{ + if (isnan(n) || isinf(n)) { + return CUDART_NAN; + } else { + return bdtrc(k, (int)n, p); + } +} + +""" + + +bdtri_definition = """ + +__device__ double bdtri(double k, int n, double y) +{ + double p, dn, dk; + double fk = floor(k); + + if (isnan(k)) { + return CUDART_NAN; + } + + if (y < 0.0 || y > 1.0 || fk < 0.0 || n <= fk) { + return CUDART_NAN; + } + + dn = n - fk; + + if (fk == n) { + return 1.0; + } + + if (fk == 0) { + if (y > 0.8) { + p = -expm1(log1p(y - 1.0) / dn); + } else { + p = 1.0 - pow(y, 1.0 / dn); + } + } else { + dk = fk + 1; + p = incbet(dn, dk, 0.5); + if (p > 0.5) { + p = incbi(dk, dn, 1.0 - y); + } else { + p = 1.0 - incbi(dn, dk, y); + } + } + return p; +} + +__device__ double bdtri_unsafe(double k, double n, double p) +{ + if (isnan(n) || isinf(n)) { + return CUDART_NAN; + } else { + return bdtri(k, (int)n, p); + } +} + +""" + + +# Note: bdtr ddd->d and fff-> are deprecated as of SciPy 1.7 +bdtr = _core.create_ufunc( + "cupyx_scipy_bdtr", + ( + ('fff->f', 'out0 = out0_type(bdtr_unsafe(in0, in1, in2));'), + 'dld->d', + ('ddd->d', 'out0 = bdtr_unsafe(in0, in1, in2);'), + ), + "out0 = bdtr(in0, (int)in1, in2);", + preamble=incbet_preamble + bdtr_definition, + doc="""Binomial distribution cumulative distribution function. + + Parameters + ---------- + k : cupy.ndarray + Number of successes (float), rounded down to the nearest integer. + n : cupy.ndarray + Number of events (int). + p : cupy.ndarray + Probability of success in a single event (float). + + Returns + ------- + y : cupy.ndarray + Probability of floor(k) or fewer successes in n independent events with + success probabilities of p. + + See Also + -------- + :func:`scipy.special.bdtr` + + """, +) + + +# Note: bdtrc ddd->d and fff->f are deprecated as of SciPy 1.7 +bdtrc = _core.create_ufunc( + "cupyx_scipy_bdtrc", + ( + ('fff->f', 'out0 = out0_type(bdtrc_unsafe(in0, in1, in2));'), + 'dld->d', + ('ddd->d', 'out0 = bdtrc_unsafe(in0, in1, in2);'), + ), + "out0 = out0_type(bdtrc(in0, in1, in2));", + preamble=incbet_preamble + bdtrc_definition, + doc="""Binomial distribution survival function. + + Returns the complemented binomial distribution function (the integral of + the density from x to infinity). + + Parameters + ---------- + k : cupy.ndarray + Number of successes (float), rounded down to the nearest integer. + n : cupy.ndarray + Number of events (int). + p : cupy.ndarray + Probability of success in a single event (float). + + Returns + ------- + y : cupy.ndarray + Probability of floor(k) + 1 or more successes in n independent events + with success probabilities of p. + + See Also + -------- + :func:`scipy.special.bdtrc` + + """, +) + + +# Note: bdtri ddd->d and fff->f are deprecated as of SciPy 1.7 +bdtri = _core.create_ufunc( + "cupyx_scipy_bdtri", + ( + ('fff->f', 'out0 = out0_type(bdtri_unsafe(in0, in1, in2));'), + 'dld->d', + ('ddd->d', 'out0 = bdtri_unsafe(in0, in1, in2);'), + ), + "out0 = out0_type(bdtri(in0, in1, in2));", + preamble=incbi_preamble + bdtri_definition, + doc="""Inverse function to `bdtr` with respect to `p`. + + Parameters + ---------- + k : cupy.ndarray + Number of successes (float), rounded down to the nearest integer. + n : cupy.ndarray + Number of events (int). + y : cupy.ndarray + Cumulative probability (probability of k or fewer successes in n + events). + + Returns + ------- + p : cupy.ndarray + The event probability such that bdtr(floor(k), n, p) = y. + + See Also + -------- + :func:`scipy.special.bdtri` + + """, +) + + +# Beta distribution functions + +btdtr = _core.create_ufunc( + "cupyx_scipy_btdtr", + ("fff->f", "ddd->d"), + "out0 = out0_type(incbet(in0, in1, in2));", + preamble=incbet_preamble, + doc="""Cumulative distribution function of the beta distribution. + + Parameters + ---------- + a : cupy.ndarray + Shape parameter (a > 0). + b : cupy.ndarray + Shape parameter (b > 0). + x : cupy.ndarray + Upper limit of integration, in [0, 1]. + + Returns + ------- + I : cupy.ndarray + Cumulative distribution function of the beta distribution with + parameters a and b at x. + + See Also + -------- + :func:`scipy.special.btdtr` + + """, +) + + +btdtri = _core.create_ufunc( + "cupyx_scipy_btdtri", + ("fff->f", "ddd->d"), + "out0 = out0_type(incbi(in0, in1, in2));", + preamble=incbi_preamble, + doc="""The p-th quantile of the beta distribution. + + This function is the inverse of the beta cumulative distribution function, + `btdtr`, returning the value of `x` for which ``btdtr(a, b, x) = p``. + + Parameters + ---------- + a : cupy.ndarray + Shape parameter (a > 0). + b : cupy.ndarray + Shape parameter (b > 0). + p : cupy.ndarray + Cumulative probability, in [0, 1]. + + Returns + ------- + x : cupy.ndarray + The quantile corresponding to p. + + See Also + -------- + :func:`scipy.special.btdtri` + + """, +) + + +# Chi square distribution functions + +chdtrc_definition = """ + +__device__ double chdtrc(double df, double x) +{ + + if (x < 0.0) { + return 1.0; /* modified by T. Oliphant */ + } + return igamc(df / 2.0, x / 2.0); +} +""" + + +chdtr_definition = """ + +__device__ double chdtr(double df, double x) +{ + if (x < 0.0) { /* || (df < 1.0) ) */ + return CUDART_NAN; + } + return igam(df / 2.0, x / 2.0); +} +""" + + +chdtri_definition = """ +__device__ double chdtri(double df, double y) +{ + double x; + + if ((y < 0.0) || (y > 1.0)) { /* || (df < 1.0) ) */ + return CUDART_NAN; + } + + x = igamci(0.5 * df, y); + return 2.0 * x; +} +""" + + +chdtrc = _core.create_ufunc( + "cupyx_scipy_chdtrc", + ("ff->f", "dd->d"), + "out0 = out0_type(chdtrc(in0, in1));", + preamble=_igam_preamble + chdtrc_definition, + doc="""Chi square survival function. + + Returns the complemented chi-squared distribution function (the integral of + the density from x to infinity). + + Parameters + ---------- + v : cupy.ndarray + Degrees of freedom. + x : cupy.ndarray + Upper bound of the integral (nonnegative float). + + Returns + ------- + y : cupy.ndarray + The complemented chi-squared distribution function with parameter df at + x. + + See Also + -------- + :func:`scipy.special.chdtrc` + + """, +) + +chdtri = _core.create_ufunc( + "cupyx_scipy_chdtri", + ("ff->f", "dd->d"), + "out0 = out0_type(chdtri(in0, in1));", + preamble=_igami_preamble + chdtri_definition, + doc="""Inverse to `chdtrc` with respect to `x`. + + Parameters + ---------- + v : cupy.ndarray + Degrees of freedom. + p : cupy.ndarray + Probability. + p : cupy.ndarray, optional + Optional output array for the function results. + + Returns + ------- + x : cupy.ndarray + Value so that the probability a Chi square random variable with `v` + degrees of freedom is greater than `x` equals `p`. + + See Also + -------- + :func:`scipy.special.chdtri` + + """, +) + + +chdtr = _core.create_ufunc( + "cupyx_scipy_chdtr", + ("ff->f", "dd->d"), + "out0 = out0_type(chdtr(in0, in1));", + preamble=_igam_preamble + chdtr_definition, + doc="""Chi-square cumulative distribution function. + + Parameters + ---------- + v : cupy.ndarray + Degrees of freedom. + x : cupy.ndarray + Upper bound of the integral (nonnegative float). + + Returns + ------- + y : cupy.ndarray + The CDF of the chi-squared distribution with parameter df at x. + + See Also + -------- + :func:`scipy.special.chdtr` + + """, +) + + +# F distribution functions + +fdtrc_definition = """ + +__device__ double fdtrc(double a, double b, double x) +{ + double w; + + if ((a <= 0.0) || (b <= 0.0) || (x < 0.0)) { + // sf_error("fdtrc", SF_ERROR_DOMAIN, NULL); + return CUDART_NAN; + } + w = b / (b + a * x); + return incbet(0.5 * b, 0.5 * a, w); +} +""" + + +fdtr_definition = """ + +__device__ double fdtr(double a, double b, double x) +{ + double w; + + if ((a <= 0.0) || (b <= 0.0) || (x < 0.0)) { + // sf_error("fdtr", SF_ERROR_DOMAIN, NULL); + return CUDART_NAN; + } + w = a * x; + w = w / (b + w); + return incbet(0.5 * a, 0.5 * b, w); +} +""" + + +fdtri_definition = """ +__device__ double fdtri(double a, double b, double y) +{ + double w, x; + + if ((a <= 0.0) || (b <= 0.0) || (y <= 0.0) || (y > 1.0)) { + // sf_error("fdtri", SF_ERROR_DOMAIN, NULL); + return CUDART_NAN; + } + y = 1.0 - y; + /* Compute probability for x = 0.5. */ + w = incbet(0.5 * b, 0.5 * a, 0.5); + /* If that is greater than y, then the solution w < .5. + * Otherwise, solve at 1-y to remove cancellation in (b - b*w). */ + if (w > y || y < 0.001) { + w = incbi(0.5 * b, 0.5 * a, y); + x = (b - b * w) / (a * w); + } + else { + w = incbi(0.5 * a, 0.5 * b, 1.0 - y); + x = b * w / (a * (1.0 - w)); + } + return x; +} +""" + + +fdtrc = _core.create_ufunc( + "cupyx_scipy_fdtrc", + ("fff->f", "ddd->d"), + "out0 = out0_type(fdtrc(in0, in1, in2));", + preamble=incbi_preamble + fdtrc_definition, + doc="""F survival function. + + Returns the complemented F-distribution function (the integral of the + density from x to infinity). + + Parameters + ---------- + dfn : cupy.ndarray + First parameter (positive float). + dfd : cupy.ndarray + Second parameter (positive float). + x : cupy.ndarray + Argument (nonnegative float). + + Returns + ------- + y : cupy.ndarray + The complemented F-distribution function with parameters dfn and dfd at + x. + + .. seealso:: :meth:`scipy.special.fdtrc` + + """, +) + +fdtri = _core.create_ufunc( + "cupyx_scipy_fdtri", + ("fff->f", "ddd->d"), + "out0 = out0_type(fdtri(in0, in1, in2));", + preamble=incbi_preamble + fdtri_definition, + doc="""The p-th quantile of the F-distribution. + + This function is the inverse of the F-distribution CDF, `fdtr`, returning + the `x` such that `fdtr(dfn, dfd, x)` = `p`. + + Parameters + ---------- + dfn : cupy.ndarray + First parameter (positive float). + dfd : cupy.ndarray + Second parameter (positive float). + p : cupy.ndarray + Cumulative probability, in [0, 1]. + + Returns + ------- + y : cupy.ndarray + The quantile corresponding to p. + + .. seealso:: :meth:`scipy.special.fdtri` + + """, +) + + +fdtr = _core.create_ufunc( + "cupyx_scipy_fdtr", + ("fff->f", "ddd->d"), + "out0 = out0_type(fdtr(in0, in1, in2));", + preamble=incbi_preamble + fdtr_definition, + doc="""F cumulative distribution function. + + + Parameters + ---------- + dfn : cupy.ndarray + First parameter (positive float). + dfd : cupy.ndarray + Second parameter (positive float). + x : cupy.ndarray + Argument (nonnegative float). + + Returns + ------- + y : cupy.ndarray + The CDF of the F-distribution with parameters dfn and dfd at x. + + .. seealso:: :meth:`scipy.special.fdtr` + + """, +) + + +# Gamma distribution functions + +gdtr_definition = """ + +__device__ double gdtr(double a, double b, double x) +{ + + if (x < 0.0) { + return CUDART_NAN; + } + return igam(b, a * x); +} +""" + + +gdtrc_definition = """ + +__device__ double gdtrc(double a, double b, double x) +{ + if (x < 0.0) { + return CUDART_NAN; + } + return (igamc(b, a * x)); +} + +""" + + +gdtr = _core.create_ufunc( + "cupyx_scipy_gdtr", + ("fff->f", "ddd->d"), + "out0 = out0_type(gdtr(in0, in1, in2));", + preamble=_igam_preamble + gdtr_definition, + doc="""Gamma distribution cumulative distribution function. + + Parameters + ---------- + a : cupy.ndarray + The rate parameter of the gamma distribution, sometimes denoted + beta (float). It is also the reciprocal of the scale parameter theta. + b : cupy.ndarray + The shape parameter of the gamma distribution, sometimes denoted + alpha (float). + x : cupy.ndarray + The quantile (upper limit of integration; float). + + Returns + ------- + F : cupy.ndarray + The CDF of the gamma distribution with parameters `a` and `b` evaluated + at `x`. + + See Also + -------- + :func:`scipy.special.gdtr` + + """, +) + + +gdtrc = _core.create_ufunc( + "cupyx_scipy_gdtrc", + ("fff->f", "ddd->d"), + "out0 = out0_type(gdtrc(in0, in1, in2));", + preamble=_igam_preamble + gdtrc_definition, + doc="""Gamma distribution survival function. + + Parameters + ---------- + a : cupy.ndarray + The rate parameter of the gamma distribution, sometimes denoted + beta (float). It is also the reciprocal of the scale parameter theta. + b : cupy.ndarray + The shape parameter of the gamma distribution, sometimes denoted + alpha (float). + x : cupy.ndarray + The quantile (lower limit of integration; float). + + Returns + ------- + I : cupy.ndarray + The survival function of the gamma distribution with parameters `a` and + `b` at `x`. + + See Also + -------- + :func:`scipy.special.gdtrc` + + """, +) + + +# Negative Binomial distribution functions + +nbdtr_definition = """ + +__device__ double nbdtr(int k, int n, double p) +{ + double dk, dn; + + if (((p < 0.0) || (p > 1.0)) || (k < 0)) + { + return CUDART_NAN; + } + dk = k + 1; + dn = n; + return (incbet(dn, dk, p)); +} + +__device__ double nbdtr_unsafe(double k, double n, double p) +{ + if (isnan(k) || isnan(n)) + { + return CUDART_NAN; + } + return nbdtr((int)k, (int)n, p); +} + +""" + + +nbdtrc_definition = """ + +__device__ double nbdtrc(int k, int n, double p) +{ + double dk, dn; + + if (((p < 0.0) || (p > 1.0)) || k < 0) + { + return CUDART_NAN; + } + + dk = k + 1; + dn = n; + return (incbet(dk, dn, 1.0 - p)); +} + +__device__ double nbdtrc_unsafe(double k, double n, double p) +{ + if (isnan(k) || isnan(n)) + { + return CUDART_NAN; + } + return nbdtrc((int)k, (int)n, p); +} + +""" + + +nbdtri_definition = """ + +__device__ double nbdtri(int k, int n, double y) +{ + double dk, dn, w; + + if (((y < 0.0) || (y > 1.0)) || (k < 0)) { + return CUDART_NAN; + } + dk = k + 1; + dn = n; + w = incbi(dn, dk, y); + return (w); +} + +__device__ double nbdtri_unsafe(double k, double n, double y) +{ + if (isnan(k) || isnan(n)) + { + return CUDART_NAN; + } + return nbdtri((int)k, (int)n, y); +} + +""" + +# Note: as in scipy we have a safe iid->d version and unsafe ddd->d one +nbdtr = _core.create_ufunc( + "cupyx_scipy_nbdtr", + ( + 'lld->d', + ('fff->f', 'out0 = out0_type(nbdtr_unsafe(in0, in1, in2));'), + ('ddd->d', 'out0 = nbdtr_unsafe(in0, in1, in2);'), + ), + "out0 = nbdtr(in0, in1, in2);", + preamble=incbet_preamble + nbdtr_definition, + doc="""Negative binomial distribution cumulative distribution function. + + Parameters + ---------- + k : cupy.ndarray + The maximum number of allowed failures (nonnegative int). + n : cupy.ndarray + The target number of successes (positive int). + p : cupy.ndarray + Probability of success in a single event (float). + + Returns + ------- + F : cupy.ndarray + The probability of `k` or fewer failures before `n` successes in a + sequence of events with individual success probability `p`. + + See Also + -------- + :func:`scipy.special.nbdtr` + + """, +) + + +nbdtrc = _core.create_ufunc( + "cupyx_scipy_nbdtrc", + ( + 'lld->d', + ('fff->f', 'out0 = out0_type(nbdtrc_unsafe(in0, in1, in2));'), + ('ddd->d', 'out0 = nbdtrc_unsafe(in0, in1, in2);'), + ), + "out0 = nbdtrc(in0, in1, in2);", + preamble=incbet_preamble + nbdtrc_definition, + doc="""Negative binomial distribution survival function. + + Parameters + ---------- + k : cupy.ndarray + The maximum number of allowed failures (nonnegative int). + n : cupy.ndarray + The target number of successes (positive int). + p : cupy.ndarray + Probability of success in a single event (float). + + Returns + ------- + F : cupy.ndarray + The probability of ``k + 1`` or more failures before `n` successes in a + sequence of events with individual success probability `p`. + + See Also + -------- + :func:`scipy.special.nbdtrc` + + """, +) + +nbdtri = _core.create_ufunc( + "cupyx_scipy_nbdtri", + ( + 'lld->d', + ('fff->f', 'out0 = out0_type(nbdtri_unsafe(in0, in1, in2));'), + ('ddd->d', 'out0 = nbdtri_unsafe(in0, in1, in2);'), + ), + "out0 = nbdtri(in0, in1, in2);", + preamble=incbi_preamble + nbdtri_definition, + doc="""Inverse function to `nbdtr` with respect to `p`. + + Parameters + ---------- + k : cupy.ndarray + The maximum number of allowed failures (nonnegative int). + n : cupy.ndarray + The target number of successes (positive int). + y : cupy.ndarray + The probability of `k` or fewer failures before `n` successes (float). + + Returns + ------- + p : cupy.ndarray + Probability of success in a single event (float) such that + ``nbdtr(k, n, p) = y``. + + See Also + -------- + :func:`scipy.special.nbdtri` + + """, +) + + +# Poisson distribution functions + +pdtr_definition = """ + +__device__ double pdtr(double k, double m) +{ + double v; + + if ((k < 0) || (m < 0)) { + return CUDART_NAN; + } + if (m == 0.0) { + return 1.0; + } + v = floor(k) + 1; + return igamc(v, m); +} + +""" + + +pdtrc_definition = """ + +__device__ double pdtrc(double k, double m) +{ + double v; + + if ((k < 0.0) || (m < 0.0)) { + return CUDART_NAN; + } + if (m == 0.0) { + return 0.0; + } + v = floor(k) + 1; + return igam(v, m); +} + +""" + + +pdtri_definition = """ + +__device__ double pdtri(int k, double y) +{ + double v; + + if ((k < 0) || (y < 0.0) || (y >= 1.0)) { + return CUDART_NAN; + } + v = k + 1; + return igamci(v, y); +} + +__device__ double pdtri_unsafe(double k, double y) +{ + if (isnan(k)) { + return CUDART_NAN; + } else { + return pdtri((int)k, y); + } +} + +""" + + +pdtr = _core.create_ufunc( + "cupyx_scipy_pdtr", + ('ff->f', 'dd->d'), + "out0 = out0_type(pdtr(in0, in1));", + preamble=_igam_preamble + pdtr_definition, + doc="""Poisson cumulative distribution function. + + Parameters + ---------- + k : cupy.ndarray + Nonnegative real argument. + m : cupy.ndarray + Nonnegative real shape parameter. + + Returns + ------- + y : cupy.ndarray + Values of the Poisson cumulative distribution function. + + See Also + -------- + :func:`scipy.special.pdtr` + + """, +) + + +pdtrc = _core.create_ufunc( + "cupyx_scipy_pdtrc", + ('ff->f', 'dd->d'), + "out0 = out0_type(pdtrc(in0, in1));", + preamble=_igam_preamble + pdtrc_definition, + doc="""Binomial distribution survival function. + + Returns the complemented binomial distribution function (the integral of + the density from x to infinity). + + Parameters + ---------- + k : cupy.ndarray + Nonnegative real argument. + m : cupy.ndarray + Nonnegative real shape parameter. + + Returns + ------- + y : cupy.ndarray + The sum of the terms from k+1 to infinity of the Poisson + distribution. + + See Also + -------- + :func:`scipy.special.pdtrc` + + """, +) + + +pdtri = _core.create_ufunc( + "cupyx_scipy_pdtri", + # Note order of entries here is important to match SciPy behavior + ('ld->d', + ('ff->f', 'out0 = out0_type(pdtri_unsafe(in0, in1));'), + ('dd->d', 'out0 = pdtri_unsafe(in0, in1);')), + "out0 = pdtri((int)in0, in1);", + preamble=_igami_preamble + pdtri_definition, + doc="""Inverse function to `pdtr` with respect to `m`. + + Parameters + ---------- + k : cupy.ndarray + Nonnegative real argument. + y : cupy.ndarray + Cumulative probability. + + Returns + ------- + m : cupy.ndarray + The Poisson variable `m` such that the sum from 0 to `k` of the Poisson + density is equal to the given probability `y`. + + See Also + -------- + :func:`scipy.special.pdtri` + + """, +) diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_trig.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_trig.py new file mode 100644 index 0000000000000000000000000000000000000000..87fb4bbd0bd7202c5cc600748e2751a9fbdaf2eb --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_trig.py @@ -0,0 +1,97 @@ +"""complex-valued trig functions adapted from SciPy's cython code: + +https://github.com/scipy/scipy/blob/master/scipy/special/_trig.pxd + +Note: The CUDA Math library defines the real-valued cospi, sinpi +""" + +csinpi_definition = """ + +#include + +// Compute sin(pi*z) for complex arguments + +__device__ complex csinpi(complex z) +{ + double x = z.real(); + double piy = M_PI*z.imag(); + double abspiy = abs(piy); + double sinpix = sinpi(x); + double cospix = cospi(x); + double exphpiy, coshfac, sinhfac; + + if (abspiy < 700) { + return complex(sinpix*cosh(piy), cospix*sinh(piy)); + } + + /* Have to be careful--sinh/cosh could overflow while cos/sin are + * small. At this large of values + * + * cosh(y) ~ exp(y)/2 + * sinh(y) ~ sgn(y)*exp(y)/2 + * + * so we can compute exp(y/2), scale by the right factor of sin/cos + * and then multiply by exp(y/2) to avoid overflow. + */ + exphpiy = exp(abspiy/2.0); + if (exphpiy == CUDART_INF) { + if (sinpix == 0.0) { + // Preserve the sign of zero + coshfac = copysign(0.0, sinpix); + } else { + coshfac = copysign(CUDART_INF, sinpix); + } + if (cospix == 0.0) { + sinhfac = copysign(0.0, cospix); + } else { + sinhfac = copysign(CUDART_INF, cospix); + } + return complex(coshfac, sinhfac); + } + coshfac = 0.5*sinpix*exphpiy; + sinhfac = 0.5*cospix*exphpiy; + return complex(coshfac*exphpiy, sinhfac*exphpiy); +} +""" + + +ccospi_definition = """ + +#include + +// Compute cos(pi*z) for complex arguments + +__device__ complex csinpi(complex z) +{ + double x = z.real(); + double piy = M_PI*z.imag(); + double abspiy = abs(piy); + double sinpix = sinpi(x); + double cospix = cospi(x); + double exphpiy, coshfac, sinhfac; + + if (abspiy < 700) { + return complex(cospix*cosh(piy), -sinpix*sinh(piy)); + } + + // See csinpi(z) for an idea of what's going on here + exphpiy = exp(abspiy/2.0); + if (exphpiy == CUDART_INF) { + if (sinpix == 0.0) { + // Preserve the sign of zero + coshfac = copysign(0.0, cospix); + } else { + coshfac = copysign(CUDART_INF, cospix); + } + if (cospix == 0.0) { + sinhfac = copysign(0.0, sinpix); + } else { + sinhfac = copysign(CUDART_INF, sinpix); + } + return complex(coshfac, sinhfac); + } + coshfac = 0.5*cospix*exphpiy; + sinhfac = 0.5*sinpix*exphpiy; + return complex(coshfac*exphpiy, sinhfac*exphpiy); +} +""" diff --git a/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_xlogy.py b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_xlogy.py new file mode 100644 index 0000000000000000000000000000000000000000..54c2f1beb4670d70482da1c8f05edf97861963b9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/cupyx/scipy/special/_xlogy.py @@ -0,0 +1,68 @@ +from cupy import _core + + +# Note: complex-valued isnan, log and log1p are all defined in +# cupy/_core/include/cupy/complex.cuh +xlogy_definition = """ + +template +static __device__ T xlogy(T x, T y) { + if ((x == (T)0.0) && !isnan(y)) { + return (T)0.0; + } else { + return x * log(y); + } +} + +""" + + +# Note: SciPy only defines dd->d and DD->D +xlogy = _core.create_ufunc( + 'cupy_xlogy', + ('ee->f', 'ff->f', 'dd->d', 'FF->F', 'DD->D'), + 'out0 = out0_type(xlogy(in0, in1));', + preamble=xlogy_definition, + doc='''Compute ``x*log(y)`` so that the result is 0 if ``x = 0``. + + Args: + x (cupy.ndarray): input data + + Returns: + cupy.ndarray: values of ``x * log(y)`` + + .. seealso:: :data:`scipy.special.xlogy` + + ''') + + +xlog1py_definition = """ + +template +static __device__ T xlog1py(T x, T y) { + if ((x == (T)0.0) && ~isnan(y)) { + return (T)0.0; + } else { + return x * log1p(y); + } +} + +""" + +# Note: SciPy only defines dd->d and DD->D +xlog1py = _core.create_ufunc( + 'cupy_xlog1py', + ('ee->f', 'ff->f', 'dd->d', 'FF->F', 'DD->D'), + 'out0 = out0_type(xlog1py(in0, in1));', + preamble=xlog1py_definition, + doc='''Compute ``x*log1p(y)`` so that the result is 0 if ``x = 0``. + + Args: + x (cupy.ndarray): input data + + Returns: + cupy.ndarray: values of ``x * log1p(y)`` + + .. seealso:: :data:`scipy.special.xlog1py` + + ''')