diff --git a/parrot/lib/python3.10/site-packages/scipy/signal/_bsplines.py b/parrot/lib/python3.10/site-packages/scipy/signal/_bsplines.py new file mode 100644 index 0000000000000000000000000000000000000000..c9b136da7c5543f517e03f09f88666290f1590d7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/signal/_bsplines.py @@ -0,0 +1,519 @@ +from numpy import (asarray, pi, zeros_like, + array, arctan2, tan, ones, arange, floor, + r_, atleast_1d, sqrt, exp, greater, cos, add, sin) + +# From splinemodule.c +from ._spline import cspline2d, sepfir2d +from ._signaltools import lfilter, sosfilt, lfiltic + +from scipy.interpolate import BSpline + +__all__ = ['spline_filter', 'gauss_spline', + 'cspline1d', 'qspline1d', 'cspline1d_eval', 'qspline1d_eval'] + + +def spline_filter(Iin, lmbda=5.0): + """Smoothing spline (cubic) filtering of a rank-2 array. + + Filter an input data set, `Iin`, using a (cubic) smoothing spline of + fall-off `lmbda`. + + Parameters + ---------- + Iin : array_like + input data set + lmbda : float, optional + spline smooghing fall-off value, default is `5.0`. + + Returns + ------- + res : ndarray + filtered input data + + Examples + -------- + We can filter an multi dimensional signal (ex: 2D image) using cubic + B-spline filter: + + >>> import numpy as np + >>> from scipy.signal import spline_filter + >>> import matplotlib.pyplot as plt + >>> orig_img = np.eye(20) # create an image + >>> orig_img[10, :] = 1.0 + >>> sp_filter = spline_filter(orig_img, lmbda=0.1) + >>> f, ax = plt.subplots(1, 2, sharex=True) + >>> for ind, data in enumerate([[orig_img, "original image"], + ... [sp_filter, "spline filter"]]): + ... ax[ind].imshow(data[0], cmap='gray_r') + ... ax[ind].set_title(data[1]) + >>> plt.tight_layout() + >>> plt.show() + + """ + intype = Iin.dtype.char + hcol = array([1.0, 4.0, 1.0], 'f') / 6.0 + if intype in ['F', 'D']: + Iin = Iin.astype('F') + ckr = cspline2d(Iin.real, lmbda) + cki = cspline2d(Iin.imag, lmbda) + outr = sepfir2d(ckr, hcol, hcol) + outi = sepfir2d(cki, hcol, hcol) + out = (outr + 1j * outi).astype(intype) + elif intype in ['f', 'd']: + ckr = cspline2d(Iin, lmbda) + out = sepfir2d(ckr, hcol, hcol) + out = out.astype(intype) + else: + raise TypeError("Invalid data type for Iin") + return out + + +_splinefunc_cache = {} + + +def gauss_spline(x, n): + r"""Gaussian approximation to B-spline basis function of order n. + + Parameters + ---------- + x : array_like + a knot vector + n : int + The order of the spline. Must be non-negative, i.e., n >= 0 + + Returns + ------- + res : ndarray + B-spline basis function values approximated by a zero-mean Gaussian + function. + + Notes + ----- + The B-spline basis function can be approximated well by a zero-mean + Gaussian function with standard-deviation equal to :math:`\sigma=(n+1)/12` + for large `n` : + + .. math:: \frac{1}{\sqrt {2\pi\sigma^2}}exp(-\frac{x^2}{2\sigma}) + + References + ---------- + .. [1] Bouma H., Vilanova A., Bescos J.O., ter Haar Romeny B.M., Gerritsen + F.A. (2007) Fast and Accurate Gaussian Derivatives Based on B-Splines. In: + Sgallari F., Murli A., Paragios N. (eds) Scale Space and Variational + Methods in Computer Vision. SSVM 2007. Lecture Notes in Computer + Science, vol 4485. Springer, Berlin, Heidelberg + .. [2] http://folk.uio.no/inf3330/scripting/doc/python/SciPy/tutorial/old/node24.html + + Examples + -------- + We can calculate B-Spline basis functions approximated by a gaussian + distribution: + + >>> import numpy as np + >>> from scipy.signal import gauss_spline + >>> knots = np.array([-1.0, 0.0, -1.0]) + >>> gauss_spline(knots, 3) + array([0.15418033, 0.6909883, 0.15418033]) # may vary + + """ + x = asarray(x) + signsq = (n + 1) / 12.0 + return 1 / sqrt(2 * pi * signsq) * exp(-x ** 2 / 2 / signsq) + + +def _cubic(x): + x = asarray(x, dtype=float) + b = BSpline.basis_element([-2, -1, 0, 1, 2], extrapolate=False) + out = b(x) + out[(x < -2) | (x > 2)] = 0 + return out + + +def _quadratic(x): + x = abs(asarray(x, dtype=float)) + b = BSpline.basis_element([-1.5, -0.5, 0.5, 1.5], extrapolate=False) + out = b(x) + out[(x < -1.5) | (x > 1.5)] = 0 + return out + + +def _coeff_smooth(lam): + xi = 1 - 96 * lam + 24 * lam * sqrt(3 + 144 * lam) + omeg = arctan2(sqrt(144 * lam - 1), sqrt(xi)) + rho = (24 * lam - 1 - sqrt(xi)) / (24 * lam) + rho = rho * sqrt((48 * lam + 24 * lam * sqrt(3 + 144 * lam)) / xi) + return rho, omeg + + +def _hc(k, cs, rho, omega): + return (cs / sin(omega) * (rho ** k) * sin(omega * (k + 1)) * + greater(k, -1)) + + +def _hs(k, cs, rho, omega): + c0 = (cs * cs * (1 + rho * rho) / (1 - rho * rho) / + (1 - 2 * rho * rho * cos(2 * omega) + rho ** 4)) + gamma = (1 - rho * rho) / (1 + rho * rho) / tan(omega) + ak = abs(k) + return c0 * rho ** ak * (cos(omega * ak) + gamma * sin(omega * ak)) + + +def _cubic_smooth_coeff(signal, lamb): + rho, omega = _coeff_smooth(lamb) + cs = 1 - 2 * rho * cos(omega) + rho * rho + K = len(signal) + k = arange(K) + + zi_2 = (_hc(0, cs, rho, omega) * signal[0] + + add.reduce(_hc(k + 1, cs, rho, omega) * signal)) + zi_1 = (_hc(0, cs, rho, omega) * signal[0] + + _hc(1, cs, rho, omega) * signal[1] + + add.reduce(_hc(k + 2, cs, rho, omega) * signal)) + + # Forward filter: + # for n in range(2, K): + # yp[n] = (cs * signal[n] + 2 * rho * cos(omega) * yp[n - 1] - + # rho * rho * yp[n - 2]) + zi = lfiltic(cs, r_[1, -2 * rho * cos(omega), rho * rho], r_[zi_1, zi_2]) + zi = zi.reshape(1, -1) + + sos = r_[cs, 0, 0, 1, -2 * rho * cos(omega), rho * rho] + sos = sos.reshape(1, -1) + + yp, _ = sosfilt(sos, signal[2:], zi=zi) + yp = r_[zi_2, zi_1, yp] + + # Reverse filter: + # for n in range(K - 3, -1, -1): + # y[n] = (cs * yp[n] + 2 * rho * cos(omega) * y[n + 1] - + # rho * rho * y[n + 2]) + + zi_2 = add.reduce((_hs(k, cs, rho, omega) + + _hs(k + 1, cs, rho, omega)) * signal[::-1]) + zi_1 = add.reduce((_hs(k - 1, cs, rho, omega) + + _hs(k + 2, cs, rho, omega)) * signal[::-1]) + + zi = lfiltic(cs, r_[1, -2 * rho * cos(omega), rho * rho], r_[zi_1, zi_2]) + zi = zi.reshape(1, -1) + y, _ = sosfilt(sos, yp[-3::-1], zi=zi) + y = r_[y[::-1], zi_1, zi_2] + return y + + +def _cubic_coeff(signal): + zi = -2 + sqrt(3) + K = len(signal) + powers = zi ** arange(K) + + if K == 1: + yplus = signal[0] + zi * add.reduce(powers * signal) + output = zi / (zi - 1) * yplus + return atleast_1d(output) + + # Forward filter: + # yplus[0] = signal[0] + zi * add.reduce(powers * signal) + # for k in range(1, K): + # yplus[k] = signal[k] + zi * yplus[k - 1] + + state = lfiltic(1, r_[1, -zi], atleast_1d(add.reduce(powers * signal))) + + b = ones(1) + a = r_[1, -zi] + yplus, _ = lfilter(b, a, signal, zi=state) + + # Reverse filter: + # output[K - 1] = zi / (zi - 1) * yplus[K - 1] + # for k in range(K - 2, -1, -1): + # output[k] = zi * (output[k + 1] - yplus[k]) + out_last = zi / (zi - 1) * yplus[K - 1] + state = lfiltic(-zi, r_[1, -zi], atleast_1d(out_last)) + + b = asarray([-zi]) + output, _ = lfilter(b, a, yplus[-2::-1], zi=state) + output = r_[output[::-1], out_last] + return output * 6.0 + + +def _quadratic_coeff(signal): + zi = -3 + 2 * sqrt(2.0) + K = len(signal) + powers = zi ** arange(K) + + if K == 1: + yplus = signal[0] + zi * add.reduce(powers * signal) + output = zi / (zi - 1) * yplus + return atleast_1d(output) + + # Forward filter: + # yplus[0] = signal[0] + zi * add.reduce(powers * signal) + # for k in range(1, K): + # yplus[k] = signal[k] + zi * yplus[k - 1] + + state = lfiltic(1, r_[1, -zi], atleast_1d(add.reduce(powers * signal))) + + b = ones(1) + a = r_[1, -zi] + yplus, _ = lfilter(b, a, signal, zi=state) + + # Reverse filter: + # output[K - 1] = zi / (zi - 1) * yplus[K - 1] + # for k in range(K - 2, -1, -1): + # output[k] = zi * (output[k + 1] - yplus[k]) + out_last = zi / (zi - 1) * yplus[K - 1] + state = lfiltic(-zi, r_[1, -zi], atleast_1d(out_last)) + + b = asarray([-zi]) + output, _ = lfilter(b, a, yplus[-2::-1], zi=state) + output = r_[output[::-1], out_last] + return output * 8.0 + + +def cspline1d(signal, lamb=0.0): + """ + Compute cubic spline coefficients for rank-1 array. + + Find the cubic spline coefficients for a 1-D signal assuming + mirror-symmetric boundary conditions. To obtain the signal back from the + spline representation mirror-symmetric-convolve these coefficients with a + length 3 FIR window [1.0, 4.0, 1.0]/ 6.0 . + + Parameters + ---------- + signal : ndarray + A rank-1 array representing samples of a signal. + lamb : float, optional + Smoothing coefficient, default is 0.0. + + Returns + ------- + c : ndarray + Cubic spline coefficients. + + See Also + -------- + cspline1d_eval : Evaluate a cubic spline at the new set of points. + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a cubic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import cspline1d, cspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = cspline1d_eval(cspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + if lamb != 0.0: + return _cubic_smooth_coeff(signal, lamb) + else: + return _cubic_coeff(signal) + + +def qspline1d(signal, lamb=0.0): + """Compute quadratic spline coefficients for rank-1 array. + + Parameters + ---------- + signal : ndarray + A rank-1 array representing samples of a signal. + lamb : float, optional + Smoothing coefficient (must be zero for now). + + Returns + ------- + c : ndarray + Quadratic spline coefficients. + + See Also + -------- + qspline1d_eval : Evaluate a quadratic spline at the new set of points. + + Notes + ----- + Find the quadratic spline coefficients for a 1-D signal assuming + mirror-symmetric boundary conditions. To obtain the signal back from the + spline representation mirror-symmetric-convolve these coefficients with a + length 3 FIR window [1.0, 6.0, 1.0]/ 8.0 . + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a quadratic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import qspline1d, qspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = qspline1d_eval(qspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + if lamb != 0.0: + raise ValueError("Smoothing quadratic splines not supported yet.") + else: + return _quadratic_coeff(signal) + + +def cspline1d_eval(cj, newx, dx=1.0, x0=0): + """Evaluate a cubic spline at the new set of points. + + `dx` is the old sample-spacing while `x0` was the old origin. In + other-words the old-sample points (knot-points) for which the `cj` + represent spline coefficients were at equally-spaced points of: + + oldx = x0 + j*dx j=0...N-1, with N=len(cj) + + Edges are handled using mirror-symmetric boundary conditions. + + Parameters + ---------- + cj : ndarray + cublic spline coefficients + newx : ndarray + New set of points. + dx : float, optional + Old sample-spacing, the default value is 1.0. + x0 : int, optional + Old origin, the default value is 0. + + Returns + ------- + res : ndarray + Evaluated a cubic spline points. + + See Also + -------- + cspline1d : Compute cubic spline coefficients for rank-1 array. + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a cubic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import cspline1d, cspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = cspline1d_eval(cspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + newx = (asarray(newx) - x0) / float(dx) + res = zeros_like(newx, dtype=cj.dtype) + if res.size == 0: + return res + N = len(cj) + cond1 = newx < 0 + cond2 = newx > (N - 1) + cond3 = ~(cond1 | cond2) + # handle general mirror-symmetry + res[cond1] = cspline1d_eval(cj, -newx[cond1]) + res[cond2] = cspline1d_eval(cj, 2 * (N - 1) - newx[cond2]) + newx = newx[cond3] + if newx.size == 0: + return res + result = zeros_like(newx, dtype=cj.dtype) + jlower = floor(newx - 2).astype(int) + 1 + for i in range(4): + thisj = jlower + i + indj = thisj.clip(0, N - 1) # handle edge cases + result += cj[indj] * _cubic(newx - thisj) + res[cond3] = result + return res + + +def qspline1d_eval(cj, newx, dx=1.0, x0=0): + """Evaluate a quadratic spline at the new set of points. + + Parameters + ---------- + cj : ndarray + Quadratic spline coefficients + newx : ndarray + New set of points. + dx : float, optional + Old sample-spacing, the default value is 1.0. + x0 : int, optional + Old origin, the default value is 0. + + Returns + ------- + res : ndarray + Evaluated a quadratic spline points. + + See Also + -------- + qspline1d : Compute quadratic spline coefficients for rank-1 array. + + Notes + ----- + `dx` is the old sample-spacing while `x0` was the old origin. In + other-words the old-sample points (knot-points) for which the `cj` + represent spline coefficients were at equally-spaced points of:: + + oldx = x0 + j*dx j=0...N-1, with N=len(cj) + + Edges are handled using mirror-symmetric boundary conditions. + + Examples + -------- + We can filter a signal to reduce and smooth out high-frequency noise with + a quadratic spline: + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.signal import qspline1d, qspline1d_eval + >>> rng = np.random.default_rng() + >>> sig = np.repeat([0., 1., 0.], 100) + >>> sig += rng.standard_normal(len(sig))*0.05 # add noise + >>> time = np.linspace(0, len(sig)) + >>> filtered = qspline1d_eval(qspline1d(sig), time) + >>> plt.plot(sig, label="signal") + >>> plt.plot(time, filtered, label="filtered") + >>> plt.legend() + >>> plt.show() + + """ + newx = (asarray(newx) - x0) / dx + res = zeros_like(newx) + if res.size == 0: + return res + N = len(cj) + cond1 = newx < 0 + cond2 = newx > (N - 1) + cond3 = ~(cond1 | cond2) + # handle general mirror-symmetry + res[cond1] = qspline1d_eval(cj, -newx[cond1]) + res[cond2] = qspline1d_eval(cj, 2 * (N - 1) - newx[cond2]) + newx = newx[cond3] + if newx.size == 0: + return res + result = zeros_like(newx) + jlower = floor(newx - 1.5).astype(int) + 1 + for i in range(3): + thisj = jlower + i + indj = thisj.clip(0, N - 1) # handle edge cases + result += cj[indj] * _quadratic(newx - thisj) + res[cond3] = result + return res diff --git a/parrot/lib/python3.10/site-packages/scipy/signal/_peak_finding.py b/parrot/lib/python3.10/site-packages/scipy/signal/_peak_finding.py new file mode 100644 index 0000000000000000000000000000000000000000..3dbb04126325414e66080cac19b98cc675441ec1 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/signal/_peak_finding.py @@ -0,0 +1,1312 @@ +""" +Functions for identifying peaks in signals. +""" +import math +import numpy as np + +from scipy.signal._wavelets import _cwt, _ricker +from scipy.stats import scoreatpercentile + +from ._peak_finding_utils import ( + _local_maxima_1d, + _select_by_peak_distance, + _peak_prominences, + _peak_widths +) + + +__all__ = ['argrelmin', 'argrelmax', 'argrelextrema', 'peak_prominences', + 'peak_widths', 'find_peaks', 'find_peaks_cwt'] + + +def _boolrelextrema(data, comparator, axis=0, order=1, mode='clip'): + """ + Calculate the relative extrema of `data`. + + Relative extrema are calculated by finding locations where + ``comparator(data[n], data[n+1:n+order+1])`` is True. + + Parameters + ---------- + data : ndarray + Array in which to find the relative extrema. + comparator : callable + Function to use to compare two data points. + Should take two arrays as arguments. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n,n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. 'wrap' (wrap around) or + 'clip' (treat overflow as the same as the last (or first) element). + Default 'clip'. See numpy.take. + + Returns + ------- + extrema : ndarray + Boolean array of the same shape as `data` that is True at an extrema, + False otherwise. + + See also + -------- + argrelmax, argrelmin + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._peak_finding import _boolrelextrema + >>> testdata = np.array([1,2,3,2,1]) + >>> _boolrelextrema(testdata, np.greater, axis=0) + array([False, False, True, False, False], dtype=bool) + + """ + if (int(order) != order) or (order < 1): + raise ValueError('Order must be an int >= 1') + + datalen = data.shape[axis] + locs = np.arange(0, datalen) + + results = np.ones(data.shape, dtype=bool) + main = data.take(locs, axis=axis, mode=mode) + for shift in range(1, order + 1): + plus = data.take(locs + shift, axis=axis, mode=mode) + minus = data.take(locs - shift, axis=axis, mode=mode) + results &= comparator(main, plus) + results &= comparator(main, minus) + if ~results.any(): + return results + return results + + +def argrelmin(data, axis=0, order=1, mode='clip'): + """ + Calculate the relative minima of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative minima. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. + Available options are 'wrap' (wrap around) or 'clip' (treat overflow + as the same as the last (or first) element). + Default 'clip'. See numpy.take. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the minima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelextrema, argrelmax, find_peaks + + Notes + ----- + This function uses `argrelextrema` with np.less as comparator. Therefore, it + requires a strict inequality on both sides of a value to consider it a + minimum. This means flat minima (more than one sample wide) are not detected. + In case of 1-D `data` `find_peaks` can be used to detect all + local minima, including flat ones, by calling it with negated `data`. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelmin + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelmin(x) + (array([1, 5]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelmin(y, axis=1) + (array([0, 2]), array([2, 1])) + + """ + return argrelextrema(data, np.less, axis, order, mode) + + +def argrelmax(data, axis=0, order=1, mode='clip'): + """ + Calculate the relative maxima of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative maxima. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. + Available options are 'wrap' (wrap around) or 'clip' (treat overflow + as the same as the last (or first) element). + Default 'clip'. See `numpy.take`. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the maxima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelextrema, argrelmin, find_peaks + + Notes + ----- + This function uses `argrelextrema` with np.greater as comparator. Therefore, + it requires a strict inequality on both sides of a value to consider it a + maximum. This means flat maxima (more than one sample wide) are not detected. + In case of 1-D `data` `find_peaks` can be used to detect all + local maxima, including flat ones. + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelmax + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelmax(x) + (array([3, 6]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelmax(y, axis=1) + (array([0]), array([1])) + """ + return argrelextrema(data, np.greater, axis, order, mode) + + +def argrelextrema(data, comparator, axis=0, order=1, mode='clip'): + """ + Calculate the relative extrema of `data`. + + Parameters + ---------- + data : ndarray + Array in which to find the relative extrema. + comparator : callable + Function to use to compare two data points. + Should take two arrays as arguments. + axis : int, optional + Axis over which to select from `data`. Default is 0. + order : int, optional + How many points on each side to use for the comparison + to consider ``comparator(n, n+x)`` to be True. + mode : str, optional + How the edges of the vector are treated. 'wrap' (wrap around) or + 'clip' (treat overflow as the same as the last (or first) element). + Default is 'clip'. See `numpy.take`. + + Returns + ------- + extrema : tuple of ndarrays + Indices of the maxima in arrays of integers. ``extrema[k]`` is + the array of indices of axis `k` of `data`. Note that the + return value is a tuple even when `data` is 1-D. + + See Also + -------- + argrelmin, argrelmax + + Notes + ----- + + .. versionadded:: 0.11.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import argrelextrema + >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0]) + >>> argrelextrema(x, np.greater) + (array([3, 6]),) + >>> y = np.array([[1, 2, 1, 2], + ... [2, 2, 0, 0], + ... [5, 3, 4, 4]]) + ... + >>> argrelextrema(y, np.less, axis=1) + (array([0, 2]), array([2, 1])) + + """ + results = _boolrelextrema(data, comparator, + axis, order, mode) + return np.nonzero(results) + + +def _arg_x_as_expected(value): + """Ensure argument `x` is a 1-D C-contiguous array of dtype('float64'). + + Used in `find_peaks`, `peak_prominences` and `peak_widths` to make `x` + compatible with the signature of the wrapped Cython functions. + + Returns + ------- + value : ndarray + A 1-D C-contiguous array with dtype('float64'). + """ + value = np.asarray(value, order='C', dtype=np.float64) + if value.ndim != 1: + raise ValueError('`x` must be a 1-D array') + return value + + +def _arg_peaks_as_expected(value): + """Ensure argument `peaks` is a 1-D C-contiguous array of dtype('intp'). + + Used in `peak_prominences` and `peak_widths` to make `peaks` compatible + with the signature of the wrapped Cython functions. + + Returns + ------- + value : ndarray + A 1-D C-contiguous array with dtype('intp'). + """ + value = np.asarray(value) + if value.size == 0: + # Empty arrays default to np.float64 but are valid input + value = np.array([], dtype=np.intp) + try: + # Safely convert to C-contiguous array of type np.intp + value = value.astype(np.intp, order='C', casting='safe', + subok=False, copy=False) + except TypeError as e: + raise TypeError("cannot safely cast `peaks` to dtype('intp')") from e + if value.ndim != 1: + raise ValueError('`peaks` must be a 1-D array') + return value + + +def _arg_wlen_as_expected(value): + """Ensure argument `wlen` is of type `np.intp` and larger than 1. + + Used in `peak_prominences` and `peak_widths`. + + Returns + ------- + value : np.intp + The original `value` rounded up to an integer or -1 if `value` was + None. + """ + if value is None: + # _peak_prominences expects an intp; -1 signals that no value was + # supplied by the user + value = -1 + elif 1 < value: + # Round up to a positive integer + if isinstance(value, float): + value = math.ceil(value) + value = np.intp(value) + else: + raise ValueError(f'`wlen` must be larger than 1, was {value}') + return value + + +def peak_prominences(x, peaks, wlen=None): + """ + Calculate the prominence of each peak in a signal. + + The prominence of a peak measures how much a peak stands out from the + surrounding baseline of the signal and is defined as the vertical distance + between the peak and its lowest contour line. + + Parameters + ---------- + x : sequence + A signal with peaks. + peaks : sequence + Indices of peaks in `x`. + wlen : int, optional + A window length in samples that optionally limits the evaluated area for + each peak to a subset of `x`. The peak is always placed in the middle of + the window therefore the given length is rounded up to the next odd + integer. This parameter can speed up the calculation (see Notes). + + Returns + ------- + prominences : ndarray + The calculated prominences for each peak in `peaks`. + left_bases, right_bases : ndarray + The peaks' bases as indices in `x` to the left and right of each peak. + The higher base of each pair is a peak's lowest contour line. + + Raises + ------ + ValueError + If a value in `peaks` is an invalid index for `x`. + + Warns + ----- + PeakPropertyWarning + For indices in `peaks` that don't point to valid local maxima in `x`, + the returned prominence will be 0 and this warning is raised. This + also happens if `wlen` is smaller than the plateau size of a peak. + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + peak_widths + Calculate the width of peaks. + + Notes + ----- + Strategy to compute a peak's prominence: + + 1. Extend a horizontal line from the current peak to the left and right + until the line either reaches the window border (see `wlen`) or + intersects the signal again at the slope of a higher peak. An + intersection with a peak of the same height is ignored. + 2. On each side find the minimal signal value within the interval defined + above. These points are the peak's bases. + 3. The higher one of the two bases marks the peak's lowest contour line. The + prominence can then be calculated as the vertical difference between the + peaks height itself and its lowest contour line. + + Searching for the peak's bases can be slow for large `x` with periodic + behavior because large chunks or even the full signal need to be evaluated + for the first algorithmic step. This evaluation area can be limited with the + parameter `wlen` which restricts the algorithm to a window around the + current peak and can shorten the calculation time if the window length is + short in relation to `x`. + However, this may stop the algorithm from finding the true global contour + line if the peak's true bases are outside this window. Instead, a higher + contour line is found within the restricted window leading to a smaller + calculated prominence. In practice, this is only relevant for the highest set + of peaks in `x`. This behavior may even be used intentionally to calculate + "local" prominences. + + .. versionadded:: 1.1.0 + + References + ---------- + .. [1] Wikipedia Article for Topographic Prominence: + https://en.wikipedia.org/wiki/Topographic_prominence + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import find_peaks, peak_prominences + >>> import matplotlib.pyplot as plt + + Create a test signal with two overlaid harmonics + + >>> x = np.linspace(0, 6 * np.pi, 1000) + >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x) + + Find all peaks and calculate prominences + + >>> peaks, _ = find_peaks(x) + >>> prominences = peak_prominences(x, peaks)[0] + >>> prominences + array([1.24159486, 0.47840168, 0.28470524, 3.10716793, 0.284603 , + 0.47822491, 2.48340261, 0.47822491]) + + Calculate the height of each peak's contour line and plot the results + + >>> contour_heights = x[peaks] - prominences + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks]) + >>> plt.show() + + Let's evaluate a second example that demonstrates several edge cases for + one peak at index 5. + + >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0]) + >>> peaks = np.array([5]) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + >>> peak_prominences(x, peaks) # -> (prominences, left_bases, right_bases) + (array([3.]), array([2]), array([6])) + + Note how the peak at index 3 of the same height is not considered as a + border while searching for the left base. Instead, two minima at 0 and 2 + are found in which case the one closer to the evaluated peak is always + chosen. On the right side, however, the base must be placed at 6 because the + higher peak represents the right border to the evaluated area. + + >>> peak_prominences(x, peaks, wlen=3.1) + (array([2.]), array([4]), array([6])) + + Here, we restricted the algorithm to a window from 3 to 7 (the length is 5 + samples because `wlen` was rounded up to the next odd integer). Thus, the + only two candidates in the evaluated area are the two neighboring samples + and a smaller prominence is calculated. + """ + x = _arg_x_as_expected(x) + peaks = _arg_peaks_as_expected(peaks) + wlen = _arg_wlen_as_expected(wlen) + return _peak_prominences(x, peaks, wlen) + + +def peak_widths(x, peaks, rel_height=0.5, prominence_data=None, wlen=None): + """ + Calculate the width of each peak in a signal. + + This function calculates the width of a peak in samples at a relative + distance to the peak's height and prominence. + + Parameters + ---------- + x : sequence + A signal with peaks. + peaks : sequence + Indices of peaks in `x`. + rel_height : float, optional + Chooses the relative height at which the peak width is measured as a + percentage of its prominence. 1.0 calculates the width of the peak at + its lowest contour line while 0.5 evaluates at half the prominence + height. Must be at least 0. See notes for further explanation. + prominence_data : tuple, optional + A tuple of three arrays matching the output of `peak_prominences` when + called with the same arguments `x` and `peaks`. This data are calculated + internally if not provided. + wlen : int, optional + A window length in samples passed to `peak_prominences` as an optional + argument for internal calculation of `prominence_data`. This argument + is ignored if `prominence_data` is given. + + Returns + ------- + widths : ndarray + The widths for each peak in samples. + width_heights : ndarray + The height of the contour lines at which the `widths` where evaluated. + left_ips, right_ips : ndarray + Interpolated positions of left and right intersection points of a + horizontal line at the respective evaluation height. + + Raises + ------ + ValueError + If `prominence_data` is supplied but doesn't satisfy the condition + ``0 <= left_base <= peak <= right_base < x.shape[0]`` for each peak, + has the wrong dtype, is not C-contiguous or does not have the same + shape. + + Warns + ----- + PeakPropertyWarning + Raised if any calculated width is 0. This may stem from the supplied + `prominence_data` or if `rel_height` is set to 0. + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks + Find peaks inside a signal based on peak properties. + peak_prominences + Calculate the prominence of peaks. + + Notes + ----- + The basic algorithm to calculate a peak's width is as follows: + + * Calculate the evaluation height :math:`h_{eval}` with the formula + :math:`h_{eval} = h_{Peak} - P \\cdot R`, where :math:`h_{Peak}` is the + height of the peak itself, :math:`P` is the peak's prominence and + :math:`R` a positive ratio specified with the argument `rel_height`. + * Draw a horizontal line at the evaluation height to both sides, starting at + the peak's current vertical position until the lines either intersect a + slope, the signal border or cross the vertical position of the peak's + base (see `peak_prominences` for an definition). For the first case, + intersection with the signal, the true intersection point is estimated + with linear interpolation. + * Calculate the width as the horizontal distance between the chosen + endpoints on both sides. As a consequence of this the maximal possible + width for each peak is the horizontal distance between its bases. + + As shown above to calculate a peak's width its prominence and bases must be + known. You can supply these yourself with the argument `prominence_data`. + Otherwise, they are internally calculated (see `peak_prominences`). + + .. versionadded:: 1.1.0 + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal import chirp, find_peaks, peak_widths + >>> import matplotlib.pyplot as plt + + Create a test signal with two overlaid harmonics + + >>> x = np.linspace(0, 6 * np.pi, 1000) + >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x) + + Find all peaks and calculate their widths at the relative height of 0.5 + (contour line at half the prominence height) and 1 (at the lowest contour + line at full prominence height). + + >>> peaks, _ = find_peaks(x) + >>> results_half = peak_widths(x, peaks, rel_height=0.5) + >>> results_half[0] # widths + array([ 64.25172825, 41.29465463, 35.46943289, 104.71586081, + 35.46729324, 41.30429622, 181.93835853, 45.37078546]) + >>> results_full = peak_widths(x, peaks, rel_height=1) + >>> results_full[0] # widths + array([181.9396084 , 72.99284945, 61.28657872, 373.84622694, + 61.78404617, 72.48822812, 253.09161876, 79.36860878]) + + Plot signal, peaks and contour lines at which the widths where calculated + + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.hlines(*results_half[1:], color="C2") + >>> plt.hlines(*results_full[1:], color="C3") + >>> plt.show() + """ + x = _arg_x_as_expected(x) + peaks = _arg_peaks_as_expected(peaks) + if prominence_data is None: + # Calculate prominence if not supplied and use wlen if supplied. + wlen = _arg_wlen_as_expected(wlen) + prominence_data = _peak_prominences(x, peaks, wlen) + return _peak_widths(x, peaks, rel_height, *prominence_data) + + +def _unpack_condition_args(interval, x, peaks): + """ + Parse condition arguments for `find_peaks`. + + Parameters + ---------- + interval : number or ndarray or sequence + Either a number or ndarray or a 2-element sequence of the former. The + first value is always interpreted as `imin` and the second, if supplied, + as `imax`. + x : ndarray + The signal with `peaks`. + peaks : ndarray + An array with indices used to reduce `imin` and / or `imax` if those are + arrays. + + Returns + ------- + imin, imax : number or ndarray or None + Minimal and maximal value in `argument`. + + Raises + ------ + ValueError : + If interval border is given as array and its size does not match the size + of `x`. + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + try: + imin, imax = interval + except (TypeError, ValueError): + imin, imax = (interval, None) + + # Reduce arrays if arrays + if isinstance(imin, np.ndarray): + if imin.size != x.size: + raise ValueError('array size of lower interval border must match x') + imin = imin[peaks] + if isinstance(imax, np.ndarray): + if imax.size != x.size: + raise ValueError('array size of upper interval border must match x') + imax = imax[peaks] + + return imin, imax + + +def _select_by_property(peak_properties, pmin, pmax): + """ + Evaluate where the generic property of peaks confirms to an interval. + + Parameters + ---------- + peak_properties : ndarray + An array with properties for each peak. + pmin : None or number or ndarray + Lower interval boundary for `peak_properties`. ``None`` is interpreted as + an open border. + pmax : None or number or ndarray + Upper interval boundary for `peak_properties`. ``None`` is interpreted as + an open border. + + Returns + ------- + keep : bool + A boolean mask evaluating to true where `peak_properties` confirms to the + interval. + + See Also + -------- + find_peaks + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + keep = np.ones(peak_properties.size, dtype=bool) + if pmin is not None: + keep &= (pmin <= peak_properties) + if pmax is not None: + keep &= (peak_properties <= pmax) + return keep + + +def _select_by_peak_threshold(x, peaks, tmin, tmax): + """ + Evaluate which peaks fulfill the threshold condition. + + Parameters + ---------- + x : ndarray + A 1-D array which is indexable by `peaks`. + peaks : ndarray + Indices of peaks in `x`. + tmin, tmax : scalar or ndarray or None + Minimal and / or maximal required thresholds. If supplied as ndarrays + their size must match `peaks`. ``None`` is interpreted as an open + border. + + Returns + ------- + keep : bool + A boolean mask evaluating to true where `peaks` fulfill the threshold + condition. + left_thresholds, right_thresholds : ndarray + Array matching `peak` containing the thresholds of each peak on + both sides. + + Notes + ----- + + .. versionadded:: 1.1.0 + """ + # Stack thresholds on both sides to make min / max operations easier: + # tmin is compared with the smaller, and tmax with the greater threshold to + # each peak's side + stacked_thresholds = np.vstack([x[peaks] - x[peaks - 1], + x[peaks] - x[peaks + 1]]) + keep = np.ones(peaks.size, dtype=bool) + if tmin is not None: + min_thresholds = np.min(stacked_thresholds, axis=0) + keep &= (tmin <= min_thresholds) + if tmax is not None: + max_thresholds = np.max(stacked_thresholds, axis=0) + keep &= (max_thresholds <= tmax) + + return keep, stacked_thresholds[0], stacked_thresholds[1] + + +def find_peaks(x, height=None, threshold=None, distance=None, + prominence=None, width=None, wlen=None, rel_height=0.5, + plateau_size=None): + """ + Find peaks inside a signal based on peak properties. + + This function takes a 1-D array and finds all local maxima by + simple comparison of neighboring values. Optionally, a subset of these + peaks can be selected by specifying conditions for a peak's properties. + + Parameters + ---------- + x : sequence + A signal with peaks. + height : number or ndarray or sequence, optional + Required height of peaks. Either a number, ``None``, an array matching + `x` or a 2-element sequence of the former. The first element is + always interpreted as the minimal and the second, if supplied, as the + maximal required height. + threshold : number or ndarray or sequence, optional + Required threshold of peaks, the vertical distance to its neighboring + samples. Either a number, ``None``, an array matching `x` or a + 2-element sequence of the former. The first element is always + interpreted as the minimal and the second, if supplied, as the maximal + required threshold. + distance : number, optional + Required minimal horizontal distance (>= 1) in samples between + neighbouring peaks. Smaller peaks are removed first until the condition + is fulfilled for all remaining peaks. + prominence : number or ndarray or sequence, optional + Required prominence of peaks. Either a number, ``None``, an array + matching `x` or a 2-element sequence of the former. The first + element is always interpreted as the minimal and the second, if + supplied, as the maximal required prominence. + width : number or ndarray or sequence, optional + Required width of peaks in samples. Either a number, ``None``, an array + matching `x` or a 2-element sequence of the former. The first + element is always interpreted as the minimal and the second, if + supplied, as the maximal required width. + wlen : int, optional + Used for calculation of the peaks prominences, thus it is only used if + one of the arguments `prominence` or `width` is given. See argument + `wlen` in `peak_prominences` for a full description of its effects. + rel_height : float, optional + Used for calculation of the peaks width, thus it is only used if `width` + is given. See argument `rel_height` in `peak_widths` for a full + description of its effects. + plateau_size : number or ndarray or sequence, optional + Required size of the flat top of peaks in samples. Either a number, + ``None``, an array matching `x` or a 2-element sequence of the former. + The first element is always interpreted as the minimal and the second, + if supplied as the maximal required plateau size. + + .. versionadded:: 1.2.0 + + Returns + ------- + peaks : ndarray + Indices of peaks in `x` that satisfy all given conditions. + properties : dict + A dictionary containing properties of the returned peaks which were + calculated as intermediate results during evaluation of the specified + conditions: + + * 'peak_heights' + If `height` is given, the height of each peak in `x`. + * 'left_thresholds', 'right_thresholds' + If `threshold` is given, these keys contain a peaks vertical + distance to its neighbouring samples. + * 'prominences', 'right_bases', 'left_bases' + If `prominence` is given, these keys are accessible. See + `peak_prominences` for a description of their content. + * 'width_heights', 'left_ips', 'right_ips' + If `width` is given, these keys are accessible. See `peak_widths` + for a description of their content. + * 'plateau_sizes', left_edges', 'right_edges' + If `plateau_size` is given, these keys are accessible and contain + the indices of a peak's edges (edges are still part of the + plateau) and the calculated plateau sizes. + + .. versionadded:: 1.2.0 + + To calculate and return properties without excluding peaks, provide the + open interval ``(None, None)`` as a value to the appropriate argument + (excluding `distance`). + + Warns + ----- + PeakPropertyWarning + Raised if a peak's properties have unexpected values (see + `peak_prominences` and `peak_widths`). + + Warnings + -------- + This function may return unexpected results for data containing NaNs. To + avoid this, NaNs should either be removed or replaced. + + See Also + -------- + find_peaks_cwt + Find peaks using the wavelet transformation. + peak_prominences + Directly calculate the prominence of peaks. + peak_widths + Directly calculate the width of peaks. + + Notes + ----- + In the context of this function, a peak or local maximum is defined as any + sample whose two direct neighbours have a smaller amplitude. For flat peaks + (more than one sample of equal amplitude wide) the index of the middle + sample is returned (rounded down in case the number of samples is even). + For noisy signals the peak locations can be off because the noise might + change the position of local maxima. In those cases consider smoothing the + signal before searching for peaks or use other peak finding and fitting + methods (like `find_peaks_cwt`). + + Some additional comments on specifying conditions: + + * Almost all conditions (excluding `distance`) can be given as half-open or + closed intervals, e.g., ``1`` or ``(1, None)`` defines the half-open + interval :math:`[1, \\infty]` while ``(None, 1)`` defines the interval + :math:`[-\\infty, 1]`. The open interval ``(None, None)`` can be specified + as well, which returns the matching properties without exclusion of peaks. + * The border is always included in the interval used to select valid peaks. + * For several conditions the interval borders can be specified with + arrays matching `x` in shape which enables dynamic constrains based on + the sample position. + * The conditions are evaluated in the following order: `plateau_size`, + `height`, `threshold`, `distance`, `prominence`, `width`. In most cases + this order is the fastest one because faster operations are applied first + to reduce the number of peaks that need to be evaluated later. + * While indices in `peaks` are guaranteed to be at least `distance` samples + apart, edges of flat peaks may be closer than the allowed `distance`. + * Use `wlen` to reduce the time it takes to evaluate the conditions for + `prominence` or `width` if `x` is large or has many local maxima + (see `peak_prominences`). + + .. versionadded:: 1.1.0 + + Examples + -------- + To demonstrate this function's usage we use a signal `x` supplied with + SciPy (see `scipy.datasets.electrocardiogram`). Let's find all peaks (local + maxima) in `x` whose amplitude lies above 0. + + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from scipy.datasets import electrocardiogram + >>> from scipy.signal import find_peaks + >>> x = electrocardiogram()[2000:4000] + >>> peaks, _ = find_peaks(x, height=0) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.plot(np.zeros_like(x), "--", color="gray") + >>> plt.show() + + We can select peaks below 0 with ``height=(None, 0)`` or use arrays matching + `x` in size to reflect a changing condition for different parts of the + signal. + + >>> border = np.sin(np.linspace(0, 3 * np.pi, x.size)) + >>> peaks, _ = find_peaks(x, height=(-border, border)) + >>> plt.plot(x) + >>> plt.plot(-border, "--", color="gray") + >>> plt.plot(border, ":", color="gray") + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + Another useful condition for periodic signals can be given with the + `distance` argument. In this case, we can easily select the positions of + QRS complexes within the electrocardiogram (ECG) by demanding a distance of + at least 150 samples. + + >>> peaks, _ = find_peaks(x, distance=150) + >>> np.diff(peaks) + array([186, 180, 177, 171, 177, 169, 167, 164, 158, 162, 172]) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + Especially for noisy signals peaks can be easily grouped by their + prominence (see `peak_prominences`). E.g., we can select all peaks except + for the mentioned QRS complexes by limiting the allowed prominence to 0.6. + + >>> peaks, properties = find_peaks(x, prominence=(None, 0.6)) + >>> properties["prominences"].max() + 0.5049999999999999 + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.show() + + And, finally, let's examine a different section of the ECG which contains + beat forms of different shape. To select only the atypical heart beats, we + combine two conditions: a minimal prominence of 1 and width of at least 20 + samples. + + >>> x = electrocardiogram()[17000:18000] + >>> peaks, properties = find_peaks(x, prominence=1, width=20) + >>> properties["prominences"], properties["widths"] + (array([1.495, 2.3 ]), array([36.93773946, 39.32723577])) + >>> plt.plot(x) + >>> plt.plot(peaks, x[peaks], "x") + >>> plt.vlines(x=peaks, ymin=x[peaks] - properties["prominences"], + ... ymax = x[peaks], color = "C1") + >>> plt.hlines(y=properties["width_heights"], xmin=properties["left_ips"], + ... xmax=properties["right_ips"], color = "C1") + >>> plt.show() + """ + # _argmaxima1d expects array of dtype 'float64' + x = _arg_x_as_expected(x) + if distance is not None and distance < 1: + raise ValueError('`distance` must be greater or equal to 1') + + peaks, left_edges, right_edges = _local_maxima_1d(x) + properties = {} + + if plateau_size is not None: + # Evaluate plateau size + plateau_sizes = right_edges - left_edges + 1 + pmin, pmax = _unpack_condition_args(plateau_size, x, peaks) + keep = _select_by_property(plateau_sizes, pmin, pmax) + peaks = peaks[keep] + properties["plateau_sizes"] = plateau_sizes + properties["left_edges"] = left_edges + properties["right_edges"] = right_edges + properties = {key: array[keep] for key, array in properties.items()} + + if height is not None: + # Evaluate height condition + peak_heights = x[peaks] + hmin, hmax = _unpack_condition_args(height, x, peaks) + keep = _select_by_property(peak_heights, hmin, hmax) + peaks = peaks[keep] + properties["peak_heights"] = peak_heights + properties = {key: array[keep] for key, array in properties.items()} + + if threshold is not None: + # Evaluate threshold condition + tmin, tmax = _unpack_condition_args(threshold, x, peaks) + keep, left_thresholds, right_thresholds = _select_by_peak_threshold( + x, peaks, tmin, tmax) + peaks = peaks[keep] + properties["left_thresholds"] = left_thresholds + properties["right_thresholds"] = right_thresholds + properties = {key: array[keep] for key, array in properties.items()} + + if distance is not None: + # Evaluate distance condition + keep = _select_by_peak_distance(peaks, x[peaks], distance) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + if prominence is not None or width is not None: + # Calculate prominence (required for both conditions) + wlen = _arg_wlen_as_expected(wlen) + properties.update(zip( + ['prominences', 'left_bases', 'right_bases'], + _peak_prominences(x, peaks, wlen=wlen) + )) + + if prominence is not None: + # Evaluate prominence condition + pmin, pmax = _unpack_condition_args(prominence, x, peaks) + keep = _select_by_property(properties['prominences'], pmin, pmax) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + if width is not None: + # Calculate widths + properties.update(zip( + ['widths', 'width_heights', 'left_ips', 'right_ips'], + _peak_widths(x, peaks, rel_height, properties['prominences'], + properties['left_bases'], properties['right_bases']) + )) + # Evaluate width condition + wmin, wmax = _unpack_condition_args(width, x, peaks) + keep = _select_by_property(properties['widths'], wmin, wmax) + peaks = peaks[keep] + properties = {key: array[keep] for key, array in properties.items()} + + return peaks, properties + + +def _identify_ridge_lines(matr, max_distances, gap_thresh): + """ + Identify ridges in the 2-D matrix. + + Expect that the width of the wavelet feature increases with increasing row + number. + + Parameters + ---------- + matr : 2-D ndarray + Matrix in which to identify ridge lines. + max_distances : 1-D sequence + At each row, a ridge line is only connected + if the relative max at row[n] is within + `max_distances`[n] from the relative max at row[n+1]. + gap_thresh : int + If a relative maximum is not found within `max_distances`, + there will be a gap. A ridge line is discontinued if + there are more than `gap_thresh` points without connecting + a new relative maximum. + + Returns + ------- + ridge_lines : tuple + Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the + ii-th ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none + found. Each ridge-line will be sorted by row (increasing), but the + order of the ridge lines is not specified. + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + Examples + -------- + >>> import numpy as np + >>> from scipy.signal._peak_finding import _identify_ridge_lines + >>> rng = np.random.default_rng() + >>> data = rng.random((5,5)) + >>> max_dist = 3 + >>> max_distances = np.full(20, max_dist) + >>> ridge_lines = _identify_ridge_lines(data, max_distances, 1) + + Notes + ----- + This function is intended to be used in conjunction with `cwt` + as part of `find_peaks_cwt`. + + """ + if len(max_distances) < matr.shape[0]: + raise ValueError('Max_distances must have at least as many rows ' + 'as matr') + + all_max_cols = _boolrelextrema(matr, np.greater, axis=1, order=1) + # Highest row for which there are any relative maxima + has_relmax = np.nonzero(all_max_cols.any(axis=1))[0] + if len(has_relmax) == 0: + return [] + start_row = has_relmax[-1] + # Each ridge line is a 3-tuple: + # rows, cols,Gap number + ridge_lines = [[[start_row], + [col], + 0] for col in np.nonzero(all_max_cols[start_row])[0]] + final_lines = [] + rows = np.arange(start_row - 1, -1, -1) + cols = np.arange(0, matr.shape[1]) + for row in rows: + this_max_cols = cols[all_max_cols[row]] + + # Increment gap number of each line, + # set it to zero later if appropriate + for line in ridge_lines: + line[2] += 1 + + # XXX These should always be all_max_cols[row] + # But the order might be different. Might be an efficiency gain + # to make sure the order is the same and avoid this iteration + prev_ridge_cols = np.array([line[1][-1] for line in ridge_lines]) + # Look through every relative maximum found at current row + # Attempt to connect them with existing ridge lines. + for ind, col in enumerate(this_max_cols): + # If there is a previous ridge line within + # the max_distance to connect to, do so. + # Otherwise start a new one. + line = None + if len(prev_ridge_cols) > 0: + diffs = np.abs(col - prev_ridge_cols) + closest = np.argmin(diffs) + if diffs[closest] <= max_distances[row]: + line = ridge_lines[closest] + if line is not None: + # Found a point close enough, extend current ridge line + line[1].append(col) + line[0].append(row) + line[2] = 0 + else: + new_line = [[row], + [col], + 0] + ridge_lines.append(new_line) + + # Remove the ridge lines with gap_number too high + # XXX Modifying a list while iterating over it. + # Should be safe, since we iterate backwards, but + # still tacky. + for ind in range(len(ridge_lines) - 1, -1, -1): + line = ridge_lines[ind] + if line[2] > gap_thresh: + final_lines.append(line) + del ridge_lines[ind] + + out_lines = [] + for line in (final_lines + ridge_lines): + sortargs = np.array(np.argsort(line[0])) + rows, cols = np.zeros_like(sortargs), np.zeros_like(sortargs) + rows[sortargs] = line[0] + cols[sortargs] = line[1] + out_lines.append([rows, cols]) + + return out_lines + + +def _filter_ridge_lines(cwt, ridge_lines, window_size=None, min_length=None, + min_snr=1, noise_perc=10): + """ + Filter ridge lines according to prescribed criteria. Intended + to be used for finding relative maxima. + + Parameters + ---------- + cwt : 2-D ndarray + Continuous wavelet transform from which the `ridge_lines` were defined. + ridge_lines : 1-D sequence + Each element should contain 2 sequences, the rows and columns + of the ridge line (respectively). + window_size : int, optional + Size of window to use to calculate noise floor. + Default is ``cwt.shape[1] / 20``. + min_length : int, optional + Minimum length a ridge line needs to be acceptable. + Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths. + min_snr : float, optional + Minimum SNR ratio. Default 1. The signal is the value of + the cwt matrix at the shortest length scale (``cwt[0, loc]``), the + noise is the `noise_perc`\\ th percentile of datapoints contained within a + window of `window_size` around ``cwt[0, loc]``. + noise_perc : float, optional + When calculating the noise floor, percentile of data points + examined below which to consider noise. Calculated using + scipy.stats.scoreatpercentile. + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + """ + num_points = cwt.shape[1] + if min_length is None: + min_length = np.ceil(cwt.shape[0] / 4) + if window_size is None: + window_size = np.ceil(num_points / 20) + + window_size = int(window_size) + hf_window, odd = divmod(window_size, 2) + + # Filter based on SNR + row_one = cwt[0, :] + noises = np.empty_like(row_one) + for ind, val in enumerate(row_one): + window_start = max(ind - hf_window, 0) + window_end = min(ind + hf_window + odd, num_points) + noises[ind] = scoreatpercentile(row_one[window_start:window_end], + per=noise_perc) + + def filt_func(line): + if len(line[0]) < min_length: + return False + snr = abs(cwt[line[0][0], line[1][0]] / noises[line[1][0]]) + if snr < min_snr: + return False + return True + + return list(filter(filt_func, ridge_lines)) + + +def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None, + gap_thresh=None, min_length=None, + min_snr=1, noise_perc=10, window_size=None): + """ + Find peaks in a 1-D array with wavelet transformation. + + The general approach is to smooth `vector` by convolving it with + `wavelet(width)` for each width in `widths`. Relative maxima which + appear at enough length scales, and with sufficiently high SNR, are + accepted. + + Parameters + ---------- + vector : ndarray + 1-D array in which to find the peaks. + widths : float or sequence + Single width or 1-D array-like of widths to use for calculating + the CWT matrix. In general, + this range should cover the expected width of peaks of interest. + wavelet : callable, optional + Should take two parameters and return a 1-D array to convolve + with `vector`. The first parameter determines the number of points + of the returned wavelet array, the second parameter is the scale + (`width`) of the wavelet. Should be normalized and symmetric. + Default is the ricker wavelet. + max_distances : ndarray, optional + At each row, a ridge line is only connected if the relative max at + row[n] is within ``max_distances[n]`` from the relative max at + ``row[n+1]``. Default value is ``widths/4``. + gap_thresh : float, optional + If a relative maximum is not found within `max_distances`, + there will be a gap. A ridge line is discontinued if there are more + than `gap_thresh` points without connecting a new relative maximum. + Default is the first value of the widths array i.e. widths[0]. + min_length : int, optional + Minimum length a ridge line needs to be acceptable. + Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths. + min_snr : float, optional + Minimum SNR ratio. Default 1. The signal is the maximum CWT coefficient + on the largest ridge line. The noise is `noise_perc` th percentile of + datapoints contained within the same ridge line. + noise_perc : float, optional + When calculating the noise floor, percentile of data points + examined below which to consider noise. Calculated using + `stats.scoreatpercentile`. Default is 10. + window_size : int, optional + Size of window to use to calculate noise floor. + Default is ``cwt.shape[1] / 20``. + + Returns + ------- + peaks_indices : ndarray + Indices of the locations in the `vector` where peaks were found. + The list is sorted. + + See Also + -------- + cwt + Continuous wavelet transform. + find_peaks + Find peaks inside a signal based on peak properties. + + Notes + ----- + This approach was designed for finding sharp peaks among noisy data, + however with proper parameter selection it should function well for + different peak shapes. + + The algorithm is as follows: + 1. Perform a continuous wavelet transform on `vector`, for the supplied + `widths`. This is a convolution of `vector` with `wavelet(width)` for + each width in `widths`. See `cwt`. + 2. Identify "ridge lines" in the cwt matrix. These are relative maxima + at each row, connected across adjacent rows. See identify_ridge_lines + 3. Filter the ridge_lines using filter_ridge_lines. + + .. versionadded:: 0.11.0 + + References + ---------- + .. [1] Bioinformatics (2006) 22 (17): 2059-2065. + :doi:`10.1093/bioinformatics/btl355` + + Examples + -------- + >>> import numpy as np + >>> from scipy import signal + >>> xs = np.arange(0, np.pi, 0.05) + >>> data = np.sin(xs) + >>> peakind = signal.find_peaks_cwt(data, np.arange(1,10)) + >>> peakind, xs[peakind], data[peakind] + ([32], array([ 1.6]), array([ 0.9995736])) + + """ + widths = np.atleast_1d(np.asarray(widths)) + + if gap_thresh is None: + gap_thresh = np.ceil(widths[0]) + if max_distances is None: + max_distances = widths / 4.0 + if wavelet is None: + wavelet = _ricker + + cwt_dat = _cwt(vector, wavelet, widths) + ridge_lines = _identify_ridge_lines(cwt_dat, max_distances, gap_thresh) + filtered = _filter_ridge_lines(cwt_dat, ridge_lines, min_length=min_length, + window_size=window_size, min_snr=min_snr, + noise_perc=noise_perc) + max_locs = np.asarray([x[1][0] for x in filtered]) + max_locs.sort() + + return max_locs diff --git a/parrot/lib/python3.10/site-packages/scipy/signal/lti_conversion.py b/parrot/lib/python3.10/site-packages/scipy/signal/lti_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..7080990afc9e23e51e8a45aaa146b64c58dda3cf --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/signal/lti_conversion.py @@ -0,0 +1,20 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.signal` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + +__all__ = [ # noqa: F822 + 'tf2ss', 'abcd_normalize', 'ss2tf', 'zpk2ss', 'ss2zpk', + 'cont2discrete', 'tf2zpk', 'zpk2tf', 'normalize' +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="signal", module="lti_conversion", + private_modules=["_lti_conversion"], all=__all__, + attribute=name) diff --git a/parrot/lib/python3.10/site-packages/scipy/signal/tests/__init__.py b/parrot/lib/python3.10/site-packages/scipy/signal/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_conj_compositeexplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_conj_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..3b0bacdad27ef87e0fe1075ba30d097d7ccc3209 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_conj_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 at::Tensor _conj(const at::Tensor & self); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_flash_attention_forward.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_flash_attention_forward.h new file mode 100644 index 0000000000000000000000000000000000000000..129daca273893d1db21c45cc2e25e61626e495dd --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_flash_attention_forward.h @@ -0,0 +1,47 @@ +#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::_flash_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, bool return_debug_mask, *, float? scale=None) -> (Tensor output, Tensor softmax_logsumexp, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask) +inline ::std::tuple _flash_attention_forward(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional & cum_seq_q, const c10::optional & cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, bool is_causal, bool return_debug_mask, c10::optional scale=c10::nullopt) { + return at::_ops::_flash_attention_forward::call(query, key, value, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, return_debug_mask, scale); +} +namespace symint { + template ::value>> + ::std::tuple _flash_attention_forward(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional & cum_seq_q, const c10::optional & cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, bool is_causal, bool return_debug_mask, c10::optional scale=c10::nullopt) { + return at::_ops::_flash_attention_forward::call(query, key, value, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, return_debug_mask, scale); + } +} + +// aten::_flash_attention_forward(Tensor query, Tensor key, Tensor value, Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, bool return_debug_mask, *, float? scale=None) -> (Tensor output, Tensor softmax_logsumexp, Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask) +inline ::std::tuple _flash_attention_forward_symint(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional & cum_seq_q, const c10::optional & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, bool return_debug_mask, c10::optional scale=c10::nullopt) { + return at::_ops::_flash_attention_forward::call(query, key, value, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, return_debug_mask, scale); +} +namespace symint { + template ::value>> + ::std::tuple _flash_attention_forward(const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const c10::optional & cum_seq_q, const c10::optional & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, bool return_debug_mask, c10::optional scale=c10::nullopt) { + return at::_ops::_flash_attention_forward::call(query, key, value, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, return_debug_mask, scale); + } +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_cosh_native.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_cosh_native.h new file mode 100644 index 0000000000000000000000000000000000000000..cdda327b295e55b61324979ffd2c1bcc1bac0045 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_cosh_native.h @@ -0,0 +1,25 @@ +#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 void _foreach_cosh_out(at::TensorList self, at::TensorList out); +TORCH_API ::std::vector foreach_tensor_cosh_slow(at::TensorList self); +TORCH_API void foreach_tensor_cosh_slow_(at::TensorList self); +TORCH_API ::std::vector foreach_tensor_cosh_cuda(at::TensorList self); +TORCH_API void foreach_tensor_cosh_cuda_(at::TensorList self); +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sin.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sin.h new file mode 100644 index 0000000000000000000000000000000000000000..db381272f0f99330d78e715179989a10b3eb443b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_sin.h @@ -0,0 +1,44 @@ +#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::_foreach_sin(Tensor[] self) -> Tensor[] +inline ::std::vector _foreach_sin(at::TensorList self) { + return at::_ops::_foreach_sin::call(self); +} + +// aten::_foreach_sin_(Tensor(a!)[] self) -> () +inline void _foreach_sin_(at::TensorList self) { + return at::_ops::_foreach_sin_::call(self); +} + +// aten::_foreach_sin.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_sin_out(at::TensorList out, at::TensorList self) { + return at::_ops::_foreach_sin_out::call(self, out); +} +// aten::_foreach_sin.out(Tensor[] self, *, Tensor(a!)[] out) -> () +inline void _foreach_sin_outf(at::TensorList self, at::TensorList out) { + return at::_ops::_foreach_sin_out::call(self, out); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_new_zeros_with_same_feature_meta_compositeexplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_new_zeros_with_same_feature_meta_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c3cec2c29433521430615a473a2aec1b47007e4f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_new_zeros_with_same_feature_meta_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 at::Tensor _new_zeros_with_same_feature_meta(const at::Tensor & self, const at::Tensor & other, int64_t self_num_batch_dims=0); +TORCH_API at::Tensor & _new_zeros_with_same_feature_meta_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other, int64_t self_num_batch_dims=0); +TORCH_API at::Tensor & _new_zeros_with_same_feature_meta_outf(const at::Tensor & self, const at::Tensor & other, int64_t self_num_batch_dims, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_nnz_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_nnz_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f9b84a95717d5b206289f0309e8fb79040d07490 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_nnz_ops.h @@ -0,0 +1,28 @@ +#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 _nnz { + using schema = int64_t (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::_nnz") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_nnz(Tensor self) -> int") + static int64_t call(const at::Tensor & self); + static int64_t redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_mm_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_mm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e6e735501146b3ccb30404869fb4099f9df29555 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_mm_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_mm { + 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::_sparse_mm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_mm(Tensor sparse, Tensor dense) -> Tensor") + static at::Tensor call(const at::Tensor & sparse, const at::Tensor & dense); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & sparse, const at::Tensor & dense); +}; + +struct TORCH_API _sparse_mm_reduce { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, c10::string_view); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_sparse_mm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "reduce") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_sparse_mm.reduce(Tensor sparse, Tensor dense, str reduce) -> Tensor") + static at::Tensor call(const at::Tensor & sparse, const at::Tensor & dense, c10::string_view reduce); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & sparse, const at::Tensor & dense, c10::string_view reduce); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_gru_cell_backward.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_gru_cell_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..b716162d690981abe0c6667c47b95fac92ebd659 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_thnn_fused_gru_cell_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::_thnn_fused_gru_cell_backward(Tensor grad_hy, Tensor workspace, bool has_bias) -> (Tensor, Tensor, Tensor, Tensor, Tensor) +inline ::std::tuple _thnn_fused_gru_cell_backward(const at::Tensor & grad_hy, const at::Tensor & workspace, bool has_bias) { + return at::_ops::_thnn_fused_gru_cell_backward::call(grad_hy, workspace, has_bias); +} + +// aten::_thnn_fused_gru_cell_backward.out(Tensor grad_hy, Tensor workspace, bool has_bias, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3, Tensor(e!) out4) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!), Tensor(e!)) +inline ::std::tuple _thnn_fused_gru_cell_backward_out(at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4, const at::Tensor & grad_hy, const at::Tensor & workspace, bool has_bias) { + return at::_ops::_thnn_fused_gru_cell_backward_out::call(grad_hy, workspace, has_bias, out0, out1, out2, out3, out4); +} +// aten::_thnn_fused_gru_cell_backward.out(Tensor grad_hy, Tensor workspace, bool has_bias, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3, Tensor(e!) out4) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!), Tensor(e!)) +inline ::std::tuple _thnn_fused_gru_cell_backward_outf(const at::Tensor & grad_hy, const at::Tensor & workspace, bool has_bias, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4) { + return at::_ops::_thnn_fused_gru_cell_backward_out::call(grad_hy, workspace, has_bias, out0, out1, out2, out3, out4); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_unique.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_unique.h new file mode 100644 index 0000000000000000000000000000000000000000..8eedeeb9fddb7c2c7f4a67cabfa4127adfb69069 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/_unique.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::_unique(Tensor self, bool sorted=True, bool return_inverse=False) -> (Tensor, Tensor) +inline ::std::tuple _unique(const at::Tensor & self, bool sorted=true, bool return_inverse=false) { + return at::_ops::_unique::call(self, sorted, return_inverse); +} + +// aten::_unique.out(Tensor self, bool sorted=True, bool return_inverse=False, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple _unique_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & self, bool sorted=true, bool return_inverse=false) { + return at::_ops::_unique_out::call(self, sorted, return_inverse, out0, out1); +} +// aten::_unique.out(Tensor self, bool sorted=True, bool return_inverse=False, *, Tensor(a!) out0, Tensor(b!) out1) -> (Tensor(a!), Tensor(b!)) +inline ::std::tuple _unique_outf(const at::Tensor & self, bool sorted, bool return_inverse, at::Tensor & out0, at::Tensor & out1) { + return at::_ops::_unique_out::call(self, sorted, return_inverse, out0, out1); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_max_pool2d_meta.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_max_pool2d_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..215891fb78f2d629f6a5af4398a06f4a8b25adab --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_max_pool2d_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_adaptive_max_pool2d : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, at::IntArrayRef output_size); +}; + +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/aminmax_cpu_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/aminmax_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..ee29be6ffc8a097b1eef9bb8e69fa002f28030f0 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/aminmax_cpu_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API ::std::tuple aminmax(const at::Tensor & self, c10::optional dim=c10::nullopt, bool keepdim=false); +TORCH_API ::std::tuple aminmax_out(at::Tensor & min, at::Tensor & max, const at::Tensor & self, c10::optional dim=c10::nullopt, bool keepdim=false); +TORCH_API ::std::tuple aminmax_outf(const at::Tensor & self, c10::optional dim, bool keepdim, at::Tensor & min, at::Tensor & max); + +} // namespace cpu +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/atan_cuda_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/atan_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..2429ecf6be19d32a6f7dd85bbfc725389e501b74 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/atan_cuda_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor atan(const at::Tensor & self); +TORCH_API at::Tensor & atan_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & atan_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & atan_(at::Tensor & self); + +} // namespace cuda +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/baddbmm_native.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/baddbmm_native.h new file mode 100644 index 0000000000000000000000000000000000000000..5062fd6e296bc170a33dcb91b8c2f47a4f87632b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/baddbmm_native.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_baddbmm_out_cpu : public at::meta::structured_baddbmm { +void impl(const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha, const at::Tensor & out); +}; +struct TORCH_API structured_baddbmm_out_cuda : public at::meta::structured_baddbmm { +void impl(const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha, const at::Tensor & out); +}; +TORCH_API at::Tensor & baddbmm_out_sparse_csr_cuda(const at::Tensor & self, const at::Tensor & batch1, const at::Tensor & batch2, const at::Scalar & beta, const at::Scalar & alpha, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/bmm_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/bmm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..7dfabe75ec355ebe0fcd2c32063466b337ac1349 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/bmm_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 bmm { + 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::bmm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bmm(Tensor self, Tensor mat2) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & mat2); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mat2); +}; + +struct TORCH_API bmm_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::bmm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bmm.out(Tensor self, Tensor mat2, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & mat2, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/diag_embed_compositeexplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/diag_embed_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..857a490cd2a051f30549884f1b728d0212aa18e3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/diag_embed_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 & diag_embed_out(at::Tensor & out, const at::Tensor & self, int64_t offset=0, int64_t dim1=-2, int64_t dim2=-1); +TORCH_API at::Tensor & diag_embed_outf(const at::Tensor & self, int64_t offset, int64_t dim1, int64_t dim2, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/fft_irfftn_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/fft_irfftn_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..e398af9726296968604cdeeea7c53f9ad954ce4d --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/fft_irfftn_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 fft_irfftn { + using schema = at::Tensor (const at::Tensor &, at::OptionalSymIntArrayRef, at::OptionalIntArrayRef, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::fft_irfftn") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fft_irfftn(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, c10::optional norm); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, c10::optional norm); +}; + +struct TORCH_API fft_irfftn_out { + using schema = at::Tensor & (const at::Tensor &, at::OptionalSymIntArrayRef, at::OptionalIntArrayRef, 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::fft_irfftn") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "fft_irfftn.out(Tensor self, SymInt[1]? s=None, int[1]? dim=None, str? norm=None, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, c10::optional norm, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::OptionalSymIntArrayRef s, at::OptionalIntArrayRef dim, c10::optional norm, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/full_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/full_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..5a8a5a06a78573884dc4de447a89bde23b3d63ec --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/full_ops.h @@ -0,0 +1,61 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API full_names { + using schema = at::Tensor (at::IntArrayRef, const at::Scalar &, c10::optional, c10::optional, c10::optional, c10::optional, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::full") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "full.names(int[] size, Scalar fill_value, *, Dimname[]? names, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor") + static at::Tensor call(at::IntArrayRef size, const at::Scalar & fill_value, c10::optional names, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, at::IntArrayRef size, const at::Scalar & fill_value, c10::optional names, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +}; + +struct TORCH_API full { + using schema = at::Tensor (c10::SymIntArrayRef, const at::Scalar &, c10::optional, c10::optional, c10::optional, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::full") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "full(SymInt[] size, Scalar fill_value, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor") + static at::Tensor call(c10::SymIntArrayRef size, const at::Scalar & fill_value, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymIntArrayRef size, const at::Scalar & fill_value, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory); +}; + +struct TORCH_API full_out { + using schema = at::Tensor & (c10::SymIntArrayRef, 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::full") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "full.out(SymInt[] size, Scalar fill_value, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(c10::SymIntArrayRef size, const at::Scalar & fill_value, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymIntArrayRef size, const at::Scalar & fill_value, at::Tensor & out); +}; + +struct TORCH_API full_names_out { + using schema = at::Tensor & (at::IntArrayRef, const at::Scalar &, 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::full") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "names_out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "full.names_out(int[] size, Scalar fill_value, *, Dimname[]? names, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(at::IntArrayRef size, const at::Scalar & fill_value, c10::optional names, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::IntArrayRef size, const at::Scalar & fill_value, c10::optional names, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/gelu_compositeexplicitautogradnonfunctional_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/gelu_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..35310f85da65d35a053dfadd33d57d87ac8d5696 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/gelu_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 gelu(const at::Tensor & self, c10::string_view approximate="none"); +TORCH_API at::Tensor & gelu_(at::Tensor & self, c10::string_view approximate="none"); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/gru.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/gru.h new file mode 100644 index 0000000000000000000000000000000000000000..3c53bfd7bf09dccf3d6fa7959bd28fed9580aadb --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/gru.h @@ -0,0 +1,35 @@ +#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::gru.input(Tensor input, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor) +inline ::std::tuple gru(const at::Tensor & input, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first) { + return at::_ops::gru_input::call(input, hx, params, has_biases, num_layers, dropout, train, bidirectional, batch_first); +} + +// aten::gru.data(Tensor data, Tensor batch_sizes, Tensor hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional) -> (Tensor, Tensor) +inline ::std::tuple gru(const at::Tensor & data, const at::Tensor & batch_sizes, const at::Tensor & hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional) { + return at::_ops::gru_data::call(data, batch_sizes, hx, params, has_biases, num_layers, dropout, train, bidirectional); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/histc_cuda_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/histc_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..dc6f0db6aeae39e5229d10539e520599cd9f127d --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/histc_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 histc(const at::Tensor & self, int64_t bins=100, const at::Scalar & min=0, const at::Scalar & max=0); +TORCH_API at::Tensor & histc_out(at::Tensor & out, const at::Tensor & self, int64_t bins=100, const at::Scalar & min=0, const at::Scalar & max=0); +TORCH_API at::Tensor & histc_outf(const at::Tensor & self, int64_t bins, const at::Scalar & min, const at::Scalar & max, at::Tensor & out); + +} // namespace cuda +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/kron.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/kron.h new file mode 100644 index 0000000000000000000000000000000000000000..02d7b1f58712de24c10718aab804f482b9d0925c --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/kron.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::kron(Tensor self, Tensor other) -> Tensor +inline at::Tensor kron(const at::Tensor & self, const at::Tensor & other) { + return at::_ops::kron::call(self, other); +} + +// aten::kron.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & kron_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other) { + return at::_ops::kron_out::call(self, other, out); +} +// aten::kron.out(Tensor self, Tensor other, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & kron_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out) { + return at::_ops::kron_out::call(self, other, out); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/lgamma_cpu_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/lgamma_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9a0f37286cf8a364a7ce77c54dfd2e9dc4352b8e --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/lgamma_cpu_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor lgamma(const at::Tensor & self); +TORCH_API at::Tensor & lgamma_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & lgamma_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & lgamma_(at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log_sigmoid_native.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log_sigmoid_native.h new file mode 100644 index 0000000000000000000000000000000000000000..2eb95092126f43659903613bd4eb9821e1916aff --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/log_sigmoid_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor log_sigmoid(const at::Tensor & self); +TORCH_API at::Tensor & log_sigmoid_out(const at::Tensor & self, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/logical_not_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/logical_not_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..ea30a59328d7dbffea950905fe83cabc2d1eea70 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/logical_not_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 logical_not { + 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::logical_not") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_not(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 logical_not_ { + 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::logical_not_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_not_(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 logical_not_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::logical_not") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "logical_not.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/matmul_backward_compositeexplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/matmul_backward_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..ec96e4a1b913da103868f80c282137e744e61981 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/matmul_backward_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 ::std::tuple matmul_backward_out(at::Tensor & out0, at::Tensor & out1, const at::Tensor & grad, const at::Tensor & self, const at::Tensor & other, ::std::array mask); +TORCH_API ::std::tuple matmul_backward_outf(const at::Tensor & grad, const at::Tensor & self, const at::Tensor & other, ::std::array mask, at::Tensor & out0, at::Tensor & out1); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/mkldnn_max_pool2d_compositeexplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/mkldnn_max_pool2d_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c6e78a879b24da91bbe3449c29046b565b934332 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/mkldnn_max_pool2d_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 & mkldnn_max_pool2d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, bool ceil_mode=false); +TORCH_API at::Tensor & mkldnn_max_pool2d_outf(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, at::IntArrayRef dilation, bool ceil_mode, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/multilabel_margin_loss_forward_cuda_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/multilabel_margin_loss_forward_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c3a721f4cab31833c273e9a3d6d7e81cf7a20d13 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/multilabel_margin_loss_forward_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 ::std::tuple multilabel_margin_loss_forward(const at::Tensor & self, const at::Tensor & target, int64_t reduction); +TORCH_API ::std::tuple multilabel_margin_loss_forward_out(at::Tensor & output, at::Tensor & is_target, const at::Tensor & self, const at::Tensor & target, int64_t reduction); +TORCH_API ::std::tuple multilabel_margin_loss_forward_outf(const at::Tensor & self, const at::Tensor & target, int64_t reduction, at::Tensor & output, at::Tensor & is_target); + +} // namespace cuda +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/nonzero_numpy_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/nonzero_numpy_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..583ae4923ceccbde2d5df17767e2903806abd9f4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/nonzero_numpy_ops.h @@ -0,0 +1,28 @@ +#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 nonzero_numpy { + using schema = ::std::vector (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::nonzero_numpy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "nonzero_numpy(Tensor self) -> Tensor[]") + static ::std::vector call(const at::Tensor & self); + static ::std::vector redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/pad.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/pad.h new file mode 100644 index 0000000000000000000000000000000000000000..2d6bb6e9e4bb1d2b91650df93c384e9d117509df --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/pad.h @@ -0,0 +1,47 @@ +#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::pad(Tensor self, SymInt[] pad, str mode="constant", float? value=None) -> Tensor +inline at::Tensor pad(const at::Tensor & self, at::IntArrayRef pad, c10::string_view mode="constant", c10::optional value=c10::nullopt) { + return at::_ops::pad::call(self, c10::fromIntArrayRefSlow(pad), mode, value); +} +namespace symint { + template ::value>> + at::Tensor pad(const at::Tensor & self, at::IntArrayRef pad, c10::string_view mode="constant", c10::optional value=c10::nullopt) { + return at::_ops::pad::call(self, c10::fromIntArrayRefSlow(pad), mode, value); + } +} + +// aten::pad(Tensor self, SymInt[] pad, str mode="constant", float? value=None) -> Tensor +inline at::Tensor pad_symint(const at::Tensor & self, c10::SymIntArrayRef pad, c10::string_view mode="constant", c10::optional value=c10::nullopt) { + return at::_ops::pad::call(self, pad, mode, value); +} +namespace symint { + template ::value>> + at::Tensor pad(const at::Tensor & self, c10::SymIntArrayRef pad, c10::string_view mode="constant", c10::optional value=c10::nullopt) { + return at::_ops::pad::call(self, pad, mode, value); + } +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/refine_names_compositeimplicitautograd_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/refine_names_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..6de924f2068befcfc9115189dfc0de17beb1c95b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/refine_names_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 refine_names(const at::Tensor & self, at::DimnameList names); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/reflection_pad1d_native.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/reflection_pad1d_native.h new file mode 100644 index 0000000000000000000000000000000000000000..f38c3d48deeeb8c8dc7c80fcf97153fd2d6b214b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/reflection_pad1d_native.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace native { +struct TORCH_API structured_reflection_pad1d_out_cpu : public at::meta::structured_reflection_pad1d { +void impl(const at::Tensor & self, at::ArrayRef padding, const at::Tensor & out); +}; +struct TORCH_API structured_reflection_pad1d_out_cuda : public at::meta::structured_reflection_pad1d { +void impl(const at::Tensor & self, at::ArrayRef padding, const at::Tensor & out); +}; +TORCH_API at::Tensor & reflection_pad1d_out_quantized_cpu(const at::Tensor & self, at::IntArrayRef padding, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/remainder_meta_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/remainder_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4ce9c77f6a0b33925bbb15e391a915e31891849e --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/remainder_meta_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor remainder(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & remainder_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & remainder_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & remainder_(at::Tensor & self, const at::Tensor & other); + +} // namespace meta +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/scalar_tensor.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/scalar_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..d4729507b38899e163485f74664c5ba0118e62d4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/scalar_tensor.h @@ -0,0 +1,43 @@ +#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::scalar_tensor(Scalar s, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor scalar_tensor(const at::Scalar & s, at::TensorOptions options={}) { + return at::_ops::scalar_tensor::call(s, optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), options.device_opt(), options.pinned_memory_opt()); +} +// aten::scalar_tensor(Scalar s, *, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None) -> Tensor +inline at::Tensor scalar_tensor(const at::Scalar & s, c10::optional dtype, c10::optional layout, c10::optional device, c10::optional pin_memory) { + return at::_ops::scalar_tensor::call(s, dtype, layout, device, pin_memory); +} + +// aten::scalar_tensor.out(Scalar s, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & scalar_tensor_out(at::Tensor & out, const at::Scalar & s) { + return at::_ops::scalar_tensor_out::call(s, out); +} +// aten::scalar_tensor.out(Scalar s, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & scalar_tensor_outf(const at::Scalar & s, at::Tensor & out) { + return at::_ops::scalar_tensor_out::call(s, out); +} + +} diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_entr_meta_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_entr_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..039dd3719f721552ec55ad4947932572e8dcdc70 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_entr_meta_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor special_entr(const at::Tensor & self); +TORCH_API at::Tensor & special_entr_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & special_entr_outf(const at::Tensor & self, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_entr_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_entr_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..01e0b2c9c547a43f14ecd56a622222f6bdd0109b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/special_entr_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_entr { + 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_entr") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_entr(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_entr_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_entr") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "special_entr.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/sum_meta.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sum_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..e8a8f4da4d913955dfc86e650ebe81121b40ba83 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/sum_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_sum_dim_IntList : public at::impl::MetaBase { + + + void meta(const at::Tensor & self, at::OptionalIntArrayRef dim, bool keepdim, c10::optional dtype); +}; + +} // namespace native +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/to_dense_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/to_dense_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..d1960732c734823ac8fe6115993fb25d783b3711 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/to_dense_ops.h @@ -0,0 +1,28 @@ +#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 to_dense { + using schema = at::Tensor (const at::Tensor &, c10::optional, c10::optional); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::to_dense") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "to_dense(Tensor self, ScalarType? dtype=None, *, bool? masked_grad=None) -> Tensor") + static at::Tensor call(const at::Tensor & self, c10::optional dtype, c10::optional masked_grad); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::optional dtype, c10::optional masked_grad); +}; + +}} // namespace at::_ops diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/trunc_cpu_dispatch.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/trunc_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..a165c17de22fdf03517f50674497d7f52dcbd1f5 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/trunc_cpu_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor trunc(const at::Tensor & self); +TORCH_API at::Tensor & trunc_out(at::Tensor & out, const at::Tensor & self); +TORCH_API at::Tensor & trunc_outf(const at::Tensor & self, at::Tensor & out); +TORCH_API at::Tensor & trunc_(at::Tensor & self); + +} // namespace cpu +} // namespace at diff --git a/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/unsqueeze.h b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/unsqueeze.h new file mode 100644 index 0000000000000000000000000000000000000000..f5efa01f8a335dfdf44863b350f2ca5a5c562039 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/ATen/ops/unsqueeze.h @@ -0,0 +1,30 @@ +#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::unsqueeze(Tensor(a) self, int dim) -> Tensor(a) +inline at::Tensor unsqueeze(const at::Tensor & self, int64_t dim) { + return at::_ops::unsqueeze::call(self, dim); +} + +} diff --git a/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a4875c43b6c9e2dbff756df8baf562776ed0ad7 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7fcf4e1454730bd11c2ca642d09143648db2deaa Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/config.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc0286a3bb87e9e4c06eed541164e6de5abd87f9 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/config.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/core.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6772b1b0a03a4f180748498c3d13c3be14f8dd2d Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/core.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/data.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e75072068a4e2adb22cf959f6a57e1d893a5d1c3 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/data.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/dataclasses.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/dataclasses.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6c31448c726f87047abdb00013cea989b4e33e8 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/dacite/__pycache__/dataclasses.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/compat.py b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..37c6480510f4918fec453ad960be4e7e168dde7d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/compat.py @@ -0,0 +1,38 @@ +# encoding: utf-8 +""" +This module provides compatibility between Python 2 and 3. Hardly +anything is used by this project to constitute including `six`_. + +.. _`six`: http://pythonhosted.org/six +""" + +import sys + +if sys.version_info[0] < 3: + # Python 2. + unicode = unicode + string_types = (basestring,) + + from collections import Iterable + from itertools import izip_longest + + def iterkeys(mapping): + return mapping.iterkeys() + +else: + # Python 3. + unicode = str + string_types = (unicode,) + + from collections.abc import Iterable + from itertools import zip_longest as izip_longest + + def iterkeys(mapping): + return mapping.keys() + +try: + # Python 3.6+. + from collections.abc import Collection +except ImportError: + # Python 2.7 - 3.5. + from collections import Container as Collection diff --git a/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/pathspec.py b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/pathspec.py new file mode 100644 index 0000000000000000000000000000000000000000..73250efeb4da23db302317e750e8e8fb3b691ebf --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/pathspec.py @@ -0,0 +1,206 @@ +# encoding: utf-8 +""" +This module provides an object oriented interface for pattern matching +of files. +""" + +from . import util +from .compat import Collection, iterkeys, izip_longest, string_types, unicode + + +class PathSpec(object): + """ + The :class:`PathSpec` class is a wrapper around a list of compiled + :class:`.Pattern` instances. + """ + + def __init__(self, patterns): + """ + Initializes the :class:`PathSpec` instance. + + *patterns* (:class:`~collections.abc.Collection` or :class:`~collections.abc.Iterable`) + yields each compiled pattern (:class:`.Pattern`). + """ + + self.patterns = patterns if isinstance(patterns, Collection) else list(patterns) + """ + *patterns* (:class:`~collections.abc.Collection` of :class:`.Pattern`) + contains the compiled patterns. + """ + + def __eq__(self, other): + """ + Tests the equality of this path-spec with *other* (:class:`PathSpec`) + by comparing their :attr:`~PathSpec.patterns` attributes. + """ + if isinstance(other, PathSpec): + paired_patterns = izip_longest(self.patterns, other.patterns) + return all(a == b for a, b in paired_patterns) + else: + return NotImplemented + + def __len__(self): + """ + Returns the number of compiled patterns this path-spec contains + (:class:`int`). + """ + return len(self.patterns) + + def __add__(self, other): + """ + Combines the :attr:`Pathspec.patterns` patterns from two + :class:`PathSpec` instances. + """ + if isinstance(other, PathSpec): + return PathSpec(self.patterns + other.patterns) + else: + return NotImplemented + + def __iadd__(self, other): + """ + Adds the :attr:`Pathspec.patterns` patterns from one :class:`PathSpec` + instance to this instance. + """ + if isinstance(other, PathSpec): + self.patterns += other.patterns + return self + else: + return NotImplemented + + @classmethod + def from_lines(cls, pattern_factory, lines): + """ + Compiles the pattern lines. + + *pattern_factory* can be either the name of a registered pattern + factory (:class:`str`), or a :class:`~collections.abc.Callable` used + to compile patterns. It must accept an uncompiled pattern (:class:`str`) + and return the compiled pattern (:class:`.Pattern`). + + *lines* (:class:`~collections.abc.Iterable`) yields each uncompiled + pattern (:class:`str`). This simply has to yield each line so it can + be a :class:`file` (e.g., from :func:`open` or :class:`io.StringIO`) + or the result from :meth:`str.splitlines`. + + Returns the :class:`PathSpec` instance. + """ + if isinstance(pattern_factory, string_types): + pattern_factory = util.lookup_pattern(pattern_factory) + if not callable(pattern_factory): + raise TypeError("pattern_factory:{!r} is not callable.".format(pattern_factory)) + + if not util._is_iterable(lines): + raise TypeError("lines:{!r} is not an iterable.".format(lines)) + + lines = [pattern_factory(line) for line in lines if line] + return cls(lines) + + def match_file(self, file, separators=None): + """ + Matches the file to this path-spec. + + *file* (:class:`str` or :class:`~pathlib.PurePath`) is the file path + to be matched against :attr:`self.patterns `. + + *separators* (:class:`~collections.abc.Collection` of :class:`str`) + optionally contains the path separators to normalize. See + :func:`~pathspec.util.normalize_file` for more information. + + Returns :data:`True` if *file* matched; otherwise, :data:`False`. + """ + norm_file = util.normalize_file(file, separators=separators) + return util.match_file(self.patterns, norm_file) + + def match_entries(self, entries, separators=None): + """ + Matches the entries to this path-spec. + + *entries* (:class:`~collections.abc.Iterable` of :class:`~util.TreeEntry`) + contains the entries to be matched against :attr:`self.patterns `. + + *separators* (:class:`~collections.abc.Collection` of :class:`str`; + or :data:`None`) optionally contains the path separators to + normalize. See :func:`~pathspec.util.normalize_file` for more + information. + + Returns the matched entries (:class:`~collections.abc.Iterable` of + :class:`~util.TreeEntry`). + """ + if not util._is_iterable(entries): + raise TypeError("entries:{!r} is not an iterable.".format(entries)) + + entry_map = util._normalize_entries(entries, separators=separators) + match_paths = util.match_files(self.patterns, iterkeys(entry_map)) + for path in match_paths: + yield entry_map[path] + + def match_files(self, files, separators=None): + """ + Matches the files to this path-spec. + + *files* (:class:`~collections.abc.Iterable` of :class:`str; or + :class:`pathlib.PurePath`) contains the file paths to be matched + against :attr:`self.patterns `. + + *separators* (:class:`~collections.abc.Collection` of :class:`str`; + or :data:`None`) optionally contains the path separators to + normalize. See :func:`~pathspec.util.normalize_file` for more + information. + + Returns the matched files (:class:`~collections.abc.Iterable` of + :class:`str`). + """ + if not util._is_iterable(files): + raise TypeError("files:{!r} is not an iterable.".format(files)) + + file_map = util.normalize_files(files, separators=separators) + matched_files = util.match_files(self.patterns, iterkeys(file_map)) + for path in matched_files: + yield file_map[path] + + def match_tree_entries(self, root, on_error=None, follow_links=None): + """ + Walks the specified root path for all files and matches them to this + path-spec. + + *root* (:class:`str`; or :class:`pathlib.PurePath`) is the root + directory to search. + + *on_error* (:class:`~collections.abc.Callable` or :data:`None`) + optionally is the error handler for file-system exceptions. See + :func:`~pathspec.util.iter_tree_entries` for more information. + + *follow_links* (:class:`bool` or :data:`None`) optionally is whether + to walk symbolic links that resolve to directories. See + :func:`~pathspec.util.iter_tree_files` for more information. + + Returns the matched files (:class:`~collections.abc.Iterable` of + :class:`str`). + """ + entries = util.iter_tree_entries(root, on_error=on_error, follow_links=follow_links) + return self.match_entries(entries) + + def match_tree_files(self, root, on_error=None, follow_links=None): + """ + Walks the specified root path for all files and matches them to this + path-spec. + + *root* (:class:`str`; or :class:`pathlib.PurePath`) is the root + directory to search for files. + + *on_error* (:class:`~collections.abc.Callable` or :data:`None`) + optionally is the error handler for file-system exceptions. See + :func:`~pathspec.util.iter_tree_files` for more information. + + *follow_links* (:class:`bool` or :data:`None`) optionally is whether + to walk symbolic links that resolve to directories. See + :func:`~pathspec.util.iter_tree_files` for more information. + + Returns the matched files (:class:`~collections.abc.Iterable` of + :class:`str`). + """ + files = util.iter_tree_files(root, on_error=on_error, follow_links=follow_links) + return self.match_files(files) + + # Alias `match_tree_files()` as `match_tree()`. + match_tree = match_tree_files diff --git a/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/pattern.py b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/pattern.py new file mode 100644 index 0000000000000000000000000000000000000000..4ba4edf790c84c51ad4ff79b76022a5f64bb8e65 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/pattern.py @@ -0,0 +1,146 @@ +# encoding: utf-8 +""" +This module provides the base definition for patterns. +""" + +import re + +from .compat import unicode + + +class Pattern(object): + """ + The :class:`Pattern` class is the abstract definition of a pattern. + """ + + # Make the class dict-less. + __slots__ = ('include',) + + def __init__(self, include): + """ + Initializes the :class:`Pattern` instance. + + *include* (:class:`bool` or :data:`None`) is whether the matched + files should be included (:data:`True`), excluded (:data:`False`), + or is a null-operation (:data:`None`). + """ + + self.include = include + """ + *include* (:class:`bool` or :data:`None`) is whether the matched + files should be included (:data:`True`), excluded (:data:`False`), + or is a null-operation (:data:`None`). + """ + + def match(self, files): + """ + Matches this pattern against the specified files. + + *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains + each file relative to the root directory (e.g., ``"relative/path/to/file"``). + + Returns an :class:`~collections.abc.Iterable` yielding each matched + file path (:class:`str`). + """ + raise NotImplementedError("{}.{} must override match().".format(self.__class__.__module__, self.__class__.__name__)) + + +class RegexPattern(Pattern): + """ + The :class:`RegexPattern` class is an implementation of a pattern + using regular expressions. + """ + + # Make the class dict-less. + __slots__ = ('regex',) + + def __init__(self, pattern, include=None): + """ + Initializes the :class:`RegexPattern` instance. + + *pattern* (:class:`unicode`, :class:`bytes`, :class:`re.RegexObject`, + or :data:`None`) is the pattern to compile into a regular + expression. + + *include* (:class:`bool` or :data:`None`) must be :data:`None` + unless *pattern* is a precompiled regular expression (:class:`re.RegexObject`) + in which case it is whether matched files should be included + (:data:`True`), excluded (:data:`False`), or is a null operation + (:data:`None`). + + .. NOTE:: Subclasses do not need to support the *include* + parameter. + """ + + self.regex = None + """ + *regex* (:class:`re.RegexObject`) is the regular expression for the + pattern. + """ + + if isinstance(pattern, (unicode, bytes)): + assert include is None, "include:{!r} must be null when pattern:{!r} is a string.".format(include, pattern) + regex, include = self.pattern_to_regex(pattern) + # NOTE: Make sure to allow a null regular expression to be + # returned for a null-operation. + if include is not None: + regex = re.compile(regex) + + elif pattern is not None and hasattr(pattern, 'match'): + # Assume pattern is a precompiled regular expression. + # - NOTE: Used specified *include*. + regex = pattern + + elif pattern is None: + # NOTE: Make sure to allow a null pattern to be passed for a + # null-operation. + assert include is None, "include:{!r} must be null when pattern:{!r} is null.".format(include, pattern) + + else: + raise TypeError("pattern:{!r} is not a string, RegexObject, or None.".format(pattern)) + + super(RegexPattern, self).__init__(include) + self.regex = regex + + def __eq__(self, other): + """ + Tests the equality of this regex pattern with *other* (:class:`RegexPattern`) + by comparing their :attr:`~Pattern.include` and :attr:`~RegexPattern.regex` + attributes. + """ + if isinstance(other, RegexPattern): + return self.include == other.include and self.regex == other.regex + else: + return NotImplemented + + def match(self, files): + """ + Matches this pattern against the specified files. + + *files* (:class:`~collections.abc.Iterable` of :class:`str`) + contains each file relative to the root directory (e.g., "relative/path/to/file"). + + Returns an :class:`~collections.abc.Iterable` yielding each matched + file path (:class:`str`). + """ + if self.include is not None: + for path in files: + if self.regex.match(path) is not None: + yield path + + @classmethod + def pattern_to_regex(cls, pattern): + """ + Convert the pattern into an uncompiled regular expression. + + *pattern* (:class:`str`) is the pattern to convert into a regular + expression. + + Returns the uncompiled regular expression (:class:`str` or :data:`None`), + and whether matched files should be included (:data:`True`), + excluded (:data:`False`), or is a null-operation (:data:`None`). + + .. NOTE:: The default implementation simply returns *pattern* and + :data:`True`. + """ + return pattern, True diff --git a/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/util.py b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/util.py new file mode 100644 index 0000000000000000000000000000000000000000..bcba8783b61c9613aa4b0dec76a36a488a1b3b60 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/_private/thirdparty/pathspec/util.py @@ -0,0 +1,600 @@ +# encoding: utf-8 +""" +This module provides utility methods for dealing with path-specs. +""" + +import os +import os.path +import posixpath +import stat + +from .compat import Collection, Iterable, string_types, unicode + +NORMALIZE_PATH_SEPS = [sep for sep in [os.sep, os.altsep] if sep and sep != posixpath.sep] +""" +*NORMALIZE_PATH_SEPS* (:class:`list` of :class:`str`) contains the path +separators that need to be normalized to the POSIX separator for the +current operating system. The separators are determined by examining +:data:`os.sep` and :data:`os.altsep`. +""" + +_registered_patterns = {} +""" +*_registered_patterns* (:class:`dict`) maps a name (:class:`str`) to the +registered pattern factory (:class:`~collections.abc.Callable`). +""" + + +def detailed_match_files(patterns, files, all_matches=None): + """ + Matches the files to the patterns, and returns which patterns matched + the files. + + *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) + contains the patterns to use. + + *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains + the normalized file paths to be matched against *patterns*. + + *all_matches* (:class:`boot` or :data:`None`) is whether to return all + matches patterns (:data:`True`), or only the last matched pattern + (:data:`False`). Default is :data:`None` for :data:`False`. + + Returns the matched files (:class:`dict`) which maps each matched file + (:class:`str`) to the patterns that matched in order (:class:`.MatchDetail`). + """ + all_files = files if isinstance(files, Collection) else list(files) + return_files = {} + for pattern in patterns: + if pattern.include is not None: + result_files = pattern.match(all_files) + if pattern.include: + # Add files and record pattern. + for result_file in result_files: + if result_file in return_files: + if all_matches: + return_files[result_file].patterns.append(pattern) + else: + return_files[result_file].patterns[0] = pattern + else: + return_files[result_file] = MatchDetail([pattern]) + + else: + # Remove files. + for file in result_files: + del return_files[file] + + return return_files + + +def _is_iterable(value): + """ + Check whether the value is an iterable (excludes strings). + + *value* is the value to check, + + Returns whether *value* is a iterable (:class:`bool`). + """ + return isinstance(value, Iterable) and not isinstance(value, (unicode, bytes)) + + +def iter_tree_entries(root, on_error=None, follow_links=None): + """ + Walks the specified directory for all files and directories. + + *root* (:class:`str`) is the root directory to search. + + *on_error* (:class:`~collections.abc.Callable` or :data:`None`) + optionally is the error handler for file-system exceptions. It will be + called with the exception (:exc:`OSError`). Reraise the exception to + abort the walk. Default is :data:`None` to ignore file-system + exceptions. + + *follow_links* (:class:`bool` or :data:`None`) optionally is whether + to walk symbolic links that resolve to directories. Default is + :data:`None` for :data:`True`. + + Raises :exc:`RecursionError` if recursion is detected. + + Returns an :class:`~collections.abc.Iterable` yielding each file or + directory entry (:class:`.TreeEntry`) relative to *root*. + """ + if on_error is not None and not callable(on_error): + raise TypeError("on_error:{!r} is not callable.".format(on_error)) + + if follow_links is None: + follow_links = True + + for entry in _iter_tree_entries_next(os.path.abspath(root), '', {}, on_error, follow_links): + yield entry + + +def iter_tree_files(root, on_error=None, follow_links=None): + """ + Walks the specified directory for all files. + + *root* (:class:`str`) is the root directory to search for files. + + *on_error* (:class:`~collections.abc.Callable` or :data:`None`) + optionally is the error handler for file-system exceptions. It will be + called with the exception (:exc:`OSError`). Reraise the exception to + abort the walk. Default is :data:`None` to ignore file-system + exceptions. + + *follow_links* (:class:`bool` or :data:`None`) optionally is whether + to walk symbolic links that resolve to directories. Default is + :data:`None` for :data:`True`. + + Raises :exc:`RecursionError` if recursion is detected. + + Returns an :class:`~collections.abc.Iterable` yielding the path to + each file (:class:`str`) relative to *root*. + """ + if on_error is not None and not callable(on_error): + raise TypeError("on_error:{!r} is not callable.".format(on_error)) + + if follow_links is None: + follow_links = True + + for entry in _iter_tree_entries_next(os.path.abspath(root), '', {}, on_error, follow_links): + if not entry.is_dir(follow_links): + yield entry.path + + +# Alias `iter_tree_files()` as `iter_tree()`. +iter_tree = iter_tree_files + + +def _iter_tree_entries_next(root_full, dir_rel, memo, on_error, follow_links): + """ + Scan the directory for all descendant files. + + *root_full* (:class:`str`) the absolute path to the root directory. + + *dir_rel* (:class:`str`) the path to the directory to scan relative to + *root_full*. + + *memo* (:class:`dict`) keeps track of ancestor directories + encountered. Maps each ancestor real path (:class:`str`) to relative + path (:class:`str`). + + *on_error* (:class:`~collections.abc.Callable` or :data:`None`) + optionally is the error handler for file-system exceptions. + + *follow_links* (:class:`bool`) is whether to walk symbolic links that + resolve to directories. + + Yields each entry (:class:`.TreeEntry`). + """ + dir_full = os.path.join(root_full, dir_rel) + dir_real = os.path.realpath(dir_full) + + # Remember each encountered ancestor directory and its canonical + # (real) path. If a canonical path is encountered more than once, + # recursion has occurred. + if dir_real not in memo: + memo[dir_real] = dir_rel + else: + raise RecursionError(real_path=dir_real, first_path=memo[dir_real], second_path=dir_rel) + + for node_name in os.listdir(dir_full): + node_rel = os.path.join(dir_rel, node_name) + node_full = os.path.join(root_full, node_rel) + + # Inspect child node. + try: + node_lstat = os.lstat(node_full) + except OSError as e: + if on_error is not None: + on_error(e) + continue + + if stat.S_ISLNK(node_lstat.st_mode): + # Child node is a link, inspect the target node. + is_link = True + try: + node_stat = os.stat(node_full) + except OSError as e: + if on_error is not None: + on_error(e) + continue + else: + is_link = False + node_stat = node_lstat + + if stat.S_ISDIR(node_stat.st_mode) and (follow_links or not is_link): + # Child node is a directory, recurse into it and yield its + # descendant files. + yield TreeEntry(node_name, node_rel, node_lstat, node_stat) + + for entry in _iter_tree_entries_next(root_full, node_rel, memo, on_error, follow_links): + yield entry + + elif stat.S_ISREG(node_stat.st_mode) or is_link: + # Child node is either a file or an unfollowed link, yield it. + yield TreeEntry(node_name, node_rel, node_lstat, node_stat) + + # NOTE: Make sure to remove the canonical (real) path of the directory + # from the ancestors memo once we are done with it. This allows the + # same directory to appear multiple times. If this is not done, the + # second occurrence of the directory will be incorrectly interpreted + # as a recursion. See . + del memo[dir_real] + + +def lookup_pattern(name): + """ + Lookups a registered pattern factory by name. + + *name* (:class:`str`) is the name of the pattern factory. + + Returns the registered pattern factory (:class:`~collections.abc.Callable`). + If no pattern factory is registered, raises :exc:`KeyError`. + """ + return _registered_patterns[name] + + +def match_file(patterns, file): + """ + Matches the file to the patterns. + + *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) + contains the patterns to use. + + *file* (:class:`str`) is the normalized file path to be matched + against *patterns*. + + Returns :data:`True` if *file* matched; otherwise, :data:`False`. + """ + matched = False + for pattern in patterns: + if pattern.include is not None: + if file in pattern.match((file,)): + matched = pattern.include + return matched + + +def match_files(patterns, files): + """ + Matches the files to the patterns. + + *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) + contains the patterns to use. + + *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains + the normalized file paths to be matched against *patterns*. + + Returns the matched files (:class:`set` of :class:`str`). + """ + all_files = files if isinstance(files, Collection) else list(files) + return_files = set() + for pattern in patterns: + if pattern.include is not None: + result_files = pattern.match(all_files) + if pattern.include: + return_files.update(result_files) + else: + return_files.difference_update(result_files) + return return_files + + +def _normalize_entries(entries, separators=None): + """ + Normalizes the entry paths to use the POSIX path separator. + + *entries* (:class:`~collections.abc.Iterable` of :class:`.TreeEntry`) + contains the entries to be normalized. + + *separators* (:class:`~collections.abc.Collection` of :class:`str`; or + :data:`None`) optionally contains the path separators to normalize. + See :func:`normalize_file` for more information. + + Returns a :class:`dict` mapping the each normalized file path (:class:`str`) + to the entry (:class:`.TreeEntry`) + """ + norm_files = {} + for entry in entries: + norm_files[normalize_file(entry.path, separators=separators)] = entry + return norm_files + + +def normalize_file(file, separators=None): + """ + Normalizes the file path to use the POSIX path separator (i.e., ``'/'``). + + *file* (:class:`str` or :class:`pathlib.PurePath`) is the file path. + + *separators* (:class:`~collections.abc.Collection` of :class:`str`; or + :data:`None`) optionally contains the path separators to normalize. + This does not need to include the POSIX path separator (``'/'``), but + including it will not affect the results. Default is :data:`None` for + :data:`NORMALIZE_PATH_SEPS`. To prevent normalization, pass an empty + container (e.g., an empty tuple ``()``). + + Returns the normalized file path (:class:`str`). + """ + # Normalize path separators. + if separators is None: + separators = NORMALIZE_PATH_SEPS + + # Convert path object to string. + norm_file = str(file) + + for sep in separators: + norm_file = norm_file.replace(sep, posixpath.sep) + + # Remove current directory prefix. + if norm_file.startswith('./'): + norm_file = norm_file[2:] + + return norm_file + + +def normalize_files(files, separators=None): + """ + Normalizes the file paths to use the POSIX path separator. + + *files* (:class:`~collections.abc.Iterable` of :class:`str` or + :class:`pathlib.PurePath`) contains the file paths to be normalized. + + *separators* (:class:`~collections.abc.Collection` of :class:`str`; or + :data:`None`) optionally contains the path separators to normalize. + See :func:`normalize_file` for more information. + + Returns a :class:`dict` mapping the each normalized file path (:class:`str`) + to the original file path (:class:`str`) + """ + norm_files = {} + for path in files: + norm_files[normalize_file(path, separators=separators)] = path + return norm_files + + +def register_pattern(name, pattern_factory, override=None): + """ + Registers the specified pattern factory. + + *name* (:class:`str`) is the name to register the pattern factory + under. + + *pattern_factory* (:class:`~collections.abc.Callable`) is used to + compile patterns. It must accept an uncompiled pattern (:class:`str`) + and return the compiled pattern (:class:`.Pattern`). + + *override* (:class:`bool` or :data:`None`) optionally is whether to + allow overriding an already registered pattern under the same name + (:data:`True`), instead of raising an :exc:`AlreadyRegisteredError` + (:data:`False`). Default is :data:`None` for :data:`False`. + """ + if not isinstance(name, string_types): + raise TypeError("name:{!r} is not a string.".format(name)) + if not callable(pattern_factory): + raise TypeError("pattern_factory:{!r} is not callable.".format(pattern_factory)) + if name in _registered_patterns and not override: + raise AlreadyRegisteredError(name, _registered_patterns[name]) + _registered_patterns[name] = pattern_factory + + +class AlreadyRegisteredError(Exception): + """ + The :exc:`AlreadyRegisteredError` exception is raised when a pattern + factory is registered under a name already in use. + """ + + def __init__(self, name, pattern_factory): + """ + Initializes the :exc:`AlreadyRegisteredError` instance. + + *name* (:class:`str`) is the name of the registered pattern. + + *pattern_factory* (:class:`~collections.abc.Callable`) is the + registered pattern factory. + """ + super(AlreadyRegisteredError, self).__init__(name, pattern_factory) + + @property + def message(self): + """ + *message* (:class:`str`) is the error message. + """ + return "{name!r} is already registered for pattern factory:{pattern_factory!r}.".format( + name=self.name, + pattern_factory=self.pattern_factory, + ) + + @property + def name(self): + """ + *name* (:class:`str`) is the name of the registered pattern. + """ + return self.args[0] + + @property + def pattern_factory(self): + """ + *pattern_factory* (:class:`~collections.abc.Callable`) is the + registered pattern factory. + """ + return self.args[1] + + +class RecursionError(Exception): + """ + The :exc:`RecursionError` exception is raised when recursion is + detected. + """ + + def __init__(self, real_path, first_path, second_path): + """ + Initializes the :exc:`RecursionError` instance. + + *real_path* (:class:`str`) is the real path that recursion was + encountered on. + + *first_path* (:class:`str`) is the first path encountered for + *real_path*. + + *second_path* (:class:`str`) is the second path encountered for + *real_path*. + """ + super(RecursionError, self).__init__(real_path, first_path, second_path) + + @property + def first_path(self): + """ + *first_path* (:class:`str`) is the first path encountered for + :attr:`self.real_path `. + """ + return self.args[1] + + @property + def message(self): + """ + *message* (:class:`str`) is the error message. + """ + return "Real path {real!r} was encountered at {first!r} and then {second!r}.".format( + real=self.real_path, + first=self.first_path, + second=self.second_path, + ) + + @property + def real_path(self): + """ + *real_path* (:class:`str`) is the real path that recursion was + encountered on. + """ + return self.args[0] + + @property + def second_path(self): + """ + *second_path* (:class:`str`) is the second path encountered for + :attr:`self.real_path `. + """ + return self.args[2] + + +class MatchDetail(object): + """ + The :class:`.MatchDetail` class contains information about + """ + + #: Make the class dict-less. + __slots__ = ('patterns',) + + def __init__(self, patterns): + """ + Initialize the :class:`.MatchDetail` instance. + + *patterns* (:class:`~collections.abc.Sequence` of :class:`~pathspec.pattern.Pattern`) + contains the patterns that matched the file in the order they were + encountered. + """ + + self.patterns = patterns + """ + *patterns* (:class:`~collections.abc.Sequence` of :class:`~pathspec.pattern.Pattern`) + contains the patterns that matched the file in the order they were + encountered. + """ + + +class TreeEntry(object): + """ + The :class:`.TreeEntry` class contains information about a file-system + entry. + """ + + #: Make the class dict-less. + __slots__ = ('_lstat', 'name', 'path', '_stat') + + def __init__(self, name, path, lstat, stat): + """ + Initialize the :class:`.TreeEntry` instance. + + *name* (:class:`str`) is the base name of the entry. + + *path* (:class:`str`) is the relative path of the entry. + + *lstat* (:class:`~os.stat_result`) is the stat result of the direct + entry. + + *stat* (:class:`~os.stat_result`) is the stat result of the entry, + potentially linked. + """ + + self._lstat = lstat + """ + *_lstat* (:class:`~os.stat_result`) is the stat result of the direct + entry. + """ + + self.name = name + """ + *name* (:class:`str`) is the base name of the entry. + """ + + self.path = path + """ + *path* (:class:`str`) is the path of the entry. + """ + + self._stat = stat + """ + *_stat* (:class:`~os.stat_result`) is the stat result of the linked + entry. + """ + + def is_dir(self, follow_links=None): + """ + Get whether the entry is a directory. + + *follow_links* (:class:`bool` or :data:`None`) is whether to follow + symbolic links. If this is :data:`True`, a symlink to a directory + will result in :data:`True`. Default is :data:`None` for :data:`True`. + + Returns whether the entry is a directory (:class:`bool`). + """ + if follow_links is None: + follow_links = True + + node_stat = self._stat if follow_links else self._lstat + return stat.S_ISDIR(node_stat.st_mode) + + def is_file(self, follow_links=None): + """ + Get whether the entry is a regular file. + + *follow_links* (:class:`bool` or :data:`None`) is whether to follow + symbolic links. If this is :data:`True`, a symlink to a regular file + will result in :data:`True`. Default is :data:`None` for :data:`True`. + + Returns whether the entry is a regular file (:class:`bool`). + """ + if follow_links is None: + follow_links = True + + node_stat = self._stat if follow_links else self._lstat + return stat.S_ISREG(node_stat.st_mode) + + def is_symlink(self): + """ + Returns whether the entry is a symbolic link (:class:`bool`). + """ + return stat.S_ISLNK(self._lstat.st_mode) + + def stat(self, follow_links=None): + """ + Get the cached stat result for the entry. + + *follow_links* (:class:`bool` or :data:`None`) is whether to follow + symbolic links. If this is :data:`True`, the stat result of the + linked file will be returned. Default is :data:`None` for :data:`True`. + + Returns that stat result (:class:`~os.stat_result`). + """ + if follow_links is None: + follow_links = True + + return self._stat if follow_links else self._lstat diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/block_builder.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/block_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..d3c232200a9d5ad18b8037b148f539aa6b2b721a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/block_builder.py @@ -0,0 +1,39 @@ +from typing import Generic + +from ray.data.block import Block, BlockAccessor, BlockType, T + + +class BlockBuilder(Generic[T]): + """A builder class for blocks.""" + + @staticmethod + def for_block(block: Block) -> "BlockBuilder": + return BlockAccessor.for_block(block).builder() + + def add(self, item: T) -> None: + """Append a single row to the block being built.""" + raise NotImplementedError + + def add_block(self, block: Block) -> None: + """Append an entire block to the block being built.""" + raise NotImplementedError + + def will_build_yield_copy(self) -> bool: + """Whether building this block will yield a new block copy.""" + raise NotImplementedError + + def build(self) -> Block: + """Build the block.""" + raise NotImplementedError + + def num_rows(self) -> int: + """Return the number of rows added in the block.""" + raise NotImplementedError + + def get_estimated_memory_usage(self) -> int: + """Return the estimated memory usage so far in bytes.""" + raise NotImplementedError + + def block_type(self) -> BlockType: + """Return the block type.""" + raise NotImplementedError diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/block_list.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/block_list.py new file mode 100644 index 0000000000000000000000000000000000000000..d04c5ec658a53d67bd60a91ee07dd670f18068b8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/block_list.py @@ -0,0 +1,98 @@ +from typing import Iterator, List, Tuple + +from ray.data._internal.memory_tracing import trace_allocation +from ray.data.block import Block, BlockMetadata +from ray.types import ObjectRef + + +class BlockList: + """A list of blocks that may be computed or pending computation. + + All blocks are known ahead of time + """ + + def __init__( + self, + blocks: List[ObjectRef[Block]], + metadata: List[BlockMetadata], + *, + owned_by_consumer: bool, + ): + assert len(blocks) == len(metadata), (blocks, metadata) + for b in blocks: + trace_allocation(b, "BlockList.__init__") + self._blocks: List[ObjectRef[Block]] = blocks + self._num_blocks = len(self._blocks) + self._metadata: List[BlockMetadata] = metadata + # Whether the block list is owned by consuming APIs, and if so it can be + # eagerly deleted after read by the consumer. + self._owned_by_consumer = owned_by_consumer + # This field can be set to indicate the number of estimated output blocks, + # since each read task may produce multiple output blocks after splitting. + self._estimated_num_blocks = None + + def __repr__(self): + return f"BlockList(owned_by_consumer={self._owned_by_consumer})" + + def get_metadata(self, fetch_if_missing: bool = False) -> List[BlockMetadata]: + """Get the metadata for all blocks.""" + return self._metadata.copy() + + def copy(self) -> "BlockList": + """Perform a shallow copy of this BlockList.""" + return BlockList( + self._blocks, self._metadata, owned_by_consumer=self._owned_by_consumer + ) + + def clear(self) -> None: + """Erase references to the tasks tracked by the BlockList.""" + self._blocks = None + + def is_cleared(self) -> bool: + """Whether this BlockList has been cleared.""" + return self._blocks is None + + def _check_if_cleared(self) -> None: + """Raise an error if this BlockList has been previously cleared.""" + if self.is_cleared(): + raise ValueError( + "This Dataset's blocks have been moved, which means that you " + "can no longer use this Dataset." + ) + + def get_blocks(self) -> List[ObjectRef[Block]]: + """Get list of the blocks of this block list. + + This blocks on the execution of the tasks generating block outputs. + The length of this iterator is not known until execution. + """ + self._check_if_cleared() + return list(self._blocks) + + def get_blocks_with_metadata(self) -> List[Tuple[ObjectRef[Block], BlockMetadata]]: + """Bulk version of iter_blocks_with_metadata(). + + Prefer calling this instead of the iter form for performance if you + don't need lazy evaluation. + """ + self.get_blocks() + return list(self.iter_blocks_with_metadata()) + + def iter_blocks_with_metadata( + self, + ) -> Iterator[Tuple[ObjectRef[Block], BlockMetadata]]: + """Iterate over the blocks along with their runtime metadata. + + This blocks on the execution of the tasks generating block outputs. + The length of this iterator is not known until execution. + """ + self._check_if_cleared() + return zip(self._blocks, self._metadata) + + def initial_num_blocks(self) -> int: + """Returns the number of blocks of this BlockList.""" + return self._num_blocks + + def estimated_num_blocks(self) -> int: + """Estimate of number of output blocks, without triggering actual execution.""" + return self._estimated_num_blocks or self._num_blocks diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/compute.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/compute.py new file mode 100644 index 0000000000000000000000000000000000000000..1590469d0325f3da64537c7d0ff1c18457a05bdb --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/compute.py @@ -0,0 +1,151 @@ +import logging +from typing import Any, Callable, Iterable, Optional, TypeVar, Union + +from ray.data._internal.execution.interfaces import TaskContext +from ray.data.block import Block, UserDefinedFunction +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger(__name__) + +T = TypeVar("T") +U = TypeVar("U") + + +# Block transform function applied by task and actor pools. +BlockTransform = Union[ + # TODO(Clark): Once Ray only supports Python 3.8+, use protocol to constrain block + # transform type. + # Callable[[Block, ...], Iterable[Block]] + # Callable[[Block, UserDefinedFunction, ...], Iterable[Block]], + Callable[[Iterable[Block], TaskContext], Iterable[Block]], + Callable[[Iterable[Block], TaskContext, UserDefinedFunction], Iterable[Block]], + Callable[..., Iterable[Block]], +] + + +@DeveloperAPI +class ComputeStrategy: + pass + + +@DeveloperAPI +class TaskPoolStrategy(ComputeStrategy): + def __init__( + self, + size: Optional[int] = None, + ): + """Construct TaskPoolStrategy for a Dataset transform. + + Args: + size: Specify the maximum size of the task pool. + """ + + if size is not None and size < 1: + raise ValueError("`size` must be >= 1", size) + self.size = size + + def __eq__(self, other: Any) -> bool: + return (isinstance(other, TaskPoolStrategy) and self.size == other.size) or ( + other == "tasks" and self.size is None + ) + + +class ActorPoolStrategy(ComputeStrategy): + """Specify the compute strategy for a Dataset transform. + + ActorPoolStrategy specifies that an autoscaling pool of actors should be used + for a given Dataset transform. This is useful for stateful setup of callable + classes. + + For a fixed-sized pool of size ``n``, specify ``compute=ActorPoolStrategy(size=n)``. + To autoscale from ``m`` to ``n`` actors, specify + ``ActorPoolStrategy(min_size=m, max_size=n)``. + + To increase opportunities for pipelining task dependency prefetching with + computation and avoiding actor startup delays, set max_tasks_in_flight_per_actor + to 2 or greater; to try to decrease the delay due to queueing of tasks on the worker + actors, set max_tasks_in_flight_per_actor to 1. + """ + + def __init__( + self, + *, + size: Optional[int] = None, + min_size: Optional[int] = None, + max_size: Optional[int] = None, + max_tasks_in_flight_per_actor: Optional[int] = None, + ): + """Construct ActorPoolStrategy for a Dataset transform. + + Args: + size: Specify a fixed size actor pool of this size. It is an error to + specify both `size` and `min_size` or `max_size`. + min_size: The minimize size of the actor pool. + max_size: The maximum size of the actor pool. + max_tasks_in_flight_per_actor: The maximum number of tasks to concurrently + send to a single actor worker. Increasing this will increase + opportunities for pipelining task dependency prefetching with + computation and avoiding actor startup delays, but will also increase + queueing delay. + """ + if size is not None: + if size < 1: + raise ValueError("size must be >= 1", size) + if max_size is not None or min_size is not None: + raise ValueError( + "min_size and max_size cannot be set at the same time as `size`" + ) + min_size = size + max_size = size + if min_size is not None and min_size < 1: + raise ValueError("min_size must be >= 1", min_size) + if max_size is not None: + if min_size is None: + min_size = 1 # Legacy default. + if min_size > max_size: + raise ValueError("min_size must be <= max_size", min_size, max_size) + if ( + max_tasks_in_flight_per_actor is not None + and max_tasks_in_flight_per_actor < 1 + ): + raise ValueError( + "max_tasks_in_flight_per_actor must be >= 1, got: ", + max_tasks_in_flight_per_actor, + ) + self.min_size = min_size or 1 + self.max_size = max_size or float("inf") + self.max_tasks_in_flight_per_actor = max_tasks_in_flight_per_actor + self.num_workers = 0 + self.ready_to_total_workers_ratio = 0.8 + + def __eq__(self, other: Any) -> bool: + return isinstance(other, ActorPoolStrategy) and ( + self.min_size == other.min_size + and self.max_size == other.max_size + and self.max_tasks_in_flight_per_actor + == other.max_tasks_in_flight_per_actor + ) + + +def get_compute(compute_spec: Union[str, ComputeStrategy]) -> ComputeStrategy: + if not isinstance(compute_spec, (TaskPoolStrategy, ActorPoolStrategy)): + raise ValueError( + "In Ray 2.5, the compute spec must be either " + f"TaskPoolStrategy or ActorPoolStategy, was: {compute_spec}." + ) + elif not compute_spec or compute_spec == "tasks": + return TaskPoolStrategy() + elif compute_spec == "actors": + return ActorPoolStrategy() + elif isinstance(compute_spec, ComputeStrategy): + return compute_spec + else: + raise ValueError("compute must be one of [`tasks`, `actors`, ComputeStrategy]") + + +def is_task_compute(compute_spec: Union[str, ComputeStrategy]) -> bool: + return ( + not compute_spec + or compute_spec == "tasks" + or isinstance(compute_spec, TaskPoolStrategy) + ) diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/delegating_block_builder.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/delegating_block_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..4655a8e241485bfc5ed284c77164ecfe8a632ece --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/delegating_block_builder.py @@ -0,0 +1,76 @@ +import collections +from typing import Any, Mapping, Optional + +from ray.data._internal.arrow_block import ArrowBlockBuilder +from ray.data._internal.block_builder import BlockBuilder +from ray.data.block import Block, BlockAccessor, BlockType, DataBatch + + +class DelegatingBlockBuilder(BlockBuilder): + def __init__(self): + self._builder = None + self._empty_block = None + + @property + def _inferred_block_type(self) -> Optional[BlockType]: + """The block type inferred from the first item added to the builder.""" + if self._builder is not None: + return self._builder.block_type() + return None + + def add(self, item: Mapping[str, Any]) -> None: + assert isinstance(item, collections.abc.Mapping), item + + if self._builder is None: + self._builder = ArrowBlockBuilder() + + self._builder.add(item) + + def add_batch(self, batch: DataBatch): + """Add a user-facing data batch to the builder. + + This data batch will be converted to an internal block and then added to the + underlying builder. + """ + block = BlockAccessor.batch_to_block(batch, self._inferred_block_type) + return self.add_block(block) + + def add_block(self, block: Block): + accessor = BlockAccessor.for_block(block) + if accessor.num_rows() == 0: + # Don't infer types of empty lists. Store the block and use it if no + # other data is added. https://github.com/ray-project/ray/issues/20290 + self._empty_block = block + return + if self._builder is None: + self._builder = accessor.builder() + else: + block_type = accessor.block_type() + assert block_type == self._inferred_block_type, ( + block_type, + self._inferred_block_type, + ) + + self._builder.add_block(accessor.to_block()) + + def will_build_yield_copy(self) -> bool: + if self._builder is None: + return True + return self._builder.will_build_yield_copy() + + def build(self) -> Block: + if self._builder is None: + if self._empty_block is not None: + self._builder = BlockAccessor.for_block(self._empty_block).builder() + self._builder.add_block(self._empty_block) + else: + self._builder = ArrowBlockBuilder() + return self._builder.build() + + def num_rows(self) -> int: + return self._builder.num_rows() if self._builder is not None else 0 + + def get_estimated_memory_usage(self) -> int: + if self._builder is None: + return 0 + return self._builder.get_estimated_memory_usage() diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/__init__.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/__pycache__/streaming_executor.cpython-310.pyc b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/__pycache__/streaming_executor.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4244f2959c5b2d5ffd6b3eda2baae194f7537d83 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/__pycache__/streaming_executor.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/autoscaling_requester.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/autoscaling_requester.py new file mode 100644 index 0000000000000000000000000000000000000000..512c3c16f488130f32ac3993bc4b24a84e5ac4fd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/autoscaling_requester.py @@ -0,0 +1,131 @@ +import math +import threading +import time +from typing import Dict, List + +import ray +from ray.data.context import DataContext +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy + +# Resource requests are considered stale after this number of seconds, and +# will be purged. +RESOURCE_REQUEST_TIMEOUT = 60 +PURGE_INTERVAL = RESOURCE_REQUEST_TIMEOUT * 2 + +# When the autoscaling is driven by memory pressure and there are abundant +# CPUs to support incremental CPUs needed to launch more tasks, we'll translate +# memory pressure into an artificial request of CPUs. The amount of CPUs we'll +# request is ARTIFICIAL_CPU_SCALING_FACTOR * ray.cluster_resources()["CPU"]. +ARTIFICIAL_CPU_SCALING_FACTOR = 1.2 + + +@ray.remote(num_cpus=0, max_restarts=-1, max_task_retries=-1) +class AutoscalingRequester: + """Actor to make resource requests to autoscaler for the datasets. + + The resource requests are set to timeout after RESOURCE_REQUEST_TIMEOUT seconds. + For those live requests, we keep track of the last request made for each execution, + which overrides all previous requests it made; then sum the requested amounts + across all executions as the final request to the autoscaler. + """ + + def __init__(self): + # execution_id -> (List[Dict], expiration timestamp) + self._resource_requests = {} + # TTL for requests. + self._timeout = RESOURCE_REQUEST_TIMEOUT + + self._self_handle = ray.get_runtime_context().current_actor + + # Start a thread to purge expired requests periodically. + def purge_thread_run(): + while True: + time.sleep(PURGE_INTERVAL) + # Call purge_expired_requests() as an actor task, + # so we don't need to handle multi-threading. + ray.get(self._self_handle.purge_expired_requests.remote()) + + self._purge_thread = threading.Thread(target=purge_thread_run, daemon=True) + self._purge_thread.start() + + def purge_expired_requests(self): + self._purge() + ray.autoscaler.sdk.request_resources(bundles=self._aggregate_requests()) + + def request_resources(self, req: List[Dict], execution_id: str): + # Purge expired requests before making request to autoscaler. + self._purge() + # For the same execution_id, we track the latest resource request and + # the its expiration timestamp. + self._resource_requests[execution_id] = ( + req, + time.time() + self._timeout, + ) + # We aggregate the resource requests across all execution_id's to Ray + # autoscaler. + ray.autoscaler.sdk.request_resources(bundles=self._aggregate_requests()) + + def _purge(self): + # Purge requests that are stale. + now = time.time() + for k, (_, t) in list(self._resource_requests.items()): + if t < now: + self._resource_requests.pop(k) + + def _aggregate_requests(self) -> List[Dict]: + req = [] + for _, (r, _) in self._resource_requests.items(): + req.extend(r) + + def get_cpus(req): + num_cpus = 0 + for r in req: + if "CPU" in r: + num_cpus += r["CPU"] + return num_cpus + + # Round up CPUs to exceed total cluster CPUs so it can actually upscale. + # This is to handle the issue where the autoscaling is driven by memory + # pressure (rather than CPUs) from streaming executor. In such case, simply + # asking for incremental CPUs (e.g. 1 CPU for each ready operator) may not + # actually be able to trigger autoscaling if existing CPUs in cluster can + # already satisfy the incremental CPUs request. + num_cpus = get_cpus(req) + if num_cpus > 0: + total = ray.cluster_resources() + if "CPU" in total and num_cpus <= total["CPU"]: + delta = ( + math.ceil(ARTIFICIAL_CPU_SCALING_FACTOR * total["CPU"]) - num_cpus + ) + req.extend([{"CPU": 1}] * delta) + + return req + + def _test_set_timeout(self, ttl): + """Set the timeout. This is for test only""" + self._timeout = ttl + + +# Creating/getting an actor from multiple threads is not safe. +# https://github.com/ray-project/ray/issues/41324 +_autoscaling_requester_lock: threading.RLock = threading.RLock() + + +def get_or_create_autoscaling_requester_actor(): + ctx = DataContext.get_current() + scheduling_strategy = ctx.scheduling_strategy + # Pin the stats actor to the local node so it fate-shares with the driver. + # Note: for Ray Client, the ray.get_runtime_context().get_node_id() should + # point to the head node. + scheduling_strategy = NodeAffinitySchedulingStrategy( + ray.get_runtime_context().get_node_id(), + soft=False, + ) + with _autoscaling_requester_lock: + return AutoscalingRequester.options( + name="AutoscalingRequester", + namespace="AutoscalingRequester", + get_if_exists=True, + lifetime="detached", + scheduling_strategy=scheduling_strategy, + ).remote() diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/bundle_queue/__init__.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/bundle_queue/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa51465258e2838a6b55b928ad3c0d0361a90d38 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/bundle_queue/__init__.py @@ -0,0 +1,9 @@ +from .bundle_queue import BundleQueue +from .fifo_bundle_queue import FIFOBundleQueue + + +def create_bundle_queue() -> BundleQueue: + return FIFOBundleQueue() + + +__all__ = ["BundleQueue", "create_bundle_queue"] diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/bundle_queue/bundle_queue.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/bundle_queue/bundle_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..f11bacf14c333febd11d840b3f4f369491a74f96 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/bundle_queue/bundle_queue.py @@ -0,0 +1,62 @@ +import abc +from typing import TYPE_CHECKING, Optional + +if TYPE_CHECKING: + from ray.data._internal.execution.interfaces import RefBundle + + +class BundleQueue(abc.ABC): + @abc.abstractmethod + def __len__(self) -> int: + """Return the number of bundles in the queue.""" + ... + + @abc.abstractmethod + def __contains__(self, bundle: "RefBundle") -> bool: + """Return whether the bundle is in the queue.""" + ... + + @abc.abstractmethod + def add(self, bundle: "RefBundle") -> None: + """Add a bundle to the queue.""" + ... + + @abc.abstractmethod + def pop(self) -> "RefBundle": + """Remove and return the head of the queue. + + Raises: + IndexError: If the queue is empty. + """ + ... + + @abc.abstractmethod + def peek(self) -> Optional["RefBundle"]: + """Return the head of the queue without removing it. + + If the queue is empty, return `None`. + """ + ... + + @abc.abstractmethod + def remove(self, bundle: "RefBundle"): + """Remove a bundle from the queue.""" + ... + + @abc.abstractmethod + def clear(self): + """Remove all bundles from the queue.""" + ... + + @abc.abstractmethod + def estimate_size_bytes(self) -> int: + """Return an estimate of the total size of objects in the queue.""" + ... + + @abc.abstractmethod + def is_empty(self): + """Return whether this queue and all of its internal data structures are empty. + + This method is used for testing. + """ + ... diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/bundle_queue/fifo_bundle_queue.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/bundle_queue/fifo_bundle_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..4422c8798eac423f7b3e0276a1b9575d5d906e96 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/bundle_queue/fifo_bundle_queue.py @@ -0,0 +1,129 @@ +from collections import defaultdict, deque +from dataclasses import dataclass +from typing import TYPE_CHECKING, Dict, List, Optional + +from .bundle_queue import BundleQueue + +if TYPE_CHECKING: + from ray.data._internal.execution.interfaces import RefBundle + + +@dataclass +class _Node: + value: "RefBundle" + next: Optional["_Node"] = None + prev: Optional["_Node"] = None + + +class FIFOBundleQueue(BundleQueue): + """A bundle queue that follows a first-in-first-out policy.""" + + def __init__(self): + # We manually implement a linked list because we need to remove elements + # efficiently, and Python's built-in data structures have O(n) removal time. + self._head: Optional[_Node] = None + self._tail: Optional[_Node] = None + # We use a dictionary to keep track of the nodes corresponding to each bundle. + # This allows us to remove a bundle from the queue in O(1) time. We need a list + # because a bundle can be added to the queue multiple times. Nodes in each list + # are insertion-ordered. + self._bundle_to_nodes: Dict["RefBundle", List[_Node]] = defaultdict(deque) + + self._nbytes = 0 + self._num_bundles = 0 + + def __len__(self) -> int: + return self._num_bundles + + def __contains__(self, bundle: "RefBundle") -> bool: + return bundle in self._bundle_to_nodes + + def add(self, bundle: "RefBundle") -> None: + """Add a bundle to the end (right) of the queue.""" + new_node = _Node(value=bundle, next=None, prev=self._tail) + # Case 1: The queue is empty. + if self._head is None: + assert self._tail is None + self._head = new_node + self._tail = new_node + # Case 2: The queue has at least one element. + else: + self._tail.next = new_node + self._tail = new_node + + self._bundle_to_nodes[bundle].append(new_node) + + self._nbytes += bundle.size_bytes() + self._num_bundles += 1 + + def pop(self) -> "RefBundle": + """Return the first (left) bundle in the queue.""" + # Case 1: The queue is empty. + if not self._head: + raise IndexError("You can't pop from an empty queue") + + bundle = self._head.value + self.remove(bundle) + + return bundle + + def peek(self) -> Optional["RefBundle"]: + """Return the first (left) bundle in the queue without removing it.""" + if self._head is None: + return None + + return self._head.value + + def remove(self, bundle: "RefBundle"): + """Remove a bundle from the queue. + + If there are multiple instances of the bundle in the queue, this method only + removes the first one. + """ + # Case 1: The queue is empty. + if bundle not in self._bundle_to_nodes: + raise ValueError(f"The bundle {bundle} is not in the queue.") + + node = self._bundle_to_nodes[bundle].popleft() + if not self._bundle_to_nodes[bundle]: + del self._bundle_to_nodes[bundle] + + # Case 2: The bundle is the only element in the queue. + if self._head is self._tail: + self._head = None + self._tail = None + # Case 3: The bundle is the first element in the queue. + elif node is self._head: + self._head = node.next + self._head.prev = None + # Case 4: The bundle is the last element in the queue. + elif node is self._tail: + self._tail = node.prev + self._tail.next = None + # Case 5: The bundle is in the middle of the queue. + else: + node.prev.next = node.next + node.next.prev = node.prev + + self._nbytes -= bundle.size_bytes() + assert self._nbytes >= 0, ( + "Expected the total size of objects in the queue to be non-negative, but " + f"got {self._nbytes} bytes instead." + ) + + self._num_bundles -= 1 + + return node.value + + def clear(self): + self._head = None + self._tail = None + self._bundle_to_nodes.clear() + self._nbytes = 0 + self._num_bundles = 0 + + def estimate_size_bytes(self) -> int: + return self._nbytes + + def is_empty(self): + return not self._bundle_to_nodes and self._head is None and self._tail is None diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/legacy_compat.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/legacy_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..3ef7ca0d08979f8e3ca8735f6557d7afba5142e5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/legacy_compat.py @@ -0,0 +1,181 @@ +"""This file contains temporary helper functions for legacy plan/executor interaction. + +It should be deleted once we fully move to the new executor backend. +""" + +from typing import Iterator, Optional, Tuple + +from ray.data._internal.block_list import BlockList +from ray.data._internal.execution.interfaces import ( + Executor, + PhysicalOperator, + RefBundle, +) +from ray.data._internal.execution.interfaces.executor import OutputIterator +from ray.data._internal.logical.optimizers import get_execution_plan +from ray.data._internal.logical.util import record_operators_usage +from ray.data._internal.plan import ExecutionPlan +from ray.data._internal.stats import DatasetStats +from ray.data._internal.util import unify_block_metadata_schema +from ray.data.block import BlockMetadata + +# Warn about tasks larger than this. +TASK_SIZE_WARN_THRESHOLD_BYTES = 100000 + + +def execute_to_legacy_bundle_iterator( + executor: Executor, + plan: ExecutionPlan, + dag_rewrite=None, +) -> Iterator[RefBundle]: + """Execute a plan with the new executor and return a bundle iterator. + + Args: + executor: The executor to use. + plan: The legacy plan to execute. + dag_rewrite: Callback that can be used to mutate the DAG prior to execution. + This is currently used as a legacy hack to inject the OutputSplit operator + for `Dataset.streaming_split()`. + + Returns: + The output as a bundle iterator. + """ + dag, stats = _get_execution_dag( + executor, + plan, + preserve_order=False, + ) + if dag_rewrite: + dag = dag_rewrite(dag) + + bundle_iter = executor.execute(dag, initial_stats=stats) + + class CacheMetadataIterator(OutputIterator): + """Wrapper for `bundle_iterator` above. + + For a given iterator which yields output RefBundles, + collect the metadata from each output bundle, and yield the + original RefBundle. Only after the entire iterator is exhausted, + we cache the resulting metadata to the execution plan.""" + + def __init__(self, base_iterator: OutputIterator): + # Note: the base_iterator should be of type StreamIterator, + # defined within `StreamingExecutor.execute()`. It must + # support the `get_next()` method. + self._base_iterator = base_iterator + self._collected_metadata = BlockMetadata( + num_rows=0, + size_bytes=0, + schema=None, + input_files=None, + exec_stats=None, + ) + + def get_next(self, output_split_idx: Optional[int] = None) -> RefBundle: + try: + bundle = self._base_iterator.get_next(output_split_idx) + self._collect_metadata(bundle) + return bundle + except StopIteration: + # Once the iterator is completely exhausted, we are done + # collecting metadata. We can add this cached metadata to the plan. + plan._snapshot_metadata = self._collected_metadata + raise + + def _collect_metadata(self, bundle: RefBundle) -> RefBundle: + """Collect the metadata from each output bundle and accumulate + results, so we can access important information, such as + row count, schema, etc., after iteration completes.""" + self._collected_metadata.num_rows += bundle.num_rows() + self._collected_metadata.size_bytes += bundle.size_bytes() + self._collected_metadata.schema = unify_block_metadata_schema( + [self._collected_metadata, *bundle.metadata] + ) + return bundle + + bundle_iter = CacheMetadataIterator(bundle_iter) + return bundle_iter + + +def execute_to_legacy_block_list( + executor: Executor, + plan: ExecutionPlan, + dataset_uuid: str, + preserve_order: bool, +) -> BlockList: + """Execute a plan with the new executor and translate it into a legacy block list. + + Args: + executor: The executor to use. + plan: The legacy plan to execute. + dataset_uuid: UUID of the dataset for this execution. + preserve_order: Whether to preserve order in execution. + + Returns: + The output as a legacy block list. + """ + dag, stats = _get_execution_dag( + executor, + plan, + preserve_order, + ) + bundles = executor.execute(dag, initial_stats=stats) + block_list = _bundles_to_block_list(bundles) + # Set the stats UUID after execution finishes. + _set_stats_uuid_recursive(executor.get_stats(), dataset_uuid) + return block_list + + +def _get_execution_dag( + executor: Executor, + plan: ExecutionPlan, + preserve_order: bool, +) -> Tuple[PhysicalOperator, DatasetStats]: + """Get the physical operators DAG from a plan.""" + # Record usage of logical operators if available. + if hasattr(plan, "_logical_plan") and plan._logical_plan is not None: + record_operators_usage(plan._logical_plan.dag) + + # Get DAG of physical operators and input statistics. + dag = get_execution_plan(plan._logical_plan).dag + stats = _get_initial_stats_from_plan(plan) + + # Enforce to preserve ordering if the plan has operators + # required to do so, such as Zip and Sort. + if preserve_order or plan.require_preserve_order(): + executor._options.preserve_order = True + + return dag, stats + + +def _get_initial_stats_from_plan(plan: ExecutionPlan) -> DatasetStats: + if plan._snapshot_bundle is not None: + return plan._snapshot_stats + # For Datasets created from "read_xxx", `plan._in_stats` contains useless data. + # For Datasets created from "from_xxx", we need to use `plan._in_stats` as + # the initial stats. Because the `FromXxx` logical operators will be translated to + # "InputDataBuffer" physical operators, which will be ignored when generating + # stats, see `StreamingExecutor._generate_stats`. + # TODO(hchen): Unify the logic by saving the initial stats in `InputDataBuffer + if plan.has_lazy_input(): + return DatasetStats(metadata={}, parent=None) + else: + return plan._in_stats + + +def _bundles_to_block_list(bundles: Iterator[RefBundle]) -> BlockList: + blocks, metadata = [], [] + owns_blocks = True + for ref_bundle in bundles: + if not ref_bundle.owns_blocks: + owns_blocks = False + blocks.extend(ref_bundle.block_refs) + metadata.extend(ref_bundle.metadata) + return BlockList(blocks, metadata, owned_by_consumer=owns_blocks) + + +def _set_stats_uuid_recursive(stats: DatasetStats, dataset_uuid: str) -> None: + if not stats.dataset_uuid: + stats.dataset_uuid = dataset_uuid + for parent in stats.parents or []: + _set_stats_uuid_recursive(parent, dataset_uuid) diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/resource_manager.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/resource_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..32b23443c7ed4cc58610ab028ed8f89968358f88 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/resource_manager.py @@ -0,0 +1,637 @@ +import logging +import os +import time +from abc import ABC, abstractmethod +from collections import defaultdict +from typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Optional + +from ray.data._internal.execution.interfaces.execution_options import ( + ExecutionOptions, + ExecutionResources, +) +from ray.data._internal.execution.interfaces.physical_operator import PhysicalOperator +from ray.data._internal.execution.operators.input_data_buffer import InputDataBuffer +from ray.data._internal.execution.util import memory_string +from ray.data.context import DataContext + +if TYPE_CHECKING: + from ray.data._internal.execution.streaming_executor_state import Topology + + +logger = logging.getLogger(__name__) +DEBUG_RESOURCE_MANAGER = os.environ.get("RAY_DATA_DEBUG_RESOURCE_MANAGER", "0") == "1" + + +class ResourceManager: + """A class that manages the resource usage of a streaming executor.""" + + # The interval in seconds at which the global resource limits are refreshed. + GLOBAL_LIMITS_UPDATE_INTERVAL_S = 10 + + # The fraction of the object store capacity that will be used as the default object + # store memory limit for the streaming executor, + # when `ReservationOpResourceAllocator` is enabled. + DEFAULT_OBJECT_STORE_MEMORY_LIMIT_FRACTION = 0.5 + + # The fraction of the object store capacity that will be used as the default object + # store memory limit for the streaming executor, + # when `ReservationOpResourceAllocator` is not enabled. + DEFAULT_OBJECT_STORE_MEMORY_LIMIT_FRACTION_WO_RESOURCE_RESERVATION = 0.25 + + def __init__( + self, + topology: "Topology", + options: ExecutionOptions, + get_total_resources: Callable[[], ExecutionResources], + ): + self._topology = topology + self._options = options + self._get_total_resources = get_total_resources + self._global_limits = ExecutionResources.zero() + self._global_limits_last_update_time = 0 + self._global_usage = ExecutionResources.zero() + self._global_running_usage = ExecutionResources.zero() + self._global_pending_usage = ExecutionResources.zero() + self._op_usages: Dict[PhysicalOperator, ExecutionResources] = {} + self._op_running_usages: Dict[PhysicalOperator, ExecutionResources] = {} + self._op_pending_usages: Dict[PhysicalOperator, ExecutionResources] = {} + # Object store memory usage internal to the operator, including the + # pending task outputs and op's internal output buffers. + self._mem_op_internal: Dict[PhysicalOperator, int] = defaultdict(int) + # Object store memory usage of the blocks that have been taken out of + # the operator, including the external output buffer in OpState, and the + # input buffers of the downstream operators. + self._mem_op_outputs: Dict[PhysicalOperator, int] = defaultdict(int) + # Whether to print debug information. + self._debug = DEBUG_RESOURCE_MANAGER + + self._downstream_fraction: Dict[PhysicalOperator, float] = {} + self._downstream_object_store_memory: Dict[PhysicalOperator, float] = {} + + self._op_resource_allocator: Optional["OpResourceAllocator"] = None + ctx = DataContext.get_current() + + if ctx.op_resource_reservation_enabled: + # We'll enable memory reservation if all operators have + # implemented accurate memory accounting. + should_enable = all( + op.implements_accurate_memory_accounting() for op in topology + ) + if should_enable: + self._op_resource_allocator = ReservationOpResourceAllocator( + self, ctx.op_resource_reservation_ratio + ) + + def _estimate_object_store_memory(self, op, state) -> int: + # Don't count input refs towards dynamic memory usage, as they have been + # pre-created already outside this execution. + if isinstance(op, InputDataBuffer): + return 0 + + # Pending task outputs. + mem_op_internal = op.metrics.obj_store_mem_pending_task_outputs or 0 + # Op's internal output buffers. + mem_op_internal += op.metrics.obj_store_mem_internal_outqueue + + # Op's external output buffer. + mem_op_outputs = state.outqueue_memory_usage() + # Input buffers of the downstream operators. + for next_op in op.output_dependencies: + mem_op_outputs += ( + next_op.metrics.obj_store_mem_internal_inqueue + + next_op.metrics.obj_store_mem_pending_task_inputs + ) + + self._mem_op_internal[op] = mem_op_internal + self._mem_op_outputs[op] = mem_op_outputs + + return mem_op_internal + mem_op_outputs + + def update_usages(self): + """Recalculate resource usages.""" + # TODO(hchen): This method will be called frequently during the execution loop. + # And some computations are redundant. We should either remove redundant + # computations or remove this method entirely and compute usages on demand. + self._global_usage = ExecutionResources(0, 0, 0) + self._global_running_usage = ExecutionResources(0, 0, 0) + self._global_pending_usage = ExecutionResources(0, 0, 0) + self._op_usages.clear() + self._op_running_usages.clear() + self._op_pending_usages.clear() + self._downstream_fraction.clear() + self._downstream_object_store_memory.clear() + + # Iterate from last to first operator. + num_ops_so_far = 0 + num_ops_total = len(self._topology) + for op, state in reversed(self._topology.items()): + # Update `self._op_usages`, `self._op_running_usages`, + # and `self._op_pending_usages`. + op.update_resource_usage() + op_usage = op.current_processor_usage() + op_running_usage = op.running_processor_usage() + op_pending_usage = op.pending_processor_usage() + + assert not op_usage.object_store_memory + assert not op_running_usage.object_store_memory + assert not op_pending_usage.object_store_memory + op_usage.object_store_memory = self._estimate_object_store_memory(op, state) + op_running_usage.object_store_memory = self._estimate_object_store_memory( + op, state + ) + self._op_usages[op] = op_usage + self._op_running_usages[op] = op_running_usage + self._op_pending_usages[op] = op_pending_usage + + # Update `self._global_usage`, `self._global_running_usage`, + # and `self._global_pending_usage`. + self._global_usage = self._global_usage.add(op_usage) + self._global_running_usage = self._global_running_usage.add( + op_running_usage + ) + self._global_pending_usage = self._global_pending_usage.add( + op_pending_usage + ) + + # Update `self._downstream_fraction` and `_downstream_object_store_memory`. + # Subtract one from denom to account for input buffer. + f = (1.0 + num_ops_so_far) / max(1.0, num_ops_total - 1.0) + num_ops_so_far += 1 + self._downstream_fraction[op] = min(1.0, f) + self._downstream_object_store_memory[ + op + ] = self._global_usage.object_store_memory + + # Update operator's object store usage, which is used by + # DatasetStats and updated on the Ray Data dashboard. + op._metrics.obj_store_mem_used = op_usage.object_store_memory + + if self._op_resource_allocator is not None: + self._op_resource_allocator.update_usages() + + def get_global_usage(self) -> ExecutionResources: + """Return the global resource usage at the current time.""" + return self._global_usage + + def get_global_running_usage(self) -> ExecutionResources: + """Return the global running resource usage at the current time.""" + return self._global_running_usage + + def get_global_pending_usage(self) -> ExecutionResources: + """Return the global pending resource usage at the current time.""" + return self._global_pending_usage + + def get_global_limits(self) -> ExecutionResources: + """Return the global resource limits at the current time. + + This method autodetects any unspecified execution resource limits based on the + current cluster size, refreshing these values periodically to support cluster + autoscaling. + """ + if ( + time.time() - self._global_limits_last_update_time + < self.GLOBAL_LIMITS_UPDATE_INTERVAL_S + ): + return self._global_limits + + self._global_limits_last_update_time = time.time() + default_limits = self._options.resource_limits + exclude = self._options.exclude_resources + total_resources = self._get_total_resources() + default_mem_fraction = ( + self.DEFAULT_OBJECT_STORE_MEMORY_LIMIT_FRACTION + if self.op_resource_allocator_enabled() + else self.DEFAULT_OBJECT_STORE_MEMORY_LIMIT_FRACTION_WO_RESOURCE_RESERVATION + ) + total_resources.object_store_memory *= default_mem_fraction + self._global_limits = default_limits.min(total_resources).subtract(exclude) + return self._global_limits + + def get_op_usage(self, op: PhysicalOperator) -> ExecutionResources: + """Return the resource usage of the given operator at the current time.""" + return self._op_usages[op] + + def get_op_usage_str(self, op: PhysicalOperator) -> str: + """Return a human-readable string representation of the resource usage of + the given operator.""" + usage_str = f"{self._op_running_usages[op].cpu:.1f} CPU" + if self._op_running_usages[op].gpu: + usage_str += f", {self._op_running_usages[op].gpu:.1f} GPU" + usage_str += ( + f", {self._op_running_usages[op].object_store_memory_str()} object store" + ) + if self._debug: + usage_str += ( + f" (in={memory_string(self._mem_op_internal[op])}," + f"out={memory_string(self._mem_op_outputs[op])})" + ) + if ( + isinstance(self._op_resource_allocator, ReservationOpResourceAllocator) + and op in self._op_resource_allocator._op_budgets + ): + budget = self._op_resource_allocator._op_budgets[op] + usage_str += f", budget=(cpu={budget.cpu:.1f}" + usage_str += f",gpu={budget.gpu:.1f}" + usage_str += f",object store={budget.object_store_memory_str()})" + return usage_str + + def get_downstream_fraction(self, op: PhysicalOperator) -> float: + """Return the downstream fraction of the given operator.""" + return self._downstream_fraction[op] + + def get_downstream_object_store_memory(self, op: PhysicalOperator) -> float: + """Return the downstream object store memory usage of the given operator.""" + return self._downstream_object_store_memory[op] + + def op_resource_allocator_enabled(self) -> bool: + """Return whether OpResourceAllocator is enabled.""" + return self._op_resource_allocator is not None + + @property + def op_resource_allocator(self) -> "OpResourceAllocator": + """Return the OpResourceAllocator.""" + assert self._op_resource_allocator is not None + return self._op_resource_allocator + + +class OpResourceAllocator(ABC): + """An interface for dynamic operator resource allocation. + + This interface allows dynamically allocating available resources to each operator, + limiting how many tasks each operator can submit, and how much data each operator + can read from its running tasks. + """ + + def __init__(self, resource_manager: ResourceManager): + self._resource_manager = resource_manager + + @abstractmethod + def update_usages(self): + """Callback to update resource usages.""" + ... + + @abstractmethod + def can_submit_new_task(self, op: PhysicalOperator) -> bool: + """Return whether the given operator can submit a new task.""" + ... + + @abstractmethod + def max_task_output_bytes_to_read(self, op: PhysicalOperator) -> Optional[int]: + """Return the maximum bytes of pending task outputs can be read for + the given operator. None means no limit.""" + ... + + +class ReservationOpResourceAllocator(OpResourceAllocator): + """An OpResourceAllocator implementation that reserves resources for each operator. + + This class reserves memory and CPU resources for eligible operators, and considers + runtime resource usages to limit the resources that each operator can use. + + It works in the following way: + 1. An operator is eligible for resource reservation, if it has enabled throttling + and hasn't completed. Ineligible operators are not throttled, but + their usage will be accounted for their upstream eligible operators. E.g., for + such a dataset "map1->limit->map2->streaming_split", we'll treat "map1->limit" as + a group and "map2->streaming_split" as another group. + 2. For each eligible operator, we reserve `reservation_ratio * global_resources / + num_eligible_ops` resources, half of which is reserved only for the operator + outputs, excluding pending task outputs. + 3. Non-reserved resources are shared among all operators. + 4. In each scheduling iteration, each eligible operator will get "remaining of their + own reserved resources" + "remaining of shared resources / num_eligible_ops" + resources. + + The `reservation_ratio` is set to 50% by default. Users can tune this value to + adjust how aggressive or conservative the resource allocation is. A higher value + will make the resource allocation more even, but may lead to underutilization and + worse performance. And vice versa. + """ + + class IdleDetector: + """Utility class for detecting idle operators. + + Note, stalling can happen when there are less resources than Data executor + expects. E.g., when some resources are preempted by non-Data code, see + `test_no_deadlock_on_resource_contention` as an example. + + This class is used to detect potential stalling and allow the execution + to make progress. + """ + + # The interval to detect idle operators. + # When downstream is idle, we'll allow reading at least one task output + # per this interval, + DETECTION_INTERVAL_S = 10.0 + # Print a warning if an operator is idle for this time. + WARN_ON_IDLE_TIME_S = 60.0 + # Whether a warning has been printed. + _warn_printed = False + + def __init__(self): + # per-op fields + self.last_num_outputs = defaultdict(int) + self.last_output_time = defaultdict(lambda: time.time()) + self.last_detection_time = defaultdict(lambda: time.time()) + + def detect_idle(self, op: PhysicalOperator): + cur_time = time.time() + if cur_time - self.last_detection_time[op] > self.DETECTION_INTERVAL_S: + cur_num_outputs = op.metrics.num_task_outputs_generated + if cur_num_outputs > self.last_num_outputs[op]: + self.last_num_outputs[op] = cur_num_outputs + self.last_output_time[op] = cur_time + self.last_detection_time[op] = cur_time + else: + self.last_detection_time[op] = cur_time + self.print_warning_if_idle_for_too_long( + op, cur_time - self.last_output_time[op] + ) + return True + return False + + @classmethod + def print_warning_if_idle_for_too_long( + cls, op: PhysicalOperator, idle_time: float + ): + """Print a warning if an operator is idle for too long.""" + if idle_time < cls.WARN_ON_IDLE_TIME_S or cls._warn_printed: + return + cls._warn_printed = True + msg = ( + f"Operator {op} is running but has no outputs for {idle_time} seconds." + " Execution may be slower than expected.\n" + "Ignore this warning if your UDF is expected to be slow." + " Otherwise, this can happen when there are fewer cluster resources" + " available to Ray Data than expected." + " If you have non-Data tasks or actors running in the cluster, exclude" + " their resources from Ray Data with" + " `DataContext.get_current().execution_options.exclude_resources`." + " This message will only print once." + ) + logger.warning(msg) + + def __init__(self, resource_manager: ResourceManager, reservation_ratio: float): + super().__init__(resource_manager) + self._reservation_ratio = reservation_ratio + assert 0.0 <= self._reservation_ratio <= 1.0 + # Per-op reserved resources, excluding `_reserved_for_op_outputs`. + self._op_reserved: Dict[PhysicalOperator, ExecutionResources] = {} + # Memory reserved exclusively for the outputs of each operator. + # "Op outputs" refer to blocks that have been taken out of an operator, + # i.e., `RessourceManager._mem_op_outputs`. + # + # Note, if we don't reserve memory for op outputs, all the budget may be used by + # the pending task outputs, and/or op's internal output buffers (the latter can + # happen when `preserve_order=True`). + # Then we'll have no budget to pull blocks from the op. + self._reserved_for_op_outputs: Dict[PhysicalOperator, float] = {} + # Total shared resources. + self._total_shared = ExecutionResources.zero() + # Resource budgets for each operator, excluding `_reserved_for_op_outputs`. + self._op_budgets: Dict[PhysicalOperator, ExecutionResources] = {} + # Whether each operator has reserved the minimum resources to run + # at least one task. + # This is used to avoid edge cases where the entire resource limits are not + # enough to run one task of each op. + # See `test_no_deadlock_on_small_cluster_resources` as an example. + self._reserved_min_resources: Dict[PhysicalOperator, bool] = {} + + self._cached_global_limits = ExecutionResources.zero() + self._cached_num_eligible_ops = 0 + + self._idle_detector = self.IdleDetector() + + def _is_op_eligible(self, op: PhysicalOperator) -> bool: + """Whether the op is eligible for memory reservation.""" + return not op.throttling_disabled() and not op.completed() + + def _get_eligible_ops(self) -> List[PhysicalOperator]: + return [ + op for op in self._resource_manager._topology if self._is_op_eligible(op) + ] + + def _update_reservation(self): + global_limits = self._resource_manager.get_global_limits() + eligible_ops = self._get_eligible_ops() + + if ( + global_limits == self._cached_global_limits + and len(eligible_ops) == self._cached_num_eligible_ops + ): + return + self._cached_global_limits = global_limits + self._cached_num_eligible_ops = len(eligible_ops) + + self._op_reserved.clear() + self._reserved_for_op_outputs.clear() + self._reserved_min_resources.clear() + self._total_shared = global_limits.copy() + + if len(eligible_ops) == 0: + return + + # Reserve `reservation_ratio * global_limits / num_ops` resources for each + # operator. + default_reserved = global_limits.scale( + self._reservation_ratio / (len(eligible_ops)) + ) + for op in eligible_ops: + # Reserve at least half of the default reserved resources for the outputs. + # This makes sure that we will have enough budget to pull blocks from the + # op. + self._reserved_for_op_outputs[op] = max( + default_reserved.object_store_memory / 2, 1.0 + ) + # Calculate the minimum amount of resources to reserve. + # 1. Make sure the reserved resources are at least to allow one task. + min_reserved = op.incremental_resource_usage().copy() + # 2. To ensure that all GPUs are utilized, reserve enough resource budget + # to launch one task for each worker. + if op.base_resource_usage().gpu > 0: + min_workers = sum( + pool.min_size() for pool in op.get_autoscaling_actor_pools() + ) + min_reserved.object_store_memory *= min_workers + # Also include `reserved_for_op_outputs`. + min_reserved.object_store_memory += self._reserved_for_op_outputs[op] + # Total resources we want to reserve for this operator. + op_total_reserved = default_reserved.max(min_reserved) + if op_total_reserved.satisfies_limit(self._total_shared): + # If the remaining resources are enough to reserve `op_total_reserved`, + # subtract it from `self._total_shared` and reserve it for this op. + self._reserved_min_resources[op] = True + self._total_shared = self._total_shared.subtract(op_total_reserved) + self._op_reserved[op] = op_total_reserved + self._op_reserved[ + op + ].object_store_memory -= self._reserved_for_op_outputs[op] + else: + # If the remaining resources are not enough to reserve the minimum + # resources for this operator, we'll only reserve the minimum object + # store memory, but not the CPU and GPU resources. + # Because Ray Core doesn't allow CPU/GPU resources to be oversubscribed. + # Note, we reserve minimum resources first for the upstream + # ops. Downstream ops need to wait for upstream ops to finish + # and release resources. + self._reserved_min_resources[op] = False + self._op_reserved[op] = ExecutionResources( + 0, + 0, + min_reserved.object_store_memory + - self._reserved_for_op_outputs[op], + ) + self._total_shared = self._total_shared.subtract( + ExecutionResources(0, 0, min_reserved.object_store_memory) + ) + + self._total_shared = self._total_shared.max(ExecutionResources.zero()) + + def can_submit_new_task(self, op: PhysicalOperator) -> bool: + if op not in self._op_budgets: + return True + budget = self._op_budgets[op] + res = op.incremental_resource_usage().satisfies_limit(budget) + return res + + def _should_unblock_streaming_output_backpressure( + self, op: PhysicalOperator + ) -> bool: + # In some edge cases, the downstream operators may have no enough resources to + # launch tasks. Then we should temporarily unblock the streaming output + # backpressure by allowing reading at least 1 block. So the current operator + # can finish at least one task and yield resources to the downstream operators. + for next_op in self._get_downstream_eligible_ops(op): + if not self._reserved_min_resources[next_op]: + # Case 1: the downstream operator hasn't reserved the minimum resources + # to run at least one task. + return True + # Case 2: the downstream operator has reserved the minimum resources, but + # the resources are preempted by non-Data tasks or actors. + # We don't have a good way to detect this case, so we'll unblock + # backpressure when the downstream operator has been idle for a while. + if self._idle_detector.detect_idle(next_op): + return True + return False + + def _get_op_outputs_usage_with_downstream(self, op: PhysicalOperator) -> float: + """Get the outputs memory usage of the given operator, including the downstream + ineligible operators. + """ + # Outputs usage of the current operator. + op_outputs_usage = self._resource_manager._mem_op_outputs[op] + # Also account the downstream ineligible operators' memory usage. + op_outputs_usage += sum( + self._resource_manager.get_op_usage(next_op).object_store_memory + for next_op in self._get_downstream_ineligible_ops(op) + ) + return op_outputs_usage + + def max_task_output_bytes_to_read(self, op: PhysicalOperator) -> Optional[int]: + if op not in self._op_budgets: + return None + res = self._op_budgets[op].object_store_memory + # Add the remaining of `_reserved_for_op_outputs`. + op_outputs_usage = self._get_op_outputs_usage_with_downstream(op) + res += max(self._reserved_for_op_outputs[op] - op_outputs_usage, 0) + res = int(res) + assert res >= 0 + if res == 0 and self._should_unblock_streaming_output_backpressure(op): + res = 1 + return res + + def _get_downstream_ineligible_ops( + self, op: PhysicalOperator + ) -> Iterable[PhysicalOperator]: + """Get the downstream ineligible operators of the given operator. + + E.g., + - "cur_map->downstream_map" will return an empty list. + - "cur_map->limit1->limit2->downstream_map" will return [limit1, limit2]. + """ + for next_op in op.output_dependencies: + if not self._is_op_eligible(next_op): + yield next_op + yield from self._get_downstream_ineligible_ops(next_op) + + def _get_downstream_eligible_ops( + self, op: PhysicalOperator + ) -> Iterable[PhysicalOperator]: + """Get the downstream eligible operators of the given operator, ignoring intermediate + ineligible operators. + + E.g., + - "cur_map->downstream_map" will return [downstream_map]. + - "cur_map->limit1->limit2->downstream_map" will return [downstream_map]. + """ + for next_op in op.output_dependencies: + if self._is_op_eligible(next_op): + yield next_op + else: + yield from self._get_downstream_eligible_ops(next_op) + + def update_usages(self): + self._update_reservation() + + self._op_budgets.clear() + eligible_ops = self._get_eligible_ops() + if len(eligible_ops) == 0: + return + + # Remaining of shared resources. + remaining_shared = self._total_shared + for op in eligible_ops: + # Calculate the memory usage of the operator. + op_mem_usage = 0 + # Add the memory usage of the operator itself, + # excluding `_reserved_for_op_outputs`. + op_mem_usage += self._resource_manager._mem_op_internal[op] + # Add the portion of op outputs usage that has + # exceeded `_reserved_for_op_outputs`. + op_outputs_usage = self._get_op_outputs_usage_with_downstream(op) + op_mem_usage += max(op_outputs_usage - self._reserved_for_op_outputs[op], 0) + op_usage = self._resource_manager.get_op_usage(op).copy() + op_usage.object_store_memory = op_mem_usage + op_reserved = self._op_reserved[op] + # How much of the reserved resources are remaining. + op_reserved_remaining = op_reserved.subtract(op_usage).max( + ExecutionResources.zero() + ) + self._op_budgets[op] = op_reserved_remaining + # How much of the reserved resources are exceeded. + # If exceeded, we need to subtract from the remaining shared resources. + op_reserved_exceeded = op_usage.subtract(op_reserved).max( + ExecutionResources.zero() + ) + remaining_shared = remaining_shared.subtract(op_reserved_exceeded) + + remaining_shared = remaining_shared.max(ExecutionResources.zero()) + + # Allocate the remaining shared resources to each operator. + for i, op in enumerate(reversed(eligible_ops)): + # By default, divide the remaining shared resources equally. + op_shared = remaining_shared.scale(1.0 / (len(eligible_ops) - i)) + # But if the op's budget is less than `incremental_resource_usage`, + # it will be useless. So we'll let the downstream operator + # borrow some resources from the upstream operator, if remaining_shared + # is still enough. + to_borrow = ( + op.incremental_resource_usage() + .subtract(self._op_budgets[op].add(op_shared)) + .max(ExecutionResources.zero()) + ) + if not to_borrow.is_zero() and op_shared.add(to_borrow).satisfies_limit( + remaining_shared + ): + op_shared = op_shared.add(to_borrow) + remaining_shared = remaining_shared.subtract(op_shared) + assert remaining_shared.is_non_negative(), ( + remaining_shared, + op, + op_shared, + to_borrow, + ) + self._op_budgets[op] = self._op_budgets[op].add(op_shared) + # We don't limit GPU resources, as not all operators + # use GPU resources. + self._op_budgets[op].gpu = float("inf") diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/streaming_executor.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/streaming_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..a4276e2bafe63f54de5934eca7a07e7df53dc370 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/streaming_executor.py @@ -0,0 +1,495 @@ +import logging +import threading +import time +import uuid +from typing import Dict, Iterator, List, Optional + +from ray.data._internal.execution.autoscaler import create_autoscaler +from ray.data._internal.execution.backpressure_policy import ( + BackpressurePolicy, + get_backpressure_policies, +) +from ray.data._internal.execution.interfaces import ( + ExecutionOptions, + ExecutionResources, + Executor, + OutputIterator, + PhysicalOperator, + RefBundle, +) +from ray.data._internal.execution.operators.input_data_buffer import InputDataBuffer +from ray.data._internal.execution.resource_manager import ResourceManager +from ray.data._internal.execution.streaming_executor_state import ( + OpState, + Topology, + build_streaming_topology, + process_completed_tasks, + select_operator_to_run, + update_operator_states, +) +from ray.data._internal.logging import get_log_directory +from ray.data._internal.progress_bar import ProgressBar +from ray.data._internal.stats import DatasetStats, StatsManager +from ray.data.context import OK_PREFIX, WARN_PREFIX, DataContext + +logger = logging.getLogger(__name__) + +# Force a progress bar update after this many events processed . This avoids the +# progress bar seeming to stall for very large scale workloads. +PROGRESS_BAR_UPDATE_INTERVAL = 50 + +# Interval for logging execution progress updates and operator metrics. +DEBUG_LOG_INTERVAL_SECONDS = 5 + +# Visible for testing. +_num_shutdown = 0 + + +class StreamingExecutor(Executor, threading.Thread): + """A streaming Dataset executor. + + This implementation executes Dataset DAGs in a fully streamed way. It runs + by setting up the operator topology, and then routing blocks through operators in + a way that maximizes throughput under resource constraints. + """ + + def __init__(self, options: ExecutionOptions, dataset_tag: str = "unknown_dataset"): + self._start_time: Optional[float] = None + self._initial_stats: Optional[DatasetStats] = None + self._final_stats: Optional[DatasetStats] = None + self._global_info: Optional[ProgressBar] = None + + self._execution_id = uuid.uuid4().hex + + # The executor can be shutdown while still running. + self._shutdown_lock = threading.RLock() + self._execution_started = False + self._shutdown = False + + # Internal execution state shared across thread boundaries. We run the control + # loop on a separate thread so that it doesn't become stalled between + # generator `yield`s. + self._topology: Optional[Topology] = None + self._output_node: Optional[OpState] = None + self._backpressure_policies: List[BackpressurePolicy] = [] + + self._dataset_tag = dataset_tag + # Stores if an operator is completed, + # used for marking when an op has just completed. + self._has_op_completed: Optional[Dict[PhysicalOperator, bool]] = None + self._max_errored_blocks = DataContext.get_current().max_errored_blocks + self._num_errored_blocks = 0 + + self._last_debug_log_time = 0 + + Executor.__init__(self, options) + thread_name = f"StreamingExecutor-{self._execution_id}" + threading.Thread.__init__(self, daemon=True, name=thread_name) + + def execute( + self, dag: PhysicalOperator, initial_stats: Optional[DatasetStats] = None + ) -> Iterator[RefBundle]: + """Executes the DAG using a streaming execution strategy. + + We take an event-loop approach to scheduling. We block on the next scheduling + event using `ray.wait`, updating operator state and dispatching new tasks. + """ + + self._initial_stats = initial_stats + self._start_time = time.perf_counter() + + if not isinstance(dag, InputDataBuffer): + context = DataContext.get_current() + if context.print_on_execution_start: + message = "Starting execution of Dataset." + log_path = get_log_directory() + if log_path is not None: + message += f" Full logs are in {log_path}" + logger.info(message) + logger.info(f"Execution plan of Dataset: {dag}") + + logger.debug("Execution config: %s", self._options) + + # Note: DAG must be initialized in order to query num_outputs_total. + # Note: Initialize global progress bar before building the streaming + # topology so bars are created in the same order as they should be + # displayed. This is done to ensure correct ordering within notebooks. + # TODO(zhilong): Implement num_output_rows_total for all + # AllToAllOperators + self._global_info = ProgressBar( + "Running", dag.num_output_rows_total(), unit="row" + ) + + # Setup the streaming DAG topology and start the runner thread. + self._topology, _ = build_streaming_topology(dag, self._options) + self._resource_manager = ResourceManager( + self._topology, + self._options, + lambda: self._autoscaler.get_total_resources(), + ) + self._backpressure_policies = get_backpressure_policies(self._topology) + self._autoscaler = create_autoscaler( + self._topology, + self._resource_manager, + self._execution_id, + ) + + self._has_op_completed = {op: False for op in self._topology} + + self._output_node: OpState = self._topology[dag] + StatsManager.register_dataset_to_stats_actor( + self._dataset_tag, + self._get_operator_tags(), + ) + self.start() + self._execution_started = True + + class StreamIterator(OutputIterator): + def __init__(self, outer: Executor): + self._outer = outer + + def get_next(self, output_split_idx: Optional[int] = None) -> RefBundle: + try: + item = self._outer._output_node.get_output_blocking( + output_split_idx + ) + if self._outer._global_info: + self._outer._global_info.update( + item.num_rows(), dag.num_output_rows_total() + ) + return item + # Needs to be BaseException to catch KeyboardInterrupt. Otherwise we + # can leave dangling progress bars by skipping shutdown. + except BaseException as e: + self._outer.shutdown(isinstance(e, StopIteration)) + raise + + def __del__(self): + self._outer.shutdown() + + return StreamIterator(self) + + def __del__(self): + self.shutdown() + + def shutdown(self, execution_completed: bool = True): + context = DataContext.get_current() + global _num_shutdown + + with self._shutdown_lock: + if not self._execution_started or self._shutdown: + return + logger.debug(f"Shutting down {self}.") + _num_shutdown += 1 + self._shutdown = True + # Give the scheduling loop some time to finish processing. + self.join(timeout=2.0) + self._update_stats_metrics( + state="FINISHED" if execution_completed else "FAILED", + force_update=True, + ) + # Once Dataset execution completes, mark it as complete + # and remove last cached execution stats. + StatsManager.clear_last_execution_stats(self._dataset_tag) + # Freeze the stats and save it. + self._final_stats = self._generate_stats() + stats_summary_string = self._final_stats.to_summary().to_string( + include_parent=False + ) + if context.enable_auto_log_stats: + logger.info(stats_summary_string) + # Close the progress bars from top to bottom to avoid them jumping + # around in the console after completion. + if self._global_info: + # Set the appropriate description that summarizes + # the result of dataset execution. + if execution_completed: + prog_bar_msg = ( + f"{OK_PREFIX} Dataset execution finished in " + f"{self._final_stats.time_total_s:.2f} seconds" + ) + else: + prog_bar_msg = f"{WARN_PREFIX} Dataset execution failed" + self._global_info.set_description(prog_bar_msg) + self._global_info.close() + for op, state in self._topology.items(): + op.shutdown() + state.close_progress_bars() + self._autoscaler.on_executor_shutdown() + + def run(self): + """Run the control loop in a helper thread. + + Results are returned via the output node's outqueue. + """ + try: + # Run scheduling loop until complete. + while True: + t_start = time.process_time() + # use process_time to avoid timing ray.wait in _scheduling_loop_step + continue_sched = self._scheduling_loop_step(self._topology) + if self._initial_stats: + self._initial_stats.streaming_exec_schedule_s.add( + time.process_time() - t_start + ) + if not continue_sched or self._shutdown: + break + except Exception as e: + # Propagate it to the result iterator. + self._output_node.mark_finished(e) + finally: + # Signal end of results. + self._output_node.mark_finished() + + def get_stats(self): + """Return the stats object for the streaming execution. + + The stats object will be updated as streaming execution progresses. + """ + if self._final_stats: + return self._final_stats + else: + return self._generate_stats() + + def _generate_stats(self) -> DatasetStats: + """Create a new stats object reflecting execution status so far.""" + stats = self._initial_stats or DatasetStats(metadata={}, parent=None) + for op in self._topology: + if isinstance(op, InputDataBuffer): + continue + builder = stats.child_builder(op.name, override_start_time=self._start_time) + stats = builder.build_multioperator(op.get_stats()) + stats.extra_metrics = op.metrics.as_dict() + stats.streaming_exec_schedule_s = ( + self._initial_stats.streaming_exec_schedule_s + if self._initial_stats + else None + ) + return stats + + def _scheduling_loop_step(self, topology: Topology) -> bool: + """Run one step of the scheduling loop. + + This runs a few general phases: + 1. Waiting for the next task completion using `ray.wait()`. + 2. Pulling completed refs into operator outqueues. + 3. Selecting and dispatching new inputs to operators. + + Returns: + True if we should continue running the scheduling loop. + """ + self._resource_manager.update_usages() + # Note: calling process_completed_tasks() is expensive since it incurs + # ray.wait() overhead, so make sure to allow multiple dispatch per call for + # greater parallelism. + num_errored_blocks = process_completed_tasks( + topology, + self._resource_manager, + self._max_errored_blocks, + ) + if self._max_errored_blocks > 0: + self._max_errored_blocks -= num_errored_blocks + self._num_errored_blocks += num_errored_blocks + + self._resource_manager.update_usages() + # Dispatch as many operators as we can for completed tasks. + self._report_current_usage() + op = select_operator_to_run( + topology, + self._resource_manager, + self._backpressure_policies, + self._autoscaler, + ensure_at_least_one_running=self._consumer_idling(), + ) + + i = 0 + while op is not None: + i += 1 + if i % PROGRESS_BAR_UPDATE_INTERVAL == 0: + self._refresh_progress_bars(topology) + topology[op].dispatch_next_task() + self._resource_manager.update_usages() + op = select_operator_to_run( + topology, + self._resource_manager, + self._backpressure_policies, + self._autoscaler, + ensure_at_least_one_running=self._consumer_idling(), + ) + + update_operator_states(topology) + self._refresh_progress_bars(topology) + + self._update_stats_metrics(state="RUNNING") + if time.time() - self._last_debug_log_time >= DEBUG_LOG_INTERVAL_SECONDS: + _log_op_metrics(topology) + _debug_dump_topology(topology, self._resource_manager) + self._last_debug_log_time = time.time() + + # Log metrics of newly completed operators. + for op in topology: + if op.completed() and not self._has_op_completed[op]: + log_str = ( + f"Operator {op} completed. " + f"Operator Metrics:\n{op._metrics.as_dict()}" + ) + logger.debug(log_str) + self._has_op_completed[op] = True + + # Keep going until all operators run to completion. + return not all(op.completed() for op in topology) + + def _refresh_progress_bars(self, topology: Topology): + # Update the progress bar to reflect scheduling decisions. + for op_state in topology.values(): + op_state.refresh_progress_bar(self._resource_manager) + # Refresh the global progress bar to update elapsed time progress. + if self._global_info: + self._global_info.refresh() + + def _consumer_idling(self) -> bool: + """Returns whether the user thread is blocked on topology execution.""" + return len(self._output_node.outqueue) == 0 + + def _report_current_usage(self) -> None: + # running_usage is the amount of resources that have been requested but + # not necessarily available + # TODO(sofian) https://github.com/ray-project/ray/issues/47520 + # We need to split the reported resources into running, pending-scheduling, + # pending-node-assignment. + running_usage = self._resource_manager.get_global_running_usage() + pending_usage = self._resource_manager.get_global_pending_usage() + limits = self._resource_manager.get_global_limits() + resources_status = ( + # TODO(scottjlee): Add dataset name/ID to progress bar output. + "Running Dataset. Active & requested resources: " + f"{running_usage.cpu:.4g}/{limits.cpu:.4g} CPU, " + ) + if running_usage.gpu > 0: + resources_status += f"{running_usage.gpu:.4g}/{limits.gpu:.4g} GPU, " + resources_status += ( + f"{running_usage.object_store_memory_str()}/" + f"{limits.object_store_memory_str()} object store" + ) + + # Only include pending section when there are pending resources. + if pending_usage.cpu or pending_usage.gpu: + if pending_usage.cpu and pending_usage.gpu: + pending_str = ( + f"{pending_usage.cpu:.4g} CPU, {pending_usage.gpu:.4g} GPU" + ) + elif pending_usage.cpu: + pending_str = f"{pending_usage.cpu:.4g} CPU" + else: + pending_str = f"{pending_usage.gpu:.4g} GPU" + resources_status += f" (pending: {pending_str})" + if self._global_info: + self._global_info.set_description(resources_status) + + def _get_operator_tags(self): + """Returns a list of operator tags.""" + return [f"{op.name}{i}" for i, op in enumerate(self._topology)] + + def _get_state_dict(self, state): + last_op, last_state = list(self._topology.items())[-1] + return { + "state": state, + "progress": last_state.num_completed_tasks, + "total": last_op.num_outputs_total(), + "end_time": time.time() if state != "RUNNING" else None, + "operators": { + f"{op.name}{i}": { + "name": op.name, + "progress": op_state.num_completed_tasks, + "total": op.num_outputs_total(), + "state": state, + } + for i, (op, op_state) in enumerate(self._topology.items()) + }, + } + + def _update_stats_metrics(self, state: str, force_update: bool = False): + StatsManager.update_execution_metrics( + self._dataset_tag, + [op.metrics for op in self._topology], + self._get_operator_tags(), + self._get_state_dict(state=state), + force_update=force_update, + ) + + +def _validate_dag(dag: PhysicalOperator, limits: ExecutionResources) -> None: + """Raises an exception on invalid DAGs. + + It checks if the the sum of min actor pool sizes are larger than the resource + limit, as well as other unsupported resource configurations. + + This should be called prior to creating the topology from the DAG. + + Args: + dag: The DAG to validate. + limits: The limits to validate against. + """ + + seen = set() + + def walk(op): + seen.add(op) + for parent in op.input_dependencies: + if parent not in seen: + yield from walk(parent) + yield op + + base_usage = ExecutionResources(cpu=1) + for op in walk(dag): + base_usage = base_usage.add(op.base_resource_usage()) + + if not base_usage.satisfies_limit(limits): + error_message = ( + "The current cluster doesn't have the required resources to execute your " + "Dataset pipeline:\n" + ) + if base_usage.cpu > limits.cpu: + error_message += ( + f"- Your application needs {base_usage.cpu} CPU(s), but your cluster " + f"only has {limits.cpu}.\n" + ) + if base_usage.gpu > limits.gpu: + error_message += ( + f"- Your application needs {base_usage.gpu} GPU(s), but your cluster " + f"only has {limits.gpu}.\n" + ) + if base_usage.object_store_memory > limits.object_store_memory: + error_message += ( + f"- Your application needs {base_usage.object_store_memory}B object " + f"store memory, but your cluster only has " + f"{limits.object_store_memory}B.\n" + ) + raise ValueError(error_message.strip()) + + +def _debug_dump_topology(topology: Topology, resource_manager: ResourceManager) -> None: + """Log current execution state for the topology for debugging. + + Args: + topology: The topology to debug. + resource_manager: The resource manager for this topology. + """ + logger.debug("Execution Progress:") + for i, (op, state) in enumerate(topology.items()): + logger.debug( + f"{i}: {state.summary_str(resource_manager)}, " + f"Blocks Outputted: {state.num_completed_tasks}/{op.num_outputs_total()}" + ) + + +def _log_op_metrics(topology: Topology) -> None: + """Logs the metrics of each operator. + + Args: + topology: The topology to debug. + """ + log_str = "Operator Metrics:\n" + for op in topology: + log_str += f"{op.name}: {op.metrics.as_dict()}\n" + logger.debug(log_str) diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/streaming_executor_state.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/streaming_executor_state.py new file mode 100644 index 0000000000000000000000000000000000000000..f91c4f536da6a5a62d5d2d4ab3c5feab2ac8edd6 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/streaming_executor_state.py @@ -0,0 +1,681 @@ +"""Contains classes that encapsulate streaming executor state. + +This is split out from streaming_executor.py to facilitate better unit testing. +""" + +import logging +import math +import threading +import time +from collections import defaultdict +from dataclasses import dataclass +from typing import Dict, List, Optional, Tuple + +import ray +from ray.data._internal.execution.autoscaler import Autoscaler +from ray.data._internal.execution.backpressure_policy import BackpressurePolicy +from ray.data._internal.execution.bundle_queue import create_bundle_queue +from ray.data._internal.execution.interfaces import ( + ExecutionOptions, + ExecutionResources, + PhysicalOperator, + RefBundle, +) +from ray.data._internal.execution.interfaces.physical_operator import ( + DataOpTask, + MetadataOpTask, + OpTask, + Waitable, +) +from ray.data._internal.execution.operators.base_physical_operator import ( + AllToAllOperator, +) +from ray.data._internal.execution.operators.input_data_buffer import InputDataBuffer +from ray.data._internal.execution.resource_manager import ResourceManager +from ray.data._internal.progress_bar import ProgressBar +from ray.data.context import DataContext + +logger = logging.getLogger(__name__) + +# Holds the full execution state of the streaming topology. It's a dict mapping each +# operator to tracked streaming exec state. +Topology = Dict[PhysicalOperator, "OpState"] + + +class OpBufferQueue: + """A FIFO queue to buffer RefBundles between upstream and downstream operators. + This class is thread-safe. + """ + + def __init__(self): + self._num_blocks = 0 + self._queue = create_bundle_queue() + self._num_per_split = defaultdict(int) + self._lock = threading.Lock() + # Used to buffer output RefBundles indexed by output splits. + self._outputs_by_split = defaultdict(create_bundle_queue) + super().__init__() + + @property + def memory_usage(self) -> int: + """The total memory usage of the queue in bytes.""" + with self._lock: + # The split queues contain bundles popped from the main queue. So, a bundle + # will either be in the main queue or in one of the split queues, and we + # don't need to worry about double counting. + return self._queue.estimate_size_bytes() + sum( + split_queue.estimate_size_bytes() + for split_queue in self._outputs_by_split.values() + ) + + @property + def num_blocks(self) -> int: + """The total number of blocks in the queue.""" + with self._lock: + return self._num_blocks + + def __len__(self): + with self._lock: + return len(self._queue) + + def has_next(self, output_split_idx: Optional[int] = None) -> bool: + """Whether next RefBundle is available. + + Args: + output_split_idx: If specified, only check ref bundles with the + given output split. + """ + if output_split_idx is None: + with self._lock: + return len(self._queue) > 0 + else: + with self._lock: + return self._num_per_split[output_split_idx] > 0 + + def append(self, ref: RefBundle): + """Append a RefBundle to the queue.""" + with self._lock: + self._queue.add(ref) + self._num_blocks += len(ref.blocks) + if ref.output_split_idx is not None: + self._num_per_split[ref.output_split_idx] += 1 + + def pop(self, output_split_idx: Optional[int] = None) -> Optional[RefBundle]: + """Pop a RefBundle from the queue. + Args: + output_split_idx: If specified, only pop a RefBundle + with the given output split. + Returns: + A RefBundle if available, otherwise None. + """ + ret = None + if output_split_idx is None: + try: + with self._lock: + ret = self._queue.pop() + except IndexError: + pass + else: + with self._lock: + split_queue = self._outputs_by_split[output_split_idx] + if len(split_queue) == 0: + # Move all ref bundles to their indexed queues + # Note, the reason why we do indexing here instead of in the append + # is because only the last `OpBufferQueue` in the DAG, which will call + # pop with output_split_idx, needs indexing. + # If we also index the `OpBufferQueue`s in the middle, we cannot + # preserve the order of ref bundles with different output splits. + with self._lock: + while len(self._queue) > 0: + ref = self._queue.pop() + self._outputs_by_split[ref.output_split_idx].add(ref) + try: + ret = split_queue.pop() + except IndexError: + pass + if ret is None: + return None + with self._lock: + self._num_blocks -= len(ret.blocks) + if ret.output_split_idx is not None: + self._num_per_split[ret.output_split_idx] -= 1 + return ret + + def clear(self): + with self._lock: + self._queue.clear() + self._num_blocks = 0 + self._num_per_split.clear() + + +@dataclass +class OpSchedulingStatus: + """The scheduling status of an operator. + + This will be updated each time when StreamingExecutor makes + a scheduling decision, i.e., in each `select_operator_to_run` + call. + """ + + # Whether the op was selected to run in the last scheduling + # decision. + selected: bool = False + # Whether the op was considered runnable in the last scheduling + # decision. + runnable: bool = False + # Whether the resources were sufficient for the operator to run + # in the last scheduling decision. + under_resource_limits: bool = False + + +class OpState: + """The execution state tracked for each PhysicalOperator. + + This tracks state to manage input and output buffering for StreamingExecutor and + progress bars, which is separate from execution state internal to the operators. + + Note: we use the `deque` data structure here because it is thread-safe, enabling + operator queues to be shared across threads. + """ + + def __init__(self, op: PhysicalOperator, inqueues: List[OpBufferQueue]): + # Each inqueue is connected to another operator's outqueue. + assert len(inqueues) == len(op.input_dependencies), (op, inqueues) + self.inqueues: List[OpBufferQueue] = inqueues + # The outqueue is connected to another operator's inqueue (they physically + # share the same Python list reference). + # + # Note: this queue is also accessed concurrently from the consumer thread. + # (in addition to the streaming executor thread). Hence, it must be a + # thread-safe type such as `deque`. + self.outqueue: OpBufferQueue = OpBufferQueue() + self.op = op + self.progress_bar = None + self.num_completed_tasks = 0 + self.inputs_done_called = False + # Tracks whether `input_done` is called for each input op. + self.input_done_called = [False] * len(op.input_dependencies) + # Used for StreamingExecutor to signal exception or end of execution + self._finished: bool = False + self._exception: Optional[Exception] = None + self._scheduling_status = OpSchedulingStatus() + + def __repr__(self): + return f"OpState({self.op.name})" + + def initialize_progress_bars(self, index: int, verbose_progress: bool) -> int: + """Create progress bars at the given index (line offset in console). + + For AllToAllOperator, zero or more sub progress bar would be created. + Return the number of enabled progress bars created for this operator. + """ + is_all_to_all = isinstance(self.op, AllToAllOperator) + # Only show 1:1 ops when in verbose progress mode. + ctx = DataContext.get_current() + progress_bar_enabled = ( + ctx.enable_progress_bars + and ctx.enable_operator_progress_bars + and (is_all_to_all or verbose_progress) + ) + self.progress_bar = ProgressBar( + "- " + self.op.name, + self.op.num_output_rows_total(), + unit="row", + position=index, + enabled=progress_bar_enabled, + ) + num_progress_bars = 1 + if is_all_to_all: + # Initialize must be called for sub progress bars, even the + # bars are not enabled via the DataContext. + num_progress_bars += self.op.initialize_sub_progress_bars(index + 1) + return num_progress_bars if progress_bar_enabled else 0 + + def close_progress_bars(self): + """Close all progress bars for this operator.""" + if self.progress_bar: + self.progress_bar.close() + if isinstance(self.op, AllToAllOperator): + self.op.close_sub_progress_bars() + + def num_queued(self) -> int: + """Return the number of queued bundles across all inqueues.""" + return sum(len(q) for q in self.inqueues) + + def num_processing(self): + """Return the number of bundles currently in processing for this operator.""" + return self.op.num_active_tasks() + self.op.internal_queue_size() + + def add_output(self, ref: RefBundle) -> None: + """Move a bundle produced by the operator to its outqueue.""" + self.outqueue.append(ref) + self.num_completed_tasks += 1 + if self.progress_bar: + assert ( + ref.num_rows() is not None + ), "RefBundle must have a valid number of rows" + self.progress_bar.update(ref.num_rows(), self.op.num_output_rows_total()) + + def refresh_progress_bar(self, resource_manager: ResourceManager) -> None: + """Update the console with the latest operator progress.""" + if self.progress_bar: + self.progress_bar.set_description(self.summary_str(resource_manager)) + self.progress_bar.refresh() + + def summary_str(self, resource_manager: ResourceManager) -> str: + # Active tasks + active = self.op.num_active_tasks() + desc = f"- {self.op.name}: Tasks: {active}" + if ( + self.op._in_task_submission_backpressure + or self.op._in_task_output_backpressure + ): + desc += " [backpressured]" + + # Actors info + desc += self.op.actor_info_progress_str() + + # Queued blocks + queued = self.num_queued() + self.op.internal_queue_size() + desc += f"; Queued blocks: {queued}" + desc += f"; Resources: {resource_manager.get_op_usage_str(self.op)}" + + # Any additional operator specific information. + suffix = self.op.progress_str() + if suffix: + desc += f"; {suffix}" + + return desc + + def dispatch_next_task(self) -> None: + """Move a bundle from the operator inqueue to the operator itself.""" + for i, inqueue in enumerate(self.inqueues): + ref = inqueue.pop() + if ref is not None: + self.op.add_input(ref, input_index=i) + return + assert False, "Nothing to dispatch" + + def get_output_blocking(self, output_split_idx: Optional[int]) -> RefBundle: + """Get an item from this node's output queue, blocking as needed. + + Returns: + The RefBundle from the output queue, or an error / end of stream indicator. + + Raises: + StopIteration: If all outputs are already consumed. + Exception: If there was an exception raised during execution. + """ + while True: + # Check if StreamingExecutor has caught an exception or is done execution. + if self._exception is not None: + raise self._exception + elif self._finished and not self.outqueue.has_next(output_split_idx): + raise StopIteration() + ref = self.outqueue.pop(output_split_idx) + if ref is not None: + return ref + time.sleep(0.01) + + def inqueue_memory_usage(self) -> int: + """Return the object store memory of this operator's inqueue.""" + total = 0 + for op, inq in zip(self.op.input_dependencies, self.inqueues): + # Exclude existing input data items from dynamic memory usage. + if not isinstance(op, InputDataBuffer): + total += inq.memory_usage + return total + + def outqueue_memory_usage(self) -> int: + """Return the object store memory of this operator's outqueue.""" + return self.outqueue.memory_usage + + def outqueue_num_blocks(self) -> int: + """Return the number of blocks in this operator's outqueue.""" + return self.outqueue.num_blocks + + def mark_finished(self, exception: Optional[Exception] = None): + """Marks this operator as finished. Used for exiting get_output_blocking.""" + if exception is None: + self._finished = True + else: + self._exception = exception + + +def build_streaming_topology( + dag: PhysicalOperator, options: ExecutionOptions +) -> Tuple[Topology, int]: + """Instantiate the streaming operator state topology for the given DAG. + + This involves creating the operator state for each operator in the DAG, + registering it with this class, and wiring up the inqueues/outqueues of + dependent operator states. + + Args: + dag: The operator DAG to instantiate. + options: The execution options to use to start operators. + + Returns: + The topology dict holding the streaming execution state. + The number of progress bars initialized so far. + """ + + topology: Topology = {} + + # DFS walk to wire up operator states. + def setup_state(op: PhysicalOperator) -> OpState: + if op in topology: + raise ValueError("An operator can only be present in a topology once.") + + # Wire up the input outqueues to this op's inqueues. + inqueues = [] + for i, parent in enumerate(op.input_dependencies): + parent_state = setup_state(parent) + inqueues.append(parent_state.outqueue) + + # Create state. + op_state = OpState(op, inqueues) + topology[op] = op_state + op.start(options) + return op_state + + setup_state(dag) + + # Create the progress bars starting from the first operator to run. + # Note that the topology dict is in topological sort order. Index zero is reserved + # for global progress information. + i = 1 + for op_state in list(topology.values()): + if not isinstance(op_state.op, InputDataBuffer): + i += op_state.initialize_progress_bars(i, options.verbose_progress) + + return (topology, i) + + +def process_completed_tasks( + topology: Topology, + resource_manager: ResourceManager, + max_errored_blocks: int, +) -> int: + """Process any newly completed tasks. To update operator + states, call `update_operator_states()` afterwards. + + Args: + topology: The toplogy of operators. + backpressure_policies: The backpressure policies to use. + max_errored_blocks: Max number of errored blocks to allow, + unlimited if negative. + Returns: + The number of errored blocks. + """ + + # All active tasks, keyed by their waitables. + active_tasks: Dict[Waitable, Tuple[OpState, OpTask]] = {} + for op, state in topology.items(): + for task in op.get_active_tasks(): + active_tasks[task.get_waitable()] = (state, task) + + max_bytes_to_read_per_op: Dict[OpState, int] = {} + if resource_manager.op_resource_allocator_enabled(): + for op, state in topology.items(): + max_bytes_to_read = ( + resource_manager.op_resource_allocator.max_task_output_bytes_to_read(op) + ) + op._in_task_output_backpressure = max_bytes_to_read == 0 + if max_bytes_to_read is not None: + max_bytes_to_read_per_op[state] = max_bytes_to_read + + # Process completed Ray tasks and notify operators. + num_errored_blocks = 0 + if active_tasks: + ready, _ = ray.wait( + list(active_tasks.keys()), + num_returns=len(active_tasks), + fetch_local=False, + timeout=0.1, + ) + + # Organize tasks by the operator they belong to, and sort them by task index. + # So that we'll process them in a deterministic order. + # This is because OpResourceAllocator may limit the number of blocks to read + # per operator. In this case, we want to have fewer tasks finish quickly and + # yield resources, instead of having all tasks output blocks together. + ready_tasks_by_op = defaultdict(list) + for ref in ready: + state, task = active_tasks[ref] + ready_tasks_by_op[state].append(task) + + for state, ready_tasks in ready_tasks_by_op.items(): + ready_tasks = sorted(ready_tasks, key=lambda t: t.task_index()) + for task in ready_tasks: + if isinstance(task, DataOpTask): + try: + bytes_read = task.on_data_ready( + max_bytes_to_read_per_op.get(state, None) + ) + if state in max_bytes_to_read_per_op: + max_bytes_to_read_per_op[state] -= bytes_read + except Exception as e: + num_errored_blocks += 1 + should_ignore = ( + max_errored_blocks < 0 + or max_errored_blocks >= num_errored_blocks + ) + error_message = ( + "An exception was raised from a task of " + f'operator "{state.op.name}".' + ) + if should_ignore: + remaining = ( + max_errored_blocks - num_errored_blocks + if max_errored_blocks >= 0 + else "unlimited" + ) + error_message += ( + " Ignoring this exception with remaining" + f" max_errored_blocks={remaining}." + ) + logger.error(error_message, exc_info=e) + else: + error_message += ( + " Dataset execution will now abort." + " To ignore this exception and continue, set" + " DataContext.max_errored_blocks." + ) + logger.error(error_message) + raise e from None + else: + assert isinstance(task, MetadataOpTask) + task.on_task_finished() + + # Pull any operator outputs into the streaming op state. + for op, op_state in topology.items(): + while op.has_next(): + op_state.add_output(op.get_next()) + + return num_errored_blocks + + +def update_operator_states(topology: Topology) -> None: + """Update operator states accordingly for newly completed tasks. + Should be called after `process_completed_tasks()`.""" + + # Call inputs_done() on ops where no more inputs are coming. + for op, op_state in topology.items(): + if op_state.inputs_done_called: + continue + all_inputs_done = True + for idx, dep in enumerate(op.input_dependencies): + if dep.completed() and not topology[dep].outqueue: + if not op_state.input_done_called[idx]: + op.input_done(idx) + op_state.input_done_called[idx] = True + else: + all_inputs_done = False + + if all_inputs_done: + op.all_inputs_done() + op_state.inputs_done_called = True + + # Traverse the topology in reverse topological order. + # For each op, if all of its downstream operators have completed. + # call mark_execution_completed() to also complete this op. + for op, op_state in reversed(list(topology.items())): + if op.completed(): + continue + dependents_completed = len(op.output_dependencies) > 0 and all( + dep.completed() for dep in op.output_dependencies + ) + if dependents_completed: + op.mark_execution_completed() + + +def select_operator_to_run( + topology: Topology, + resource_manager: ResourceManager, + backpressure_policies: List[BackpressurePolicy], + autoscaler: Autoscaler, + ensure_at_least_one_running: bool, +) -> Optional[PhysicalOperator]: + """Select an operator to run, if possible. + + The objective of this function is to maximize the throughput of the overall + pipeline, subject to defined memory and parallelism limits. + + This is currently implemented by applying backpressure on operators that are + producing outputs faster than they are consuming them `len(outqueue)`, as well as + operators with a large number of running tasks `num_processing()`. + + Note that memory limits also apply to the outqueue of the output operator. This + provides backpressure if the consumer is slow. However, once a bundle is returned + to the user, it is no longer tracked. + """ + # Filter to ops that are eligible for execution. + ops = [] + for op, state in topology.items(): + if resource_manager.op_resource_allocator_enabled(): + under_resource_limits = ( + resource_manager.op_resource_allocator.can_submit_new_task(op) + ) + else: + under_resource_limits = _execution_allowed(op, resource_manager) + in_backpressure = not under_resource_limits or any( + not p.can_add_input(op) for p in backpressure_policies + ) + op_runnable = False + if ( + not in_backpressure + and not op.completed() + and state.num_queued() > 0 + and op.should_add_input() + ): + ops.append(op) + op_runnable = True + # Update scheduling status + state._scheduling_status = OpSchedulingStatus( + selected=False, + runnable=op_runnable, + under_resource_limits=under_resource_limits, + ) + + # Signal whether op in backpressure for stats collections + op.notify_in_task_submission_backpressure(in_backpressure) + + # To ensure liveness, allow at least 1 op to run regardless of limits. This is + # gated on `ensure_at_least_one_running`, which is set if the consumer is blocked. + if ( + ensure_at_least_one_running + and not ops + and all(op.num_active_tasks() == 0 for op in topology) + ): + # The topology is entirely idle, so choose from all ready ops ignoring limits. + ops = [ + op + for op, state in topology.items() + if state.num_queued() > 0 and not op.completed() + ] + + selected_op = None + if ops: + # Run metadata-only operators first. After that, choose the operator with the + # least memory usage. + selected_op = min( + ops, + key=lambda op: ( + not op.throttling_disabled(), + resource_manager.get_op_usage(op).object_store_memory, + ), + ) + topology[selected_op]._scheduling_status.selected = True + autoscaler.try_trigger_scaling() + return selected_op + + +def _execution_allowed(op: PhysicalOperator, resource_manager: ResourceManager) -> bool: + """Return whether an operator is allowed to execute given resource usage. + + Operators are throttled globally based on CPU and GPU limits for the stream. + + For an N operator DAG, we only throttle the kth operator (in the source-to-sink + ordering) on object store utilization if the cumulative object store utilization + for the kth operator and every operator downstream from it is greater than + k/N * global_limit; i.e., the N - k operator sub-DAG is using more object store + memory than it's share. + + Args: + op: The operator to check. + resource_manager: The ResourceManager of the current dataset. + + Returns: + Whether the op is allowed to run. + """ + if op.throttling_disabled(): + return True + + global_usage = resource_manager.get_global_usage() + global_limits = resource_manager.get_global_limits() + + # To avoid starvation problems when dealing with fractional resource types, + # convert all quantities to integer (0 or 1) for deciding admissibility. This + # allows operators with non-integral requests to slightly overshoot the limit. + global_floored = ExecutionResources( + cpu=math.floor(global_usage.cpu or 0), + gpu=math.floor(global_usage.gpu or 0), + object_store_memory=global_usage.object_store_memory, + ) + inc = op.incremental_resource_usage() + if inc.cpu and inc.gpu: + raise NotImplementedError( + "Operator incremental resource usage cannot specify both CPU " + "and GPU at the same time, since it may cause deadlock." + ) + + # Ignore the scale of CPU and GPU requests, i.e., treating them as either 1 or 0. + # This ensures operators don't get starved due to the shape of their resource + # requests. + inc_indicator = ExecutionResources( + cpu=1 if inc.cpu else 0, + gpu=1 if inc.gpu else 0, + object_store_memory=0, + ) + + # Under global limits; always allow. + new_usage = global_floored.add(inc_indicator) + if new_usage.satisfies_limit(global_limits): + return True + + # We're over global limits, but execution may still be allowed if memory is the + # only bottleneck and this wouldn't impact downstream memory limits. This avoids + # stalling the execution for memory bottlenecks that occur upstream. + # See for more context: https://github.com/ray-project/ray/pull/32673 + global_limits_sans_memory = ExecutionResources.for_limits( + cpu=global_limits.cpu, gpu=global_limits.gpu + ) + global_ok_sans_memory = new_usage.satisfies_limit(global_limits_sans_memory) + downstream_memory = resource_manager.get_downstream_object_store_memory(op) + downstream_limit = global_limits.scale(resource_manager.get_downstream_fraction(op)) + downstream_memory_ok = ExecutionResources( + object_store_memory=downstream_memory + ).satisfies_limit(downstream_limit) + + return global_ok_sans_memory and downstream_memory_ok diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/util.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/util.py new file mode 100644 index 0000000000000000000000000000000000000000..d3bf3d9f1f54d0f9da6f7b55b2160e1228d43764 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/execution/util.py @@ -0,0 +1,80 @@ +from concurrent.futures import ThreadPoolExecutor +from typing import TYPE_CHECKING, Any, List + +import ray +from ray.data.block import BlockAccessor, CallableClass + +if TYPE_CHECKING: + from ray.data._internal.execution.interfaces import RefBundle + + +def make_ref_bundles(simple_data: List[List[Any]]) -> List["RefBundle"]: + """Create ref bundles from a list of block data. + + One bundle is created for each input block. + """ + import pandas as pd + + from ray.data._internal.execution.interfaces import RefBundle + + output = [] + for block in simple_data: + block = pd.DataFrame({"id": block}) + output.append( + RefBundle( + [ + ( + ray.put(block), + BlockAccessor.for_block(block).get_metadata(), + ) + ], + owns_blocks=True, + ) + ) + return output + + +memory_units = ["B", "KB", "MB", "GB", "TB", "PB"] + + +def memory_string(num_bytes: float) -> str: + """Return a human-readable memory string for the given amount of bytes.""" + k = 0 + while num_bytes >= 1024 and k < len(memory_units) - 1: + num_bytes /= 1024 + k += 1 + return f"{num_bytes:.1f}{memory_units[k]}" + + +def locality_string(locality_hits: int, locality_misses) -> str: + """Return a human-readable string for object locality stats.""" + if not locality_misses: + return "[all objects local]" + return f"[{locality_hits}/{locality_hits + locality_misses} objects local]" + + +def make_callable_class_concurrent(callable_cls: CallableClass) -> CallableClass: + """Returns a thread-safe CallableClass with the same logic as the provided + `callable_cls`. + + This function allows the usage of concurrent actors by safeguarding user logic + behind a separate thread. + + This allows batch slicing and formatting to occur concurrently, to overlap with the + user provided UDF. + """ + + class _Wrapper(callable_cls): + def __init__(self, *args, **kwargs): + self.thread_pool_executor = ThreadPoolExecutor(max_workers=1) + super().__init__(*args, **kwargs) + + def __repr__(self): + return super().__repr__() + + def __call__(self, *args, **kwargs): + # ThreadPoolExecutor will reuse the same thread for every submit call. + future = self.thread_pool_executor.submit(super().__call__, *args, **kwargs) + return future.result() + + return _Wrapper diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/logging.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..0f6eb6b7fab862e51c230edc2c47d4aacb91ed62 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/logging.py @@ -0,0 +1,208 @@ +import logging +import logging.config +import os +from typing import Optional + +import yaml + +import ray + +DEFAULT_CONFIG = { + "version": 1, + "disable_existing_loggers": False, + "formatters": { + "ray": { + "format": "%(asctime)s\t%(levelname)s %(filename)s:%(lineno)s -- %(message)s" # noqa: E501 + }, + "ray_json": {"class": "ray._private.ray_logging.formatters.JSONFormatter"}, + }, + "filters": { + "console_filter": {"()": "ray.data._internal.logging.HiddenRecordFilter"}, + "core_context_filter": { + "()": "ray._private.ray_logging.filters.CoreContextFilter" + }, + }, + "handlers": { + "file": { + "class": "ray.data._internal.logging.SessionFileHandler", + "formatter": "ray", + "filename": "ray-data.log", + }, + "file_json": { + "class": "ray.data._internal.logging.SessionFileHandler", + "formatter": "ray_json", + "filename": "ray-data.log", + "filters": ["core_context_filter"], + }, + "console": { + "class": "ray._private.log.PlainRayHandler", + "formatter": "ray", + "level": "INFO", + "filters": ["console_filter"], + }, + }, + "loggers": { + "ray.data": { + "level": "DEBUG", + "handlers": ["file", "console"], + "propagate": False, + }, + "ray.air.util.tensor_extensions": { + "level": "DEBUG", + "handlers": ["file", "console"], + "propagate": False, + }, + }, +} + +# Dictionary of substitutions to be performed when using JSON mode. Handlers with names +# corresponding to keys will be replaced by those corresponding to values. +RAY_DATA_LOG_HANDLER_JSON_SUBSTITUTIONS = {"file": "file_json"} + +# Env. variable to specify the encoding of the file logs when using the default config. +RAY_DATA_LOG_ENCODING_ENV_VAR_NAME = "RAY_DATA_LOG_ENCODING" + +# Env. variable to specify the logging config path use defaults if not set +RAY_DATA_LOGGING_CONFIG_ENV_VAR_NAME = "RAY_DATA_LOGGING_CONFIG" + +# To facilitate debugging, Ray Data writes debug logs to a file. However, if Ray Data +# logs every scheduler loop, logging might impact performance. So, we add a "TRACE" +# level where logs aren't written by default. +# +# Use the following code to log a message at the "TRACE" level: +# ``` +# logger.log(logging.getLevelName("TRACE"), "Your message here.") +# ```` +logging.addLevelName(logging.DEBUG - 1, "TRACE") + + +class HiddenRecordFilter: + """Filters out log records with the "hide" attribute set to True. + + This filter allows you to override default logging behavior. For example, if errors + are printed by default, and you don't want to print a specific error, you can set + the "hide" attribute to avoid printing the message. + + .. testcode:: + + import logging + logger = logging.getLogger("ray.data.spam") + + # This warning won't be printed to the console. + logger.warning("ham", extra={"hide": True}) + """ + + def filter(self, record): + return not getattr(record, "hide", False) + + +class SessionFileHandler(logging.Handler): + """A handler that writes to a log file in the Ray session directory. + + The Ray session directory isn't available until Ray is initialized, so this handler + lazily creates the file handler when you emit a log record. + + Args: + filename: The name of the log file. The file is created in the 'logs' directory + of the Ray session directory. + """ + + def __init__(self, filename: str): + super().__init__() + self._filename = filename + self._handler = None + self._formatter = None + self._path = None + + def emit(self, record): + if self._handler is None: + self._try_create_handler() + if self._handler is not None: + self._handler.emit(record) + + def setFormatter(self, fmt: logging.Formatter) -> None: + if self._handler is not None: + self._handler.setFormatter(fmt) + self._formatter = fmt + + def _try_create_handler(self): + assert self._handler is None + + log_directory = get_log_directory() + if log_directory is None: + return + + os.makedirs(log_directory, exist_ok=True) + + self._path = os.path.join(log_directory, self._filename) + self._handler = logging.FileHandler(self._path) + if self._formatter is not None: + self._handler.setFormatter(self._formatter) + + +def configure_logging() -> None: + """Configure the Python logger named 'ray.data'. + + This function loads the configration YAML specified by "RAY_DATA_LOGGING_CONFIG" + environment variable. If the variable isn't set, this function loads the default + "logging.yaml" file that is adjacent to this module. + + If "RAY_DATA_LOG_ENCODING" is specified as "JSON" we will enable JSON logging mode + if using the default logging config. + """ + + def _load_logging_config(config_path: str): + with open(config_path) as file: + config = yaml.safe_load(file) + return config + + # Dynamically load env vars + config_path = os.environ.get(RAY_DATA_LOGGING_CONFIG_ENV_VAR_NAME) + log_encoding = os.environ.get(RAY_DATA_LOG_ENCODING_ENV_VAR_NAME) + + if config_path is not None: + config = _load_logging_config(config_path) + else: + config = DEFAULT_CONFIG + if log_encoding is not None and log_encoding.upper() == "JSON": + for logger in config["loggers"].values(): + for ( + old_handler_name, + new_handler_name, + ) in RAY_DATA_LOG_HANDLER_JSON_SUBSTITUTIONS.items(): + logger["handlers"].remove(old_handler_name) + logger["handlers"].append(new_handler_name) + + logging.config.dictConfig(config) + + # After configuring logger, warn if RAY_DATA_LOGGING_CONFIG is used with + # RAY_DATA_LOG_ENCODING, because they are not both supported together. + if config_path is not None and log_encoding is not None: + logger = logging.getLogger(__name__) + logger.warning( + "Using `RAY_DATA_LOG_ENCODING` is not supported with " + + "`RAY_DATA_LOGGING_CONFIG`" + ) + + +def reset_logging() -> None: + """Reset the logger named 'ray.data' to its initial state. + + Used for testing. + """ + logger = logging.getLogger("ray.data") + logger.handlers.clear() + logger.setLevel(logging.NOTSET) + + +def get_log_directory() -> Optional[str]: + """Return the directory where Ray Data writes log files. + + If Ray isn't initialized, this function returns ``None``. + """ + global_node = ray._private.worker._global_node + if global_node is None: + return None + + session_dir = global_node.get_session_dir_path() + return os.path.join(session_dir, "logs", "ray-data") diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/numpy_support.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/numpy_support.py new file mode 100644 index 0000000000000000000000000000000000000000..d04060fc831e8135d42056539e4c8295d0739542 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/numpy_support.py @@ -0,0 +1,167 @@ +import collections +import logging +from datetime import datetime +from typing import Any, Dict, List, Union + +import numpy as np + +from ray.air.util.tensor_extensions.utils import create_ragged_ndarray +from ray.data._internal.util import _truncated_repr + +logger = logging.getLogger(__name__) + + +def is_array_like(value: Any) -> bool: + """Checks whether objects are array-like, excluding numpy scalars.""" + + return hasattr(value, "__array__") and hasattr(value, "__len__") + + +def is_valid_udf_return(udf_return_col: Any) -> bool: + """Check whether a UDF column is valid. + + Valid columns must either be a list of elements, or an array-like object. + """ + + return isinstance(udf_return_col, list) or is_array_like(udf_return_col) + + +def is_nested_list(udf_return_col: List[Any]) -> bool: + for e in udf_return_col: + if isinstance(e, list): + return True + return False + + +def validate_numpy_batch(batch: Union[Dict[str, np.ndarray], Dict[str, list]]) -> None: + if not isinstance(batch, collections.abc.Mapping) or any( + not is_valid_udf_return(col) for col in batch.values() + ): + raise ValueError( + "Batch must be an ndarray or dictionary of ndarrays when converting " + f"a numpy batch to a block, got: {type(batch)} " + f"({_truncated_repr(batch)})" + ) + + +def _detect_highest_datetime_precision(datetime_list: List[datetime]) -> str: + highest_precision = "D" + + for dt in datetime_list: + if dt.microsecond != 0 and dt.microsecond % 1000 != 0: + highest_precision = "us" + break + elif dt.microsecond != 0 and dt.microsecond % 1000 == 0: + highest_precision = "ms" + elif dt.hour != 0 or dt.minute != 0 or dt.second != 0: + # pyarrow does not support h or m, use s for those cases too + highest_precision = "s" + + return highest_precision + + +def _convert_datetime_list_to_array(datetime_list: List[datetime]) -> np.ndarray: + precision = _detect_highest_datetime_precision(datetime_list) + + return np.array( + [np.datetime64(dt, precision) for dt in datetime_list], + dtype=f"datetime64[{precision}]", + ) + + +def convert_to_numpy(column_values: Any) -> np.ndarray: + """Convert UDF columns (output of map_batches) to numpy, if possible. + + This includes lists of scalars, objects supporting the array protocol, and lists + of objects supporting the array protocol, such as `[1, 2, 3]`, `Tensor([1, 2, 3])`, + and `[array(1), array(2), array(3)]`. + + Returns: + The input as an np.ndarray if possible, otherwise the original input. + + Raises: + ValueError if an input was array-like but we failed to convert it to an array. + """ + + if isinstance(column_values, np.ndarray): + # No copy/conversion needed, just keep it verbatim. + return column_values + + elif isinstance(column_values, list): + if len(column_values) == 1 and isinstance(column_values[0], np.ndarray): + # Optimization to avoid conversion overhead from list to np.array. + return np.expand_dims(column_values[0], axis=0) + + if all(isinstance(elem, datetime) for elem in column_values): + return _convert_datetime_list_to_array(column_values) + + # Try to convert list values into an numpy array via + # np.array(), so users don't need to manually cast. + # NOTE: we don't cast generic iterables, since types like + # `str` are also Iterable. + try: + # Convert array-like objects (like torch.Tensor) to `np.ndarray`s + if all(is_array_like(e) for e in column_values): + # Use np.asarray() instead of np.array() to avoid copying if possible. + column_values = [np.asarray(e) for e in column_values] + + shapes = set() + has_object = False + for e in column_values: + if isinstance(e, np.ndarray): + shapes.add((e.dtype, e.shape)) + elif isinstance(e, bytes): + # Don't convert variable length binary data to Numpy arrays as it + # treats zero encoding as termination by default. + # Per recommendation from + # https://github.com/apache/arrow/issues/26470, + # we use object dtype. + # https://github.com/ray-project/ray/issues/35586#issuecomment-1558148261 + has_object = True + elif not np.isscalar(e): + has_object = True + + # When column values are + # - Arrays of heterogeneous shapes + # - Byte-strings (viewed as arrays of heterogeneous shapes) + # - Non-scalar objects (tuples, lists, arbitrary object types) + # + # Custom "ragged ndarray" is created, represented as an array of + # references (ie ndarray with dtype=object) + if has_object or len(shapes) > 1: + # This util works around some limitations of np.array(dtype=object). + return create_ragged_ndarray(column_values) + else: + return np.array(column_values) + + except Exception as e: + logger.error( + f"Failed to convert column values to numpy array: " + f"{_truncated_repr(column_values)}", + exc_info=e, + ) + + raise ValueError( + "Failed to convert column values to numpy array: " + f"({_truncated_repr(column_values)}): {e}." + ) from e + + elif is_array_like(column_values): + # Converts other array-like objects such as torch.Tensor. + try: + # Use np.asarray() instead of np.array() to avoid copying if possible. + return np.asarray(column_values) + except Exception as e: + logger.error( + f"Failed to convert column values to numpy array: " + f"{_truncated_repr(column_values)}", + exc_info=e, + ) + + raise ValueError( + "Failed to convert column values to numpy array: " + f"({_truncated_repr(column_values)}): {e}." + ) from e + + else: + return column_values diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/progress_bar.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/progress_bar.py new file mode 100644 index 0000000000000000000000000000000000000000..805a0724ca89fc3d4f9368c47a3081b0f23c056b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/progress_bar.py @@ -0,0 +1,217 @@ +import logging +import threading +from typing import Any, List, Optional + +import ray +from ray.experimental import tqdm_ray +from ray.types import ObjectRef +from ray.util.debug import log_once + +logger = logging.getLogger(__name__) + +try: + import tqdm + + needs_warning = False +except ImportError: + tqdm = None + needs_warning = True + +# Used a signal to cancel execution. +_canceled_threads = set() +_canceled_threads_lock = threading.Lock() + + +def extract_num_rows(result: Any) -> int: + """Extract the number of rows from a result object. + + Args: + result: The result object from which to extract the number of rows. + + Returns: + The number of rows, defaulting to 1 if it cannot be determined. + """ + if hasattr(result, "num_rows"): + return result.num_rows + elif hasattr(result, "__len__"): + # For output is DataFrame,i.e. sort_sample + return len(result) + else: + return 1 + + +class ProgressBar: + """Thin wrapper around tqdm to handle soft imports. + + If `total` is `None` known (for example, it is unknown + because no tasks have finished yet), doesn't display the full + progress bar. Still displays basic progress stats from tqdm.""" + + # If the name/description of the progress bar exceeds this length, + # it will be truncated. + MAX_NAME_LENGTH = 100 + + def __init__( + self, + name: str, + total: Optional[int], + unit: str, + position: int = 0, + enabled: Optional[bool] = None, + ): + self._desc = self._truncate_name(name) + self._progress = 0 + # Prepend a space to the unit for better formatting. + if unit[0] != " ": + unit = " " + unit + + if enabled is None: + from ray.data import DataContext + + enabled = DataContext.get_current().enable_progress_bars + if not enabled: + self._bar = None + elif tqdm: + ctx = ray.data.context.DataContext.get_current() + if ctx.use_ray_tqdm: + self._bar = tqdm_ray.tqdm(total=total, unit=unit, position=position) + else: + self._bar = tqdm.tqdm( + total=total or 0, + position=position, + dynamic_ncols=True, + unit=unit, + unit_scale=True, + ) + self._bar.set_description(self._desc) + else: + global needs_warning + if needs_warning: + print("[dataset]: Run `pip install tqdm` to enable progress reporting.") + needs_warning = False + self._bar = None + + def _truncate_name(self, name: str) -> str: + ctx = ray.data.context.DataContext.get_current() + if ( + not ctx.enable_progress_bar_name_truncation + or len(name) <= self.MAX_NAME_LENGTH + ): + return name + + op_names = name.split("->") + if len(op_names) == 1: + return op_names[0] + + # Include as many operators as possible without approximately + # exceeding `MAX_NAME_LENGTH`. Always include the first and + # last operator names soit is easy to identify the DAG. + truncated_op_names = [op_names[0]] + for op_name in op_names[1:-1]: + if ( + len("->".join(truncated_op_names)) + + len("->") + + len(op_name) + + len("->") + + len(op_names[-1]) + ) > self.MAX_NAME_LENGTH: + truncated_op_names.append("...") + if log_once("ray_data_truncate_operator_name"): + logger.warning( + f"Truncating long operator name to {self.MAX_NAME_LENGTH} " + "characters. To disable this behavior, set " + "`ray.data.DataContext.get_current()." + "DEFAULT_ENABLE_PROGRESS_BAR_NAME_TRUNCATION = False`." + ) + break + truncated_op_names.append(op_name) + truncated_op_names.append(op_names[-1]) + return "->".join(truncated_op_names) + + def block_until_complete(self, remaining: List[ObjectRef]) -> None: + t = threading.current_thread() + while remaining: + done, remaining = ray.wait( + remaining, num_returns=len(remaining), fetch_local=False, timeout=0.1 + ) + total_rows_processed = 0 + for _, result in zip(done, ray.get(done)): + num_rows = extract_num_rows(result) + total_rows_processed += num_rows + self.update(total_rows_processed) + + with _canceled_threads_lock: + if t in _canceled_threads: + break + + def fetch_until_complete(self, refs: List[ObjectRef]) -> List[Any]: + ref_to_result = {} + remaining = refs + t = threading.current_thread() + # Triggering fetch_local redundantly for the same object is slower. + # We only need to trigger the fetch_local once for each object, + # raylet will persist these fetch requests even after ray.wait returns. + # See https://github.com/ray-project/ray/issues/30375. + fetch_local = True + while remaining: + done, remaining = ray.wait( + remaining, + num_returns=len(remaining), + fetch_local=fetch_local, + timeout=0.1, + ) + if fetch_local: + fetch_local = False + total_rows_processed = 0 + for ref, result in zip(done, ray.get(done)): + ref_to_result[ref] = result + num_rows = extract_num_rows(result) + total_rows_processed += num_rows + self.update(total_rows_processed) + + with _canceled_threads_lock: + if t in _canceled_threads: + break + + return [ref_to_result[ref] for ref in refs] + + def set_description(self, name: str) -> None: + name = self._truncate_name(name) + if self._bar and name != self._desc: + self._desc = name + self._bar.set_description(self._desc) + + def get_description(self) -> str: + return self._desc + + def refresh(self): + if self._bar: + self._bar.refresh() + + def update(self, i: int = 0, total: Optional[int] = None) -> None: + if self._bar and (i != 0 or self._bar.total != total): + self._progress += i + if total is not None: + self._bar.total = total + if self._bar.total is not None and self._progress > self._bar.total: + # If the progress goes over 100%, update the total. + self._bar.total = self._progress + self._bar.update(i) + + def close(self): + if self._bar: + if self._bar.total is not None and self._progress != self._bar.total: + # If the progress is not complete, update the total. + self._bar.total = self._progress + self._bar.refresh() + self._bar.close() + self._bar = None + + def __del__(self): + self.close() + + def __getstate__(self): + return {} + + def __setstate__(self, state): + self._bar = None # Progress bar is disabled on remote nodes. diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/remote_fn.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/remote_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..511604c0bd2e65b0974795d2ce260147325cbebb --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/remote_fn.py @@ -0,0 +1,80 @@ +from typing import Any, Dict, Hashable, List + +import ray + +CACHED_FUNCTIONS = {} + + +def cached_remote_fn(fn: Any, **ray_remote_args) -> Any: + """Lazily defines a ray.remote function. + + This is used in Datasets to avoid circular import issues with ray.remote. + (ray imports ray.data in order to allow ``ray.data.read_foo()`` to work, + which means ray.remote cannot be used top-level in ray.data). + + NOTE: Dynamic arguments should not be passed in directly, + and should be set with ``options`` instead: + ``cached_remote_fn(fn, **static_args).options(**dynamic_args)``. + """ + + # NOTE: Hash of the passed in arguments guarantees that we're caching + # complete instantiation of the Ray's remote method + # + # To compute the hash of passed in arguments and make sure it's deterministic + # - Sort all KV-pairs by the keys + # - Convert sorted list into tuple + # - Compute hash of the resulting tuple + hashable_args = _make_hashable(ray_remote_args) + args_hash = hash(hashable_args) + + if (fn, args_hash) not in CACHED_FUNCTIONS: + default_ray_remote_args = { + # Use the default scheduling strategy for all tasks so that we will + # not inherit a placement group from the caller, if there is one. + # The caller of this function may override the scheduling strategy + # as needed. + "scheduling_strategy": "DEFAULT", + "max_retries": -1, + } + ray_remote_args = {**default_ray_remote_args, **ray_remote_args} + _add_system_error_to_retry_exceptions(ray_remote_args) + + CACHED_FUNCTIONS[(fn, args_hash)] = ray.remote(**ray_remote_args)(fn) + + return CACHED_FUNCTIONS[(fn, args_hash)] + + +def _make_hashable(obj): + if isinstance(obj, (List, tuple)): + return tuple([_make_hashable(o) for o in obj]) + elif isinstance(obj, Dict): + converted = [(_make_hashable(k), _make_hashable(v)) for k, v in obj.items()] + return tuple(sorted(converted, key=lambda t: t[0])) + elif isinstance(obj, Hashable): + return obj + else: + raise ValueError(f"Type {type(obj)} is not hashable") + + +def _add_system_error_to_retry_exceptions(ray_remote_args) -> None: + """Modify the remote args so that Ray retries `RaySystemError`s. + + Ray typically automatically retries system errors. However, in some cases, Ray won't + retry system errors if they're raised from task code. To ensure that Ray Data is + fault tolerant to those errors, we need to add `RaySystemError` to the + `retry_exceptions` list. + + TODO: Fix this in Ray Core. See https://github.com/ray-project/ray/pull/45079. + """ + retry_exceptions = ray_remote_args.get("retry_exceptions", False) + assert isinstance(retry_exceptions, (list, bool)) + + if ( + isinstance(retry_exceptions, list) + and ray.exceptions.RaySystemError not in retry_exceptions + ): + retry_exceptions.append(ray.exceptions.RaySystemError) + elif not retry_exceptions: + retry_exceptions = [ray.exceptions.RaySystemError] + + ray_remote_args["retry_exceptions"] = retry_exceptions diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/size_estimator.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/size_estimator.py new file mode 100644 index 0000000000000000000000000000000000000000..75714cc50b8d61e2b103820a730a4051810c4277 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/size_estimator.py @@ -0,0 +1,92 @@ +from typing import Any, List + +import ray +from ray import cloudpickle + +_ray_initialized = False + + +class SizeEstimator: + """Efficiently estimates the Ray serialized size of a stream of items. + + For efficiency, this only samples a fraction of the added items for real + Ray-serialization. + """ + + def __init__(self): + self._running_mean = RunningMean() + self._count = 0 + + def add(self, item: Any) -> None: + self._count += 1 + if self._count <= 10: + self._running_mean.add(self._real_size(item), weight=1) + elif self._count <= 100: + if self._count % 10 == 0: + self._running_mean.add(self._real_size(item), weight=10) + elif self._count % 100 == 0: + self._running_mean.add(self._real_size(item), weight=100) + + def add_block(self, block: List[Any]) -> None: + if self._count < 10: + for i in range(min(10 - self._count, len(block))): + self._running_mean.add(self._real_size(block[i]), weight=1) + if self._count < 100: + for i in range( + 10 - (self._count % 10), min(100 - self._count, len(block)), 10 + ): + self._running_mean.add(self._real_size(block[i]), weight=10) + if (len(block) + (self._count % 100)) // 100 > 1: + for i in range(100 - (self._count % 100), len(block), 100): + self._running_mean.add(self._real_size(block[i]), weight=100) + self._count += len(block) + + def size_bytes(self) -> int: + return int(self._running_mean.mean * self._count) + + def _real_size(self, item: Any) -> int: + is_client = ray.util.client.ray.is_connected() + # In client mode, fallback to using Ray cloudpickle instead of the + # real serializer. + if is_client: + return len(cloudpickle.dumps(item)) + + # We're using an internal Ray API, and have to ensure it's + # initialized # by calling a public API. + global _ray_initialized + if not _ray_initialized: + _ray_initialized = True + ray.put(None) + return ( + ray._private.worker.global_worker.get_serialization_context() + .serialize(item) + .total_bytes + ) + + +# Adapted from the RLlib MeanStdFilter. +class RunningMean: + def __init__(self): + self._weight = 0 + self._mean = 0 + + def add(self, x: int, weight: int = 1) -> None: + if weight == 0: + return + n1 = self._weight + n2 = weight + n = n1 + n2 + M = (n1 * self._mean + n2 * x) / n + self._weight = n + self._mean = M + + @property + def n(self) -> int: + return self._weight + + @property + def mean(self) -> float: + return self._mean + + def __repr__(self): + return "(n={}, mean={})".format(self.n, self.mean) diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/split.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/split.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7fe145af095f655828038fa1aff520dc0f6487 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/split.py @@ -0,0 +1,297 @@ +import itertools +import logging +from typing import Iterable, List, Tuple, Union + +import ray +from ray.data._internal.memory_tracing import trace_deallocation +from ray.data._internal.remote_fn import cached_remote_fn +from ray.data.block import ( + Block, + BlockAccessor, + BlockExecStats, + BlockMetadata, + BlockPartition, +) +from ray.types import ObjectRef + +logger = logging.getLogger(__name__) + + +def _calculate_blocks_rows( + blocks_with_metadata: BlockPartition, +) -> List[int]: + """Calculate the number of rows for a list of blocks with metadata.""" + get_num_rows = cached_remote_fn(_get_num_rows) + block_rows = [] + for block, metadata in blocks_with_metadata: + if metadata.num_rows is None: + # Need to fetch number of rows. + num_rows = ray.get(get_num_rows.remote(block)) + metadata.num_rows = num_rows + else: + num_rows = metadata.num_rows + block_rows.append(num_rows) + return block_rows + + +def _generate_valid_indices( + num_rows_per_block: List[int], + split_indices: List[int], +) -> List[int]: + """Generate valid split indices by apply min(index, total_num_rows) + to every index.""" + total_rows = sum(num_rows_per_block) + return [min(index, total_rows) for index in split_indices] + + +def _generate_per_block_split_indices( + num_rows_per_block: List[int], + split_indices: List[int], +) -> List[List[int]]: + """Given num rows per block and valid split indices, generate per block split indices. + + Args: + num_rows_per_block: num of rows per block. + split_indices: The (global) indices at which to split the blocks. + Returns: + Per block split indices indicates each input block's split point(s). + """ + # for each split index, we iterate though the currnet input block + # to see if the index falls into this block. if the index + # falls into this block, we push it back to the current block's + # split indices. Otherwise, we move on to the next block. + per_block_split_indices = [] + current_input_block_id = 0 + current_block_split_indices = [] + current_block_global_offset = 0 + current_index_id = 0 + + while current_index_id < len(split_indices): + split_index = split_indices[current_index_id] + current_block_row = num_rows_per_block[current_input_block_id] + if split_index - current_block_global_offset <= current_block_row: + current_block_split_indices.append( + split_index - current_block_global_offset + ) + current_index_id += 1 + continue + per_block_split_indices.append(current_block_split_indices) + current_block_split_indices = [] + current_block_global_offset += num_rows_per_block[current_input_block_id] + current_input_block_id += 1 + + # we might finished all the indices but there are still blocks left, also + # current_block_split_indices might not be added yet. + while len(per_block_split_indices) < len(num_rows_per_block): + per_block_split_indices.append(current_block_split_indices) + current_block_split_indices = [] + return per_block_split_indices + + +def _split_single_block( + block_id: int, + block: Block, + meta: BlockMetadata, + split_indices: List[int], +) -> Tuple[Union[Tuple[int, List[BlockMetadata]], Block], ...]: + """Split the provided block at the given indices. + + Args: + block_id: the id of this block in the block list. + block: block to be split. + meta: metadata of the block, we expect meta.num is valid. + split_indices: the indices where the block should be split. + Returns: + returns block_id, split blocks metadata, and a list of blocks + in the following form. We return blocks in this way + so that the owner of blocks could be the caller(driver) + instead of worker itself. + Tuple(block_id, split_blocks_meta), block0, block1 ... + """ + split_meta = [] + split_blocks = [] + block_accessor = BlockAccessor.for_block(block) + prev_index = 0 + # append one more entry at the last so we don't + # need handle empty edge case. + split_indices.append(meta.num_rows) + for index in split_indices: + logger.debug(f"slicing block {prev_index}:{index}") + stats = BlockExecStats.builder() + split_block = block_accessor.slice(prev_index, index) + accessor = BlockAccessor.for_block(split_block) + _meta = BlockMetadata( + num_rows=accessor.num_rows(), + size_bytes=accessor.size_bytes(), + schema=meta.schema, + input_files=meta.input_files, + exec_stats=stats.build(), + ) + split_meta.append(_meta) + split_blocks.append(split_block) + prev_index = index + results = [(block_id, split_meta)] + results.extend(split_blocks) + return tuple(results) + + +def _drop_empty_block_split(block_split_indices: List[int], num_rows: int) -> List[int]: + """drop split indices that creates empty block split. This could happen when there + are duplicated indices, or index equal to 0 (start of the block) or num_block_rows + (end of the block). + """ + prev_index = -1 + optimized_indices = [] + for index in block_split_indices: + if index == 0 or index == num_rows: + continue + if index == prev_index: + continue + optimized_indices.append(index) + prev_index = index + return optimized_indices + + +def _split_all_blocks( + blocks_with_metadata: List[Tuple[ObjectRef[Block], BlockMetadata]], + per_block_split_indices: List[List[int]], + owned_by_consumer: bool, +) -> Iterable[Tuple[ObjectRef[Block], BlockMetadata]]: + """Split all the input blocks based on the split indices""" + split_single_block = cached_remote_fn(_split_single_block) + + all_blocks_split_results: List[BlockPartition] = [None] * len(blocks_with_metadata) + + per_block_split_metadata_futures = [] + per_block_split_block_refs = [] + + # tracking splitted blocks for gc. + blocks_splitted = [] + for block_id, block_split_indices in enumerate(per_block_split_indices): + (block_ref, meta) = blocks_with_metadata[block_id] + block_row = meta.num_rows + block_split_indices = _drop_empty_block_split(block_split_indices, block_row) + if len(block_split_indices) == 0: + # optimization: if no split is needed, we just need to add it to the + # result + all_blocks_split_results[block_id] = [(block_ref, meta)] + else: + # otherwise call split remote function. + object_refs = split_single_block.options( + scheduling_strategy="SPREAD", num_returns=2 + len(block_split_indices) + ).remote( + block_id, + block_ref, + meta, + block_split_indices, + ) + per_block_split_metadata_futures.append(object_refs[0]) + per_block_split_block_refs.append(object_refs[1:]) + + blocks_splitted.append(block_ref) + + if per_block_split_metadata_futures: + # only get metadata. + per_block_split_metadata = ray.get(per_block_split_metadata_futures) + for (block_id, meta), block_refs in zip( + per_block_split_metadata, per_block_split_block_refs + ): + assert len(meta) == len(block_refs) + all_blocks_split_results[block_id] = zip(block_refs, meta) + + # We make a copy for the blocks that have been splitted, so the input blocks + # can be cleared if they are owned by consumer (consumer-owned blocks will + # only be consumed by the owner). + if owned_by_consumer: + for b in blocks_splitted: + trace_deallocation(b, "split._split_all_blocks") + else: + for b in blocks_splitted: + trace_deallocation(b, "split._split_all_blocks", free=False) + + return itertools.chain.from_iterable(all_blocks_split_results) + + +def _generate_global_split_results( + all_blocks_split_results: Iterable[Tuple[ObjectRef[Block], BlockMetadata]], + global_split_sizes: List[int], +) -> Tuple[List[List[ObjectRef[Block]]], List[List[BlockMetadata]]]: + """Reassemble per block's split result into final split result.""" + result_blocks = [] + result_metas = [] + + current_blocks = [] + current_meta = [] + current_split_size = 0 + current_split_id = 0 + + while current_split_id < len(global_split_sizes): + if current_split_size >= global_split_sizes[current_split_id]: + assert current_split_size == global_split_sizes[current_split_id] + result_blocks.append(current_blocks) + result_metas.append(current_meta) + + current_blocks = [] + current_meta = [] + current_split_size = 0 + current_split_id += 1 + else: + (block_ref, meta) = next(all_blocks_split_results) + current_blocks.append(block_ref) + current_meta.append(meta) + current_split_size += meta.num_rows + + return result_blocks, result_metas + + +def _split_at_indices( + blocks_with_metadata: List[Tuple[ObjectRef[Block], BlockMetadata]], + indices: List[int], + owned_by_consumer: bool = True, + block_rows: List[int] = None, +) -> Tuple[List[List[ObjectRef[Block]]], List[List[BlockMetadata]]]: + """Split blocks at the provided indices. + + Args: + blocks_with_metadata: Block futures to split, including the associated metadata. + indices: The (global) indices at which to split the blocks. + owned_by_consumer: Whether the provided blocks are owned by the consumer. + block_rows: The number of rows for each block, in case it has already been + computed. + + Returns: + The block split futures and their metadata. If an index split is empty, the + corresponding block split will be empty . + """ + + # We implement the split in 3 phases. + # phase 1: calculate the per block split indices. + blocks_with_metadata = list(blocks_with_metadata) + if len(blocks_with_metadata) == 0: + return ([[]] * (len(indices) + 1), [[]] * (len(indices) + 1)) + if block_rows is None: + block_rows = _calculate_blocks_rows(blocks_with_metadata) + valid_indices = _generate_valid_indices(block_rows, indices) + per_block_split_indices: List[List[int]] = _generate_per_block_split_indices( + block_rows, valid_indices + ) + + # phase 2: split each block based on the indices from previous step. + all_blocks_split_results: Iterable[ + Tuple[ObjectRef[Block], BlockMetadata] + ] = _split_all_blocks( + blocks_with_metadata, per_block_split_indices, owned_by_consumer + ) + + # phase 3: generate the final split. + + # first calculate the size for each split. + helper = [0] + valid_indices + [sum(block_rows)] + split_sizes = [helper[i] - helper[i - 1] for i in range(1, len(helper))] + + return _generate_global_split_results(all_blocks_split_results, split_sizes) + + +def _get_num_rows(block: Block) -> int: + """Get the number of rows contained in the provided block.""" + return BlockAccessor.for_block(block).num_rows() diff --git a/vllm/lib/python3.10/site-packages/ray/data/_internal/util.py b/vllm/lib/python3.10/site-packages/ray/data/_internal/util.py new file mode 100644 index 0000000000000000000000000000000000000000..1d0b70cf6a6c97b1901d7897219b9e86b14a1ebe --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ray/data/_internal/util.py @@ -0,0 +1,1091 @@ +import importlib +import logging +import os +import pathlib +import random +import sys +import threading +import time +import urllib.parse +from collections import deque +from types import ModuleType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Iterable, + Iterator, + List, + Optional, + Tuple, + TypeVar, + Union, +) + +import numpy as np + +import ray +from ray._private.utils import _get_pyarrow_version +from ray.data.context import DEFAULT_READ_OP_MIN_NUM_BLOCKS, WARN_PREFIX, DataContext + +if TYPE_CHECKING: + import pandas + import pyarrow + + from ray.data._internal.compute import ComputeStrategy + from ray.data._internal.planner.exchange.sort_task_spec import SortKey + from ray.data.block import Block, BlockMetadata, UserDefinedFunction + from ray.data.datasource import Datasource, Reader + from ray.util.placement_group import PlacementGroup + +logger = logging.getLogger(__name__) + + +KiB = 1024 # bytes +MiB = 1024 * KiB +GiB = 1024 * MiB + + +# NOTE: Make sure that these lower and upper bounds stay in sync with version +# constraints given in python/setup.py. +# Inclusive minimum pyarrow version. +MIN_PYARROW_VERSION = "6.0.1" +RAY_DISABLE_PYARROW_VERSION_CHECK = "RAY_DISABLE_PYARROW_VERSION_CHECK" +_VERSION_VALIDATED = False +_LOCAL_SCHEME = "local" +_EXAMPLE_SCHEME = "example" + + +LazyModule = Union[None, bool, ModuleType] +_pyarrow_dataset: LazyModule = None + + +class _NullSentinel: + """Sentinel value that sorts greater than any other value.""" + + def __eq__(self, other): + return isinstance(other, _NullSentinel) + + def __lt__(self, other): + return False + + def __le__(self, other): + return isinstance(other, _NullSentinel) + + def __gt__(self, other): + return True + + def __ge__(self, other): + return True + + +NULL_SENTINEL = _NullSentinel() + + +def _lazy_import_pyarrow_dataset() -> LazyModule: + global _pyarrow_dataset + if _pyarrow_dataset is None: + try: + from pyarrow import dataset as _pyarrow_dataset + except ModuleNotFoundError: + # If module is not found, set _pyarrow to False so we won't + # keep trying to import it on every _lazy_import_pyarrow() call. + _pyarrow_dataset = False + return _pyarrow_dataset + + +def _check_pyarrow_version(): + """Check that pyarrow's version is within the supported bounds.""" + global _VERSION_VALIDATED + + if not _VERSION_VALIDATED: + if os.environ.get(RAY_DISABLE_PYARROW_VERSION_CHECK, "0") == "1": + _VERSION_VALIDATED = True + return + + version = _get_pyarrow_version() + if version is not None: + from packaging.version import parse as parse_version + + if parse_version(version) < parse_version(MIN_PYARROW_VERSION): + raise ImportError( + f"Dataset requires pyarrow >= {MIN_PYARROW_VERSION}, but " + f"{version} is installed. Reinstall with " + f'`pip install -U "pyarrow"`. ' + "If you want to disable this pyarrow version check, set the " + f"environment variable {RAY_DISABLE_PYARROW_VERSION_CHECK}=1." + ) + else: + logger.warning( + "You are using the 'pyarrow' module, but the exact version is unknown " + "(possibly carried as an internal component by another module). Please " + f"make sure you are using pyarrow >= {MIN_PYARROW_VERSION} to ensure " + "compatibility with Ray Dataset. " + "If you want to disable this pyarrow version check, set the " + f"environment variable {RAY_DISABLE_PYARROW_VERSION_CHECK}=1." + ) + _VERSION_VALIDATED = True + + +def _autodetect_parallelism( + parallelism: int, + target_max_block_size: int, + ctx: DataContext, + datasource_or_legacy_reader: Optional[Union["Datasource", "Reader"]] = None, + mem_size: Optional[int] = None, + placement_group: Optional["PlacementGroup"] = None, + avail_cpus: Optional[int] = None, +) -> Tuple[int, str, Optional[int]]: + """Returns parallelism to use and the min safe parallelism to avoid OOMs. + + This detects parallelism using the following heuristics, applied in order: + + 1) We start with the default value of 200. This can be overridden by + setting the `read_op_min_num_blocks` attribute of + :class:`~ray.data.context.DataContext`. + 2) Min block size. If the parallelism would make blocks smaller than this + threshold, the parallelism is reduced to avoid the overhead of tiny blocks. + 3) Max block size. If the parallelism would make blocks larger than this + threshold, the parallelism is increased to avoid OOMs during processing. + 4) Available CPUs. If the parallelism cannot make use of all the available + CPUs in the cluster, the parallelism is increased until it can. + + Args: + parallelism: The user-requested parallelism, or -1 for auto-detection. + target_max_block_size: The target max block size to + produce. We pass this separately from the + DatasetContext because it may be set per-op instead of + per-Dataset. + ctx: The current Dataset context to use for configs. + datasource_or_legacy_reader: The datasource or legacy reader, to be used for + data size estimation. + mem_size: If passed, then used to compute the parallelism according to + target_max_block_size. + placement_group: The placement group that this Dataset + will execute inside, if any. + avail_cpus: Override avail cpus detection (for testing only). + + Returns: + Tuple of detected parallelism (only if -1 was specified), the reason + for the detected parallelism (only if -1 was specified), and the estimated + inmemory size of the dataset. + """ + min_safe_parallelism = 1 + max_reasonable_parallelism = sys.maxsize + if mem_size is None and datasource_or_legacy_reader: + mem_size = datasource_or_legacy_reader.estimate_inmemory_data_size() + if mem_size is not None and not np.isnan(mem_size): + min_safe_parallelism = max(1, int(mem_size / target_max_block_size)) + max_reasonable_parallelism = max(1, int(mem_size / ctx.target_min_block_size)) + + reason = "" + if parallelism < 0: + if parallelism != -1: + raise ValueError("`parallelism` must either be -1 or a positive integer.") + + if ( + ctx.min_parallelism is not None + and ctx.min_parallelism != DEFAULT_READ_OP_MIN_NUM_BLOCKS + and ctx.read_op_min_num_blocks == DEFAULT_READ_OP_MIN_NUM_BLOCKS + ): + logger.warning( + "``DataContext.min_parallelism`` is deprecated in Ray 2.10. " + "Please specify ``DataContext.read_op_min_num_blocks`` instead." + ) + ctx.read_op_min_num_blocks = ctx.min_parallelism + + # Start with 2x the number of cores as a baseline, with a min floor. + if placement_group is None: + placement_group = ray.util.get_current_placement_group() + avail_cpus = avail_cpus or _estimate_avail_cpus(placement_group) + parallelism = max( + min(ctx.read_op_min_num_blocks, max_reasonable_parallelism), + min_safe_parallelism, + avail_cpus * 2, + ) + + if parallelism == ctx.read_op_min_num_blocks: + reason = ( + "DataContext.get_current().read_op_min_num_blocks=" + f"{ctx.read_op_min_num_blocks}" + ) + elif parallelism == max_reasonable_parallelism: + reason = ( + "output blocks of size at least " + "DataContext.get_current().target_min_block_size=" + f"{ctx.target_min_block_size / (1024 * 1024)}MiB" + ) + elif parallelism == min_safe_parallelism: + reason = ( + "output blocks of size at most " + "DataContext.get_current().target_max_block_size=" + f"{ctx.target_max_block_size / (1024 * 1024)}MiB" + ) + else: + reason = ( + "parallelism at least twice the available number " + f"of CPUs ({avail_cpus})" + ) + + logger.debug( + f"Autodetected parallelism={parallelism} based on " + f"estimated_available_cpus={avail_cpus} and " + f"estimated_data_size={mem_size}." + ) + + return parallelism, reason, mem_size + + +def _estimate_avail_cpus(cur_pg: Optional["PlacementGroup"]) -> int: + """Estimates the available CPU parallelism for this Dataset in the cluster. + + If we aren't in a placement group, this is trivially the number of CPUs in the + cluster. Otherwise, we try to calculate how large the placement group is relative + to the size of the cluster. + + Args: + cur_pg: The current placement group, if any. + """ + cluster_cpus = int(ray.cluster_resources().get("CPU", 1)) + cluster_gpus = int(ray.cluster_resources().get("GPU", 0)) + + # If we're in a placement group, we shouldn't assume the entire cluster's + # resources are available for us to use. Estimate an upper bound on what's + # reasonable to assume is available for datasets to use. + if cur_pg: + pg_cpus = 0 + for bundle in cur_pg.bundle_specs: + # Calculate the proportion of the cluster this placement group "takes up". + # Then scale our cluster_cpus proportionally to avoid over-parallelizing + # if there are many parallel Tune trials using the cluster. + cpu_fraction = bundle.get("CPU", 0) / max(1, cluster_cpus) + gpu_fraction = bundle.get("GPU", 0) / max(1, cluster_gpus) + max_fraction = max(cpu_fraction, gpu_fraction) + # Over-parallelize by up to a factor of 2, but no more than that. It's + # preferrable to over-estimate than under-estimate. + pg_cpus += 2 * int(max_fraction * cluster_cpus) + + return min(cluster_cpus, pg_cpus) + + return cluster_cpus + + +def _estimate_available_parallelism() -> int: + """Estimates the available CPU parallelism for this Dataset in the cluster. + If we are currently in a placement group, take that into account.""" + cur_pg = ray.util.get_current_placement_group() + return _estimate_avail_cpus(cur_pg) + + +def _warn_on_high_parallelism(requested_parallelism, num_read_tasks): + available_cpu_slots = ray.available_resources().get("CPU", 1) + if ( + requested_parallelism + and num_read_tasks > available_cpu_slots * 4 + and num_read_tasks >= 5000 + ): + logger.warning( + f"{WARN_PREFIX} The requested parallelism of {requested_parallelism} " + "is more than 4x the number of available CPU slots in the cluster of " + f"{available_cpu_slots}. This can " + "lead to slowdowns during the data reading phase due to excessive " + "task creation. Reduce the parallelism to match with the available " + "CPU slots in the cluster, or set parallelism to -1 for Ray Data " + "to automatically determine the parallelism. " + "You can ignore this message if the cluster is expected to autoscale." + ) + + +def _check_import(obj, *, module: str, package: str) -> None: + """Check if a required dependency is installed. + + If `module` can't be imported, this function raises an `ImportError` instructing + the user to install `package` from PyPI. + + Args: + obj: The object that has a dependency. + module: The name of the module to import. + package: The name of the package on PyPI. + """ + try: + importlib.import_module(module) + except ImportError: + raise ImportError( + f"`{obj.__class__.__name__}` depends on '{package}', but '{package}' " + f"couldn't be imported. You can install '{package}' by running `pip " + f"install {package}`." + ) + + +def _resolve_custom_scheme(path: str) -> str: + """Returns the resolved path if the given path follows a Ray-specific custom + scheme. Othewise, returns the path unchanged. + + The supported custom schemes are: "local", "example". + """ + parsed_uri = urllib.parse.urlparse(path) + if parsed_uri.scheme == _LOCAL_SCHEME: + path = parsed_uri.netloc + parsed_uri.path + elif parsed_uri.scheme == _EXAMPLE_SCHEME: + example_data_path = pathlib.Path(__file__).parent.parent / "examples" / "data" + path = example_data_path / (parsed_uri.netloc + parsed_uri.path) + path = str(path.resolve()) + return path + + +def _is_local_scheme(paths: Union[str, List[str]]) -> bool: + """Returns True if the given paths are in local scheme. + Note: The paths must be in same scheme, i.e. it's invalid and + will raise error if paths are mixed with different schemes. + """ + if isinstance(paths, str): + paths = [paths] + if isinstance(paths, pathlib.Path): + paths = [str(paths)] + elif not isinstance(paths, list) or any(not isinstance(p, str) for p in paths): + raise ValueError("paths must be a path string or a list of path strings.") + elif len(paths) == 0: + raise ValueError("Must provide at least one path.") + num = sum(urllib.parse.urlparse(path).scheme == _LOCAL_SCHEME for path in paths) + if num > 0 and num < len(paths): + raise ValueError( + "The paths must all be local-scheme or not local-scheme, " + f"but found mixed {paths}" + ) + return num == len(paths) + + +def _truncated_repr(obj: Any) -> str: + """Utility to return a truncated object representation for error messages.""" + msg = str(obj) + if len(msg) > 200: + msg = msg[:200] + "..." + return msg + + +def _insert_doc_at_pattern( + obj, + *, + message: str, + pattern: str, + insert_after: bool = True, + directive: Optional[str] = None, + skip_matches: int = 0, +) -> str: + if "\n" in message: + raise ValueError( + "message shouldn't contain any newlines, since this function will insert " + f"its own linebreaks when text wrapping: {message}" + ) + + doc = obj.__doc__.strip() + if not doc: + doc = "" + + if pattern == "" and insert_after: + # Empty pattern + insert_after means that we want to append the message to the + # end of the docstring. + head = doc + tail = "" + else: + tail = doc + i = tail.find(pattern) + skip_matches_left = skip_matches + while i != -1: + if insert_after: + # Set offset to the first character after the pattern. + offset = i + len(pattern) + else: + # Set offset to the first character in the matched line. + offset = tail[:i].rfind("\n") + 1 + head = tail[:offset] + tail = tail[offset:] + skip_matches_left -= 1 + if skip_matches_left <= 0: + break + elif not insert_after: + # Move past the found pattern, since we're skipping it. + tail = tail[i - offset + len(pattern) :] + i = tail.find(pattern) + else: + raise ValueError( + f"Pattern {pattern} not found after {skip_matches} skips in docstring " + f"{doc}" + ) + # Get indentation of the to-be-inserted text. + after_lines = list(filter(bool, tail.splitlines())) + if len(after_lines) > 0: + lines = after_lines + else: + lines = list(filter(bool, reversed(head.splitlines()))) + # Should always have at least one non-empty line in the docstring. + assert len(lines) > 0 + indent = " " * (len(lines[0]) - len(lines[0].lstrip())) + # Handle directive. + message = message.strip("\n") + if directive is not None: + base = f"{indent}.. {directive}::\n" + message = message.replace("\n", "\n" + indent + " " * 4) + message = base + indent + " " * 4 + message + else: + message = indent + message.replace("\n", "\n" + indent) + # Add two blank lines before/after message, if necessary. + if insert_after ^ (pattern == "\n\n"): + # Only two blank lines before message if: + # 1. Inserting message after pattern and pattern is not two blank lines. + # 2. Inserting message before pattern and pattern is two blank lines. + message = "\n\n" + message + if (not insert_after) ^ (pattern == "\n\n"): + # Only two blank lines after message if: + # 1. Inserting message before pattern and pattern is not two blank lines. + # 2. Inserting message after pattern and pattern is two blank lines. + message = message + "\n\n" + + # Insert message before/after pattern. + parts = [head, message, tail] + # Build new docstring. + obj.__doc__ = "".join(parts) + + +def _consumption_api( + if_more_than_read: bool = False, + datasource_metadata: Optional[str] = None, + extra_condition: Optional[str] = None, + delegate: Optional[str] = None, + pattern="Examples:", + insert_after=False, +): + """Annotate the function with an indication that it's a consumption API, and that it + will trigger Dataset execution. + """ + base = ( + " will trigger execution of the lazy transformations performed on " + "this dataset." + ) + if delegate: + message = delegate + base + elif not if_more_than_read: + message = "This operation" + base + else: + condition = "If this dataset consists of more than a read, " + if datasource_metadata is not None: + condition += ( + f"or if the {datasource_metadata} can't be determined from the " + "metadata provided by the datasource, " + ) + if extra_condition is not None: + condition += extra_condition + ", " + message = condition + "then this operation" + base + + def wrap(obj): + _insert_doc_at_pattern( + obj, + message=message, + pattern=pattern, + insert_after=insert_after, + directive="note", + ) + return obj + + return wrap + + +def ConsumptionAPI(*args, **kwargs): + """Annotate the function with an indication that it's a consumption API, and that it + will trigger Dataset execution. + """ + if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): + return _consumption_api()(args[0]) + return _consumption_api(*args, **kwargs) + + +def _all_to_all_api(*args, **kwargs): + """Annotate the function with an indication that it's a all to all API, and that it + is an operation that requires all inputs to be materialized in-memory to execute. + """ + + def wrap(obj): + _insert_doc_at_pattern( + obj, + message=( + "This operation requires all inputs to be " + "materialized in object store for it to execute." + ), + pattern="Examples:", + insert_after=False, + directive="note", + ) + return obj + + return wrap + + +def AllToAllAPI(*args, **kwargs): + """Annotate the function with an indication that it's a all to all API, and that it + is an operation that requires all inputs to be materialized in-memory to execute. + """ + # This should only be used as a decorator for dataset methods. + assert len(args) == 1 and len(kwargs) == 0 and callable(args[0]) + return _all_to_all_api()(args[0]) + + +def _split_list(arr: List[Any], num_splits: int) -> List[List[Any]]: + """Split the list into `num_splits` lists. + + The splits will be even if the `num_splits` divides the length of list, otherwise + the remainder (suppose it's R) will be allocated to the first R splits (one for + each). + This is the same as numpy.array_split(). The reason we make this a separate + implementation is to allow the heterogeneity in the elements in the list. + """ + assert num_splits > 0 + q, r = divmod(len(arr), num_splits) + splits = [ + arr[i * q + min(i, r) : (i + 1) * q + min(i + 1, r)] for i in range(num_splits) + ] + return splits + + +def get_compute_strategy( + fn: "UserDefinedFunction", + fn_constructor_args: Optional[Iterable[Any]] = None, + compute: Optional[Union[str, "ComputeStrategy"]] = None, + concurrency: Optional[Union[int, Tuple[int, int]]] = None, +) -> "ComputeStrategy": + """Get `ComputeStrategy` based on the function or class, and concurrency + information. + + Args: + fn: The function or generator to apply to a record batch, or a class type + that can be instantiated to create such a callable. + fn_constructor_args: Positional arguments to pass to ``fn``'s constructor. + compute: Either "tasks" (default) to use Ray Tasks or an + :class:`~ray.data.ActorPoolStrategy` to use an autoscaling actor pool. + concurrency: The number of Ray workers to use concurrently. + + Returns: + The `ComputeStrategy` for execution. + """ + # Lazily import these objects to avoid circular imports. + from ray.data._internal.compute import ActorPoolStrategy, TaskPoolStrategy + from ray.data.block import CallableClass + + if isinstance(fn, CallableClass): + is_callable_class = True + else: + # TODO(chengsu): disallow object that is not a function. For example, + # An object instance of class often indicates a bug in user code. + is_callable_class = False + if fn_constructor_args is not None: + raise ValueError( + "``fn_constructor_args`` can only be specified if providing a " + f"callable class instance for ``fn``, but got: {fn}." + ) + + if compute is not None: + # Legacy code path to support `compute` argument. + logger.warning( + "The argument ``compute`` is deprecated in Ray 2.9. Please specify " + "argument ``concurrency`` instead. For more information, see " + "https://docs.ray.io/en/master/data/transforming-data.html#" + "stateful-transforms." + ) + if is_callable_class and ( + compute == "tasks" or isinstance(compute, TaskPoolStrategy) + ): + raise ValueError( + "``compute`` must specify an actor compute strategy when using a " + f"callable class, but got: {compute}. For example, use " + "``compute=ray.data.ActorPoolStrategy(size=n)``." + ) + elif not is_callable_class and ( + compute == "actors" or isinstance(compute, ActorPoolStrategy) + ): + raise ValueError( + f"``compute`` is specified as the actor compute strategy: {compute}, " + f"but ``fn`` is not a callable class: {fn}. Pass a callable class or " + "use the default ``compute`` strategy." + ) + return compute + elif concurrency is not None: + if isinstance(concurrency, tuple): + if ( + len(concurrency) == 2 + and isinstance(concurrency[0], int) + and isinstance(concurrency[1], int) + ): + if is_callable_class: + return ActorPoolStrategy( + min_size=concurrency[0], max_size=concurrency[1] + ) + else: + raise ValueError( + "``concurrency`` is set as a tuple of integers, but ``fn`` " + f"is not a callable class: {fn}. Use ``concurrency=n`` to " + "control maximum number of workers to use." + ) + else: + raise ValueError( + "``concurrency`` is expected to be set as a tuple of " + f"integers, but got: {concurrency}." + ) + elif isinstance(concurrency, int): + if is_callable_class: + return ActorPoolStrategy(size=concurrency) + else: + return TaskPoolStrategy(size=concurrency) + else: + raise ValueError( + "``concurrency`` is expected to be set as an integer or a " + f"tuple of integers, but got: {concurrency}." + ) + else: + if is_callable_class: + raise ValueError( + "``concurrency`` must be specified when using a callable class. " + "For example, use ``concurrency=n`` for a pool of ``n`` workers." + ) + else: + return TaskPoolStrategy() + + +def capfirst(s: str): + """Capitalize the first letter of a string + + Args: + s: String to capitalize + + Returns: + Capitalized string + """ + return s[0].upper() + s[1:] + + +def capitalize(s: str): + """Capitalize a string, removing '_' and keeping camelcase. + + Args: + s: String to capitalize + + Returns: + Capitalized string with no underscores. + """ + return "".join(capfirst(x) for x in s.split("_")) + + +def pandas_df_to_arrow_block(df: "pandas.DataFrame") -> "Block": + from ray.data.block import BlockAccessor, BlockExecStats + + block = BlockAccessor.for_block(df).to_arrow() + stats = BlockExecStats.builder() + return ( + block, + BlockAccessor.for_block(block).get_metadata(exec_stats=stats.build()), + ) + + +def ndarray_to_block(ndarray: np.ndarray, ctx: DataContext) -> "Block": + from ray.data.block import BlockAccessor, BlockExecStats + + DataContext._set_current(ctx) + + stats = BlockExecStats.builder() + block = BlockAccessor.batch_to_block({"data": ndarray}) + metadata = BlockAccessor.for_block(block).get_metadata(exec_stats=stats.build()) + return block, metadata + + +def get_table_block_metadata( + table: Union["pyarrow.Table", "pandas.DataFrame"] +) -> "BlockMetadata": + from ray.data.block import BlockAccessor, BlockExecStats + + stats = BlockExecStats.builder() + return BlockAccessor.for_block(table).get_metadata(exec_stats=stats.build()) + + +def unify_block_metadata_schema( + metadata: List["BlockMetadata"], +) -> Optional[Union[type, "pyarrow.lib.Schema"]]: + """For the input list of BlockMetadata, return a unified schema of the + corresponding blocks. If the metadata have no valid schema, returns None. + """ + # Some blocks could be empty, in which case we cannot get their schema. + # TODO(ekl) validate schema is the same across different blocks. + from ray.data._internal.arrow_ops.transform_pyarrow import unify_schemas + + # First check if there are blocks with computed schemas, then unify + # valid schemas from all such blocks. + schemas_to_unify = [] + for m in metadata: + if m.schema is not None and (m.num_rows is None or m.num_rows > 0): + schemas_to_unify.append(m.schema) + if schemas_to_unify: + # Check valid pyarrow installation before attempting schema unification + try: + import pyarrow as pa + except ImportError: + pa = None + # If the result contains PyArrow schemas, unify them + if pa is not None and all(isinstance(s, pa.Schema) for s in schemas_to_unify): + return unify_schemas(schemas_to_unify) + # Otherwise, if the resulting schemas are simple types (e.g. int), + # return the first schema. + return schemas_to_unify[0] + return None + + +def find_partition_index( + table: Union["pyarrow.Table", "pandas.DataFrame"], + desired: List[Any], + sort_key: "SortKey", +) -> int: + columns = sort_key.get_columns() + descending = sort_key.get_descending() + + left, right = 0, len(table) + for i in range(len(desired)): + if left == right: + return right + col_name = columns[i] + col_vals = table[col_name].to_numpy()[left:right] + desired_val = desired[i] + + # Handle null values - replace them with sentinel values + if desired_val is None: + desired_val = NULL_SENTINEL + + # Replace None/NaN values in col_vals with sentinel + null_mask = col_vals == None # noqa: E711 + if null_mask.any(): + col_vals = col_vals.copy() # Make a copy to avoid modifying original + col_vals[null_mask] = NULL_SENTINEL + + prevleft = left + if descending is True: + left = prevleft + ( + len(col_vals) + - np.searchsorted( + col_vals, + desired_val, + side="right", + sorter=np.arange(len(col_vals) - 1, -1, -1), + ) + ) + right = prevleft + ( + len(col_vals) + - np.searchsorted( + col_vals, + desired_val, + side="left", + sorter=np.arange(len(col_vals) - 1, -1, -1), + ) + ) + else: + left = prevleft + np.searchsorted(col_vals, desired_val, side="left") + right = prevleft + np.searchsorted(col_vals, desired_val, side="right") + return right if descending is True else left + + +def find_partitions(table, boundaries, sort_key): + partitions = [] + + # For each boundary value, count the number of items that are less + # than it. Since the block is sorted, these counts partition the items + # such that boundaries[i] <= x < boundaries[i + 1] for each x in + # partition[i]. If `descending` is true, `boundaries` would also be + # in descending order and we only need to count the number of items + # *greater than* the boundary value instead. + bounds = [ + find_partition_index(table, boundary, sort_key) for boundary in boundaries + ] + + last_idx = 0 + for idx in bounds: + partitions.append(table[last_idx:idx]) + last_idx = idx + partitions.append(table[last_idx:]) + return partitions + + +def get_attribute_from_class_name(class_name: str) -> Any: + """Get Python attribute from the provided class name. + + The caller needs to make sure the provided class name includes + full module name, and can be imported successfully. + """ + from importlib import import_module + + paths = class_name.split(".") + if len(paths) < 2: + raise ValueError(f"Cannot create object from {class_name}.") + + module_name = ".".join(paths[:-1]) + attribute_name = paths[-1] + return getattr(import_module(module_name), attribute_name) + + +class Queue: + """A thread-safe queue implementation for multiple producers and consumers. + + Provide `release()` to exit producer threads cooperatively for resource release. + """ + + def __init__(self, queue_size: int): + # The queue shared across multiple producer threads. + self._queue = deque() + # The boolean varilable to indicate whether producer threads should exit. + self._threads_exit = False + # The semaphore for producer threads to put item into queue. + self._producer_semaphore = threading.Semaphore(queue_size) + # The semaphore for consumer threads to get item from queue. + self._consumer_semaphore = threading.Semaphore(0) + # The mutex lock to guard access of `self._queue` and `self._threads_exit`. + self._mutex = threading.Lock() + + def put(self, item: Any) -> bool: + """Put an item into the queue. + + Block if necessary until a free slot is available in queue. + This method is called by producer threads. + + Returns: + True if the caller thread should exit immediately. + """ + self._producer_semaphore.acquire() + with self._mutex: + if self._threads_exit: + return True + else: + self._queue.append(item) + self._consumer_semaphore.release() + return False + + def get(self) -> Any: + """Remove and return an item from the queue. + + Block if necessary until an item is available in queue. + This method is called by consumer threads. + """ + self._consumer_semaphore.acquire() + with self._mutex: + next_item = self._queue.popleft() + self._producer_semaphore.release() + return next_item + + def release(self, num_threads: int): + """Release `num_threads` of producers so they would exit cooperatively.""" + with self._mutex: + self._threads_exit = True + for _ in range(num_threads): + # NOTE: After Python 3.9+, Semaphore.release(n) can be used to + # release all threads at once. + self._producer_semaphore.release() + + def qsize(self): + """Return the size of the queue.""" + with self._mutex: + return len(self._queue) + + +T = TypeVar("T") +U = TypeVar("U") + + +def make_async_gen( + base_iterator: Iterator[T], + fn: Callable[[Iterator[T]], Iterator[U]], + num_workers: int = 1, +) -> Iterator[U]: + """Returns a new iterator with elements fetched from the base_iterator + in an async fashion using a threadpool. + + Each thread in the threadpool will fetch data from the base_iterator in a + thread-safe fashion, and apply the provided `fn` computation concurrently. + + Args: + base_iterator: The iterator to asynchronously fetch from. + fn: The function to run on the input iterator. + num_workers: The number of threads to use in the threadpool. Defaults to 1. + + Returns: + An iterator with the same elements as outputted from `fn`. + """ + + if num_workers < 1: + raise ValueError("Size of threadpool must be at least 1.") + + # Use a lock to fetch from the base_iterator in a thread-safe fashion. + def convert_to_threadsafe_iterator(base_iterator: Iterator[T]) -> Iterator[T]: + class ThreadSafeIterator: + def __init__(self, it): + self.lock = threading.Lock() + self.it = it + + def __next__(self): + with self.lock: + return next(self.it) + + def __iter__(self): + return self + + return ThreadSafeIterator(base_iterator) + + thread_safe_generator = convert_to_threadsafe_iterator(base_iterator) + + class Sentinel: + def __init__(self, thread_index: int): + self.thread_index = thread_index + + output_queue = Queue(1) + + # Because pulling from the base iterator cannot happen concurrently, + # we must execute the expensive computation in a separate step which + # can be parallelized via a threadpool. + def execute_computation(thread_index: int): + try: + for item in fn(thread_safe_generator): + if output_queue.put(item): + # Return early when it's instructed to do so. + return + output_queue.put(Sentinel(thread_index)) + except Exception as e: + output_queue.put(e) + + # Use separate threads to produce output batches. + threads = [ + threading.Thread(target=execute_computation, args=(i,), daemon=True) + for i in range(num_workers) + ] + + for thread in threads: + thread.start() + + # Use main thread to consume output batches. + num_threads_finished = 0 + try: + while True: + next_item = output_queue.get() + if isinstance(next_item, Exception): + raise next_item + if isinstance(next_item, Sentinel): + num_threads_finished += 1 + else: + yield next_item + if num_threads_finished >= num_workers: + break + finally: + # Cooperatively exit all producer threads. + # This is to avoid these daemon threads hanging there with holding batches in + # memory, which can cause GRAM OOM easily. This can happen when caller breaks + # in the middle of iteration. + num_threads_alive = num_workers - num_threads_finished + if num_threads_alive > 0: + output_queue.release(num_threads_alive) + + +def call_with_retry( + f: Callable[[], Any], + description: str, + *, + match: Optional[List[str]] = None, + max_attempts: int = 10, + max_backoff_s: int = 32, +) -> Any: + """Retry a function with exponential backoff. + + Args: + f: The function to retry. + match: A list of strings to match in the exception message. If ``None``, any + error is retried. + description: An imperitive description of the function being retried. For + example, "open the file". + max_attempts: The maximum number of attempts to retry. + max_backoff_s: The maximum number of seconds to backoff. + """ + assert max_attempts >= 1, f"`max_attempts` must be positive. Got {max_attempts}." + + for i in range(max_attempts): + try: + return f() + except Exception as e: + is_retryable = match is None or any( + [pattern in str(e) for pattern in match] + ) + if is_retryable and i + 1 < max_attempts: + # Retry with binary expoential backoff with random jitter. + backoff = min((2 ** (i + 1)), max_backoff_s) * random.random() + logger.debug( + f"Retrying {i+1} attempts to {description} after {backoff} seconds." + ) + time.sleep(backoff) + else: + raise e from None + + +def iterate_with_retry( + iterable_factory: Callable[[], Iterable], + description: str, + *, + match: Optional[List[str]] = None, + max_attempts: int = 10, + max_backoff_s: int = 32, +) -> Any: + """Iterate through an iterable with retries. + + If the iterable raises an exception, this function recreates and re-iterates + through the iterable, while skipping the items that have already been yielded. + + Args: + iterable_factory: A no-argument function that creates the iterable. + match: A list of strings to match in the exception message. If ``None``, any + error is retried. + description: An imperitive description of the function being retried. For + example, "open the file". + max_attempts: The maximum number of attempts to retry. + max_backoff_s: The maximum number of seconds to backoff. + """ + assert max_attempts >= 1, f"`max_attempts` must be positive. Got {max_attempts}." + + num_items_yielded = 0 + for i in range(max_attempts): + try: + iterable = iterable_factory() + for i, item in enumerate(iterable): + if i < num_items_yielded: + # Skip items that have already been yielded. + continue + + num_items_yielded += 1 + yield item + return + except Exception as e: + is_retryable = match is None or any( + [pattern in str(e) for pattern in match] + ) + if is_retryable and i + 1 < max_attempts: + # Retry with binary expoential backoff with random jitter. + backoff = min((2 ** (i + 1)), max_backoff_s) * random.random() + logger.debug( + f"Retrying {i+1} attempts to {description} after {backoff} seconds." + ) + time.sleep(backoff) + else: + raise e from None + + +def create_dataset_tag(dataset_name: Optional[str], *args): + tag = dataset_name or "dataset" + for arg in args: + tag += f"_{arg}" + return tag + + +def convert_bytes_to_human_readable_str(num_bytes: int) -> str: + if num_bytes >= 1e9: + num_bytes_str = f"{round(num_bytes / 1e9)}GB" + elif num_bytes >= 1e6: + num_bytes_str = f"{round(num_bytes / 1e6)}MB" + else: + num_bytes_str = f"{round(num_bytes / 1e3)}KB" + return num_bytes_str