diff --git a/.gitattributes b/.gitattributes index cbe55d00ed560f43fa3799feb6969e9969e8c0f0..469ffe2a0e5e6c442986ceb2b6b1e4dafddd0fd2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1484,3 +1484,4 @@ parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_distribut parrot/lib/python3.10/site-packages/scipy/constants/__pycache__/_codata.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text vllm/lib/python3.10/site-packages/ray/_private/__pycache__/worker.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text parrot/lib/python3.10/site-packages/scipy/stats/tests/__pycache__/test_morestats.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text +parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_multivariate.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/__init__.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..012c872bf850dfab12ed94253c5d5b16c0a93674 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/__init__.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28697c7d8e20ffacdc005d783e2a54113db92edb Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef714ce5ef2a997071eb9f701843ade078228a3e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_impl.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a100bcb6b58e86ca37cc4c061da1317d0aa03aa Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_fitpack_py.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_interpolate.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_interpolate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d6700ba93b3433e554a2c718097cd29fb6e1e85 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_interpolate.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd84074980d7bd6828137873193142ae3b457b67 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndbspline.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..243eb754c8e5442ac47ac86aee33e954c11b90d5 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_ndgriddata.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_pade.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_pade.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..916842af8f2c5bb380b7c7e8826f52dee70a5838 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_pade.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af90ab5f970806e9170fca7bc82d8c4da5ab7378 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_polyint.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8e3ab868a437f8b2e60b6df249bd49a2d86c339 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbf.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5111db434b666fc4cdba34ac5f1ac90adecc03c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/_rbfinterp.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87a255ef345065a0edf6df89d6060fd27968c573 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79ece0141f0b307d7a23822e9b2007eacc4903da Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/fitpack2.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a9e077feaa32bcde8c8e36df0d7bdc7f6c44b21 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/interpolate.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00ff78a7fc4cdeca9ab79c83822cd9b5cda0c558 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/ndgriddata.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/polyint.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/polyint.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec8b2b032d09737801622da6d60ef4da323c91bf Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/polyint.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/rbf.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/rbf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95f2c1a3adb98d9ca22a95a5912624406c0cd776 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/interpolate/__pycache__/rbf.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav b/parrot/lib/python3.10/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav new file mode 100644 index 0000000000000000000000000000000000000000..f8d332e94208f448b8377fed7a539181e13bb65c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccc9e1bd9beb3f893239629529f6c19decafd37c6fce0a976211cdc6c0310c9e +size 13 diff --git a/parrot/lib/python3.10/site-packages/scipy/spatial/_geometric_slerp.py b/parrot/lib/python3.10/site-packages/scipy/spatial/_geometric_slerp.py new file mode 100644 index 0000000000000000000000000000000000000000..c3a7a81a1209bff2b1758aa2d6a5248a3d4360fd --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/spatial/_geometric_slerp.py @@ -0,0 +1,240 @@ +from __future__ import annotations + +__all__ = ['geometric_slerp'] + +import warnings +from typing import TYPE_CHECKING + +import numpy as np +from scipy.spatial.distance import euclidean + +if TYPE_CHECKING: + import numpy.typing as npt + + +def _geometric_slerp(start, end, t): + # create an orthogonal basis using QR decomposition + basis = np.vstack([start, end]) + Q, R = np.linalg.qr(basis.T) + signs = 2 * (np.diag(R) >= 0) - 1 + Q = Q.T * signs.T[:, np.newaxis] + R = R.T * signs.T[:, np.newaxis] + + # calculate the angle between `start` and `end` + c = np.dot(start, end) + s = np.linalg.det(R) + omega = np.arctan2(s, c) + + # interpolate + start, end = Q + s = np.sin(t * omega) + c = np.cos(t * omega) + return start * c[:, np.newaxis] + end * s[:, np.newaxis] + + +def geometric_slerp( + start: npt.ArrayLike, + end: npt.ArrayLike, + t: npt.ArrayLike, + tol: float = 1e-7, +) -> np.ndarray: + """ + Geometric spherical linear interpolation. + + The interpolation occurs along a unit-radius + great circle arc in arbitrary dimensional space. + + Parameters + ---------- + start : (n_dimensions, ) array-like + Single n-dimensional input coordinate in a 1-D array-like + object. `n` must be greater than 1. + end : (n_dimensions, ) array-like + Single n-dimensional input coordinate in a 1-D array-like + object. `n` must be greater than 1. + t : float or (n_points,) 1D array-like + A float or 1D array-like of doubles representing interpolation + parameters, with values required in the inclusive interval + between 0 and 1. A common approach is to generate the array + with ``np.linspace(0, 1, n_pts)`` for linearly spaced points. + Ascending, descending, and scrambled orders are permitted. + tol : float + The absolute tolerance for determining if the start and end + coordinates are antipodes. + + Returns + ------- + result : (t.size, D) + An array of doubles containing the interpolated + spherical path and including start and + end when 0 and 1 t are used. The + interpolated values should correspond to the + same sort order provided in the t array. The result + may be 1-dimensional if ``t`` is a float. + + Raises + ------ + ValueError + If ``start`` and ``end`` are antipodes, not on the + unit n-sphere, or for a variety of degenerate conditions. + + See Also + -------- + scipy.spatial.transform.Slerp : 3-D Slerp that works with quaternions + + Notes + ----- + The implementation is based on the mathematical formula provided in [1]_, + and the first known presentation of this algorithm, derived from study of + 4-D geometry, is credited to Glenn Davis in a footnote of the original + quaternion Slerp publication by Ken Shoemake [2]_. + + .. versionadded:: 1.5.0 + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Slerp#Geometric_Slerp + .. [2] Ken Shoemake (1985) Animating rotation with quaternion curves. + ACM SIGGRAPH Computer Graphics, 19(3): 245-254. + + Examples + -------- + Interpolate four linearly-spaced values on the circumference of + a circle spanning 90 degrees: + + >>> import numpy as np + >>> from scipy.spatial import geometric_slerp + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111) + >>> start = np.array([1, 0]) + >>> end = np.array([0, 1]) + >>> t_vals = np.linspace(0, 1, 4) + >>> result = geometric_slerp(start, + ... end, + ... t_vals) + + The interpolated results should be at 30 degree intervals + recognizable on the unit circle: + + >>> ax.scatter(result[...,0], result[...,1], c='k') + >>> circle = plt.Circle((0, 0), 1, color='grey') + >>> ax.add_artist(circle) + >>> ax.set_aspect('equal') + >>> plt.show() + + Attempting to interpolate between antipodes on a circle is + ambiguous because there are two possible paths, and on a + sphere there are infinite possible paths on the geodesic surface. + Nonetheless, one of the ambiguous paths is returned along + with a warning: + + >>> opposite_pole = np.array([-1, 0]) + >>> with np.testing.suppress_warnings() as sup: + ... sup.filter(UserWarning) + ... geometric_slerp(start, + ... opposite_pole, + ... t_vals) + array([[ 1.00000000e+00, 0.00000000e+00], + [ 5.00000000e-01, 8.66025404e-01], + [-5.00000000e-01, 8.66025404e-01], + [-1.00000000e+00, 1.22464680e-16]]) + + Extend the original example to a sphere and plot interpolation + points in 3D: + + >>> from mpl_toolkits.mplot3d import proj3d + >>> fig = plt.figure() + >>> ax = fig.add_subplot(111, projection='3d') + + Plot the unit sphere for reference (optional): + + >>> u = np.linspace(0, 2 * np.pi, 100) + >>> v = np.linspace(0, np.pi, 100) + >>> x = np.outer(np.cos(u), np.sin(v)) + >>> y = np.outer(np.sin(u), np.sin(v)) + >>> z = np.outer(np.ones(np.size(u)), np.cos(v)) + >>> ax.plot_surface(x, y, z, color='y', alpha=0.1) + + Interpolating over a larger number of points + may provide the appearance of a smooth curve on + the surface of the sphere, which is also useful + for discretized integration calculations on a + sphere surface: + + >>> start = np.array([1, 0, 0]) + >>> end = np.array([0, 0, 1]) + >>> t_vals = np.linspace(0, 1, 200) + >>> result = geometric_slerp(start, + ... end, + ... t_vals) + >>> ax.plot(result[...,0], + ... result[...,1], + ... result[...,2], + ... c='k') + >>> plt.show() + """ + + start = np.asarray(start, dtype=np.float64) + end = np.asarray(end, dtype=np.float64) + t = np.asarray(t) + + if t.ndim > 1: + raise ValueError("The interpolation parameter " + "value must be one dimensional.") + + if start.ndim != 1 or end.ndim != 1: + raise ValueError("Start and end coordinates " + "must be one-dimensional") + + if start.size != end.size: + raise ValueError("The dimensions of start and " + "end must match (have same size)") + + if start.size < 2 or end.size < 2: + raise ValueError("The start and end coordinates must " + "both be in at least two-dimensional " + "space") + + if np.array_equal(start, end): + return np.linspace(start, start, t.size) + + # for points that violate equation for n-sphere + for coord in [start, end]: + if not np.allclose(np.linalg.norm(coord), 1.0, + rtol=1e-9, + atol=0): + raise ValueError("start and end are not" + " on a unit n-sphere") + + if not isinstance(tol, float): + raise ValueError("tol must be a float") + else: + tol = np.fabs(tol) + + coord_dist = euclidean(start, end) + + # diameter of 2 within tolerance means antipodes, which is a problem + # for all unit n-spheres (even the 0-sphere would have an ambiguous path) + if np.allclose(coord_dist, 2.0, rtol=0, atol=tol): + warnings.warn("start and end are antipodes " + "using the specified tolerance; " + "this may cause ambiguous slerp paths", + stacklevel=2) + + t = np.asarray(t, dtype=np.float64) + + if t.size == 0: + return np.empty((0, start.size)) + + if t.min() < 0 or t.max() > 1: + raise ValueError("interpolation parameter must be in [0, 1]") + + if t.ndim == 0: + return _geometric_slerp(start, + end, + np.atleast_1d(t)).ravel() + else: + return _geometric_slerp(start, + end, + t) diff --git a/parrot/lib/python3.10/site-packages/scipy/spatial/_kdtree.py b/parrot/lib/python3.10/site-packages/scipy/spatial/_kdtree.py new file mode 100644 index 0000000000000000000000000000000000000000..f65412e9e4ad3a0e0da3876c861430d678fe858c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/spatial/_kdtree.py @@ -0,0 +1,920 @@ +# Copyright Anne M. Archibald 2008 +# Released under the scipy license +import numpy as np +from ._ckdtree import cKDTree, cKDTreeNode + +__all__ = ['minkowski_distance_p', 'minkowski_distance', + 'distance_matrix', + 'Rectangle', 'KDTree'] + + +def minkowski_distance_p(x, y, p=2): + """Compute the pth power of the L**p distance between two arrays. + + For efficiency, this function computes the L**p distance but does + not extract the pth root. If `p` is 1 or infinity, this is equal to + the actual L**p distance. + + The last dimensions of `x` and `y` must be the same length. Any + other dimensions must be compatible for broadcasting. + + Parameters + ---------- + x : (..., K) array_like + Input array. + y : (..., K) array_like + Input array. + p : float, 1 <= p <= infinity + Which Minkowski p-norm to use. + + Returns + ------- + dist : ndarray + pth power of the distance between the input arrays. + + Examples + -------- + >>> from scipy.spatial import minkowski_distance_p + >>> minkowski_distance_p([[0, 0], [0, 0]], [[1, 1], [0, 1]]) + array([2, 1]) + + """ + x = np.asarray(x) + y = np.asarray(y) + + # Find smallest common datatype with float64 (return type of this + # function) - addresses #10262. + # Don't just cast to float64 for complex input case. + common_datatype = np.promote_types(np.promote_types(x.dtype, y.dtype), + 'float64') + + # Make sure x and y are NumPy arrays of correct datatype. + x = x.astype(common_datatype) + y = y.astype(common_datatype) + + if p == np.inf: + return np.amax(np.abs(y-x), axis=-1) + elif p == 1: + return np.sum(np.abs(y-x), axis=-1) + else: + return np.sum(np.abs(y-x)**p, axis=-1) + + +def minkowski_distance(x, y, p=2): + """Compute the L**p distance between two arrays. + + The last dimensions of `x` and `y` must be the same length. Any + other dimensions must be compatible for broadcasting. + + Parameters + ---------- + x : (..., K) array_like + Input array. + y : (..., K) array_like + Input array. + p : float, 1 <= p <= infinity + Which Minkowski p-norm to use. + + Returns + ------- + dist : ndarray + Distance between the input arrays. + + Examples + -------- + >>> from scipy.spatial import minkowski_distance + >>> minkowski_distance([[0, 0], [0, 0]], [[1, 1], [0, 1]]) + array([ 1.41421356, 1. ]) + + """ + x = np.asarray(x) + y = np.asarray(y) + if p == np.inf or p == 1: + return minkowski_distance_p(x, y, p) + else: + return minkowski_distance_p(x, y, p)**(1./p) + + +class Rectangle: + """Hyperrectangle class. + + Represents a Cartesian product of intervals. + """ + def __init__(self, maxes, mins): + """Construct a hyperrectangle.""" + self.maxes = np.maximum(maxes,mins).astype(float) + self.mins = np.minimum(maxes,mins).astype(float) + self.m, = self.maxes.shape + + def __repr__(self): + return "" % list(zip(self.mins, self.maxes)) + + def volume(self): + """Total volume.""" + return np.prod(self.maxes-self.mins) + + def split(self, d, split): + """Produce two hyperrectangles by splitting. + + In general, if you need to compute maximum and minimum + distances to the children, it can be done more efficiently + by updating the maximum and minimum distances to the parent. + + Parameters + ---------- + d : int + Axis to split hyperrectangle along. + split : float + Position along axis `d` to split at. + + """ + mid = np.copy(self.maxes) + mid[d] = split + less = Rectangle(self.mins, mid) + mid = np.copy(self.mins) + mid[d] = split + greater = Rectangle(mid, self.maxes) + return less, greater + + def min_distance_point(self, x, p=2.): + """ + Return the minimum distance between input and points in the + hyperrectangle. + + Parameters + ---------- + x : array_like + Input. + p : float, optional + Input. + + """ + return minkowski_distance( + 0, np.maximum(0, np.maximum(self.mins-x, x-self.maxes)), + p + ) + + def max_distance_point(self, x, p=2.): + """ + Return the maximum distance between input and points in the hyperrectangle. + + Parameters + ---------- + x : array_like + Input array. + p : float, optional + Input. + + """ + return minkowski_distance(0, np.maximum(self.maxes-x, x-self.mins), p) + + def min_distance_rectangle(self, other, p=2.): + """ + Compute the minimum distance between points in the two hyperrectangles. + + Parameters + ---------- + other : hyperrectangle + Input. + p : float + Input. + + """ + return minkowski_distance( + 0, + np.maximum(0, np.maximum(self.mins-other.maxes, + other.mins-self.maxes)), + p + ) + + def max_distance_rectangle(self, other, p=2.): + """ + Compute the maximum distance between points in the two hyperrectangles. + + Parameters + ---------- + other : hyperrectangle + Input. + p : float, optional + Input. + + """ + return minkowski_distance( + 0, np.maximum(self.maxes-other.mins, other.maxes-self.mins), p) + + +class KDTree(cKDTree): + """kd-tree for quick nearest-neighbor lookup. + + This class provides an index into a set of k-dimensional points + which can be used to rapidly look up the nearest neighbors of any + point. + + Parameters + ---------- + data : array_like, shape (n,m) + The n data points of dimension m to be indexed. This array is + not copied unless this is necessary to produce a contiguous + array of doubles, and so modifying this data will result in + bogus results. The data are also copied if the kd-tree is built + with copy_data=True. + leafsize : positive int, optional + The number of points at which the algorithm switches over to + brute-force. Default: 10. + compact_nodes : bool, optional + If True, the kd-tree is built to shrink the hyperrectangles to + the actual data range. This usually gives a more compact tree that + is robust against degenerated input data and gives faster queries + at the expense of longer build time. Default: True. + copy_data : bool, optional + If True the data is always copied to protect the kd-tree against + data corruption. Default: False. + balanced_tree : bool, optional + If True, the median is used to split the hyperrectangles instead of + the midpoint. This usually gives a more compact tree and + faster queries at the expense of longer build time. Default: True. + boxsize : array_like or scalar, optional + Apply a m-d toroidal topology to the KDTree.. The topology is generated + by :math:`x_i + n_i L_i` where :math:`n_i` are integers and :math:`L_i` + is the boxsize along i-th dimension. The input data shall be wrapped + into :math:`[0, L_i)`. A ValueError is raised if any of the data is + outside of this bound. + + Notes + ----- + The algorithm used is described in Maneewongvatana and Mount 1999. + The general idea is that the kd-tree is a binary tree, each of whose + nodes represents an axis-aligned hyperrectangle. Each node specifies + an axis and splits the set of points based on whether their coordinate + along that axis is greater than or less than a particular value. + + During construction, the axis and splitting point are chosen by the + "sliding midpoint" rule, which ensures that the cells do not all + become long and thin. + + The tree can be queried for the r closest neighbors of any given point + (optionally returning only those within some maximum distance of the + point). It can also be queried, with a substantial gain in efficiency, + for the r approximate closest neighbors. + + For large dimensions (20 is already large) do not expect this to run + significantly faster than brute force. High-dimensional nearest-neighbor + queries are a substantial open problem in computer science. + + Attributes + ---------- + data : ndarray, shape (n,m) + The n data points of dimension m to be indexed. This array is + not copied unless this is necessary to produce a contiguous + array of doubles. The data are also copied if the kd-tree is built + with `copy_data=True`. + leafsize : positive int + The number of points at which the algorithm switches over to + brute-force. + m : int + The dimension of a single data-point. + n : int + The number of data points. + maxes : ndarray, shape (m,) + The maximum value in each dimension of the n data points. + mins : ndarray, shape (m,) + The minimum value in each dimension of the n data points. + size : int + The number of nodes in the tree. + + """ + + class node: + @staticmethod + def _create(ckdtree_node=None): + """Create either an inner or leaf node, wrapping a cKDTreeNode instance""" + if ckdtree_node is None: + return KDTree.node(ckdtree_node) + elif ckdtree_node.split_dim == -1: + return KDTree.leafnode(ckdtree_node) + else: + return KDTree.innernode(ckdtree_node) + + def __init__(self, ckdtree_node=None): + if ckdtree_node is None: + ckdtree_node = cKDTreeNode() + self._node = ckdtree_node + + def __lt__(self, other): + return id(self) < id(other) + + def __gt__(self, other): + return id(self) > id(other) + + def __le__(self, other): + return id(self) <= id(other) + + def __ge__(self, other): + return id(self) >= id(other) + + def __eq__(self, other): + return id(self) == id(other) + + class leafnode(node): + @property + def idx(self): + return self._node.indices + + @property + def children(self): + return self._node.children + + class innernode(node): + def __init__(self, ckdtreenode): + assert isinstance(ckdtreenode, cKDTreeNode) + super().__init__(ckdtreenode) + self.less = KDTree.node._create(ckdtreenode.lesser) + self.greater = KDTree.node._create(ckdtreenode.greater) + + @property + def split_dim(self): + return self._node.split_dim + + @property + def split(self): + return self._node.split + + @property + def children(self): + return self._node.children + + @property + def tree(self): + if not hasattr(self, "_tree"): + self._tree = KDTree.node._create(super().tree) + + return self._tree + + def __init__(self, data, leafsize=10, compact_nodes=True, copy_data=False, + balanced_tree=True, boxsize=None): + data = np.asarray(data) + if data.dtype.kind == 'c': + raise TypeError("KDTree does not work with complex data") + + # Note KDTree has different default leafsize from cKDTree + super().__init__(data, leafsize, compact_nodes, copy_data, + balanced_tree, boxsize) + + def query( + self, x, k=1, eps=0, p=2, distance_upper_bound=np.inf, workers=1): + r"""Query the kd-tree for nearest neighbors. + + Parameters + ---------- + x : array_like, last dimension self.m + An array of points to query. + k : int or Sequence[int], optional + Either the number of nearest neighbors to return, or a list of the + k-th nearest neighbors to return, starting from 1. + eps : nonnegative float, optional + Return approximate nearest neighbors; the kth returned value + is guaranteed to be no further than (1+eps) times the + distance to the real kth nearest neighbor. + p : float, 1<=p<=infinity, optional + Which Minkowski p-norm to use. + 1 is the sum-of-absolute-values distance ("Manhattan" distance). + 2 is the usual Euclidean distance. + infinity is the maximum-coordinate-difference distance. + A large, finite p may cause a ValueError if overflow can occur. + distance_upper_bound : nonnegative float, optional + Return only neighbors within this distance. This is used to prune + tree searches, so if you are doing a series of nearest-neighbor + queries, it may help to supply the distance to the nearest neighbor + of the most recent point. + workers : int, optional + Number of workers to use for parallel processing. If -1 is given + all CPU threads are used. Default: 1. + + .. versionadded:: 1.6.0 + + Returns + ------- + d : float or array of floats + The distances to the nearest neighbors. + If ``x`` has shape ``tuple+(self.m,)``, then ``d`` has shape + ``tuple+(k,)``. + When k == 1, the last dimension of the output is squeezed. + Missing neighbors are indicated with infinite distances. + Hits are sorted by distance (nearest first). + + .. versionchanged:: 1.9.0 + Previously if ``k=None``, then `d` was an object array of + shape ``tuple``, containing lists of distances. This behavior + has been removed, use `query_ball_point` instead. + + i : integer or array of integers + The index of each neighbor in ``self.data``. + ``i`` is the same shape as d. + Missing neighbors are indicated with ``self.n``. + + Examples + -------- + + >>> import numpy as np + >>> from scipy.spatial import KDTree + >>> x, y = np.mgrid[0:5, 2:8] + >>> tree = KDTree(np.c_[x.ravel(), y.ravel()]) + + To query the nearest neighbours and return squeezed result, use + + >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=1) + >>> print(dd, ii, sep='\n') + [2. 0.2236068] + [ 0 13] + + To query the nearest neighbours and return unsqueezed result, use + + >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[1]) + >>> print(dd, ii, sep='\n') + [[2. ] + [0.2236068]] + [[ 0] + [13]] + + To query the second nearest neighbours and return unsqueezed result, + use + + >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[2]) + >>> print(dd, ii, sep='\n') + [[2.23606798] + [0.80622577]] + [[ 6] + [19]] + + To query the first and second nearest neighbours, use + + >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=2) + >>> print(dd, ii, sep='\n') + [[2. 2.23606798] + [0.2236068 0.80622577]] + [[ 0 6] + [13 19]] + + or, be more specific + + >>> dd, ii = tree.query([[0, 0], [2.2, 2.9]], k=[1, 2]) + >>> print(dd, ii, sep='\n') + [[2. 2.23606798] + [0.2236068 0.80622577]] + [[ 0 6] + [13 19]] + + """ + x = np.asarray(x) + if x.dtype.kind == 'c': + raise TypeError("KDTree does not work with complex data") + + if k is None: + raise ValueError("k must be an integer or a sequence of integers") + + d, i = super().query(x, k, eps, p, distance_upper_bound, workers) + if isinstance(i, int): + i = np.intp(i) + return d, i + + def query_ball_point(self, x, r, p=2., eps=0, workers=1, + return_sorted=None, return_length=False): + """Find all points within distance r of point(s) x. + + Parameters + ---------- + x : array_like, shape tuple + (self.m,) + The point or points to search for neighbors of. + r : array_like, float + The radius of points to return, must broadcast to the length of x. + p : float, optional + Which Minkowski p-norm to use. Should be in the range [1, inf]. + A finite large p may cause a ValueError if overflow can occur. + eps : nonnegative float, optional + Approximate search. Branches of the tree are not explored if their + nearest points are further than ``r / (1 + eps)``, and branches are + added in bulk if their furthest points are nearer than + ``r * (1 + eps)``. + workers : int, optional + Number of jobs to schedule for parallel processing. If -1 is given + all processors are used. Default: 1. + + .. versionadded:: 1.6.0 + return_sorted : bool, optional + Sorts returned indices if True and does not sort them if False. If + None, does not sort single point queries, but does sort + multi-point queries which was the behavior before this option + was added. + + .. versionadded:: 1.6.0 + return_length : bool, optional + Return the number of points inside the radius instead of a list + of the indices. + + .. versionadded:: 1.6.0 + + Returns + ------- + results : list or array of lists + If `x` is a single point, returns a list of the indices of the + neighbors of `x`. If `x` is an array of points, returns an object + array of shape tuple containing lists of neighbors. + + Notes + ----- + If you have many points whose neighbors you want to find, you may save + substantial amounts of time by putting them in a KDTree and using + query_ball_tree. + + Examples + -------- + >>> import numpy as np + >>> from scipy import spatial + >>> x, y = np.mgrid[0:5, 0:5] + >>> points = np.c_[x.ravel(), y.ravel()] + >>> tree = spatial.KDTree(points) + >>> sorted(tree.query_ball_point([2, 0], 1)) + [5, 10, 11, 15] + + Query multiple points and plot the results: + + >>> import matplotlib.pyplot as plt + >>> points = np.asarray(points) + >>> plt.plot(points[:,0], points[:,1], '.') + >>> for results in tree.query_ball_point(([2, 0], [3, 3]), 1): + ... nearby_points = points[results] + ... plt.plot(nearby_points[:,0], nearby_points[:,1], 'o') + >>> plt.margins(0.1, 0.1) + >>> plt.show() + + """ + x = np.asarray(x) + if x.dtype.kind == 'c': + raise TypeError("KDTree does not work with complex data") + return super().query_ball_point( + x, r, p, eps, workers, return_sorted, return_length) + + def query_ball_tree(self, other, r, p=2., eps=0): + """ + Find all pairs of points between `self` and `other` whose distance is + at most r. + + Parameters + ---------- + other : KDTree instance + The tree containing points to search against. + r : float + The maximum distance, has to be positive. + p : float, optional + Which Minkowski norm to use. `p` has to meet the condition + ``1 <= p <= infinity``. + eps : float, optional + Approximate search. Branches of the tree are not explored + if their nearest points are further than ``r/(1+eps)``, and + branches are added in bulk if their furthest points are nearer + than ``r * (1+eps)``. `eps` has to be non-negative. + + Returns + ------- + results : list of lists + For each element ``self.data[i]`` of this tree, ``results[i]`` is a + list of the indices of its neighbors in ``other.data``. + + Examples + -------- + You can search all pairs of points between two kd-trees within a distance: + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.spatial import KDTree + >>> rng = np.random.default_rng() + >>> points1 = rng.random((15, 2)) + >>> points2 = rng.random((15, 2)) + >>> plt.figure(figsize=(6, 6)) + >>> plt.plot(points1[:, 0], points1[:, 1], "xk", markersize=14) + >>> plt.plot(points2[:, 0], points2[:, 1], "og", markersize=14) + >>> kd_tree1 = KDTree(points1) + >>> kd_tree2 = KDTree(points2) + >>> indexes = kd_tree1.query_ball_tree(kd_tree2, r=0.2) + >>> for i in range(len(indexes)): + ... for j in indexes[i]: + ... plt.plot([points1[i, 0], points2[j, 0]], + ... [points1[i, 1], points2[j, 1]], "-r") + >>> plt.show() + + """ + return super().query_ball_tree(other, r, p, eps) + + def query_pairs(self, r, p=2., eps=0, output_type='set'): + """Find all pairs of points in `self` whose distance is at most r. + + Parameters + ---------- + r : positive float + The maximum distance. + p : float, optional + Which Minkowski norm to use. `p` has to meet the condition + ``1 <= p <= infinity``. + eps : float, optional + Approximate search. Branches of the tree are not explored + if their nearest points are further than ``r/(1+eps)``, and + branches are added in bulk if their furthest points are nearer + than ``r * (1+eps)``. `eps` has to be non-negative. + output_type : string, optional + Choose the output container, 'set' or 'ndarray'. Default: 'set' + + .. versionadded:: 1.6.0 + + Returns + ------- + results : set or ndarray + Set of pairs ``(i,j)``, with ``i < j``, for which the corresponding + positions are close. If output_type is 'ndarray', an ndarry is + returned instead of a set. + + Examples + -------- + You can search all pairs of points in a kd-tree within a distance: + + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from scipy.spatial import KDTree + >>> rng = np.random.default_rng() + >>> points = rng.random((20, 2)) + >>> plt.figure(figsize=(6, 6)) + >>> plt.plot(points[:, 0], points[:, 1], "xk", markersize=14) + >>> kd_tree = KDTree(points) + >>> pairs = kd_tree.query_pairs(r=0.2) + >>> for (i, j) in pairs: + ... plt.plot([points[i, 0], points[j, 0]], + ... [points[i, 1], points[j, 1]], "-r") + >>> plt.show() + + """ + return super().query_pairs(r, p, eps, output_type) + + def count_neighbors(self, other, r, p=2., weights=None, cumulative=True): + """Count how many nearby pairs can be formed. + + Count the number of pairs ``(x1,x2)`` can be formed, with ``x1`` drawn + from ``self`` and ``x2`` drawn from ``other``, and where + ``distance(x1, x2, p) <= r``. + + Data points on ``self`` and ``other`` are optionally weighted by the + ``weights`` argument. (See below) + + This is adapted from the "two-point correlation" algorithm described by + Gray and Moore [1]_. See notes for further discussion. + + Parameters + ---------- + other : KDTree + The other tree to draw points from, can be the same tree as self. + r : float or one-dimensional array of floats + The radius to produce a count for. Multiple radii are searched with + a single tree traversal. + If the count is non-cumulative(``cumulative=False``), ``r`` defines + the edges of the bins, and must be non-decreasing. + p : float, optional + 1<=p<=infinity. + Which Minkowski p-norm to use. + Default 2.0. + A finite large p may cause a ValueError if overflow can occur. + weights : tuple, array_like, or None, optional + If None, the pair-counting is unweighted. + If given as a tuple, weights[0] is the weights of points in + ``self``, and weights[1] is the weights of points in ``other``; + either can be None to indicate the points are unweighted. + If given as an array_like, weights is the weights of points in + ``self`` and ``other``. For this to make sense, ``self`` and + ``other`` must be the same tree. If ``self`` and ``other`` are two + different trees, a ``ValueError`` is raised. + Default: None + + .. versionadded:: 1.6.0 + cumulative : bool, optional + Whether the returned counts are cumulative. When cumulative is set + to ``False`` the algorithm is optimized to work with a large number + of bins (>10) specified by ``r``. When ``cumulative`` is set to + True, the algorithm is optimized to work with a small number of + ``r``. Default: True + + .. versionadded:: 1.6.0 + + Returns + ------- + result : scalar or 1-D array + The number of pairs. For unweighted counts, the result is integer. + For weighted counts, the result is float. + If cumulative is False, ``result[i]`` contains the counts with + ``(-inf if i == 0 else r[i-1]) < R <= r[i]`` + + Notes + ----- + Pair-counting is the basic operation used to calculate the two point + correlation functions from a data set composed of position of objects. + + Two point correlation function measures the clustering of objects and + is widely used in cosmology to quantify the large scale structure + in our Universe, but it may be useful for data analysis in other fields + where self-similar assembly of objects also occur. + + The Landy-Szalay estimator for the two point correlation function of + ``D`` measures the clustering signal in ``D``. [2]_ + + For example, given the position of two sets of objects, + + - objects ``D`` (data) contains the clustering signal, and + + - objects ``R`` (random) that contains no signal, + + .. math:: + + \\xi(r) = \\frac{ - 2 f + f^2}{f^2}, + + where the brackets represents counting pairs between two data sets + in a finite bin around ``r`` (distance), corresponding to setting + `cumulative=False`, and ``f = float(len(D)) / float(len(R))`` is the + ratio between number of objects from data and random. + + The algorithm implemented here is loosely based on the dual-tree + algorithm described in [1]_. We switch between two different + pair-cumulation scheme depending on the setting of ``cumulative``. + The computing time of the method we use when for + ``cumulative == False`` does not scale with the total number of bins. + The algorithm for ``cumulative == True`` scales linearly with the + number of bins, though it is slightly faster when only + 1 or 2 bins are used. [5]_. + + As an extension to the naive pair-counting, + weighted pair-counting counts the product of weights instead + of number of pairs. + Weighted pair-counting is used to estimate marked correlation functions + ([3]_, section 2.2), + or to properly calculate the average of data per distance bin + (e.g. [4]_, section 2.1 on redshift). + + .. [1] Gray and Moore, + "N-body problems in statistical learning", + Mining the sky, 2000, + https://arxiv.org/abs/astro-ph/0012333 + + .. [2] Landy and Szalay, + "Bias and variance of angular correlation functions", + The Astrophysical Journal, 1993, + http://adsabs.harvard.edu/abs/1993ApJ...412...64L + + .. [3] Sheth, Connolly and Skibba, + "Marked correlations in galaxy formation models", + Arxiv e-print, 2005, + https://arxiv.org/abs/astro-ph/0511773 + + .. [4] Hawkins, et al., + "The 2dF Galaxy Redshift Survey: correlation functions, + peculiar velocities and the matter density of the Universe", + Monthly Notices of the Royal Astronomical Society, 2002, + http://adsabs.harvard.edu/abs/2003MNRAS.346...78H + + .. [5] https://github.com/scipy/scipy/pull/5647#issuecomment-168474926 + + Examples + -------- + You can count neighbors number between two kd-trees within a distance: + + >>> import numpy as np + >>> from scipy.spatial import KDTree + >>> rng = np.random.default_rng() + >>> points1 = rng.random((5, 2)) + >>> points2 = rng.random((5, 2)) + >>> kd_tree1 = KDTree(points1) + >>> kd_tree2 = KDTree(points2) + >>> kd_tree1.count_neighbors(kd_tree2, 0.2) + 1 + + This number is same as the total pair number calculated by + `query_ball_tree`: + + >>> indexes = kd_tree1.query_ball_tree(kd_tree2, r=0.2) + >>> sum([len(i) for i in indexes]) + 1 + + """ + return super().count_neighbors(other, r, p, weights, cumulative) + + def sparse_distance_matrix( + self, other, max_distance, p=2., output_type='dok_matrix'): + """Compute a sparse distance matrix. + + Computes a distance matrix between two KDTrees, leaving as zero + any distance greater than max_distance. + + Parameters + ---------- + other : KDTree + + max_distance : positive float + + p : float, 1<=p<=infinity + Which Minkowski p-norm to use. + A finite large p may cause a ValueError if overflow can occur. + + output_type : string, optional + Which container to use for output data. Options: 'dok_matrix', + 'coo_matrix', 'dict', or 'ndarray'. Default: 'dok_matrix'. + + .. versionadded:: 1.6.0 + + Returns + ------- + result : dok_matrix, coo_matrix, dict or ndarray + Sparse matrix representing the results in "dictionary of keys" + format. If a dict is returned the keys are (i,j) tuples of indices. + If output_type is 'ndarray' a record array with fields 'i', 'j', + and 'v' is returned, + + Examples + -------- + You can compute a sparse distance matrix between two kd-trees: + + >>> import numpy as np + >>> from scipy.spatial import KDTree + >>> rng = np.random.default_rng() + >>> points1 = rng.random((5, 2)) + >>> points2 = rng.random((5, 2)) + >>> kd_tree1 = KDTree(points1) + >>> kd_tree2 = KDTree(points2) + >>> sdm = kd_tree1.sparse_distance_matrix(kd_tree2, 0.3) + >>> sdm.toarray() + array([[0. , 0. , 0.12295571, 0. , 0. ], + [0. , 0. , 0. , 0. , 0. ], + [0.28942611, 0. , 0. , 0.2333084 , 0. ], + [0. , 0. , 0. , 0. , 0. ], + [0.24617575, 0.29571802, 0.26836782, 0. , 0. ]]) + + You can check distances above the `max_distance` are zeros: + + >>> from scipy.spatial import distance_matrix + >>> distance_matrix(points1, points2) + array([[0.56906522, 0.39923701, 0.12295571, 0.8658745 , 0.79428925], + [0.37327919, 0.7225693 , 0.87665969, 0.32580855, 0.75679479], + [0.28942611, 0.30088013, 0.6395831 , 0.2333084 , 0.33630734], + [0.31994999, 0.72658602, 0.71124834, 0.55396483, 0.90785663], + [0.24617575, 0.29571802, 0.26836782, 0.57714465, 0.6473269 ]]) + + """ + return super().sparse_distance_matrix( + other, max_distance, p, output_type) + + +def distance_matrix(x, y, p=2, threshold=1000000): + """Compute the distance matrix. + + Returns the matrix of all pair-wise distances. + + Parameters + ---------- + x : (M, K) array_like + Matrix of M vectors in K dimensions. + y : (N, K) array_like + Matrix of N vectors in K dimensions. + p : float, 1 <= p <= infinity + Which Minkowski p-norm to use. + threshold : positive int + If ``M * N * K`` > `threshold`, algorithm uses a Python loop instead + of large temporary arrays. + + Returns + ------- + result : (M, N) ndarray + Matrix containing the distance from every vector in `x` to every vector + in `y`. + + Examples + -------- + >>> from scipy.spatial import distance_matrix + >>> distance_matrix([[0,0],[0,1]], [[1,0],[1,1]]) + array([[ 1. , 1.41421356], + [ 1.41421356, 1. ]]) + + """ + + x = np.asarray(x) + m, k = x.shape + y = np.asarray(y) + n, kk = y.shape + + if k != kk: + raise ValueError(f"x contains {k}-dimensional vectors but y contains " + f"{kk}-dimensional vectors") + + if m*n*k <= threshold: + return minkowski_distance(x[:,np.newaxis,:],y[np.newaxis,:,:],p) + else: + result = np.empty((m,n),dtype=float) # FIXME: figure out the best dtype + if m < n: + for i in range(m): + result[i,:] = minkowski_distance(x[i],y,p) + else: + for j in range(n): + result[:,j] = minkowski_distance(x,y[j],p) + return result diff --git a/parrot/lib/python3.10/site-packages/scipy/spatial/_procrustes.py b/parrot/lib/python3.10/site-packages/scipy/spatial/_procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..ec460056ca06ebdff007423f91577cbd8f22e24c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/spatial/_procrustes.py @@ -0,0 +1,132 @@ +""" +This module provides functions to perform full Procrustes analysis. + +This code was originally written by Justin Kucynski and ported over from +scikit-bio by Yoshiki Vazquez-Baeza. +""" + +import numpy as np +from scipy.linalg import orthogonal_procrustes + + +__all__ = ['procrustes'] + + +def procrustes(data1, data2): + r"""Procrustes analysis, a similarity test for two data sets. + + Each input matrix is a set of points or vectors (the rows of the matrix). + The dimension of the space is the number of columns of each matrix. Given + two identically sized matrices, procrustes standardizes both such that: + + - :math:`tr(AA^{T}) = 1`. + + - Both sets of points are centered around the origin. + + Procrustes ([1]_, [2]_) then applies the optimal transform to the second + matrix (including scaling/dilation, rotations, and reflections) to minimize + :math:`M^{2}=\sum(data1-data2)^{2}`, or the sum of the squares of the + pointwise differences between the two input datasets. + + This function was not designed to handle datasets with different numbers of + datapoints (rows). If two data sets have different dimensionality + (different number of columns), simply add columns of zeros to the smaller + of the two. + + Parameters + ---------- + data1 : array_like + Matrix, n rows represent points in k (columns) space `data1` is the + reference data, after it is standardised, the data from `data2` will be + transformed to fit the pattern in `data1` (must have >1 unique points). + data2 : array_like + n rows of data in k space to be fit to `data1`. Must be the same + shape ``(numrows, numcols)`` as data1 (must have >1 unique points). + + Returns + ------- + mtx1 : array_like + A standardized version of `data1`. + mtx2 : array_like + The orientation of `data2` that best fits `data1`. Centered, but not + necessarily :math:`tr(AA^{T}) = 1`. + disparity : float + :math:`M^{2}` as defined above. + + Raises + ------ + ValueError + If the input arrays are not two-dimensional. + If the shape of the input arrays is different. + If the input arrays have zero columns or zero rows. + + See Also + -------- + scipy.linalg.orthogonal_procrustes + scipy.spatial.distance.directed_hausdorff : Another similarity test + for two data sets + + Notes + ----- + - The disparity should not depend on the order of the input matrices, but + the output matrices will, as only the first output matrix is guaranteed + to be scaled such that :math:`tr(AA^{T}) = 1`. + + - Duplicate data points are generally ok, duplicating a data point will + increase its effect on the procrustes fit. + + - The disparity scales as the number of points per input matrix. + + References + ---------- + .. [1] Krzanowski, W. J. (2000). "Principles of Multivariate analysis". + .. [2] Gower, J. C. (1975). "Generalized procrustes analysis". + + Examples + -------- + >>> import numpy as np + >>> from scipy.spatial import procrustes + + The matrix ``b`` is a rotated, shifted, scaled and mirrored version of + ``a`` here: + + >>> a = np.array([[1, 3], [1, 2], [1, 1], [2, 1]], 'd') + >>> b = np.array([[4, -2], [4, -4], [4, -6], [2, -6]], 'd') + >>> mtx1, mtx2, disparity = procrustes(a, b) + >>> round(disparity) + 0.0 + + """ + mtx1 = np.array(data1, dtype=np.float64, copy=True) + mtx2 = np.array(data2, dtype=np.float64, copy=True) + + if mtx1.ndim != 2 or mtx2.ndim != 2: + raise ValueError("Input matrices must be two-dimensional") + if mtx1.shape != mtx2.shape: + raise ValueError("Input matrices must be of same shape") + if mtx1.size == 0: + raise ValueError("Input matrices must be >0 rows and >0 cols") + + # translate all the data to the origin + mtx1 -= np.mean(mtx1, 0) + mtx2 -= np.mean(mtx2, 0) + + norm1 = np.linalg.norm(mtx1) + norm2 = np.linalg.norm(mtx2) + + if norm1 == 0 or norm2 == 0: + raise ValueError("Input matrices must contain >1 unique points") + + # change scaling of data (in rows) such that trace(mtx*mtx') = 1 + mtx1 /= norm1 + mtx2 /= norm2 + + # transform mtx2 to minimize disparity + R, s = orthogonal_procrustes(mtx1, mtx2) + mtx2 = np.dot(mtx2, R.T) * s + + # measure the dissimilarity between the two datasets + disparity = np.sum(np.square(mtx1 - mtx2)) + + return mtx1, mtx2, disparity + diff --git a/parrot/lib/python3.10/site-packages/scipy/spatial/distance.pyi b/parrot/lib/python3.10/site-packages/scipy/spatial/distance.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0e231b46dd3b2d248e54d1259b384b9e48facd9a --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/spatial/distance.pyi @@ -0,0 +1,211 @@ +from __future__ import annotations +from typing import (overload, Any, SupportsFloat, Literal, Protocol, SupportsIndex) + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +# Anything that can be parsed by `np.float64.__init__` and is thus +# compatible with `ndarray.__setitem__` (for a float64 array) +_FloatValue = None | str | bytes | SupportsFloat | SupportsIndex + +class _MetricCallback1(Protocol): + def __call__( + self, __XA: NDArray[Any], __XB: NDArray[Any] + ) -> _FloatValue: ... + +class _MetricCallback2(Protocol): + def __call__( + self, __XA: NDArray[Any], __XB: NDArray[Any], **kwargs: Any + ) -> _FloatValue: ... + +# TODO: Use a single protocol with a parameter specification variable +# once available (PEP 612) +_MetricCallback = _MetricCallback1 | _MetricCallback2 + +_MetricKind = Literal[ + 'braycurtis', + 'canberra', + 'chebychev', 'chebyshev', 'cheby', 'cheb', 'ch', + 'cityblock', 'cblock', 'cb', 'c', + 'correlation', 'co', + 'cosine', 'cos', + 'dice', + 'euclidean', 'euclid', 'eu', 'e', + 'hamming', 'hamm', 'ha', 'h', + 'minkowski', 'mi', 'm', 'pnorm', + 'jaccard', 'jacc', 'ja', 'j', + 'jensenshannon', 'js', + 'kulczynski1', + 'mahalanobis', 'mahal', 'mah', + 'rogerstanimoto', + 'russellrao', + 'seuclidean', 'se', 's', + 'sokalmichener', + 'sokalsneath', + 'sqeuclidean', 'sqe', 'sqeuclid', + 'yule', +] + +# Function annotations + +def braycurtis( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def canberra( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +# TODO: Add `metric`-specific overloads +# Returns a float64 or float128 array, depending on the input dtype +@overload +def cdist( + XA: ArrayLike, + XB: ArrayLike, + metric: _MetricKind = ..., + *, + out: None | NDArray[np.floating[Any]] = ..., + p: float = ..., + w: ArrayLike | None = ..., + V: ArrayLike | None = ..., + VI: ArrayLike | None = ..., +) -> NDArray[np.floating[Any]]: ... +@overload +def cdist( + XA: ArrayLike, + XB: ArrayLike, + metric: _MetricCallback, + *, + out: None | NDArray[np.floating[Any]] = ..., + **kwargs: Any, +) -> NDArray[np.floating[Any]]: ... + +# TODO: Wait for dtype support; the return type is +# dependent on the input arrays dtype +def chebyshev( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> Any: ... + +# TODO: Wait for dtype support; the return type is +# dependent on the input arrays dtype +def cityblock( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> Any: ... + +def correlation( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ..., centered: bool = ... +) -> np.float64: ... + +def cosine( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def dice( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... + +def directed_hausdorff( + u: ArrayLike, v: ArrayLike, seed: int | None = ... +) -> tuple[float, int, int]: ... + +def euclidean( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... + +def hamming( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def is_valid_dm( + D: ArrayLike, + tol: float = ..., + throw: bool = ..., + name: str | None = ..., + warning: bool = ..., +) -> bool: ... + +def is_valid_y( + y: ArrayLike, + warning: bool = ..., + throw: bool = ..., + name: str | None = ..., +) -> bool: ... + +def jaccard( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def jensenshannon( + p: ArrayLike, q: ArrayLike, base: float | None = ... +) -> np.float64: ... + +def kulczynski1( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def mahalanobis( + u: ArrayLike, v: ArrayLike, VI: ArrayLike +) -> np.float64: ... + +def minkowski( + u: ArrayLike, v: ArrayLike, p: float = ..., w: ArrayLike | None = ... +) -> float: ... + +def num_obs_dm(d: ArrayLike) -> int: ... + +def num_obs_y(Y: ArrayLike) -> int: ... + +# TODO: Add `metric`-specific overloads +@overload +def pdist( + X: ArrayLike, + metric: _MetricKind = ..., + *, + out: None | NDArray[np.floating[Any]] = ..., + p: float = ..., + w: ArrayLike | None = ..., + V: ArrayLike | None = ..., + VI: ArrayLike | None = ..., +) -> NDArray[np.floating[Any]]: ... +@overload +def pdist( + X: ArrayLike, + metric: _MetricCallback, + *, + out: None | NDArray[np.floating[Any]] = ..., + **kwargs: Any, +) -> NDArray[np.floating[Any]]: ... + +def seuclidean( + u: ArrayLike, v: ArrayLike, V: ArrayLike +) -> float: ... + +def sokalmichener( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... + +def sokalsneath( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def sqeuclidean( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> np.float64: ... + +def squareform( + X: ArrayLike, + force: Literal["no", "tomatrix", "tovector"] = ..., + checks: bool = ..., +) -> NDArray[Any]: ... + +def rogerstanimoto( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... + +def russellrao( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... + +def yule( + u: ArrayLike, v: ArrayLike, w: ArrayLike | None = ... +) -> float: ... diff --git a/parrot/lib/python3.10/site-packages/scipy/spatial/kdtree.py b/parrot/lib/python3.10/site-packages/scipy/spatial/kdtree.py new file mode 100644 index 0000000000000000000000000000000000000000..512205ddc15dc7d427f8df908ee346895295b674 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/spatial/kdtree.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.spatial` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'KDTree', + 'Rectangle', + 'cKDTree', + 'distance_matrix', + 'minkowski_distance', + 'minkowski_distance_p', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="spatial", module="kdtree", + private_modules=["_kdtree"], all=__all__, + attribute=name) diff --git a/parrot/lib/python3.10/site-packages/scipy/spatial/qhull.py b/parrot/lib/python3.10/site-packages/scipy/spatial/qhull.py new file mode 100644 index 0000000000000000000000000000000000000000..a8d51bf239bfe48077e66a36bcbf59f6dbadaf95 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/spatial/qhull.py @@ -0,0 +1,25 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.spatial` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'ConvexHull', + 'Delaunay', + 'HalfspaceIntersection', + 'QhullError', + 'Voronoi', + 'tsearch', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package="spatial", module="qhull", + private_modules=["_qhull"], all=__all__, + attribute=name) diff --git a/parrot/lib/python3.10/site-packages/scipy/spatial/tests/__init__.py b/parrot/lib/python3.10/site-packages/scipy/spatial/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/parrot/lib/python3.10/site-packages/scipy/spatial/tests/test__plotutils.py b/parrot/lib/python3.10/site-packages/scipy/spatial/tests/test__plotutils.py new file mode 100644 index 0000000000000000000000000000000000000000..0e2553bf7ad56e97b567e5b334ccf17921f7f7f3 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/spatial/tests/test__plotutils.py @@ -0,0 +1,91 @@ +import pytest +import numpy as np +from numpy.testing import assert_, assert_array_equal, assert_allclose + +try: + import matplotlib + matplotlib.rcParams['backend'] = 'Agg' + import matplotlib.pyplot as plt + has_matplotlib = True +except Exception: + has_matplotlib = False + +from scipy.spatial import \ + delaunay_plot_2d, voronoi_plot_2d, convex_hull_plot_2d, \ + Delaunay, Voronoi, ConvexHull + + +@pytest.mark.skipif(not has_matplotlib, reason="Matplotlib not available") +class TestPlotting: + points = [(0,0), (0,1), (1,0), (1,1)] + + def test_delaunay(self): + # Smoke test + fig = plt.figure() + obj = Delaunay(self.points) + s_before = obj.simplices.copy() + r = delaunay_plot_2d(obj, ax=fig.gca()) + assert_array_equal(obj.simplices, s_before) # shouldn't modify + assert_(r is fig) + delaunay_plot_2d(obj, ax=fig.gca()) + + def test_voronoi(self): + # Smoke test + fig = plt.figure() + obj = Voronoi(self.points) + r = voronoi_plot_2d(obj, ax=fig.gca()) + assert_(r is fig) + voronoi_plot_2d(obj) + voronoi_plot_2d(obj, show_vertices=False) + + def test_convex_hull(self): + # Smoke test + fig = plt.figure() + tri = ConvexHull(self.points) + r = convex_hull_plot_2d(tri, ax=fig.gca()) + assert_(r is fig) + convex_hull_plot_2d(tri) + + def test_gh_19653(self): + # aspect ratio sensitivity of voronoi_plot_2d + # infinite Voronoi edges + points = np.array([[245.059986986012, 10.971011721360075], + [320.49044143557785, 10.970258360366753], + [239.79023081978914, 13.108487516946218], + [263.38325791238833, 12.93241352743668], + [219.53334398353175, 13.346107628161008]]) + vor = Voronoi(points) + fig = voronoi_plot_2d(vor) + ax = fig.gca() + infinite_segments = ax.collections[1].get_segments() + expected_segments = np.array([[[282.77256, -254.76904], + [282.729714, -4544.744698]], + [[282.77256014, -254.76904029], + [430.08561382, 4032.67658742]], + [[229.26733285, -20.39957514], + [-168.17167404, -4291.92545966]], + [[289.93433364, 5151.40412217], + [330.40553385, 9441.18887532]]]) + assert_allclose(infinite_segments, expected_segments) + + def test_gh_19653_smaller_aspect(self): + # reasonable behavior for less extreme aspect + # ratio + points = np.array([[24.059986986012, 10.971011721360075], + [32.49044143557785, 10.970258360366753], + [23.79023081978914, 13.108487516946218], + [26.38325791238833, 12.93241352743668], + [21.53334398353175, 13.346107628161008]]) + vor = Voronoi(points) + fig = voronoi_plot_2d(vor) + ax = fig.gca() + infinite_segments = ax.collections[1].get_segments() + expected_segments = np.array([[[28.274979, 8.335027], + [28.270463, -42.19763338]], + [[28.27497869, 8.33502697], + [43.73223829, 56.44555501]], + [[22.51805823, 11.8621754], + [-12.09266506, -24.95694485]], + [[29.53092448, 78.46952378], + [33.82572726, 128.81934455]]]) + assert_allclose(infinite_segments, expected_segments) diff --git a/parrot/lib/python3.10/site-packages/scipy/spatial/tests/test__procrustes.py b/parrot/lib/python3.10/site-packages/scipy/spatial/tests/test__procrustes.py new file mode 100644 index 0000000000000000000000000000000000000000..42a3c4d35bd55e2ffecefb691c805f517c56d6ca --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/spatial/tests/test__procrustes.py @@ -0,0 +1,116 @@ +import numpy as np +from numpy.testing import assert_allclose, assert_equal, assert_almost_equal +from pytest import raises as assert_raises + +from scipy.spatial import procrustes + + +class TestProcrustes: + def setup_method(self): + """creates inputs""" + # an L + self.data1 = np.array([[1, 3], [1, 2], [1, 1], [2, 1]], 'd') + + # a larger, shifted, mirrored L + self.data2 = np.array([[4, -2], [4, -4], [4, -6], [2, -6]], 'd') + + # an L shifted up 1, right 1, and with point 4 shifted an extra .5 + # to the right + # pointwise distance disparity with data1: 3*(2) + (1 + 1.5^2) + self.data3 = np.array([[2, 4], [2, 3], [2, 2], [3, 2.5]], 'd') + + # data4, data5 are standardized (trace(A*A') = 1). + # procrustes should return an identical copy if they are used + # as the first matrix argument. + shiftangle = np.pi / 8 + self.data4 = np.array([[1, 0], [0, 1], [-1, 0], + [0, -1]], 'd') / np.sqrt(4) + self.data5 = np.array([[np.cos(shiftangle), np.sin(shiftangle)], + [np.cos(np.pi / 2 - shiftangle), + np.sin(np.pi / 2 - shiftangle)], + [-np.cos(shiftangle), + -np.sin(shiftangle)], + [-np.cos(np.pi / 2 - shiftangle), + -np.sin(np.pi / 2 - shiftangle)]], + 'd') / np.sqrt(4) + + def test_procrustes(self): + # tests procrustes' ability to match two matrices. + # + # the second matrix is a rotated, shifted, scaled, and mirrored version + # of the first, in two dimensions only + # + # can shift, mirror, and scale an 'L'? + a, b, disparity = procrustes(self.data1, self.data2) + assert_allclose(b, a) + assert_almost_equal(disparity, 0.) + + # if first mtx is standardized, leaves first mtx unchanged? + m4, m5, disp45 = procrustes(self.data4, self.data5) + assert_equal(m4, self.data4) + + # at worst, data3 is an 'L' with one point off by .5 + m1, m3, disp13 = procrustes(self.data1, self.data3) + #assert_(disp13 < 0.5 ** 2) + + def test_procrustes2(self): + # procrustes disparity should not depend on order of matrices + m1, m3, disp13 = procrustes(self.data1, self.data3) + m3_2, m1_2, disp31 = procrustes(self.data3, self.data1) + assert_almost_equal(disp13, disp31) + + # try with 3d, 8 pts per + rand1 = np.array([[2.61955202, 0.30522265, 0.55515826], + [0.41124708, -0.03966978, -0.31854548], + [0.91910318, 1.39451809, -0.15295084], + [2.00452023, 0.50150048, 0.29485268], + [0.09453595, 0.67528885, 0.03283872], + [0.07015232, 2.18892599, -1.67266852], + [0.65029688, 1.60551637, 0.80013549], + [-0.6607528, 0.53644208, 0.17033891]]) + + rand3 = np.array([[0.0809969, 0.09731461, -0.173442], + [-1.84888465, -0.92589646, -1.29335743], + [0.67031855, -1.35957463, 0.41938621], + [0.73967209, -0.20230757, 0.52418027], + [0.17752796, 0.09065607, 0.29827466], + [0.47999368, -0.88455717, -0.57547934], + [-0.11486344, -0.12608506, -0.3395779], + [-0.86106154, -0.28687488, 0.9644429]]) + res1, res3, disp13 = procrustes(rand1, rand3) + res3_2, res1_2, disp31 = procrustes(rand3, rand1) + assert_almost_equal(disp13, disp31) + + def test_procrustes_shape_mismatch(self): + assert_raises(ValueError, procrustes, + np.array([[1, 2], [3, 4]]), + np.array([[5, 6, 7], [8, 9, 10]])) + + def test_procrustes_empty_rows_or_cols(self): + empty = np.array([[]]) + assert_raises(ValueError, procrustes, empty, empty) + + def test_procrustes_no_variation(self): + assert_raises(ValueError, procrustes, + np.array([[42, 42], [42, 42]]), + np.array([[45, 45], [45, 45]])) + + def test_procrustes_bad_number_of_dimensions(self): + # fewer dimensions in one dataset + assert_raises(ValueError, procrustes, + np.array([1, 1, 2, 3, 5, 8]), + np.array([[1, 2], [3, 4]])) + + # fewer dimensions in both datasets + assert_raises(ValueError, procrustes, + np.array([1, 1, 2, 3, 5, 8]), + np.array([1, 1, 2, 3, 5, 8])) + + # zero dimensions + assert_raises(ValueError, procrustes, np.array(7), np.array(11)) + + # extra dimensions + assert_raises(ValueError, procrustes, + np.array([[[11], [7]]]), + np.array([[[5, 13]]])) + diff --git a/parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_multivariate.cpython-310.pyc b/parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_multivariate.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6db95abf7cc465397127e3f17bf633e1d78ac641 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_multivariate.cpython-310.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:08c903c75c989b012035d1ab96baf8c0560bc1b7731728a292e2f061a8d1abb0 +size 212286 diff --git a/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/INSTALLER b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/METADATA b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1eaaae955f155091e4516629699af17fcfb8e57a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/METADATA @@ -0,0 +1,151 @@ +Metadata-Version: 2.3 +Name: ftfy +Version: 6.3.1 +Summary: Fixes mojibake and other problems with Unicode, after the fact +Project-URL: Homepage, https://ftfy.readthedocs.io/en/latest/ +Project-URL: Documentation, https://ftfy.readthedocs.io/en/latest/ +Project-URL: Repository, https://github.com/rspeer/python-ftfy +Project-URL: Issues, https://github.com/rspeer/python-ftfy/issues/ +Project-URL: Changelog, https://github.com/rspeer/python-ftfy/blob/main/CHANGELOG.md +Project-URL: Blog, https://posts.arborelia.net +Author-email: Robyn Speer +License: Apache-2.0 +License-File: LICENSE.txt +Requires-Python: >=3.9 +Requires-Dist: wcwidth +Description-Content-Type: text/markdown + +# ftfy: fixes text for you + +[![PyPI package](https://badge.fury.io/py/ftfy.svg)](https://badge.fury.io/py/ftfy) +[![Docs](https://readthedocs.org/projects/ftfy/badge/?version=latest)](https://ftfy.readthedocs.org/en/latest/) + +```python + +>>> from ftfy import fix_encoding +>>> print(fix_encoding("(ง'⌣')ง")) +(ง'⌣')ง + +``` + +The full documentation of ftfy is available at [ftfy.readthedocs.org](https://ftfy.readthedocs.org). The documentation covers a lot more than this README, so here are some links into it: + +- [Fixing problems and getting explanations](https://ftfy.readthedocs.io/en/latest/explain.html) +- [Configuring ftfy](https://ftfy.readthedocs.io/en/latest/config.html) +- [Encodings ftfy can handle](https://ftfy.readthedocs.io/en/latest/encodings.html) +- [“Fixer” functions](https://ftfy.readthedocs.io/en/latest/fixes.html) +- [Is ftfy an encoding detector?](https://ftfy.readthedocs.io/en/latest/detect.html) +- [Heuristics for detecting mojibake](https://ftfy.readthedocs.io/en/latest/heuristic.html) +- [Support for “bad” encodings](https://ftfy.readthedocs.io/en/latest/bad_encodings.html) +- [Command-line usage](https://ftfy.readthedocs.io/en/latest/cli.html) +- [Citing ftfy](https://ftfy.readthedocs.io/en/latest/cite.html) + +## Testimonials + +- “My life is livable again!” + — [@planarrowspace](https://twitter.com/planarrowspace) +- “A handy piece of magic” + — [@simonw](https://twitter.com/simonw) +- “Saved me a large amount of frustrating dev work” + — [@iancal](https://twitter.com/iancal) +- “ftfy did the right thing right away, with no faffing about. Excellent work, solving a very tricky real-world (whole-world!) problem.” + — Brennan Young +- “I have no idea when I’m gonna need this, but I’m definitely bookmarking it.” + — [/u/ocrow](https://reddit.com/u/ocrow) + +## What it does + +Here are some examples (found in the real world) of what ftfy can do: + +ftfy can fix mojibake (encoding mix-ups), by detecting patterns of characters that were clearly meant to be UTF-8 but were decoded as something else: + + >>> import ftfy + >>> ftfy.fix_text('✔ No problems') + '✔ No problems' + +Does this sound impossible? It's really not. UTF-8 is a well-designed encoding that makes it obvious when it's being misused, and a string of mojibake usually contains all the information we need to recover the original string. + +ftfy can fix multiple layers of mojibake simultaneously: + + >>> ftfy.fix_text('The Mona Lisa doesn’t have eyebrows.') + "The Mona Lisa doesn't have eyebrows." + +It can fix mojibake that has had "curly quotes" applied on top of it, which cannot be consistently decoded until the quotes are uncurled: + + >>> ftfy.fix_text("l’humanité") + "l'humanité" + +ftfy can fix mojibake that would have included the character U+A0 (non-breaking space), but the U+A0 was turned into an ASCII space and then combined with another following space: + + >>> ftfy.fix_text('Ã\xa0 perturber la réflexion') + 'à perturber la réflexion' + >>> ftfy.fix_text('à perturber la réflexion') + 'à perturber la réflexion' + +ftfy can also decode HTML entities that appear outside of HTML, even in cases where the entity has been incorrectly capitalized: + + >>> # by the HTML 5 standard, only 'PÉREZ' is acceptable + >>> ftfy.fix_text('P&EACUTE;REZ') + 'PÉREZ' + +These fixes are not applied in all cases, because ftfy has a strongly-held goal of avoiding false positives -- it should never change correctly-decoded text to something else. + +The following text could be encoded in Windows-1252 and decoded in UTF-8, and it would decode as 'MARQUɅ'. However, the original text is already sensible, so it is unchanged. + + >>> ftfy.fix_text('IL Y MARQUÉ…') + 'IL Y MARQUÉ…' + +## Installing + +ftfy is a Python 3 package that can be installed using `pip` or `uv pip`: + + pip install ftfy + +(Or use `pip3 install ftfy` on systems where Python 2 and 3 are both globally installed and `pip` refers to Python 2.) + +If you use `poetry`, you can use ftfy as a dependency in the usual way (such as `poetry add ftfy`). + +### Local development + +ftfy is developed using [uv](https://github.com/astral-sh/uv). You can build a virtual environment with its local dependencies by running `uv venv`, and test it with `uv run pytest`. + +## Who maintains ftfy? + +I'm Robyn Speer, also known as Elia Robyn Lake. You can find my projects +[on GitHub](https://github.com/rspeer) and my posts on [my own blog](https://posts.arborelia.net). + +## Citing ftfy + +ftfy has been used as a crucial data processing step in major NLP research. + +It's important to give credit appropriately to everyone whose work you build on in research. This includes software, not just high-status contributions such as mathematical models. All I ask when you use ftfy for research is that you cite it. + +ftfy has a citable record [on Zenodo](https://zenodo.org/record/2591652). A citation of ftfy may look like this: + + Robyn Speer. (2019). ftfy (Version 5.5). Zenodo. + http://doi.org/10.5281/zenodo.2591652 + +In BibTeX format, the citation is:: + + @misc{speer-2019-ftfy, + author = {Robyn Speer}, + title = {ftfy}, + note = {Version 5.5}, + year = 2019, + howpublished = {Zenodo}, + doi = {10.5281/zenodo.2591652}, + url = {https://doi.org/10.5281/zenodo.2591652} + } + +## Important license clarifications + +If you do not follow ftfy's license, you do not have a license to ftfy. + +This sounds obvious and tautological, but there are people who think open source licenses mean that they can just do what they want, especially in the field of generative AI. It's a permissive license but you still have to follow it. The [Apache license](https://www.apache.org/licenses/LICENSE-2.0) is the only thing that gives you permission to use and copy ftfy; otherwise, all rights are reserved. + +If you use or distribute ftfy, you must follow the terms of the [Apache license](https://www.apache.org/licenses/LICENSE-2.0), including that you must attribute the author of ftfy (Robyn Speer) correctly. + +You _may not_ make a derived work of ftfy that obscures its authorship, such as by putting its code in an AI training dataset, including the code in AI training at runtime, or using a generative AI that copies code from such a dataset. + +At my discretion, I may notify you of a license violation, and give you a chance to either remedy it or delete all copies of ftfy in your possession. + diff --git a/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/RECORD b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..fa88bf2f4c43517110c383dccef4a43aa4e3301b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/RECORD @@ -0,0 +1,27 @@ +../../../bin/ftfy,sha256=fsTFYlFg_hHOGgoB6KG_JEyQpmLe6ytRIO1iDxH9dZM,217 +ftfy-6.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +ftfy-6.3.1.dist-info/METADATA,sha256=g_Z8YoA3djfFYLXogCoAum7lErCh6h2uXf8edFsZ0d8,7257 +ftfy-6.3.1.dist-info/RECORD,, +ftfy-6.3.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +ftfy-6.3.1.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87 +ftfy-6.3.1.dist-info/entry_points.txt,sha256=sy4Ei29IqZhQRgYFC17GVrT1JkE6l1-ooJheKulSqO8,39 +ftfy-6.3.1.dist-info/licenses/LICENSE.txt,sha256=oL_FAgvC4eggVRoGJccMlfqomMFec3EA_0iAqhAZeFc,552 +ftfy/__init__.py,sha256=ekX6ZbJnR3UxmgWwpM2_0Eoizn82ukCYQRv57Bsiyzw,29593 +ftfy/__pycache__/__init__.cpython-310.pyc,, +ftfy/__pycache__/badness.cpython-310.pyc,, +ftfy/__pycache__/chardata.cpython-310.pyc,, +ftfy/__pycache__/cli.cpython-310.pyc,, +ftfy/__pycache__/fixes.cpython-310.pyc,, +ftfy/__pycache__/formatting.cpython-310.pyc,, +ftfy/bad_codecs/__init__.py,sha256=sPKWae974vjc3JeOsGhZ8ZFNUoPTISx988zBbxJ7SIQ,3282 +ftfy/bad_codecs/__pycache__/__init__.cpython-310.pyc,, +ftfy/bad_codecs/__pycache__/sloppy.cpython-310.pyc,, +ftfy/bad_codecs/__pycache__/utf8_variants.cpython-310.pyc,, +ftfy/bad_codecs/sloppy.py,sha256=bzgoZAQIrzRUxb-qJmDVX6_Eh2l143IqstdFFFayTII,6814 +ftfy/bad_codecs/utf8_variants.py,sha256=WlyMbOtUFftePEj_SpxDTXirPAj8HcuxVZ1aSYApVh0,9964 +ftfy/badness.py,sha256=jOR-ucAfX6LTjmUP4EdHS95VN766WXG3IsprQHnfb9M,15561 +ftfy/chardata.py,sha256=tAXqrX2Y3zBslAZoj6tFBy-Yn-_-UwF1uszvKN7cVck,34911 +ftfy/cli.py,sha256=q9DNi4LuhKGrleoH_Z3aB6J0oST34a2WWatap7Odr7s,4137 +ftfy/fixes.py,sha256=G8XQKzMlcsw4aPhRrQgcwAMcxqatf7EDmNaOrsY-C6U,18233 +ftfy/formatting.py,sha256=pbmBunYydgPs3bxMhCXFtaTM0_3qT_yp6esZvjvOKZk,5882 +ftfy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/WHEEL b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..cdd68a497cdfa8d3f2b837225beacef711b85047 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.25.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/entry_points.txt b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..99476a44fd1015a1c391431110d1773503340096 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +ftfy = ftfy.cli:main diff --git a/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/licenses/LICENSE.txt b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..275a4299e4d3204f13d5dec6cea39a852267b78d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/ftfy-6.3.1.dist-info/licenses/LICENSE.txt @@ -0,0 +1,13 @@ +Copyright 2023 Robyn Speer + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vllm/lib/python3.10/site-packages/markdown_it/cli/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/markdown_it/cli/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c1463d7eded59795f4cce2841f315c4223e8302 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/markdown_it/cli/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/markdown_it/helpers/parse_link_title.py b/vllm/lib/python3.10/site-packages/markdown_it/helpers/parse_link_title.py new file mode 100644 index 0000000000000000000000000000000000000000..8f589336f60ea16a7fdf73c023cad2e5092d58e3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/markdown_it/helpers/parse_link_title.py @@ -0,0 +1,60 @@ +"""Parse link title +""" +from ..common.utils import charCodeAt, unescapeAll + + +class _Result: + __slots__ = ("ok", "pos", "lines", "str") + + def __init__(self) -> None: + self.ok = False + self.pos = 0 + self.lines = 0 + self.str = "" + + def __str__(self) -> str: + return self.str + + +def parseLinkTitle(string: str, pos: int, maximum: int) -> _Result: + lines = 0 + start = pos + result = _Result() + + if pos >= maximum: + return result + + marker = charCodeAt(string, pos) + + # /* " */ /* ' */ /* ( */ + if marker != 0x22 and marker != 0x27 and marker != 0x28: + return result + + pos += 1 + + # if opening marker is "(", switch it to closing marker ")" + if marker == 0x28: + marker = 0x29 + + while pos < maximum: + code = charCodeAt(string, pos) + if code == marker: + title = string[start + 1 : pos] + title = unescapeAll(title) + result.pos = pos + 1 + result.lines = lines + result.str = title + result.ok = True + return result + elif code == 0x28 and marker == 0x29: # /* ( */ /* ) */ + return result + elif code == 0x0A: + lines += 1 + elif code == 0x5C and pos + 1 < maximum: # /* \ */ + pos += 1 + if charCodeAt(string, pos) == 0x0A: + lines += 1 + + pos += 1 + + return result diff --git a/vllm/lib/python3.10/site-packages/multipart/__init__.py b/vllm/lib/python3.10/site-packages/multipart/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67f0e5bb403eb5b05821d846190b7b8ea482cc37 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/multipart/__init__.py @@ -0,0 +1,24 @@ +# This only works if using a file system, other loaders not implemented. + +import importlib.util +import sys +import warnings +from pathlib import Path + +for p in sys.path: + file_path = Path(p, "multipart.py") + try: + if file_path.is_file(): + spec = importlib.util.spec_from_file_location("multipart", file_path) + assert spec is not None, f"{file_path} found but not loadable!" + module = importlib.util.module_from_spec(spec) + sys.modules["multipart"] = module + assert spec.loader is not None, f"{file_path} must be loadable!" + spec.loader.exec_module(module) + break + except PermissionError: + pass +else: + warnings.warn("Please use `import python_multipart` instead.", PendingDeprecationWarning, stacklevel=2) + from python_multipart import * + from python_multipart import __all__, __author__, __copyright__, __license__, __version__ diff --git a/vllm/lib/python3.10/site-packages/multipart/__pycache__/decoders.cpython-310.pyc b/vllm/lib/python3.10/site-packages/multipart/__pycache__/decoders.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebc10c3aafc5e4cc1951ad7c6bab127d724da0c7 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/multipart/__pycache__/decoders.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/multipart/__pycache__/exceptions.cpython-310.pyc b/vllm/lib/python3.10/site-packages/multipart/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..412da3fca05167a7c0852d80f695b46cde6ac84c Binary files /dev/null and b/vllm/lib/python3.10/site-packages/multipart/__pycache__/exceptions.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/multipart/decoders.py b/vllm/lib/python3.10/site-packages/multipart/decoders.py new file mode 100644 index 0000000000000000000000000000000000000000..31acdfbf1d69a0a13dcde2742fdeb6ff04e98e7d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/multipart/decoders.py @@ -0,0 +1 @@ +from python_multipart.decoders import * diff --git a/vllm/lib/python3.10/site-packages/multipart/exceptions.py b/vllm/lib/python3.10/site-packages/multipart/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..36815d1980abcf496bf63b0ac93525053111dc79 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/multipart/exceptions.py @@ -0,0 +1 @@ +from python_multipart.exceptions import * diff --git a/vllm/lib/python3.10/site-packages/multipart/multipart.py b/vllm/lib/python3.10/site-packages/multipart/multipart.py new file mode 100644 index 0000000000000000000000000000000000000000..7bf567dfc297e9e97c10073b2022efc993e39b93 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/multipart/multipart.py @@ -0,0 +1 @@ +from python_multipart.multipart import * diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/__init__.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d92b5ff072a85fe925114e74b0975f8a0da192b2 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/__init__.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/asn1.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/asn1.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a91c8c7bf99634247bd5585cb6bf6df4048532ef Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/asn1.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/cli.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/cli.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89d27872711782614763c686ca4f31de84f67a9b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/cli.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/common.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/common.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..895bc357534ef6b72b48a0da73f6486839283a9e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/common.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/core.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/core.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c22329b263e14fca6b49b3745e64d702a0e8298 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/core.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/key.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/key.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85804185974da6ad7cd0d15653362f0036cd8724 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/key.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/parallel.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/parallel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa62531325f55089c74b02166b6cd5404ecd0e6b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/parallel.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/pem.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/pem.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0910e98b2dca5f765e01ec66493c9c0837e85ffe Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/pem.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/pkcs1.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/pkcs1.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b28439b8512c1b70ae0b171d062becafe22ebe66 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/pkcs1.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/pkcs1_v2.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/pkcs1_v2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f40381a4161b840e78216984ef2e94d915d1ae9 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/pkcs1_v2.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/prime.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/prime.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88e40554f44631e82515d0ae82927d383932c995 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/prime.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/randnum.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/randnum.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b55642d0a03c4851e4de37e8dea61e2ea10fc91 Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/randnum.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/transform.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/transform.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07351d539aaf6476155145aa8f99d757263e8b5b Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/transform.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/__pycache__/util.cpython-310.pyc b/vllm/lib/python3.10/site-packages/rsa/__pycache__/util.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08cfabd99478a180a3f453c46dfd5db0c605d46f Binary files /dev/null and b/vllm/lib/python3.10/site-packages/rsa/__pycache__/util.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/rsa/asn1.py b/vllm/lib/python3.10/site-packages/rsa/asn1.py new file mode 100644 index 0000000000000000000000000000000000000000..b91806fbff2ed2d5f9b35eeb097ee87eba68e467 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/asn1.py @@ -0,0 +1,52 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""ASN.1 definitions. + +Not all ASN.1-handling code use these definitions, but when it does, they should be here. +""" + +from pyasn1.type import univ, namedtype, tag + + +class PubKeyHeader(univ.Sequence): + componentType = namedtype.NamedTypes( + namedtype.NamedType("oid", univ.ObjectIdentifier()), + namedtype.NamedType("parameters", univ.Null()), + ) + + +class OpenSSLPubKey(univ.Sequence): + componentType = namedtype.NamedTypes( + namedtype.NamedType("header", PubKeyHeader()), + # This little hack (the implicit tag) allows us to get a Bit String as Octet String + namedtype.NamedType( + "key", + univ.OctetString().subtype(implicitTag=tag.Tag(tagClass=0, tagFormat=0, tagId=3)), + ), + ) + + +class AsnPubKey(univ.Sequence): + """ASN.1 contents of DER encoded public key: + + RSAPublicKey ::= SEQUENCE { + modulus INTEGER, -- n + publicExponent INTEGER, -- e + """ + + componentType = namedtype.NamedTypes( + namedtype.NamedType("modulus", univ.Integer()), + namedtype.NamedType("publicExponent", univ.Integer()), + ) diff --git a/vllm/lib/python3.10/site-packages/rsa/cli.py b/vllm/lib/python3.10/site-packages/rsa/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..5a6b6506a3355db5d7d04453c481f0fe22cc094e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/cli.py @@ -0,0 +1,321 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Commandline scripts. + +These scripts are called by the executables defined in setup.py. +""" + +import abc +import sys +import typing +import optparse + +import rsa +import rsa.key +import rsa.pkcs1 + +HASH_METHODS = sorted(rsa.pkcs1.HASH_METHODS.keys()) +Indexable = typing.Union[typing.Tuple, typing.List[str]] + + +def keygen() -> None: + """Key generator.""" + + # Parse the CLI options + parser = optparse.OptionParser( + usage="usage: %prog [options] keysize", + description='Generates a new RSA key pair of "keysize" bits.', + ) + + parser.add_option( + "--pubout", + type="string", + help="Output filename for the public key. The public key is " + "not saved if this option is not present. You can use " + "pyrsa-priv2pub to create the public key file later.", + ) + + parser.add_option( + "-o", + "--out", + type="string", + help="Output filename for the private key. The key is " + "written to stdout if this option is not present.", + ) + + parser.add_option( + "--form", + help="key format of the private and public keys - default PEM", + choices=("PEM", "DER"), + default="PEM", + ) + + (cli, cli_args) = parser.parse_args(sys.argv[1:]) + + if len(cli_args) != 1: + parser.print_help() + raise SystemExit(1) + + try: + keysize = int(cli_args[0]) + except ValueError as ex: + parser.print_help() + print("Not a valid number: %s" % cli_args[0], file=sys.stderr) + raise SystemExit(1) from ex + + print("Generating %i-bit key" % keysize, file=sys.stderr) + (pub_key, priv_key) = rsa.newkeys(keysize) + + # Save public key + if cli.pubout: + print("Writing public key to %s" % cli.pubout, file=sys.stderr) + data = pub_key.save_pkcs1(format=cli.form) + with open(cli.pubout, "wb") as outfile: + outfile.write(data) + + # Save private key + data = priv_key.save_pkcs1(format=cli.form) + + if cli.out: + print("Writing private key to %s" % cli.out, file=sys.stderr) + with open(cli.out, "wb") as outfile: + outfile.write(data) + else: + print("Writing private key to stdout", file=sys.stderr) + sys.stdout.buffer.write(data) + + +class CryptoOperation(metaclass=abc.ABCMeta): + """CLI callable that operates with input, output, and a key.""" + + keyname = "public" # or 'private' + usage = "usage: %%prog [options] %(keyname)s_key" + description = "" + operation = "decrypt" + operation_past = "decrypted" + operation_progressive = "decrypting" + input_help = "Name of the file to %(operation)s. Reads from stdin if " "not specified." + output_help = ( + "Name of the file to write the %(operation_past)s file " + "to. Written to stdout if this option is not present." + ) + expected_cli_args = 1 + has_output = True + + key_class = rsa.PublicKey # type: typing.Type[rsa.key.AbstractKey] + + def __init__(self) -> None: + self.usage = self.usage % self.__class__.__dict__ + self.input_help = self.input_help % self.__class__.__dict__ + self.output_help = self.output_help % self.__class__.__dict__ + + @abc.abstractmethod + def perform_operation( + self, indata: bytes, key: rsa.key.AbstractKey, cli_args: Indexable + ) -> typing.Any: + """Performs the program's operation. + + Implement in a subclass. + + :returns: the data to write to the output. + """ + + def __call__(self) -> None: + """Runs the program.""" + + (cli, cli_args) = self.parse_cli() + + key = self.read_key(cli_args[0], cli.keyform) + + indata = self.read_infile(cli.input) + + print(self.operation_progressive.title(), file=sys.stderr) + outdata = self.perform_operation(indata, key, cli_args) + + if self.has_output: + self.write_outfile(outdata, cli.output) + + def parse_cli(self) -> typing.Tuple[optparse.Values, typing.List[str]]: + """Parse the CLI options + + :returns: (cli_opts, cli_args) + """ + + parser = optparse.OptionParser(usage=self.usage, description=self.description) + + parser.add_option("-i", "--input", type="string", help=self.input_help) + + if self.has_output: + parser.add_option("-o", "--output", type="string", help=self.output_help) + + parser.add_option( + "--keyform", + help="Key format of the %s key - default PEM" % self.keyname, + choices=("PEM", "DER"), + default="PEM", + ) + + (cli, cli_args) = parser.parse_args(sys.argv[1:]) + + if len(cli_args) != self.expected_cli_args: + parser.print_help() + raise SystemExit(1) + + return cli, cli_args + + def read_key(self, filename: str, keyform: str) -> rsa.key.AbstractKey: + """Reads a public or private key.""" + + print("Reading %s key from %s" % (self.keyname, filename), file=sys.stderr) + with open(filename, "rb") as keyfile: + keydata = keyfile.read() + + return self.key_class.load_pkcs1(keydata, keyform) + + def read_infile(self, inname: str) -> bytes: + """Read the input file""" + + if inname: + print("Reading input from %s" % inname, file=sys.stderr) + with open(inname, "rb") as infile: + return infile.read() + + print("Reading input from stdin", file=sys.stderr) + return sys.stdin.buffer.read() + + def write_outfile(self, outdata: bytes, outname: str) -> None: + """Write the output file""" + + if outname: + print("Writing output to %s" % outname, file=sys.stderr) + with open(outname, "wb") as outfile: + outfile.write(outdata) + else: + print("Writing output to stdout", file=sys.stderr) + sys.stdout.buffer.write(outdata) + + +class EncryptOperation(CryptoOperation): + """Encrypts a file.""" + + keyname = "public" + description = ( + "Encrypts a file. The file must be shorter than the key " "length in order to be encrypted." + ) + operation = "encrypt" + operation_past = "encrypted" + operation_progressive = "encrypting" + + def perform_operation( + self, indata: bytes, pub_key: rsa.key.AbstractKey, cli_args: Indexable = () + ) -> bytes: + """Encrypts files.""" + assert isinstance(pub_key, rsa.key.PublicKey) + return rsa.encrypt(indata, pub_key) + + +class DecryptOperation(CryptoOperation): + """Decrypts a file.""" + + keyname = "private" + description = ( + "Decrypts a file. The original file must be shorter than " + "the key length in order to have been encrypted." + ) + operation = "decrypt" + operation_past = "decrypted" + operation_progressive = "decrypting" + key_class = rsa.PrivateKey + + def perform_operation( + self, indata: bytes, priv_key: rsa.key.AbstractKey, cli_args: Indexable = () + ) -> bytes: + """Decrypts files.""" + assert isinstance(priv_key, rsa.key.PrivateKey) + return rsa.decrypt(indata, priv_key) + + +class SignOperation(CryptoOperation): + """Signs a file.""" + + keyname = "private" + usage = "usage: %%prog [options] private_key hash_method" + description = ( + "Signs a file, outputs the signature. Choose the hash " + "method from %s" % ", ".join(HASH_METHODS) + ) + operation = "sign" + operation_past = "signature" + operation_progressive = "Signing" + key_class = rsa.PrivateKey + expected_cli_args = 2 + + output_help = ( + "Name of the file to write the signature to. Written " + "to stdout if this option is not present." + ) + + def perform_operation( + self, indata: bytes, priv_key: rsa.key.AbstractKey, cli_args: Indexable + ) -> bytes: + """Signs files.""" + assert isinstance(priv_key, rsa.key.PrivateKey) + + hash_method = cli_args[1] + if hash_method not in HASH_METHODS: + raise SystemExit("Invalid hash method, choose one of %s" % ", ".join(HASH_METHODS)) + + return rsa.sign(indata, priv_key, hash_method) + + +class VerifyOperation(CryptoOperation): + """Verify a signature.""" + + keyname = "public" + usage = "usage: %%prog [options] public_key signature_file" + description = ( + "Verifies a signature, exits with status 0 upon success, " + "prints an error message and exits with status 1 upon error." + ) + operation = "verify" + operation_past = "verified" + operation_progressive = "Verifying" + key_class = rsa.PublicKey + expected_cli_args = 2 + has_output = False + + def perform_operation( + self, indata: bytes, pub_key: rsa.key.AbstractKey, cli_args: Indexable + ) -> None: + """Verifies files.""" + assert isinstance(pub_key, rsa.key.PublicKey) + + signature_file = cli_args[1] + + with open(signature_file, "rb") as sigfile: + signature = sigfile.read() + + try: + rsa.verify(indata, signature, pub_key) + except rsa.VerificationError as ex: + raise SystemExit("Verification failed.") from ex + + print("Verification OK", file=sys.stderr) + + +encrypt = EncryptOperation() +decrypt = DecryptOperation() +sign = SignOperation() +verify = VerifyOperation() diff --git a/vllm/lib/python3.10/site-packages/rsa/common.py b/vllm/lib/python3.10/site-packages/rsa/common.py new file mode 100644 index 0000000000000000000000000000000000000000..520dfec64aa84753d13bf49cddb93db97a4509da --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/common.py @@ -0,0 +1,184 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Common functionality shared by several modules.""" + +import typing + + +class NotRelativePrimeError(ValueError): + def __init__(self, a: int, b: int, d: int, msg: str = "") -> None: + super().__init__(msg or "%d and %d are not relatively prime, divider=%i" % (a, b, d)) + self.a = a + self.b = b + self.d = d + + +def bit_size(num: int) -> int: + """ + Number of bits needed to represent a integer excluding any prefix + 0 bits. + + Usage:: + + >>> bit_size(1023) + 10 + >>> bit_size(1024) + 11 + >>> bit_size(1025) + 11 + + :param num: + Integer value. If num is 0, returns 0. Only the absolute value of the + number is considered. Therefore, signed integers will be abs(num) + before the number's bit length is determined. + :returns: + Returns the number of bits in the integer. + """ + + try: + return num.bit_length() + except AttributeError as ex: + raise TypeError("bit_size(num) only supports integers, not %r" % type(num)) from ex + + +def byte_size(number: int) -> int: + """ + Returns the number of bytes required to hold a specific long number. + + The number of bytes is rounded up. + + Usage:: + + >>> byte_size(1 << 1023) + 128 + >>> byte_size((1 << 1024) - 1) + 128 + >>> byte_size(1 << 1024) + 129 + + :param number: + An unsigned integer + :returns: + The number of bytes required to hold a specific long number. + """ + if number == 0: + return 1 + return ceil_div(bit_size(number), 8) + + +def ceil_div(num: int, div: int) -> int: + """ + Returns the ceiling function of a division between `num` and `div`. + + Usage:: + + >>> ceil_div(100, 7) + 15 + >>> ceil_div(100, 10) + 10 + >>> ceil_div(1, 4) + 1 + + :param num: Division's numerator, a number + :param div: Division's divisor, a number + + :return: Rounded up result of the division between the parameters. + """ + quanta, mod = divmod(num, div) + if mod: + quanta += 1 + return quanta + + +def extended_gcd(a: int, b: int) -> typing.Tuple[int, int, int]: + """Returns a tuple (r, i, j) such that r = gcd(a, b) = ia + jb""" + # r = gcd(a,b) i = multiplicitive inverse of a mod b + # or j = multiplicitive inverse of b mod a + # Neg return values for i or j are made positive mod b or a respectively + # Iterateive Version is faster and uses much less stack space + x = 0 + y = 1 + lx = 1 + ly = 0 + oa = a # Remember original a/b to remove + ob = b # negative values from return results + while b != 0: + q = a // b + (a, b) = (b, a % b) + (x, lx) = ((lx - (q * x)), x) + (y, ly) = ((ly - (q * y)), y) + if lx < 0: + lx += ob # If neg wrap modulo original b + if ly < 0: + ly += oa # If neg wrap modulo original a + return a, lx, ly # Return only positive values + + +def inverse(x: int, n: int) -> int: + """Returns the inverse of x % n under multiplication, a.k.a x^-1 (mod n) + + >>> inverse(7, 4) + 3 + >>> (inverse(143, 4) * 143) % 4 + 1 + """ + + (divider, inv, _) = extended_gcd(x, n) + + if divider != 1: + raise NotRelativePrimeError(x, n, divider) + + return inv + + +def crt(a_values: typing.Iterable[int], modulo_values: typing.Iterable[int]) -> int: + """Chinese Remainder Theorem. + + Calculates x such that x = a[i] (mod m[i]) for each i. + + :param a_values: the a-values of the above equation + :param modulo_values: the m-values of the above equation + :returns: x such that x = a[i] (mod m[i]) for each i + + + >>> crt([2, 3], [3, 5]) + 8 + + >>> crt([2, 3, 2], [3, 5, 7]) + 23 + + >>> crt([2, 3, 0], [7, 11, 15]) + 135 + """ + + m = 1 + x = 0 + + for modulo in modulo_values: + m *= modulo + + for (m_i, a_i) in zip(modulo_values, a_values): + M_i = m // m_i + inv = inverse(M_i, m_i) + + x = (x + a_i * M_i * inv) % m + + return x + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/vllm/lib/python3.10/site-packages/rsa/core.py b/vllm/lib/python3.10/site-packages/rsa/core.py new file mode 100644 index 0000000000000000000000000000000000000000..729123b6a80a008a59755290fd99df227ef6e77b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/core.py @@ -0,0 +1,53 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Core mathematical operations. + +This is the actual core RSA implementation, which is only defined +mathematically on integers. +""" + + +def assert_int(var: int, name: str) -> None: + if isinstance(var, int): + return + + raise TypeError("%s should be an integer, not %s" % (name, var.__class__)) + + +def encrypt_int(message: int, ekey: int, n: int) -> int: + """Encrypts a message using encryption key 'ekey', working modulo n""" + + assert_int(message, "message") + assert_int(ekey, "ekey") + assert_int(n, "n") + + if message < 0: + raise ValueError("Only non-negative numbers are supported") + + if message > n: + raise OverflowError("The message %i is too long for n=%i" % (message, n)) + + return pow(message, ekey, n) + + +def decrypt_int(cyphertext: int, dkey: int, n: int) -> int: + """Decrypts a cypher text using the decryption key 'dkey', working modulo n""" + + assert_int(cyphertext, "cyphertext") + assert_int(dkey, "dkey") + assert_int(n, "n") + + message = pow(cyphertext, dkey, n) + return message diff --git a/vllm/lib/python3.10/site-packages/rsa/key.py b/vllm/lib/python3.10/site-packages/rsa/key.py new file mode 100644 index 0000000000000000000000000000000000000000..b6b17f91925822d419cd68fa855d9359482f85d5 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/key.py @@ -0,0 +1,858 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""RSA key generation code. + +Create new keys with the newkeys() function. It will give you a PublicKey and a +PrivateKey object. + +Loading and saving keys requires the pyasn1 module. This module is imported as +late as possible, such that other functionality will remain working in absence +of pyasn1. + +.. note:: + + Storing public and private keys via the `pickle` module is possible. + However, it is insecure to load a key from an untrusted source. + The pickle module is not secure against erroneous or maliciously + constructed data. Never unpickle data received from an untrusted + or unauthenticated source. + +""" + +import threading +import typing +import warnings + +import rsa.prime +import rsa.pem +import rsa.common +import rsa.randnum +import rsa.core + + +DEFAULT_EXPONENT = 65537 + + +T = typing.TypeVar("T", bound="AbstractKey") + + +class AbstractKey: + """Abstract superclass for private and public keys.""" + + __slots__ = ("n", "e", "blindfac", "blindfac_inverse", "mutex") + + def __init__(self, n: int, e: int) -> None: + self.n = n + self.e = e + + # These will be computed properly on the first call to blind(). + self.blindfac = self.blindfac_inverse = -1 + + # Used to protect updates to the blinding factor in multi-threaded + # environments. + self.mutex = threading.Lock() + + @classmethod + def _load_pkcs1_pem(cls: typing.Type[T], keyfile: bytes) -> T: + """Loads a key in PKCS#1 PEM format, implement in a subclass. + + :param keyfile: contents of a PEM-encoded file that contains + the public key. + :type keyfile: bytes + + :return: the loaded key + :rtype: AbstractKey + """ + + @classmethod + def _load_pkcs1_der(cls: typing.Type[T], keyfile: bytes) -> T: + """Loads a key in PKCS#1 PEM format, implement in a subclass. + + :param keyfile: contents of a DER-encoded file that contains + the public key. + :type keyfile: bytes + + :return: the loaded key + :rtype: AbstractKey + """ + + def _save_pkcs1_pem(self) -> bytes: + """Saves the key in PKCS#1 PEM format, implement in a subclass. + + :returns: the PEM-encoded key. + :rtype: bytes + """ + + def _save_pkcs1_der(self) -> bytes: + """Saves the key in PKCS#1 DER format, implement in a subclass. + + :returns: the DER-encoded key. + :rtype: bytes + """ + + @classmethod + def load_pkcs1(cls: typing.Type[T], keyfile: bytes, format: str = "PEM") -> T: + """Loads a key in PKCS#1 DER or PEM format. + + :param keyfile: contents of a DER- or PEM-encoded file that contains + the key. + :type keyfile: bytes + :param format: the format of the file to load; 'PEM' or 'DER' + :type format: str + + :return: the loaded key + :rtype: AbstractKey + """ + + methods = { + "PEM": cls._load_pkcs1_pem, + "DER": cls._load_pkcs1_der, + } + + method = cls._assert_format_exists(format, methods) + return method(keyfile) + + @staticmethod + def _assert_format_exists( + file_format: str, methods: typing.Mapping[str, typing.Callable] + ) -> typing.Callable: + """Checks whether the given file format exists in 'methods'.""" + + try: + return methods[file_format] + except KeyError as ex: + formats = ", ".join(sorted(methods.keys())) + raise ValueError( + "Unsupported format: %r, try one of %s" % (file_format, formats) + ) from ex + + def save_pkcs1(self, format: str = "PEM") -> bytes: + """Saves the key in PKCS#1 DER or PEM format. + + :param format: the format to save; 'PEM' or 'DER' + :type format: str + :returns: the DER- or PEM-encoded key. + :rtype: bytes + """ + + methods = { + "PEM": self._save_pkcs1_pem, + "DER": self._save_pkcs1_der, + } + + method = self._assert_format_exists(format, methods) + return method() + + def blind(self, message: int) -> typing.Tuple[int, int]: + """Performs blinding on the message. + + :param message: the message, as integer, to blind. + :param r: the random number to blind with. + :return: tuple (the blinded message, the inverse of the used blinding factor) + + The blinding is such that message = unblind(decrypt(blind(encrypt(message))). + + See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29 + """ + blindfac, blindfac_inverse = self._update_blinding_factor() + blinded = (message * pow(blindfac, self.e, self.n)) % self.n + return blinded, blindfac_inverse + + def unblind(self, blinded: int, blindfac_inverse: int) -> int: + """Performs blinding on the message using random number 'blindfac_inverse'. + + :param blinded: the blinded message, as integer, to unblind. + :param blindfac: the factor to unblind with. + :return: the original message. + + The blinding is such that message = unblind(decrypt(blind(encrypt(message))). + + See https://en.wikipedia.org/wiki/Blinding_%28cryptography%29 + """ + return (blindfac_inverse * blinded) % self.n + + def _initial_blinding_factor(self) -> int: + for _ in range(1000): + blind_r = rsa.randnum.randint(self.n - 1) + if rsa.prime.are_relatively_prime(self.n, blind_r): + return blind_r + raise RuntimeError("unable to find blinding factor") + + def _update_blinding_factor(self) -> typing.Tuple[int, int]: + """Update blinding factors. + + Computing a blinding factor is expensive, so instead this function + does this once, then updates the blinding factor as per section 9 + of 'A Timing Attack against RSA with the Chinese Remainder Theorem' + by Werner Schindler. + See https://tls.mbed.org/public/WSchindler-RSA_Timing_Attack.pdf + + :return: the new blinding factor and its inverse. + """ + + with self.mutex: + if self.blindfac < 0: + # Compute initial blinding factor, which is rather slow to do. + self.blindfac = self._initial_blinding_factor() + self.blindfac_inverse = rsa.common.inverse(self.blindfac, self.n) + else: + # Reuse previous blinding factor. + self.blindfac = pow(self.blindfac, 2, self.n) + self.blindfac_inverse = pow(self.blindfac_inverse, 2, self.n) + + return self.blindfac, self.blindfac_inverse + + +class PublicKey(AbstractKey): + """Represents a public RSA key. + + This key is also known as the 'encryption key'. It contains the 'n' and 'e' + values. + + Supports attributes as well as dictionary-like access. Attribute access is + faster, though. + + >>> PublicKey(5, 3) + PublicKey(5, 3) + + >>> key = PublicKey(5, 3) + >>> key.n + 5 + >>> key['n'] + 5 + >>> key.e + 3 + >>> key['e'] + 3 + + """ + + __slots__ = () + + def __getitem__(self, key: str) -> int: + return getattr(self, key) + + def __repr__(self) -> str: + return "PublicKey(%i, %i)" % (self.n, self.e) + + def __getstate__(self) -> typing.Tuple[int, int]: + """Returns the key as tuple for pickling.""" + return self.n, self.e + + def __setstate__(self, state: typing.Tuple[int, int]) -> None: + """Sets the key from tuple.""" + self.n, self.e = state + AbstractKey.__init__(self, self.n, self.e) + + def __eq__(self, other: typing.Any) -> bool: + if other is None: + return False + + if not isinstance(other, PublicKey): + return False + + return self.n == other.n and self.e == other.e + + def __ne__(self, other: typing.Any) -> bool: + return not (self == other) + + def __hash__(self) -> int: + return hash((self.n, self.e)) + + @classmethod + def _load_pkcs1_der(cls, keyfile: bytes) -> "PublicKey": + """Loads a key in PKCS#1 DER format. + + :param keyfile: contents of a DER-encoded file that contains the public + key. + :return: a PublicKey object + + First let's construct a DER encoded key: + + >>> import base64 + >>> b64der = 'MAwCBQCNGmYtAgMBAAE=' + >>> der = base64.standard_b64decode(b64der) + + This loads the file: + + >>> PublicKey._load_pkcs1_der(der) + PublicKey(2367317549, 65537) + + """ + + from pyasn1.codec.der import decoder + from rsa.asn1 import AsnPubKey + + (priv, _) = decoder.decode(keyfile, asn1Spec=AsnPubKey()) + return cls(n=int(priv["modulus"]), e=int(priv["publicExponent"])) + + def _save_pkcs1_der(self) -> bytes: + """Saves the public key in PKCS#1 DER format. + + :returns: the DER-encoded public key. + :rtype: bytes + """ + + from pyasn1.codec.der import encoder + from rsa.asn1 import AsnPubKey + + # Create the ASN object + asn_key = AsnPubKey() + asn_key.setComponentByName("modulus", self.n) + asn_key.setComponentByName("publicExponent", self.e) + + return encoder.encode(asn_key) + + @classmethod + def _load_pkcs1_pem(cls, keyfile: bytes) -> "PublicKey": + """Loads a PKCS#1 PEM-encoded public key file. + + The contents of the file before the "-----BEGIN RSA PUBLIC KEY-----" and + after the "-----END RSA PUBLIC KEY-----" lines is ignored. + + :param keyfile: contents of a PEM-encoded file that contains the public + key. + :return: a PublicKey object + """ + + der = rsa.pem.load_pem(keyfile, "RSA PUBLIC KEY") + return cls._load_pkcs1_der(der) + + def _save_pkcs1_pem(self) -> bytes: + """Saves a PKCS#1 PEM-encoded public key file. + + :return: contents of a PEM-encoded file that contains the public key. + :rtype: bytes + """ + + der = self._save_pkcs1_der() + return rsa.pem.save_pem(der, "RSA PUBLIC KEY") + + @classmethod + def load_pkcs1_openssl_pem(cls, keyfile: bytes) -> "PublicKey": + """Loads a PKCS#1.5 PEM-encoded public key file from OpenSSL. + + These files can be recognised in that they start with BEGIN PUBLIC KEY + rather than BEGIN RSA PUBLIC KEY. + + The contents of the file before the "-----BEGIN PUBLIC KEY-----" and + after the "-----END PUBLIC KEY-----" lines is ignored. + + :param keyfile: contents of a PEM-encoded file that contains the public + key, from OpenSSL. + :type keyfile: bytes + :return: a PublicKey object + """ + + der = rsa.pem.load_pem(keyfile, "PUBLIC KEY") + return cls.load_pkcs1_openssl_der(der) + + @classmethod + def load_pkcs1_openssl_der(cls, keyfile: bytes) -> "PublicKey": + """Loads a PKCS#1 DER-encoded public key file from OpenSSL. + + :param keyfile: contents of a DER-encoded file that contains the public + key, from OpenSSL. + :return: a PublicKey object + """ + + from rsa.asn1 import OpenSSLPubKey + from pyasn1.codec.der import decoder + from pyasn1.type import univ + + (keyinfo, _) = decoder.decode(keyfile, asn1Spec=OpenSSLPubKey()) + + if keyinfo["header"]["oid"] != univ.ObjectIdentifier("1.2.840.113549.1.1.1"): + raise TypeError("This is not a DER-encoded OpenSSL-compatible public key") + + return cls._load_pkcs1_der(keyinfo["key"][1:]) + + +class PrivateKey(AbstractKey): + """Represents a private RSA key. + + This key is also known as the 'decryption key'. It contains the 'n', 'e', + 'd', 'p', 'q' and other values. + + Supports attributes as well as dictionary-like access. Attribute access is + faster, though. + + >>> PrivateKey(3247, 65537, 833, 191, 17) + PrivateKey(3247, 65537, 833, 191, 17) + + exp1, exp2 and coef will be calculated: + + >>> pk = PrivateKey(3727264081, 65537, 3349121513, 65063, 57287) + >>> pk.exp1 + 55063 + >>> pk.exp2 + 10095 + >>> pk.coef + 50797 + + """ + + __slots__ = ("d", "p", "q", "exp1", "exp2", "coef") + + def __init__(self, n: int, e: int, d: int, p: int, q: int) -> None: + AbstractKey.__init__(self, n, e) + self.d = d + self.p = p + self.q = q + + # Calculate exponents and coefficient. + self.exp1 = int(d % (p - 1)) + self.exp2 = int(d % (q - 1)) + self.coef = rsa.common.inverse(q, p) + + def __getitem__(self, key: str) -> int: + return getattr(self, key) + + def __repr__(self) -> str: + return "PrivateKey(%i, %i, %i, %i, %i)" % ( + self.n, + self.e, + self.d, + self.p, + self.q, + ) + + def __getstate__(self) -> typing.Tuple[int, int, int, int, int, int, int, int]: + """Returns the key as tuple for pickling.""" + return self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef + + def __setstate__(self, state: typing.Tuple[int, int, int, int, int, int, int, int]) -> None: + """Sets the key from tuple.""" + self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef = state + AbstractKey.__init__(self, self.n, self.e) + + def __eq__(self, other: typing.Any) -> bool: + if other is None: + return False + + if not isinstance(other, PrivateKey): + return False + + return ( + self.n == other.n + and self.e == other.e + and self.d == other.d + and self.p == other.p + and self.q == other.q + and self.exp1 == other.exp1 + and self.exp2 == other.exp2 + and self.coef == other.coef + ) + + def __ne__(self, other: typing.Any) -> bool: + return not (self == other) + + def __hash__(self) -> int: + return hash((self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef)) + + def blinded_decrypt(self, encrypted: int) -> int: + """Decrypts the message using blinding to prevent side-channel attacks. + + :param encrypted: the encrypted message + :type encrypted: int + + :returns: the decrypted message + :rtype: int + """ + + # Blinding and un-blinding should be using the same factor + blinded, blindfac_inverse = self.blind(encrypted) + + # Instead of using the core functionality, use the Chinese Remainder + # Theorem and be 2-4x faster. This the same as: + # + # decrypted = rsa.core.decrypt_int(blinded, self.d, self.n) + s1 = pow(blinded, self.exp1, self.p) + s2 = pow(blinded, self.exp2, self.q) + h = ((s1 - s2) * self.coef) % self.p + decrypted = s2 + self.q * h + + return self.unblind(decrypted, blindfac_inverse) + + def blinded_encrypt(self, message: int) -> int: + """Encrypts the message using blinding to prevent side-channel attacks. + + :param message: the message to encrypt + :type message: int + + :returns: the encrypted message + :rtype: int + """ + + blinded, blindfac_inverse = self.blind(message) + encrypted = rsa.core.encrypt_int(blinded, self.d, self.n) + return self.unblind(encrypted, blindfac_inverse) + + @classmethod + def _load_pkcs1_der(cls, keyfile: bytes) -> "PrivateKey": + """Loads a key in PKCS#1 DER format. + + :param keyfile: contents of a DER-encoded file that contains the private + key. + :type keyfile: bytes + :return: a PrivateKey object + + First let's construct a DER encoded key: + + >>> import base64 + >>> b64der = 'MC4CAQACBQDeKYlRAgMBAAECBQDHn4npAgMA/icCAwDfxwIDANcXAgInbwIDAMZt' + >>> der = base64.standard_b64decode(b64der) + + This loads the file: + + >>> PrivateKey._load_pkcs1_der(der) + PrivateKey(3727264081, 65537, 3349121513, 65063, 57287) + + """ + + from pyasn1.codec.der import decoder + + (priv, _) = decoder.decode(keyfile) + + # ASN.1 contents of DER encoded private key: + # + # RSAPrivateKey ::= SEQUENCE { + # version Version, + # modulus INTEGER, -- n + # publicExponent INTEGER, -- e + # privateExponent INTEGER, -- d + # prime1 INTEGER, -- p + # prime2 INTEGER, -- q + # exponent1 INTEGER, -- d mod (p-1) + # exponent2 INTEGER, -- d mod (q-1) + # coefficient INTEGER, -- (inverse of q) mod p + # otherPrimeInfos OtherPrimeInfos OPTIONAL + # } + + if priv[0] != 0: + raise ValueError("Unable to read this file, version %s != 0" % priv[0]) + + as_ints = map(int, priv[1:6]) + key = cls(*as_ints) + + exp1, exp2, coef = map(int, priv[6:9]) + + if (key.exp1, key.exp2, key.coef) != (exp1, exp2, coef): + warnings.warn( + "You have provided a malformed keyfile. Either the exponents " + "or the coefficient are incorrect. Using the correct values " + "instead.", + UserWarning, + ) + + return key + + def _save_pkcs1_der(self) -> bytes: + """Saves the private key in PKCS#1 DER format. + + :returns: the DER-encoded private key. + :rtype: bytes + """ + + from pyasn1.type import univ, namedtype + from pyasn1.codec.der import encoder + + class AsnPrivKey(univ.Sequence): + componentType = namedtype.NamedTypes( + namedtype.NamedType("version", univ.Integer()), + namedtype.NamedType("modulus", univ.Integer()), + namedtype.NamedType("publicExponent", univ.Integer()), + namedtype.NamedType("privateExponent", univ.Integer()), + namedtype.NamedType("prime1", univ.Integer()), + namedtype.NamedType("prime2", univ.Integer()), + namedtype.NamedType("exponent1", univ.Integer()), + namedtype.NamedType("exponent2", univ.Integer()), + namedtype.NamedType("coefficient", univ.Integer()), + ) + + # Create the ASN object + asn_key = AsnPrivKey() + asn_key.setComponentByName("version", 0) + asn_key.setComponentByName("modulus", self.n) + asn_key.setComponentByName("publicExponent", self.e) + asn_key.setComponentByName("privateExponent", self.d) + asn_key.setComponentByName("prime1", self.p) + asn_key.setComponentByName("prime2", self.q) + asn_key.setComponentByName("exponent1", self.exp1) + asn_key.setComponentByName("exponent2", self.exp2) + asn_key.setComponentByName("coefficient", self.coef) + + return encoder.encode(asn_key) + + @classmethod + def _load_pkcs1_pem(cls, keyfile: bytes) -> "PrivateKey": + """Loads a PKCS#1 PEM-encoded private key file. + + The contents of the file before the "-----BEGIN RSA PRIVATE KEY-----" and + after the "-----END RSA PRIVATE KEY-----" lines is ignored. + + :param keyfile: contents of a PEM-encoded file that contains the private + key. + :type keyfile: bytes + :return: a PrivateKey object + """ + + der = rsa.pem.load_pem(keyfile, b"RSA PRIVATE KEY") + return cls._load_pkcs1_der(der) + + def _save_pkcs1_pem(self) -> bytes: + """Saves a PKCS#1 PEM-encoded private key file. + + :return: contents of a PEM-encoded file that contains the private key. + :rtype: bytes + """ + + der = self._save_pkcs1_der() + return rsa.pem.save_pem(der, b"RSA PRIVATE KEY") + + +def find_p_q( + nbits: int, + getprime_func: typing.Callable[[int], int] = rsa.prime.getprime, + accurate: bool = True, +) -> typing.Tuple[int, int]: + """Returns a tuple of two different primes of nbits bits each. + + The resulting p * q has exactly 2 * nbits bits, and the returned p and q + will not be equal. + + :param nbits: the number of bits in each of p and q. + :param getprime_func: the getprime function, defaults to + :py:func:`rsa.prime.getprime`. + + *Introduced in Python-RSA 3.1* + + :param accurate: whether to enable accurate mode or not. + :returns: (p, q), where p > q + + >>> (p, q) = find_p_q(128) + >>> from rsa import common + >>> common.bit_size(p * q) + 256 + + When not in accurate mode, the number of bits can be slightly less + + >>> (p, q) = find_p_q(128, accurate=False) + >>> from rsa import common + >>> common.bit_size(p * q) <= 256 + True + >>> common.bit_size(p * q) > 240 + True + + """ + + total_bits = nbits * 2 + + # Make sure that p and q aren't too close or the factoring programs can + # factor n. + shift = nbits // 16 + pbits = nbits + shift + qbits = nbits - shift + + # Choose the two initial primes + p = getprime_func(pbits) + q = getprime_func(qbits) + + def is_acceptable(p: int, q: int) -> bool: + """Returns True iff p and q are acceptable: + + - p and q differ + - (p * q) has the right nr of bits (when accurate=True) + """ + + if p == q: + return False + + if not accurate: + return True + + # Make sure we have just the right amount of bits + found_size = rsa.common.bit_size(p * q) + return total_bits == found_size + + # Keep choosing other primes until they match our requirements. + change_p = False + while not is_acceptable(p, q): + # Change p on one iteration and q on the other + if change_p: + p = getprime_func(pbits) + else: + q = getprime_func(qbits) + + change_p = not change_p + + # We want p > q as described on + # http://www.di-mgt.com.au/rsa_alg.html#crt + return max(p, q), min(p, q) + + +def calculate_keys_custom_exponent(p: int, q: int, exponent: int) -> typing.Tuple[int, int]: + """Calculates an encryption and a decryption key given p, q and an exponent, + and returns them as a tuple (e, d) + + :param p: the first large prime + :param q: the second large prime + :param exponent: the exponent for the key; only change this if you know + what you're doing, as the exponent influences how difficult your + private key can be cracked. A very common choice for e is 65537. + :type exponent: int + + """ + + phi_n = (p - 1) * (q - 1) + + try: + d = rsa.common.inverse(exponent, phi_n) + except rsa.common.NotRelativePrimeError as ex: + raise rsa.common.NotRelativePrimeError( + exponent, + phi_n, + ex.d, + msg="e (%d) and phi_n (%d) are not relatively prime (divider=%i)" + % (exponent, phi_n, ex.d), + ) from ex + + if (exponent * d) % phi_n != 1: + raise ValueError( + "e (%d) and d (%d) are not mult. inv. modulo " "phi_n (%d)" % (exponent, d, phi_n) + ) + + return exponent, d + + +def calculate_keys(p: int, q: int) -> typing.Tuple[int, int]: + """Calculates an encryption and a decryption key given p and q, and + returns them as a tuple (e, d) + + :param p: the first large prime + :param q: the second large prime + + :return: tuple (e, d) with the encryption and decryption exponents. + """ + + return calculate_keys_custom_exponent(p, q, DEFAULT_EXPONENT) + + +def gen_keys( + nbits: int, + getprime_func: typing.Callable[[int], int], + accurate: bool = True, + exponent: int = DEFAULT_EXPONENT, +) -> typing.Tuple[int, int, int, int]: + """Generate RSA keys of nbits bits. Returns (p, q, e, d). + + Note: this can take a long time, depending on the key size. + + :param nbits: the total number of bits in ``p`` and ``q``. Both ``p`` and + ``q`` will use ``nbits/2`` bits. + :param getprime_func: either :py:func:`rsa.prime.getprime` or a function + with similar signature. + :param exponent: the exponent for the key; only change this if you know + what you're doing, as the exponent influences how difficult your + private key can be cracked. A very common choice for e is 65537. + :type exponent: int + """ + + # Regenerate p and q values, until calculate_keys doesn't raise a + # ValueError. + while True: + (p, q) = find_p_q(nbits // 2, getprime_func, accurate) + try: + (e, d) = calculate_keys_custom_exponent(p, q, exponent=exponent) + break + except ValueError: + pass + + return p, q, e, d + + +def newkeys( + nbits: int, + accurate: bool = True, + poolsize: int = 1, + exponent: int = DEFAULT_EXPONENT, +) -> typing.Tuple[PublicKey, PrivateKey]: + """Generates public and private keys, and returns them as (pub, priv). + + The public key is also known as the 'encryption key', and is a + :py:class:`rsa.PublicKey` object. The private key is also known as the + 'decryption key' and is a :py:class:`rsa.PrivateKey` object. + + :param nbits: the number of bits required to store ``n = p*q``. + :param accurate: when True, ``n`` will have exactly the number of bits you + asked for. However, this makes key generation much slower. When False, + `n`` may have slightly less bits. + :param poolsize: the number of processes to use to generate the prime + numbers. If set to a number > 1, a parallel algorithm will be used. + This requires Python 2.6 or newer. + :param exponent: the exponent for the key; only change this if you know + what you're doing, as the exponent influences how difficult your + private key can be cracked. A very common choice for e is 65537. + :type exponent: int + + :returns: a tuple (:py:class:`rsa.PublicKey`, :py:class:`rsa.PrivateKey`) + + The ``poolsize`` parameter was added in *Python-RSA 3.1* and requires + Python 2.6 or newer. + + """ + + if nbits < 16: + raise ValueError("Key too small") + + if poolsize < 1: + raise ValueError("Pool size (%i) should be >= 1" % poolsize) + + # Determine which getprime function to use + if poolsize > 1: + from rsa import parallel + + def getprime_func(nbits: int) -> int: + return parallel.getprime(nbits, poolsize=poolsize) + + else: + getprime_func = rsa.prime.getprime + + # Generate the key components + (p, q, e, d) = gen_keys(nbits, getprime_func, accurate=accurate, exponent=exponent) + + # Create the key objects + n = p * q + + return (PublicKey(n, e), PrivateKey(n, e, d, p, q)) + + +__all__ = ["PublicKey", "PrivateKey", "newkeys"] + +if __name__ == "__main__": + import doctest + + try: + for count in range(100): + (failures, tests) = doctest.testmod() + if failures: + break + + if (count % 10 == 0 and count) or count == 1: + print("%i times" % count) + except KeyboardInterrupt: + print("Aborted") + else: + print("Doctests done") diff --git a/vllm/lib/python3.10/site-packages/rsa/parallel.py b/vllm/lib/python3.10/site-packages/rsa/parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..ab992480ff5b95400ee31643a60c1e93b876617e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/parallel.py @@ -0,0 +1,96 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Functions for parallel computation on multiple cores. + +Introduced in Python-RSA 3.1. + +.. note:: + + Requires Python 2.6 or newer. + +""" + +import multiprocessing as mp +from multiprocessing.connection import Connection + +import rsa.prime +import rsa.randnum + + +def _find_prime(nbits: int, pipe: Connection) -> None: + while True: + integer = rsa.randnum.read_random_odd_int(nbits) + + # Test for primeness + if rsa.prime.is_prime(integer): + pipe.send(integer) + return + + +def getprime(nbits: int, poolsize: int) -> int: + """Returns a prime number that can be stored in 'nbits' bits. + + Works in multiple threads at the same time. + + >>> p = getprime(128, 3) + >>> rsa.prime.is_prime(p-1) + False + >>> rsa.prime.is_prime(p) + True + >>> rsa.prime.is_prime(p+1) + False + + >>> from rsa import common + >>> common.bit_size(p) == 128 + True + + """ + + (pipe_recv, pipe_send) = mp.Pipe(duplex=False) + + # Create processes + try: + procs = [mp.Process(target=_find_prime, args=(nbits, pipe_send)) for _ in range(poolsize)] + # Start processes + for p in procs: + p.start() + + result = pipe_recv.recv() + finally: + pipe_recv.close() + pipe_send.close() + + # Terminate processes + for p in procs: + p.terminate() + + return result + + +__all__ = ["getprime"] + +if __name__ == "__main__": + print("Running doctests 1000x or until failure") + import doctest + + for count in range(100): + (failures, tests) = doctest.testmod() + if failures: + break + + if count % 10 == 0 and count: + print("%i times" % count) + + print("Doctests done") diff --git a/vllm/lib/python3.10/site-packages/rsa/pem.py b/vllm/lib/python3.10/site-packages/rsa/pem.py new file mode 100644 index 0000000000000000000000000000000000000000..eb9c0446fca6e6fe2cbb003585c1180002f2ea5a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/pem.py @@ -0,0 +1,134 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Functions that load and write PEM-encoded files.""" + +import base64 +import typing + +# Should either be ASCII strings or bytes. +FlexiText = typing.Union[str, bytes] + + +def _markers(pem_marker: FlexiText) -> typing.Tuple[bytes, bytes]: + """ + Returns the start and end PEM markers, as bytes. + """ + + if not isinstance(pem_marker, bytes): + pem_marker = pem_marker.encode("ascii") + + return ( + b"-----BEGIN " + pem_marker + b"-----", + b"-----END " + pem_marker + b"-----", + ) + + +def _pem_lines(contents: bytes, pem_start: bytes, pem_end: bytes) -> typing.Iterator[bytes]: + """Generator over PEM lines between pem_start and pem_end.""" + + in_pem_part = False + seen_pem_start = False + + for line in contents.splitlines(): + line = line.strip() + + # Skip empty lines + if not line: + continue + + # Handle start marker + if line == pem_start: + if in_pem_part: + raise ValueError('Seen start marker "%r" twice' % pem_start) + + in_pem_part = True + seen_pem_start = True + continue + + # Skip stuff before first marker + if not in_pem_part: + continue + + # Handle end marker + if in_pem_part and line == pem_end: + in_pem_part = False + break + + # Load fields + if b":" in line: + continue + + yield line + + # Do some sanity checks + if not seen_pem_start: + raise ValueError('No PEM start marker "%r" found' % pem_start) + + if in_pem_part: + raise ValueError('No PEM end marker "%r" found' % pem_end) + + +def load_pem(contents: FlexiText, pem_marker: FlexiText) -> bytes: + """Loads a PEM file. + + :param contents: the contents of the file to interpret + :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY' + when your file has '-----BEGIN RSA PRIVATE KEY-----' and + '-----END RSA PRIVATE KEY-----' markers. + + :return: the base64-decoded content between the start and end markers. + + @raise ValueError: when the content is invalid, for example when the start + marker cannot be found. + + """ + + # We want bytes, not text. If it's text, it can be converted to ASCII bytes. + if not isinstance(contents, bytes): + contents = contents.encode("ascii") + + (pem_start, pem_end) = _markers(pem_marker) + pem_lines = [line for line in _pem_lines(contents, pem_start, pem_end)] + + # Base64-decode the contents + pem = b"".join(pem_lines) + return base64.standard_b64decode(pem) + + +def save_pem(contents: bytes, pem_marker: FlexiText) -> bytes: + """Saves a PEM file. + + :param contents: the contents to encode in PEM format + :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY' + when your file has '-----BEGIN RSA PRIVATE KEY-----' and + '-----END RSA PRIVATE KEY-----' markers. + + :return: the base64-encoded content between the start and end markers, as bytes. + + """ + + (pem_start, pem_end) = _markers(pem_marker) + + b64 = base64.standard_b64encode(contents).replace(b"\n", b"") + pem_lines = [pem_start] + + for block_start in range(0, len(b64), 64): + block = b64[block_start : block_start + 64] + pem_lines.append(block) + + pem_lines.append(pem_end) + pem_lines.append(b"") + + return b"\n".join(pem_lines) diff --git a/vllm/lib/python3.10/site-packages/rsa/pkcs1.py b/vllm/lib/python3.10/site-packages/rsa/pkcs1.py new file mode 100644 index 0000000000000000000000000000000000000000..b7f54220186b57f59b6fcb3ac27cab441d20cd9d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/pkcs1.py @@ -0,0 +1,485 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Functions for PKCS#1 version 1.5 encryption and signing + +This module implements certain functionality from PKCS#1 version 1.5. For a +very clear example, read http://www.di-mgt.com.au/rsa_alg.html#pkcs1schemes + +At least 8 bytes of random padding is used when encrypting a message. This makes +these methods much more secure than the ones in the ``rsa`` module. + +WARNING: this module leaks information when decryption fails. The exceptions +that are raised contain the Python traceback information, which can be used to +deduce where in the process the failure occurred. DO NOT PASS SUCH INFORMATION +to your users. +""" + +import hashlib +import os +import sys +import typing +from hmac import compare_digest + +from . import common, transform, core, key + +if typing.TYPE_CHECKING: + HashType = hashlib._Hash +else: + HashType = typing.Any + +# ASN.1 codes that describe the hash algorithm used. +HASH_ASN1 = { + "MD5": b"\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10", + "SHA-1": b"\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14", + "SHA-224": b"\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c", + "SHA-256": b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20", + "SHA-384": b"\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30", + "SHA-512": b"\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40", +} + +HASH_METHODS: typing.Dict[str, typing.Callable[[], HashType]] = { + "MD5": hashlib.md5, + "SHA-1": hashlib.sha1, + "SHA-224": hashlib.sha224, + "SHA-256": hashlib.sha256, + "SHA-384": hashlib.sha384, + "SHA-512": hashlib.sha512, +} +"""Hash methods supported by this library.""" + + +if sys.version_info >= (3, 6): + # Python 3.6 introduced SHA3 support. + HASH_ASN1.update( + { + "SHA3-256": b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x08\x05\x00\x04\x20", + "SHA3-384": b"\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x09\x05\x00\x04\x30", + "SHA3-512": b"\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x0a\x05\x00\x04\x40", + } + ) + + HASH_METHODS.update( + { + "SHA3-256": hashlib.sha3_256, + "SHA3-384": hashlib.sha3_384, + "SHA3-512": hashlib.sha3_512, + } + ) + + +class CryptoError(Exception): + """Base class for all exceptions in this module.""" + + +class DecryptionError(CryptoError): + """Raised when decryption fails.""" + + +class VerificationError(CryptoError): + """Raised when verification fails.""" + + +def _pad_for_encryption(message: bytes, target_length: int) -> bytes: + r"""Pads the message for encryption, returning the padded message. + + :return: 00 02 RANDOM_DATA 00 MESSAGE + + >>> block = _pad_for_encryption(b'hello', 16) + >>> len(block) + 16 + >>> block[0:2] + b'\x00\x02' + >>> block[-6:] + b'\x00hello' + + """ + + max_msglength = target_length - 11 + msglength = len(message) + + if msglength > max_msglength: + raise OverflowError( + "%i bytes needed for message, but there is only" + " space for %i" % (msglength, max_msglength) + ) + + # Get random padding + padding = b"" + padding_length = target_length - msglength - 3 + + # We remove 0-bytes, so we'll end up with less padding than we've asked for, + # so keep adding data until we're at the correct length. + while len(padding) < padding_length: + needed_bytes = padding_length - len(padding) + + # Always read at least 8 bytes more than we need, and trim off the rest + # after removing the 0-bytes. This increases the chance of getting + # enough bytes, especially when needed_bytes is small + new_padding = os.urandom(needed_bytes + 5) + new_padding = new_padding.replace(b"\x00", b"") + padding = padding + new_padding[:needed_bytes] + + assert len(padding) == padding_length + + return b"".join([b"\x00\x02", padding, b"\x00", message]) + + +def _pad_for_signing(message: bytes, target_length: int) -> bytes: + r"""Pads the message for signing, returning the padded message. + + The padding is always a repetition of FF bytes. + + :return: 00 01 PADDING 00 MESSAGE + + >>> block = _pad_for_signing(b'hello', 16) + >>> len(block) + 16 + >>> block[0:2] + b'\x00\x01' + >>> block[-6:] + b'\x00hello' + >>> block[2:-6] + b'\xff\xff\xff\xff\xff\xff\xff\xff' + + """ + + max_msglength = target_length - 11 + msglength = len(message) + + if msglength > max_msglength: + raise OverflowError( + "%i bytes needed for message, but there is only" + " space for %i" % (msglength, max_msglength) + ) + + padding_length = target_length - msglength - 3 + + return b"".join([b"\x00\x01", padding_length * b"\xff", b"\x00", message]) + + +def encrypt(message: bytes, pub_key: key.PublicKey) -> bytes: + """Encrypts the given message using PKCS#1 v1.5 + + :param message: the message to encrypt. Must be a byte string no longer than + ``k-11`` bytes, where ``k`` is the number of bytes needed to encode + the ``n`` component of the public key. + :param pub_key: the :py:class:`rsa.PublicKey` to encrypt with. + :raise OverflowError: when the message is too large to fit in the padded + block. + + >>> from rsa import key, common + >>> (pub_key, priv_key) = key.newkeys(256) + >>> message = b'hello' + >>> crypto = encrypt(message, pub_key) + + The crypto text should be just as long as the public key 'n' component: + + >>> len(crypto) == common.byte_size(pub_key.n) + True + + """ + + keylength = common.byte_size(pub_key.n) + padded = _pad_for_encryption(message, keylength) + + payload = transform.bytes2int(padded) + encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n) + block = transform.int2bytes(encrypted, keylength) + + return block + + +def decrypt(crypto: bytes, priv_key: key.PrivateKey) -> bytes: + r"""Decrypts the given message using PKCS#1 v1.5 + + The decryption is considered 'failed' when the resulting cleartext doesn't + start with the bytes 00 02, or when the 00 byte between the padding and + the message cannot be found. + + :param crypto: the crypto text as returned by :py:func:`rsa.encrypt` + :param priv_key: the :py:class:`rsa.PrivateKey` to decrypt with. + :raise DecryptionError: when the decryption fails. No details are given as + to why the code thinks the decryption fails, as this would leak + information about the private key. + + + >>> import rsa + >>> (pub_key, priv_key) = rsa.newkeys(256) + + It works with strings: + + >>> crypto = encrypt(b'hello', pub_key) + >>> decrypt(crypto, priv_key) + b'hello' + + And with binary data: + + >>> crypto = encrypt(b'\x00\x00\x00\x00\x01', pub_key) + >>> decrypt(crypto, priv_key) + b'\x00\x00\x00\x00\x01' + + Altering the encrypted information will *likely* cause a + :py:class:`rsa.pkcs1.DecryptionError`. If you want to be *sure*, use + :py:func:`rsa.sign`. + + + .. warning:: + + Never display the stack trace of a + :py:class:`rsa.pkcs1.DecryptionError` exception. It shows where in the + code the exception occurred, and thus leaks information about the key. + It's only a tiny bit of information, but every bit makes cracking the + keys easier. + + >>> crypto = encrypt(b'hello', pub_key) + >>> crypto = crypto[0:5] + b'X' + crypto[6:] # change a byte + >>> decrypt(crypto, priv_key) + Traceback (most recent call last): + ... + rsa.pkcs1.DecryptionError: Decryption failed + + """ + + blocksize = common.byte_size(priv_key.n) + encrypted = transform.bytes2int(crypto) + decrypted = priv_key.blinded_decrypt(encrypted) + cleartext = transform.int2bytes(decrypted, blocksize) + + # Detect leading zeroes in the crypto. These are not reflected in the + # encrypted value (as leading zeroes do not influence the value of an + # integer). This fixes CVE-2020-13757. + if len(crypto) > blocksize: + # This is operating on public information, so doesn't need to be constant-time. + raise DecryptionError("Decryption failed") + + # If we can't find the cleartext marker, decryption failed. + cleartext_marker_bad = not compare_digest(cleartext[:2], b"\x00\x02") + + # Find the 00 separator between the padding and the message + sep_idx = cleartext.find(b"\x00", 2) + + # sep_idx indicates the position of the `\x00` separator that separates the + # padding from the actual message. The padding should be at least 8 bytes + # long (see https://tools.ietf.org/html/rfc8017#section-7.2.2 step 3), which + # means the separator should be at least at index 10 (because of the + # `\x00\x02` marker that precedes it). + sep_idx_bad = sep_idx < 10 + + anything_bad = cleartext_marker_bad | sep_idx_bad + if anything_bad: + raise DecryptionError("Decryption failed") + + return cleartext[sep_idx + 1 :] + + +def sign_hash(hash_value: bytes, priv_key: key.PrivateKey, hash_method: str) -> bytes: + """Signs a precomputed hash with the private key. + + Hashes the message, then signs the hash with the given key. This is known + as a "detached signature", because the message itself isn't altered. + + :param hash_value: A precomputed hash to sign (ignores message). + :param priv_key: the :py:class:`rsa.PrivateKey` to sign with + :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1', + 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'. + :return: a message signature block. + :raise OverflowError: if the private key is too small to contain the + requested hash. + + """ + + # Get the ASN1 code for this hash method + if hash_method not in HASH_ASN1: + raise ValueError("Invalid hash method: %s" % hash_method) + asn1code = HASH_ASN1[hash_method] + + # Encrypt the hash with the private key + cleartext = asn1code + hash_value + keylength = common.byte_size(priv_key.n) + padded = _pad_for_signing(cleartext, keylength) + + payload = transform.bytes2int(padded) + encrypted = priv_key.blinded_encrypt(payload) + block = transform.int2bytes(encrypted, keylength) + + return block + + +def sign(message: bytes, priv_key: key.PrivateKey, hash_method: str) -> bytes: + """Signs the message with the private key. + + Hashes the message, then signs the hash with the given key. This is known + as a "detached signature", because the message itself isn't altered. + + :param message: the message to sign. Can be an 8-bit string or a file-like + object. If ``message`` has a ``read()`` method, it is assumed to be a + file-like object. + :param priv_key: the :py:class:`rsa.PrivateKey` to sign with + :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1', + 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'. + :return: a message signature block. + :raise OverflowError: if the private key is too small to contain the + requested hash. + + """ + + msg_hash = compute_hash(message, hash_method) + return sign_hash(msg_hash, priv_key, hash_method) + + +def verify(message: bytes, signature: bytes, pub_key: key.PublicKey) -> str: + """Verifies that the signature matches the message. + + The hash method is detected automatically from the signature. + + :param message: the signed message. Can be an 8-bit string or a file-like + object. If ``message`` has a ``read()`` method, it is assumed to be a + file-like object. + :param signature: the signature block, as created with :py:func:`rsa.sign`. + :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message. + :raise VerificationError: when the signature doesn't match the message. + :returns: the name of the used hash. + + """ + + keylength = common.byte_size(pub_key.n) + encrypted = transform.bytes2int(signature) + decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n) + clearsig = transform.int2bytes(decrypted, keylength) + + # Get the hash method + method_name = _find_method_hash(clearsig) + message_hash = compute_hash(message, method_name) + + # Reconstruct the expected padded hash + cleartext = HASH_ASN1[method_name] + message_hash + expected = _pad_for_signing(cleartext, keylength) + + if len(signature) != keylength: + raise VerificationError("Verification failed") + + # Compare with the signed one + if expected != clearsig: + raise VerificationError("Verification failed") + + return method_name + + +def find_signature_hash(signature: bytes, pub_key: key.PublicKey) -> str: + """Returns the hash name detected from the signature. + + If you also want to verify the message, use :py:func:`rsa.verify()` instead. + It also returns the name of the used hash. + + :param signature: the signature block, as created with :py:func:`rsa.sign`. + :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message. + :returns: the name of the used hash. + """ + + keylength = common.byte_size(pub_key.n) + encrypted = transform.bytes2int(signature) + decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n) + clearsig = transform.int2bytes(decrypted, keylength) + + return _find_method_hash(clearsig) + + +def yield_fixedblocks(infile: typing.BinaryIO, blocksize: int) -> typing.Iterator[bytes]: + """Generator, yields each block of ``blocksize`` bytes in the input file. + + :param infile: file to read and separate in blocks. + :param blocksize: block size in bytes. + :returns: a generator that yields the contents of each block + """ + + while True: + block = infile.read(blocksize) + + read_bytes = len(block) + if read_bytes == 0: + break + + yield block + + if read_bytes < blocksize: + break + + +def compute_hash(message: typing.Union[bytes, typing.BinaryIO], method_name: str) -> bytes: + """Returns the message digest. + + :param message: the signed message. Can be an 8-bit string or a file-like + object. If ``message`` has a ``read()`` method, it is assumed to be a + file-like object. + :param method_name: the hash method, must be a key of + :py:const:`rsa.pkcs1.HASH_METHODS`. + + """ + + if method_name not in HASH_METHODS: + raise ValueError("Invalid hash method: %s" % method_name) + + method = HASH_METHODS[method_name] + hasher = method() + + if isinstance(message, bytes): + hasher.update(message) + else: + assert hasattr(message, "read") and hasattr(message.read, "__call__") + # read as 1K blocks + for block in yield_fixedblocks(message, 1024): + hasher.update(block) + + return hasher.digest() + + +def _find_method_hash(clearsig: bytes) -> str: + """Finds the hash method. + + :param clearsig: full padded ASN1 and hash. + :return: the used hash method. + :raise VerificationFailed: when the hash method cannot be found + """ + + for (hashname, asn1code) in HASH_ASN1.items(): + if asn1code in clearsig: + return hashname + + raise VerificationError("Verification failed") + + +__all__ = [ + "encrypt", + "decrypt", + "sign", + "verify", + "DecryptionError", + "VerificationError", + "CryptoError", +] + +if __name__ == "__main__": + print("Running doctests 1000x or until failure") + import doctest + + for count in range(1000): + (failures, tests) = doctest.testmod() + if failures: + break + + if count % 100 == 0 and count: + print("%i times" % count) + + print("Doctests done") diff --git a/vllm/lib/python3.10/site-packages/rsa/pkcs1_v2.py b/vllm/lib/python3.10/site-packages/rsa/pkcs1_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..cc2c3170421c854e3f5ae3e24a536a577569b9ab --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/pkcs1_v2.py @@ -0,0 +1,100 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Functions for PKCS#1 version 2 encryption and signing + +This module implements certain functionality from PKCS#1 version 2. Main +documentation is RFC 2437: https://tools.ietf.org/html/rfc2437 +""" + +from rsa import ( + common, + pkcs1, + transform, +) + + +def mgf1(seed: bytes, length: int, hasher: str = "SHA-1") -> bytes: + """ + MGF1 is a Mask Generation Function based on a hash function. + + A mask generation function takes an octet string of variable length and a + desired output length as input, and outputs an octet string of the desired + length. The plaintext-awareness of RSAES-OAEP relies on the random nature of + the output of the mask generation function, which in turn relies on the + random nature of the underlying hash. + + :param bytes seed: seed from which mask is generated, an octet string + :param int length: intended length in octets of the mask, at most 2^32(hLen) + :param str hasher: hash function (hLen denotes the length in octets of the hash + function output) + + :return: mask, an octet string of length `length` + :rtype: bytes + + :raise OverflowError: when `length` is too large for the specified `hasher` + :raise ValueError: when specified `hasher` is invalid + """ + + try: + hash_length = pkcs1.HASH_METHODS[hasher]().digest_size + except KeyError as ex: + raise ValueError( + "Invalid `hasher` specified. Please select one of: {hash_list}".format( + hash_list=", ".join(sorted(pkcs1.HASH_METHODS.keys())) + ) + ) from ex + + # If l > 2^32(hLen), output "mask too long" and stop. + if length > (2 ** 32 * hash_length): + raise OverflowError( + "Desired length should be at most 2**32 times the hasher's output " + "length ({hash_length} for {hasher} function)".format( + hash_length=hash_length, + hasher=hasher, + ) + ) + + # Looping `counter` from 0 to ceil(l / hLen)-1, build `output` based on the + # hashes formed by (`seed` + C), being `C` an octet string of length 4 + # generated by converting `counter` with the primitive I2OSP + output = b"".join( + pkcs1.compute_hash( + seed + transform.int2bytes(counter, fill_size=4), + method_name=hasher, + ) + for counter in range(common.ceil_div(length, hash_length) + 1) + ) + + # Output the leading `length` octets of `output` as the octet string mask. + return output[:length] + + +__all__ = [ + "mgf1", +] + +if __name__ == "__main__": + print("Running doctests 1000x or until failure") + import doctest + + for count in range(1000): + (failures, tests) = doctest.testmod() + if failures: + break + + if count % 100 == 0 and count: + print("%i times" % count) + + print("Doctests done") diff --git a/vllm/lib/python3.10/site-packages/rsa/prime.py b/vllm/lib/python3.10/site-packages/rsa/prime.py new file mode 100644 index 0000000000000000000000000000000000000000..481c4d77dbbfcc92c15fd2b5c088c4f264054895 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/prime.py @@ -0,0 +1,198 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Numerical functions related to primes. + +Implementation based on the book Algorithm Design by Michael T. Goodrich and +Roberto Tamassia, 2002. +""" + +import rsa.common +import rsa.randnum + +__all__ = ["getprime", "are_relatively_prime"] + + +def gcd(p: int, q: int) -> int: + """Returns the greatest common divisor of p and q + + >>> gcd(48, 180) + 12 + """ + + while q != 0: + (p, q) = (q, p % q) + return p + + +def get_primality_testing_rounds(number: int) -> int: + """Returns minimum number of rounds for Miller-Rabing primality testing, + based on number bitsize. + + According to NIST FIPS 186-4, Appendix C, Table C.3, minimum number of + rounds of M-R testing, using an error probability of 2 ** (-100), for + different p, q bitsizes are: + * p, q bitsize: 512; rounds: 7 + * p, q bitsize: 1024; rounds: 4 + * p, q bitsize: 1536; rounds: 3 + See: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf + """ + + # Calculate number bitsize. + bitsize = rsa.common.bit_size(number) + # Set number of rounds. + if bitsize >= 1536: + return 3 + if bitsize >= 1024: + return 4 + if bitsize >= 512: + return 7 + # For smaller bitsizes, set arbitrary number of rounds. + return 10 + + +def miller_rabin_primality_testing(n: int, k: int) -> bool: + """Calculates whether n is composite (which is always correct) or prime + (which theoretically is incorrect with error probability 4**-k), by + applying Miller-Rabin primality testing. + + For reference and implementation example, see: + https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test + + :param n: Integer to be tested for primality. + :type n: int + :param k: Number of rounds (witnesses) of Miller-Rabin testing. + :type k: int + :return: False if the number is composite, True if it's probably prime. + :rtype: bool + """ + + # prevent potential infinite loop when d = 0 + if n < 2: + return False + + # Decompose (n - 1) to write it as (2 ** r) * d + # While d is even, divide it by 2 and increase the exponent. + d = n - 1 + r = 0 + + while not (d & 1): + r += 1 + d >>= 1 + + # Test k witnesses. + for _ in range(k): + # Generate random integer a, where 2 <= a <= (n - 2) + a = rsa.randnum.randint(n - 3) + 1 + + x = pow(a, d, n) + if x == 1 or x == n - 1: + continue + + for _ in range(r - 1): + x = pow(x, 2, n) + if x == 1: + # n is composite. + return False + if x == n - 1: + # Exit inner loop and continue with next witness. + break + else: + # If loop doesn't break, n is composite. + return False + + return True + + +def is_prime(number: int) -> bool: + """Returns True if the number is prime, and False otherwise. + + >>> is_prime(2) + True + >>> is_prime(42) + False + >>> is_prime(41) + True + """ + + # Check for small numbers. + if number < 10: + return number in {2, 3, 5, 7} + + # Check for even numbers. + if not (number & 1): + return False + + # Calculate minimum number of rounds. + k = get_primality_testing_rounds(number) + + # Run primality testing with (minimum + 1) rounds. + return miller_rabin_primality_testing(number, k + 1) + + +def getprime(nbits: int) -> int: + """Returns a prime number that can be stored in 'nbits' bits. + + >>> p = getprime(128) + >>> is_prime(p-1) + False + >>> is_prime(p) + True + >>> is_prime(p+1) + False + + >>> from rsa import common + >>> common.bit_size(p) == 128 + True + """ + + assert nbits > 3 # the loop will hang on too small numbers + + while True: + integer = rsa.randnum.read_random_odd_int(nbits) + + # Test for primeness + if is_prime(integer): + return integer + + # Retry if not prime + + +def are_relatively_prime(a: int, b: int) -> bool: + """Returns True if a and b are relatively prime, and False if they + are not. + + >>> are_relatively_prime(2, 3) + True + >>> are_relatively_prime(2, 4) + False + """ + + d = gcd(a, b) + return d == 1 + + +if __name__ == "__main__": + print("Running doctests 1000x or until failure") + import doctest + + for count in range(1000): + (failures, tests) = doctest.testmod() + if failures: + break + + if count % 100 == 0 and count: + print("%i times" % count) + + print("Doctests done") diff --git a/vllm/lib/python3.10/site-packages/rsa/py.typed b/vllm/lib/python3.10/site-packages/rsa/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..bfd62201214101d8f7cf4d98890e22d3e8f93951 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. The rsa package uses inline types. diff --git a/vllm/lib/python3.10/site-packages/rsa/randnum.py b/vllm/lib/python3.10/site-packages/rsa/randnum.py new file mode 100644 index 0000000000000000000000000000000000000000..bb255c57703d91ef50469604f22165e58ce1e407 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/randnum.py @@ -0,0 +1,95 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Functions for generating random numbers.""" + +# Source inspired by code by Yesudeep Mangalapilly + +import os +import struct + +from rsa import common, transform + + +def read_random_bits(nbits: int) -> bytes: + """Reads 'nbits' random bits. + + If nbits isn't a whole number of bytes, an extra byte will be appended with + only the lower bits set. + """ + + nbytes, rbits = divmod(nbits, 8) + + # Get the random bytes + randomdata = os.urandom(nbytes) + + # Add the remaining random bits + if rbits > 0: + randomvalue = ord(os.urandom(1)) + randomvalue >>= 8 - rbits + randomdata = struct.pack("B", randomvalue) + randomdata + + return randomdata + + +def read_random_int(nbits: int) -> int: + """Reads a random integer of approximately nbits bits.""" + + randomdata = read_random_bits(nbits) + value = transform.bytes2int(randomdata) + + # Ensure that the number is large enough to just fill out the required + # number of bits. + value |= 1 << (nbits - 1) + + return value + + +def read_random_odd_int(nbits: int) -> int: + """Reads a random odd integer of approximately nbits bits. + + >>> read_random_odd_int(512) & 1 + 1 + """ + + value = read_random_int(nbits) + + # Make sure it's odd + return value | 1 + + +def randint(maxvalue: int) -> int: + """Returns a random integer x with 1 <= x <= maxvalue + + May take a very long time in specific situations. If maxvalue needs N bits + to store, the closer maxvalue is to (2 ** N) - 1, the faster this function + is. + """ + + bit_size = common.bit_size(maxvalue) + + tries = 0 + while True: + value = read_random_int(bit_size) + if value <= maxvalue: + break + + if tries % 10 == 0 and tries: + # After a lot of tries to get the right number of bits but still + # smaller than maxvalue, decrease the number of bits by 1. That'll + # dramatically increase the chances to get a large enough number. + bit_size -= 1 + tries += 1 + + return value diff --git a/vllm/lib/python3.10/site-packages/rsa/transform.py b/vllm/lib/python3.10/site-packages/rsa/transform.py new file mode 100644 index 0000000000000000000000000000000000000000..76ca8499c4d4fb37df2c0ef190e4c21a2ae493c2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/transform.py @@ -0,0 +1,72 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Data transformation functions. + +From bytes to a number, number to bytes, etc. +""" + +import math + + +def bytes2int(raw_bytes: bytes) -> int: + r"""Converts a list of bytes or an 8-bit string to an integer. + + When using unicode strings, encode it to some encoding like UTF8 first. + + >>> (((128 * 256) + 64) * 256) + 15 + 8405007 + >>> bytes2int(b'\x80@\x0f') + 8405007 + + """ + return int.from_bytes(raw_bytes, "big", signed=False) + + +def int2bytes(number: int, fill_size: int = 0) -> bytes: + """ + Convert an unsigned integer to bytes (big-endian):: + + Does not preserve leading zeros if you don't specify a fill size. + + :param number: + Integer value + :param fill_size: + If the optional fill size is given the length of the resulting + byte string is expected to be the fill size and will be padded + with prefix zero bytes to satisfy that length. + :returns: + Raw bytes (base-256 representation). + :raises: + ``OverflowError`` when fill_size is given and the number takes up more + bytes than fit into the block. This requires the ``overflow`` + argument to this function to be set to ``False`` otherwise, no + error will be raised. + """ + + if number < 0: + raise ValueError("Number must be an unsigned integer: %d" % number) + + bytes_required = max(1, math.ceil(number.bit_length() / 8)) + + if fill_size > 0: + return number.to_bytes(fill_size, "big") + + return number.to_bytes(bytes_required, "big") + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/vllm/lib/python3.10/site-packages/rsa/util.py b/vllm/lib/python3.10/site-packages/rsa/util.py new file mode 100644 index 0000000000000000000000000000000000000000..8a598ccabe7b068e3a065431864a8d8f2d928790 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/rsa/util.py @@ -0,0 +1,97 @@ +# Copyright 2011 Sybren A. Stüvel +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Utility functions.""" + +import sys +from optparse import OptionParser + +import rsa.key + + +def private_to_public() -> None: + """Reads a private key and outputs the corresponding public key.""" + + # Parse the CLI options + parser = OptionParser( + usage="usage: %prog [options]", + description="Reads a private key and outputs the " + "corresponding public key. Both private and public keys use " + "the format described in PKCS#1 v1.5", + ) + + parser.add_option( + "-i", + "--input", + dest="infilename", + type="string", + help="Input filename. Reads from stdin if not specified", + ) + parser.add_option( + "-o", + "--output", + dest="outfilename", + type="string", + help="Output filename. Writes to stdout of not specified", + ) + + parser.add_option( + "--inform", + dest="inform", + help="key format of input - default PEM", + choices=("PEM", "DER"), + default="PEM", + ) + + parser.add_option( + "--outform", + dest="outform", + help="key format of output - default PEM", + choices=("PEM", "DER"), + default="PEM", + ) + + (cli, cli_args) = parser.parse_args(sys.argv) + + # Read the input data + if cli.infilename: + print( + "Reading private key from %s in %s format" % (cli.infilename, cli.inform), + file=sys.stderr, + ) + with open(cli.infilename, "rb") as infile: + in_data = infile.read() + else: + print("Reading private key from stdin in %s format" % cli.inform, file=sys.stderr) + in_data = sys.stdin.read().encode("ascii") + + assert type(in_data) == bytes, type(in_data) + + # Take the public fields and create a public key + priv_key = rsa.key.PrivateKey.load_pkcs1(in_data, cli.inform) + pub_key = rsa.key.PublicKey(priv_key.n, priv_key.e) + + # Save to the output file + out_data = pub_key.save_pkcs1(cli.outform) + + if cli.outfilename: + print( + "Writing public key to %s in %s format" % (cli.outfilename, cli.outform), + file=sys.stderr, + ) + with open(cli.outfilename, "wb") as outfile: + outfile.write(out_data) + else: + print("Writing public key to stdout in %s format" % cli.outform, file=sys.stderr) + sys.stdout.write(out_data.decode("ascii")) diff --git a/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/INSTALLER b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/LICENSE b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..4555634d3e51beb788e94ac535d01b6482514a5b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/LICENSE @@ -0,0 +1,35 @@ +From xFormers: + +Copyright (c) Facebook, Inc. and its affiliates + + +=== + +BSD 3-Clause License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America + and IDIAP Research Institute nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +POSSIBILITY OF SUCH DAMAGE. diff --git a/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/METADATA b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..a956a0fc49ffafc7b07a55c1d00753d5e4b5ba66 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/METADATA @@ -0,0 +1,21 @@ +Metadata-Version: 2.1 +Name: xformers +Version: 0.0.28.post3 +Summary: XFormers: A collection of composable Transformer building blocks. +Home-page: https://facebookresearch.github.io/xformers/ +Author: Facebook AI Research +Author-email: oncall+xformers@xmail.facebook.com +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: License :: OSI Approved :: BSD License +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Operating System :: OS Independent +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: numpy +Requires-Dist: torch==2.5.1 + +XFormers: A collection of composable Transformer building blocks.XFormers aims at being able to reproduce most architectures in the Transformer-family SOTA,defined as compatible and combined building blocks as opposed to monolithic models diff --git a/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/RECORD b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..7f300389cc6324d225214f6c51c921be0f5a444e --- /dev/null +++ b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/RECORD @@ -0,0 +1,373 @@ +xformers-0.0.28.post3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +xformers-0.0.28.post3.dist-info/LICENSE,sha256=iwaVhtHd3wMc1GkkT2Y_GzmnThI1eC5iVcJJQ-ACt-o,1610 +xformers-0.0.28.post3.dist-info/METADATA,sha256=N6abyrP_cOV8tkpxSbHOTynvPNO4MHIC8WQU3gojjFU,1014 +xformers-0.0.28.post3.dist-info/RECORD,, +xformers-0.0.28.post3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +xformers-0.0.28.post3.dist-info/WHEEL,sha256=MxDuPpvkMaXLq_RQVb7oY7-yV_IeOYeifIMhtGld23w,114 +xformers-0.0.28.post3.dist-info/top_level.txt,sha256=4Px1VcGhKk0j3XhKXjA8HtTm6EQOb0hazeJ5nQsNlKk,9 +xformers/_C.so,sha256=nwn4NHfChZmFOXjCcxZj5Rfyf7oncUH_dNaswepcYMs,50942528 +xformers/__init__.py,sha256=TKDA28gOAQdAzwVvU9IEpGWz677QRKgVFmnqvngAg2w,1710 +xformers/__pycache__/__init__.cpython-310.pyc,, +xformers/__pycache__/_cpp_lib.cpython-310.pyc,, +xformers/__pycache__/_deprecation_warning.cpython-310.pyc,, +xformers/__pycache__/attn_bias_utils.cpython-310.pyc,, +xformers/__pycache__/checkpoint.cpython-310.pyc,, +xformers/__pycache__/info.cpython-310.pyc,, +xformers/__pycache__/test.cpython-310.pyc,, +xformers/__pycache__/utils.cpython-310.pyc,, +xformers/__pycache__/version.cpython-310.pyc,, +xformers/_cpp_lib.py,sha256=diLPbor1Tp80qZKvJLeoiYKYRfBf8UnsO2UbaMRuQLI,4958 +xformers/_deprecation_warning.py,sha256=a2-JfNsT7EGLG5ZFarz7GTdnMe6EA3cli4BNfr3Wtog,456 +xformers/_flash_attn/__init__.py,sha256=nsWkr1gPPxMV3ZfrC8Vcslhb7Z7ZHGsE--W46Od0luQ,285 +xformers/_flash_attn/__pycache__/__init__.cpython-310.pyc,, +xformers/_flash_attn/__pycache__/bert_padding.cpython-310.pyc,, +xformers/_flash_attn/__pycache__/flash_attn_interface.cpython-310.pyc,, +xformers/_flash_attn/__pycache__/flash_attn_triton.cpython-310.pyc,, +xformers/_flash_attn/__pycache__/flash_attn_triton_og.cpython-310.pyc,, +xformers/_flash_attn/__pycache__/flash_blocksparse_attention.cpython-310.pyc,, +xformers/_flash_attn/__pycache__/flash_blocksparse_attn_interface.cpython-310.pyc,, +xformers/_flash_attn/__pycache__/fused_softmax.cpython-310.pyc,, +xformers/_flash_attn/bert_padding.py,sha256=MYMu_Dg9AcnM4-D56X0QGxp5WieqJ045RAvC4kPFI5w,9535 +xformers/_flash_attn/flash_attn_interface.py,sha256=50ocGgMKfGorthN3M6fngQTlTb6x0H8G9KGJpV1JePM,47350 +xformers/_flash_attn/flash_attn_triton.py,sha256=Du81zbh8Ls70ExEsm00opziGvjGFfcZCoZDUO2zut9Q,41112 +xformers/_flash_attn/flash_attn_triton_og.py,sha256=LmvDju7LJG-wOYhoR6Zc2AmdPK2oWyB1VJpMjRhnWnE,11328 +xformers/_flash_attn/flash_blocksparse_attention.py,sha256=aJlttNZVxVaktCNYAfP5AdqeZDu8jv42_ZbTkRnDkWg,7469 +xformers/_flash_attn/flash_blocksparse_attn_interface.py,sha256=2qK2KvVCt851_j8ZzHvjS-aMfdgVDu1yne67-iScWfo,7265 +xformers/_flash_attn/fused_softmax.py,sha256=0-XbXo7R1a5h4-EpUzPy--lwlGytfTDW34WGM5nmBAY,7793 +xformers/_flash_attn/layers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +xformers/_flash_attn/layers/__pycache__/__init__.cpython-310.pyc,, +xformers/_flash_attn/layers/__pycache__/patch_embed.cpython-310.pyc,, +xformers/_flash_attn/layers/__pycache__/rotary.cpython-310.pyc,, +xformers/_flash_attn/layers/patch_embed.py,sha256=H58CgME_qSOPTZLOG08wFgrQS1j34pvNwMPrkTj3Ek4,2136 +xformers/_flash_attn/layers/rotary.py,sha256=RmDtuIpbFY-dqLATKwaPTjuVswcGJgL21_LvHwn2uw8,18874 +xformers/_flash_attn/losses/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +xformers/_flash_attn/losses/__pycache__/__init__.cpython-310.pyc,, +xformers/_flash_attn/losses/__pycache__/cross_entropy.cpython-310.pyc,, +xformers/_flash_attn/losses/cross_entropy.py,sha256=tj5IoeUZuSzA1_82UFr7o-1WuoHyKAc1gVS6fWzAbDQ,3197 +xformers/_flash_attn/models/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +xformers/_flash_attn/models/__pycache__/__init__.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/baichuan.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/bert.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/bigcode.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/btlm.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/falcon.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/gpt.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/gpt_neox.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/gptj.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/llama.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/opt.cpython-310.pyc,, +xformers/_flash_attn/models/__pycache__/vit.cpython-310.pyc,, +xformers/_flash_attn/models/baichuan.py,sha256=eFNWwoRQ02AIeQP0OoK8pNvYw0dqnHOshLigCQPkAEc,5730 +xformers/_flash_attn/models/bert.py,sha256=-y6wVYzAfDqWWeO6n-dLapT1scn0lIsadKJKFzn48Vg,33241 +xformers/_flash_attn/models/bigcode.py,sha256=mkYeItoJtmWVf2wKkUs5oXjwdbTdGSo5eHxi0-1maZ8,9383 +xformers/_flash_attn/models/btlm.py,sha256=d8YDjYTa2G1DutYu-YuVf15S_Dn6oKn8-HzERoersLA,4631 +xformers/_flash_attn/models/falcon.py,sha256=mA3wGv1a4zhbrUSlFNVVmTgVjiXc1sFTOi55eYpgSPo,6033 +xformers/_flash_attn/models/gpt.py,sha256=QGBMCw_osxD4VMMj1uC6TMlXlM5lIInxSUKmq5J5kSU,47669 +xformers/_flash_attn/models/gpt_neox.py,sha256=_704a9KQ2PcnID8uMV7yZ4ggjGlh1zZH5gszue6D1bI,5159 +xformers/_flash_attn/models/gptj.py,sha256=k2eqMNyMbU7CJVM_BHBjlKt0ByFz6ITSETqS1mJa89g,4436 +xformers/_flash_attn/models/llama.py,sha256=bDRI308iRpeJngZLrQlLTGYAmwYotqzUxnjBMirfn-k,16581 +xformers/_flash_attn/models/opt.py,sha256=L0ZIWKpSP44lcEbiVCzVT9un_5gFMAW6cvnS3KHcb-A,5164 +xformers/_flash_attn/models/vit.py,sha256=7i0WUI_jZvQ5TMoSKPPzf77ZcyMDfDJuQaINzXN_iQU,14074 +xformers/_flash_attn/modules/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +xformers/_flash_attn/modules/__pycache__/__init__.cpython-310.pyc,, +xformers/_flash_attn/modules/__pycache__/block.cpython-310.pyc,, +xformers/_flash_attn/modules/__pycache__/embedding.cpython-310.pyc,, +xformers/_flash_attn/modules/__pycache__/mha.cpython-310.pyc,, +xformers/_flash_attn/modules/__pycache__/mlp.cpython-310.pyc,, +xformers/_flash_attn/modules/block.py,sha256=WLi7JKj9_Zpk89ppzC7WTIoykJJ7TLOJbUSZePNnW1E,17349 +xformers/_flash_attn/modules/embedding.py,sha256=RCVeeiomlGNkLeQD8G6Udvex-NDI_xKD45hXjgZ2lbQ,8693 +xformers/_flash_attn/modules/mha.py,sha256=V6Ynog9pb_G9UVxetRjXlmWGExZlxmJkYVwAExXqUEk,43297 +xformers/_flash_attn/modules/mlp.py,sha256=G6KPQagfKq1DRn7hQRJ3OHznFJLZHj_PiidZE_zcLgg,6033 +xformers/_flash_attn/ops/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +xformers/_flash_attn/ops/__pycache__/__init__.cpython-310.pyc,, +xformers/_flash_attn/ops/__pycache__/activations.cpython-310.pyc,, +xformers/_flash_attn/ops/__pycache__/fused_dense.cpython-310.pyc,, +xformers/_flash_attn/ops/__pycache__/layer_norm.cpython-310.pyc,, +xformers/_flash_attn/ops/__pycache__/rms_norm.cpython-310.pyc,, +xformers/_flash_attn/ops/activations.py,sha256=4f9iruZ2SKJSmOlNQ9L3t5EpQ2tKJVlyy-iBBF6sMgs,3936 +xformers/_flash_attn/ops/fused_dense.py,sha256=ACJKqkIfxZibxI3nb5ycb3pXBKaL_CM63rUUyQYNAUE,27907 +xformers/_flash_attn/ops/layer_norm.py,sha256=zr7NXIm-2mtEynTp1CS0fbFGI2Mqdp41dY4AfDWF6EQ,22443 +xformers/_flash_attn/ops/rms_norm.py,sha256=XEnihcj0a4aSz4LO55m5iKGVn4HKTeKN8TIyHjuDgxI,3988 +xformers/_flash_attn/ops/triton/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1 +xformers/_flash_attn/ops/triton/__pycache__/__init__.cpython-310.pyc,, +xformers/_flash_attn/ops/triton/__pycache__/cross_entropy.cpython-310.pyc,, +xformers/_flash_attn/ops/triton/__pycache__/k_activations.cpython-310.pyc,, +xformers/_flash_attn/ops/triton/__pycache__/layer_norm.cpython-310.pyc,, +xformers/_flash_attn/ops/triton/__pycache__/linear.cpython-310.pyc,, +xformers/_flash_attn/ops/triton/__pycache__/mlp.cpython-310.pyc,, +xformers/_flash_attn/ops/triton/__pycache__/rotary.cpython-310.pyc,, +xformers/_flash_attn/ops/triton/cross_entropy.py,sha256=H2BMSRhivo-BW3uVFmvJD6WhivARqHDe9WbxgMJVqnQ,12454 +xformers/_flash_attn/ops/triton/k_activations.py,sha256=-Z3vIyO4JkqBMipKsPvhzmxljtBdIhJCsl_M-_ESqBo,4034 +xformers/_flash_attn/ops/triton/layer_norm.py,sha256=rNJwuijsZ6sKDtKHlkbT0qDzbi6vetVjjibpy9YRHFQ,35715 +xformers/_flash_attn/ops/triton/linear.py,sha256=OtRvKz8xdpl-7v3q_ZTaS9fdBt9XrzMyapgRr50uBbM,20841 +xformers/_flash_attn/ops/triton/mlp.py,sha256=_5lbZJFZg_pXeXYITGt4V_6LkB_yddClB_jt-diCOdw,6068 +xformers/_flash_attn/ops/triton/rotary.py,sha256=-uMWkh2DhbhZYRY2PeMWZ8x3lDbuYp0ljsgHYYP3NYk,8582 +xformers/_flash_attn/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +xformers/_flash_attn/utils/__pycache__/__init__.cpython-310.pyc,, +xformers/_flash_attn/utils/__pycache__/benchmark.cpython-310.pyc,, +xformers/_flash_attn/utils/__pycache__/distributed.cpython-310.pyc,, +xformers/_flash_attn/utils/__pycache__/generation.cpython-310.pyc,, +xformers/_flash_attn/utils/__pycache__/pretrained.cpython-310.pyc,, +xformers/_flash_attn/utils/benchmark.py,sha256=JDtzdVhFyMIQqs3edbcXdXnmDf-O7RVpmZmn2ZFCvI0,7369 +xformers/_flash_attn/utils/distributed.py,sha256=qhcybRXtslssuV9LYaQy37haPaPtklM4YUMDx9UvnnQ,5825 +xformers/_flash_attn/utils/generation.py,sha256=9IVPvkf_hlbsxCWgECUA03293qHxXzWDFCTAOdqbAVo,30694 +xformers/_flash_attn/utils/pretrained.py,sha256=VZ6qk90sBJA7M86gRzPsNc_CkQXkj5HyrJvwl0I355k,3246 +xformers/attn_bias_utils.py,sha256=2MD_FqAf7Xci5W7jbeu6E3IYxqj0-4q6aWSXA_qzhko,19178 +xformers/benchmarks/LRA/__init__.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198 +xformers/benchmarks/LRA/__pycache__/__init__.cpython-310.pyc,, +xformers/benchmarks/LRA/__pycache__/batch_fetch_results.cpython-310.pyc,, +xformers/benchmarks/LRA/__pycache__/batch_submit.cpython-310.pyc,, +xformers/benchmarks/LRA/__pycache__/run_grid_search.cpython-310.pyc,, +xformers/benchmarks/LRA/__pycache__/run_tasks.cpython-310.pyc,, +xformers/benchmarks/LRA/__pycache__/run_with_submitit.cpython-310.pyc,, +xformers/benchmarks/LRA/batch_fetch_results.py,sha256=QsTgzFU45VP636TPiewnVCKD57bOR_YkjZq2KjMLzqc,3508 +xformers/benchmarks/LRA/batch_submit.py,sha256=7BgzEgSCJNN4vaQ8m-hEY2x5DxSkaPzp_Jorr2fS5p4,1685 +xformers/benchmarks/LRA/code/__init__.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198 +xformers/benchmarks/LRA/code/__pycache__/__init__.cpython-310.pyc,, +xformers/benchmarks/LRA/code/__pycache__/dataset.cpython-310.pyc,, +xformers/benchmarks/LRA/code/__pycache__/model_wrapper.cpython-310.pyc,, +xformers/benchmarks/LRA/code/dataset.py,sha256=6iMOhcM8rY75Ub_t3fopBxGjo1zCWwSIRAC3eHqAsIs,1403 +xformers/benchmarks/LRA/code/model_wrapper.py,sha256=18YKbVAASeoaGZqhM-Ps3scvblLbVoImHWKJqY7CQjw,9777 +xformers/benchmarks/LRA/run_grid_search.py,sha256=yLhNnQv4HDbEdQVApCdJiZzFes9VeGZjPOafHAaZ5Ew,5327 +xformers/benchmarks/LRA/run_tasks.py,sha256=GZP6cUgE1ftpQrp2IOf-MWbYJFcokt9bsLA8Q6PNyIU,9294 +xformers/benchmarks/LRA/run_with_submitit.py,sha256=WUtQJLYWnVVcp6mbmBQuqiA3pdvayEpZzqEpW5FZRz0,4612 +xformers/benchmarks/__init__.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198 +xformers/benchmarks/__pycache__/__init__.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_attn_decoding.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_core.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_indexing.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_mem_eff_attention.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_merge_attentions.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_multi_head_dispatch.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_nystrom_utils.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_revnet.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_sddmm.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_sequence_parallel_fused.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_sp24.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_swiglu.cpython-310.pyc,, +xformers/benchmarks/__pycache__/benchmark_tiled_matmul.cpython-310.pyc,, +xformers/benchmarks/__pycache__/utils.cpython-310.pyc,, +xformers/benchmarks/benchmark_attn_decoding.py,sha256=Jp45OCalf0Wfk8WZ1y8NBqyccup9lSnFs9R1Oq6Gjqg,12368 +xformers/benchmarks/benchmark_core.py,sha256=83x0wl7ouGqRgECQiRE3kzTXQwXHP3uWpQHvqxJWBlw,8626 +xformers/benchmarks/benchmark_indexing.py,sha256=W55qQHBuwlEp98X3XzoCrlHQg7NF00b9gc52_qDzhSE,5288 +xformers/benchmarks/benchmark_mem_eff_attention.py,sha256=HG8mfTCy1oFOsnOOQZ8zOGrOWotRTFU0fVJ4d4_xn0M,10101 +xformers/benchmarks/benchmark_merge_attentions.py,sha256=_6iSEhJGoeljSrVbOdi-tncYHPQNE7lj1wrTQlubSLo,3042 +xformers/benchmarks/benchmark_multi_head_dispatch.py,sha256=1ZAnVLx9rIRzRxgOx50tSdGZSHveH-n4aTU7wjJnlUc,3365 +xformers/benchmarks/benchmark_nystrom_utils.py,sha256=mUML4twJT1LCoCwtvS_3isfcHDS4XTH18leB_kix-OY,3230 +xformers/benchmarks/benchmark_revnet.py,sha256=qG7SxXpoJ-bi5cajWukyft7qVprmVfqqtx9PRQqIdI8,2671 +xformers/benchmarks/benchmark_sddmm.py,sha256=Tvq1rgXpeaj7kGjCKn_6pX2QA7TOt_aNG-nLCYa9_Eo,3765 +xformers/benchmarks/benchmark_sequence_parallel_fused.py,sha256=-Ob3G3c0xTJs--bw5yZQ203UqY1maOtKM3K5ZCDB6tw,14454 +xformers/benchmarks/benchmark_sp24.py,sha256=xcp-cR8t7U5WGfvbDoZeDUoTLXD-w7vVQerfd2kybVw,4861 +xformers/benchmarks/benchmark_swiglu.py,sha256=UD6tmg4JaPYct6KLwqnE_7UsFewKY_GpgV8XZMa1hFM,4295 +xformers/benchmarks/benchmark_tiled_matmul.py,sha256=lo_y3IA-8a6cgcMv5w2bJjU_FQBcMFsmllUEod4hISw,3779 +xformers/benchmarks/utils.py,sha256=MsKzrEjOWbNEi3UMSN8nRSEXkheC5_Ho27J3ysg8r6A,24202 +xformers/checkpoint.py,sha256=PUYtKs1QE-3ZKoBfWhIT-aFHMD_uYJq4ZBNePE-Ug6o,20337 +xformers/components/__init__.py,sha256=vu5FoGbeQpZbcgBdQ0m8mtsmWfBv7TVAe6oynsk7JXs,3377 +xformers/components/__pycache__/__init__.cpython-310.pyc,, +xformers/components/__pycache__/activations.cpython-310.pyc,, +xformers/components/__pycache__/input_projection.cpython-310.pyc,, +xformers/components/__pycache__/multi_head_dispatch.cpython-310.pyc,, +xformers/components/__pycache__/patch_embedding.cpython-310.pyc,, +xformers/components/__pycache__/residual.cpython-310.pyc,, +xformers/components/__pycache__/reversible.cpython-310.pyc,, +xformers/components/__pycache__/simplicial_embedding.cpython-310.pyc,, +xformers/components/activations.py,sha256=_IZvFRgrwJsjZy4z-qbnjDl8P1PM4MOp3k00OvaO5b8,2002 +xformers/components/attention/__init__.py,sha256=DHcMUQ13ANJAL1sClBXu0f-wJOAprJeMByQBYG4NYJ0,3802 +xformers/components/attention/__pycache__/__init__.cpython-310.pyc,, +xformers/components/attention/__pycache__/_sputnik_sparse.cpython-310.pyc,, +xformers/components/attention/__pycache__/attention_mask.cpython-310.pyc,, +xformers/components/attention/__pycache__/attention_patterns.cpython-310.pyc,, +xformers/components/attention/__pycache__/base.cpython-310.pyc,, +xformers/components/attention/__pycache__/compositional.cpython-310.pyc,, +xformers/components/attention/__pycache__/core.cpython-310.pyc,, +xformers/components/attention/__pycache__/favor.cpython-310.pyc,, +xformers/components/attention/__pycache__/fourier_mix.cpython-310.pyc,, +xformers/components/attention/__pycache__/global_tokens.cpython-310.pyc,, +xformers/components/attention/__pycache__/lambda_layer.cpython-310.pyc,, +xformers/components/attention/__pycache__/linformer.cpython-310.pyc,, +xformers/components/attention/__pycache__/local.cpython-310.pyc,, +xformers/components/attention/__pycache__/nystrom.cpython-310.pyc,, +xformers/components/attention/__pycache__/ortho.cpython-310.pyc,, +xformers/components/attention/__pycache__/pooling.cpython-310.pyc,, +xformers/components/attention/__pycache__/random.cpython-310.pyc,, +xformers/components/attention/__pycache__/scaled_dot_product.cpython-310.pyc,, +xformers/components/attention/__pycache__/sparsity_config.cpython-310.pyc,, +xformers/components/attention/__pycache__/utils.cpython-310.pyc,, +xformers/components/attention/__pycache__/visual.cpython-310.pyc,, +xformers/components/attention/_sputnik_sparse.py,sha256=bibk2S-Coatt45gO9fzLTaAgUMKXbRi5U0eR_-QAbnw,3164 +xformers/components/attention/attention_mask.py,sha256=Y0zyM5JDnFzfE0TGPx4BxEeQlqIPX-XnZpO_lskQn4w,4585 +xformers/components/attention/attention_patterns.py,sha256=mZ-s8R-DS6XrOP_-ExZZku7XWVKUOEVfUdHpB9D5kek,9945 +xformers/components/attention/base.py,sha256=X8qmru_ln4eSac68rnYZzfAF3pbQDz5l6UxfRE-pR6Y,3305 +xformers/components/attention/compositional.py,sha256=H1prPE_o3Ymd_HbxBnjNWnz7vzYzA_9L5zgixpyWAlM,12954 +xformers/components/attention/core.py,sha256=1VvBVYQEhjfIroVpoTBbJ6W4cEjPIXOCJzWltnXQekE,7625 +xformers/components/attention/favor.py,sha256=55z-Hjv23fjwEGsRg8Qtyq7yX57C7Uz5czgIS19vLA4,6194 +xformers/components/attention/feature_maps/__init__.py,sha256=YT-iC15A-WTj9uy6etXp6tWNBDo3tolDjGDc-DYmzvA,592 +xformers/components/attention/feature_maps/__pycache__/__init__.cpython-310.pyc,, +xformers/components/attention/feature_maps/__pycache__/base.cpython-310.pyc,, +xformers/components/attention/feature_maps/__pycache__/softmax.cpython-310.pyc,, +xformers/components/attention/feature_maps/base.py,sha256=u4jzwUZludL_mFLYL6SzGFUFJGKkbHWYKE9iO5BzFzA,1672 +xformers/components/attention/feature_maps/softmax.py,sha256=tpI2yz8wk1fC1mv9zCHQpvc54ozSQTGJVBA37pvufqE,10606 +xformers/components/attention/fourier_mix.py,sha256=AKMjFgmSBomER9A8c9mbuERjnLR9KAcMafawRJ0eCko,1184 +xformers/components/attention/global_tokens.py,sha256=JkN_jrNesrgjd6G_JzFdokGZLEYKDTnYHHc5IOmzYAw,4091 +xformers/components/attention/lambda_layer.py,sha256=a15tl5a9VMi1NaKCrEps2-Tb46RaA0R_M6L8zAA0YiI,2814 +xformers/components/attention/linformer.py,sha256=U-lqxbOdbx3CXnX7swpUvYaZXKJUNrGxJT4_jiyNH1c,2491 +xformers/components/attention/local.py,sha256=MDUq0UDzP4NpUxJZ5gOtPeLT0bRcE6vsA3iMnylqg7g,3815 +xformers/components/attention/nystrom.py,sha256=Za5veGImsv9j-rnA0fAHd61TGyNnfdY6I1O4AKWgje0,11405 +xformers/components/attention/ortho.py,sha256=2FWSaeqZ5m3QdyL_-BYZtNNXSL4xQVo9LXLN0si7bOQ,12124 +xformers/components/attention/pooling.py,sha256=-KGQxK9gSPxILByF_OsEaQfJqLr9GwbwjcgbYXDmOwM,2490 +xformers/components/attention/random.py,sha256=0bcvaYreWLNeW3bA3fvuJXIZINxXW0hqw4hsFauQ--M,4131 +xformers/components/attention/scaled_dot_product.py,sha256=vUcRVzQT3ol6hIqrTcCudlaCru1W1ZcZgjaTIkl7Lr4,4504 +xformers/components/attention/sparsity_config.py,sha256=lZLGeKVcqnKVGKqkjE5Av2yGIHB5zZvU9IwrR3UrvZo,41608 +xformers/components/attention/utils.py,sha256=04aEVvDG9LjzD9NfsQ3Kj-kZSnMFCppCFrJx6NPoV8g,3803 +xformers/components/attention/visual.py,sha256=EiMRHtf10q7EnwQF_gKdXCp-BsMHj0yHeDCC6SKFx2Q,2929 +xformers/components/feedforward/__init__.py,sha256=rfrm9w6hHacyANVqlHpQj4NF5tZJUcmMWMvSbQMoT1g,2367 +xformers/components/feedforward/__pycache__/__init__.cpython-310.pyc,, +xformers/components/feedforward/__pycache__/base.cpython-310.pyc,, +xformers/components/feedforward/__pycache__/conv_mlp.cpython-310.pyc,, +xformers/components/feedforward/__pycache__/mixture_of_experts.cpython-310.pyc,, +xformers/components/feedforward/__pycache__/mlp.cpython-310.pyc,, +xformers/components/feedforward/base.py,sha256=YUgACRbibSrQom02k4JW5hoPgkhxJD6F40PKF5UWLaw,1594 +xformers/components/feedforward/conv_mlp.py,sha256=iZwK8xy8FN9KhqXde8WcbNitoEDA4ertlYo6E1ua6cE,3011 +xformers/components/feedforward/mixture_of_experts.py,sha256=Zci7y55TvQRGpmARVzsj7db8Y-xs1NVPioXP3nEkhr0,5343 +xformers/components/feedforward/mlp.py,sha256=u5z2uYfgyddrz4o-xdylqyNo8onRg34CGacRGtkCsAQ,1308 +xformers/components/input_projection.py,sha256=7oH2EfhMsujvjpXxIHzg5A3gT5xA0vJ2trb2-pZoh3g,3121 +xformers/components/multi_head_dispatch.py,sha256=53-Wl6AgY8h8uf6LjGl1TOw85G7ChKec1qWa6017ePU,10265 +xformers/components/patch_embedding.py,sha256=GpoaIBbVJ3ANUIOtTsHOHcjKXxekmg7ZCQqSNqbeezI,2400 +xformers/components/positional_embedding/__init__.py,sha256=sN-9Mk3SeY8snW70vqSedHYqmAwzi5hZjcOfHFNPJos,2755 +xformers/components/positional_embedding/__pycache__/__init__.cpython-310.pyc,, +xformers/components/positional_embedding/__pycache__/base.cpython-310.pyc,, +xformers/components/positional_embedding/__pycache__/param.cpython-310.pyc,, +xformers/components/positional_embedding/__pycache__/rotary.cpython-310.pyc,, +xformers/components/positional_embedding/__pycache__/sine.cpython-310.pyc,, +xformers/components/positional_embedding/__pycache__/vocab.cpython-310.pyc,, +xformers/components/positional_embedding/base.py,sha256=R9dgW6lgfqc_JKZwWSLKc6_NhOGAOPDKh4NvYhIbCDE,1069 +xformers/components/positional_embedding/param.py,sha256=mvvt_ZKrFL9ZogeuXO8RxFlKGIiaLBF1YE-XcwiZRfg,1544 +xformers/components/positional_embedding/rotary.py,sha256=_mYWMVhwNUdl62aMfrTOfY2W8P8fjqjXLcbrwB-aLEo,3274 +xformers/components/positional_embedding/sine.py,sha256=kOeakSCWG4KcI05C5Qouh9fpBHIunEI_-8EGDD-U_g8,1365 +xformers/components/positional_embedding/vocab.py,sha256=T-kvJyuU5HpB98_zuLUm2NLfhYsjW8zNnTCUqXhKi_4,1768 +xformers/components/residual.py,sha256=jTAnAytB9dZoXv-xEw9NBL2NnSqo3C68q9jlOpfS04I,5693 +xformers/components/reversible.py,sha256=JiqaElzMv-c16fbA2SJYCrj8LpjXgg1N8l9Uwtmfmuo,5390 +xformers/components/simplicial_embedding.py,sha256=qNWz-ZW7yVYhWNOcpmIuhbN8Vtz95IQAClHXNsDYTNM,2118 +xformers/cpp_lib.json,sha256=qWyhHc8R86em2g6SMnFyWU1keXCjhZ8QiIXt2n4OSsA,402 +xformers/factory/__init__.py,sha256=4DY_EmTQiTJLO1Ttk8H7cVNx92e6ZuFm8kW9E5Xod0A,617 +xformers/factory/__pycache__/__init__.cpython-310.pyc,, +xformers/factory/__pycache__/block_configs.cpython-310.pyc,, +xformers/factory/__pycache__/block_factory.cpython-310.pyc,, +xformers/factory/__pycache__/hydra_helper.cpython-310.pyc,, +xformers/factory/__pycache__/model_factory.cpython-310.pyc,, +xformers/factory/__pycache__/weight_init.cpython-310.pyc,, +xformers/factory/block_configs.py,sha256=Cy_lI_lDp8yfqnRxLrNpszGU1UzUljuw-1bIdNEgEpY,8175 +xformers/factory/block_factory.py,sha256=i6VSVQoku9qShZmdosawlLFyKCrrYEmP81ujGP9Fflc,12960 +xformers/factory/hydra_helper.py,sha256=5bP3myNgAai_J_Se69wVSkE1C5HGE2HZU_TW2xstgCA,1312 +xformers/factory/model_factory.py,sha256=F3qk8ZO-n0XLD8cPU6iRjvXik9IspoiCOrXr3N2wVos,11899 +xformers/factory/weight_init.py,sha256=DUZBhDIbkbtdk4GYzqp-Xu-yXjvWFueD3fOx4OhvqTE,9988 +xformers/helpers/__init__.py,sha256=3zcfxEo1NykSJOddz1xp2I_ftiTsyaT0xPe-zpRZP3c,263 +xformers/helpers/__pycache__/__init__.cpython-310.pyc,, +xformers/helpers/__pycache__/hierarchical_configs.cpython-310.pyc,, +xformers/helpers/__pycache__/test_utils.cpython-310.pyc,, +xformers/helpers/__pycache__/timm_sparse_attention.cpython-310.pyc,, +xformers/helpers/hierarchical_configs.py,sha256=sWNlYaxOI905dszrRlD8NNoj-gvXgtQWpygMyeZKsYM,3924 +xformers/helpers/test_utils.py,sha256=OMD0494dmlWHmU-xH-l7ssRimZkufofxrbeZj0qsly0,800 +xformers/helpers/timm_sparse_attention.py,sha256=E22N74lKwmAkwRX1SI4SZEpvxgBN1ZeJIYoVLvHnmro,1528 +xformers/info.py,sha256=EzzBOTz7vp1OUPDlFT5yBSs3ItqAzMhfK975bv-A2FM,2672 +xformers/ops/__init__.py,sha256=X7_uUyc_zxCAQplQBHG1Agb2Kh-qf8Tj67djP2dxddU,3501 +xformers/ops/__pycache__/__init__.cpython-310.pyc,, +xformers/ops/__pycache__/common.cpython-310.pyc,, +xformers/ops/__pycache__/differentiable_collectives.cpython-310.pyc,, +xformers/ops/__pycache__/indexing.cpython-310.pyc,, +xformers/ops/__pycache__/ipc.cpython-310.pyc,, +xformers/ops/__pycache__/modpar_layers.cpython-310.pyc,, +xformers/ops/__pycache__/rmsnorm.cpython-310.pyc,, +xformers/ops/__pycache__/rope_padded.cpython-310.pyc,, +xformers/ops/__pycache__/seqpar.cpython-310.pyc,, +xformers/ops/__pycache__/sequence_parallel_fused_ops.cpython-310.pyc,, +xformers/ops/__pycache__/sp24.cpython-310.pyc,, +xformers/ops/__pycache__/swiglu_op.cpython-310.pyc,, +xformers/ops/__pycache__/tiled_matmul.cpython-310.pyc,, +xformers/ops/__pycache__/unbind.cpython-310.pyc,, +xformers/ops/_triton/__init__.py,sha256=G7u-HQ1NEf-mlR3LN5qupDMVCHHA94H1S_aXoStfKOI,741 +xformers/ops/_triton/__pycache__/__init__.cpython-310.pyc,, +xformers/ops/_triton/__pycache__/k_index_select_cat.cpython-310.pyc,, +xformers/ops/_triton/__pycache__/k_scaled_index_add.cpython-310.pyc,, +xformers/ops/_triton/__pycache__/rmsnorm_kernels.cpython-310.pyc,, +xformers/ops/_triton/__pycache__/rope_padded_kernels.cpython-310.pyc,, +xformers/ops/_triton/__pycache__/tiled_matmul_kernels.cpython-310.pyc,, +xformers/ops/_triton/k_index_select_cat.py,sha256=_gFAuuUbKd_CH0Awkc_sspxE0lmd4Y-gLndLu3G3brA,6194 +xformers/ops/_triton/k_scaled_index_add.py,sha256=KCEgK-9s_A1jdEVvBn84GlA4py7ZBrQSuxWyYaJG_jc,12802 +xformers/ops/_triton/rmsnorm_kernels.py,sha256=5Q8hW66p_vmKyDWiGKpO5OLMdl5T8BD1JzrGgLa_vHs,5254 +xformers/ops/_triton/rope_padded_kernels.py,sha256=4eto-GxPRBJDK9Bu_iuXaBh1jZ0wqOQANT8WKlRlH9s,7350 +xformers/ops/_triton/tiled_matmul_kernels.py,sha256=kPgBpMf8uz52eaP4-WoR82Wv5NK2GM4qdV2Rjf52DTk,13808 +xformers/ops/common.py,sha256=bgeQP7DxTkWhj_xiM-GUZ7QBoxRzg-VY3NfEOns5hhs,1911 +xformers/ops/differentiable_collectives.py,sha256=moSee9BpQDlfXgEq_P3IqxYcF9NjJGi8jbge_cJ9yGI,5356 +xformers/ops/fmha/__init__.py,sha256=68Igupx4OHt73ZRjykX7fnqBjR8ezimcKclpmB_CfWI,30478 +xformers/ops/fmha/__pycache__/__init__.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/attn_bias.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/ck.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/ck_decoder.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/ck_splitk.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/common.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/cutlass.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/dispatch.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/flash.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/flash3.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/torch_attention_compat.cpython-310.pyc,, +xformers/ops/fmha/__pycache__/triton_splitk.cpython-310.pyc,, +xformers/ops/fmha/_triton/__init__.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198 +xformers/ops/fmha/_triton/__pycache__/__init__.cpython-310.pyc,, +xformers/ops/fmha/_triton/__pycache__/splitk_kernels.cpython-310.pyc,, +xformers/ops/fmha/_triton/splitk_kernels.py,sha256=-xRJc2px_DXrkLekPeDIgcekKDqkY_eET2p1tzw3KeA,40672 +xformers/ops/fmha/attn_bias.py,sha256=8y1qek-riIuV-Ek78EMSMDaaDjQokxDCW1n0UzdFNMI,60332 +xformers/ops/fmha/ck.py,sha256=UMspvNjMdgWEG86_kuwAh3yXbMqN63Oj7JzxXplgTtI,17057 +xformers/ops/fmha/ck_decoder.py,sha256=3Lm0DA4TYgBu7KmlKEntnaDSL21iv__d3-z-BH5RAB4,5092 +xformers/ops/fmha/ck_splitk.py,sha256=4_kVxgiKM0YBUsQaWV071I6y4kDNmNore47rAZ_i-oc,6411 +xformers/ops/fmha/common.py,sha256=pw-pcpErmjfHJxL6LgxLm2hWTtn6UbVkvD4JrTia9MI,18579 +xformers/ops/fmha/cutlass.py,sha256=7QrJuAY1YlzEX__nH4B7lLwCMwCBs11Ykb0pnESiYyI,17611 +xformers/ops/fmha/dispatch.py,sha256=BpkB5kFQkqjEZ_93olV5FMn2SRfH5Cl_UT4rKix9KP4,6334 +xformers/ops/fmha/flash.py,sha256=1TCe6z89MDsf7LLUrnIps9XR1g-NgDTol19Hh6e4zsI,28942 +xformers/ops/fmha/flash3.py,sha256=JNLwxQgCXtkVuZ0zrmJM4itPPLitmmaaAyQTAxMT8a4,13492 +xformers/ops/fmha/torch_attention_compat.py,sha256=ifY6vGyzG2oQtCkAr276Wm8Y9U3gEGsoSvfBYZ3WK5w,5594 +xformers/ops/fmha/triton_splitk.py,sha256=8bqMisrKRfncHFr8WkNRigQuSu-oFtGup9ru2fG5Orw,36605 +xformers/ops/indexing.py,sha256=uQDU1rqgh-huDvOdtMekgSQSMXVndrC0n3vn8CFHNrI,6927 +xformers/ops/ipc.py,sha256=Q5YRa5G1LrAbm8syGZiSBzPvMqQEvR-gqML6t_18G-0,6649 +xformers/ops/modpar_layers.py,sha256=gOg2cAn3G-xhp1bQTM33dA1adQc5bmZp6v-jF4bh_sM,5703 +xformers/ops/rmsnorm.py,sha256=ofNCqraOJZBt_z1WoTMuW5HgfCr2wpJ_zkL_b0e-n2s,3358 +xformers/ops/rope_padded.py,sha256=bI6JCNHO0Rggp9oYW23KV4ONsoPqk4tGT3EGejqRZvY,12100 +xformers/ops/seqpar.py,sha256=dTNVh1DPAYJeOP-dmopGEuulQQ9WjLvo7BU0B7Y8zcU,12063 +xformers/ops/sequence_parallel_fused_ops.py,sha256=UVaJf0onPork4jw5LAVqa0-h-jryu0jpLdwevhQuSog,36973 +xformers/ops/sp24.py,sha256=6UNvf_85rVxpRKEe6NMqXRA49tnG97Bbw9SPXi3G27k,27950 +xformers/ops/swiglu_op.py,sha256=xD_XCCgipIwdmzaljY5BtoAcokSIyYX2cjEgjG8LdRg,17456 +xformers/ops/tiled_matmul.py,sha256=mzGdPYDKIBwgwitOOo0R6ld_Q5wtm4mHawElx3bMPqY,12792 +xformers/ops/unbind.py,sha256=KWEif28duVWbzj14bL-O3jJTxMuTZPvuGqCkZQhsgYQ,3925 +xformers/profiler/__init__.py,sha256=4jTj_MGJ-HkCkHwkx6QneBm27dMMPxvNa6kLwro86bk,421 +xformers/profiler/__pycache__/__init__.cpython-310.pyc,, +xformers/profiler/__pycache__/api.cpython-310.pyc,, +xformers/profiler/__pycache__/device_limits.cpython-310.pyc,, +xformers/profiler/__pycache__/find_slowest.cpython-310.pyc,, +xformers/profiler/__pycache__/profile_analyzer.cpython-310.pyc,, +xformers/profiler/__pycache__/profiler.cpython-310.pyc,, +xformers/profiler/__pycache__/profiler_dcgm.cpython-310.pyc,, +xformers/profiler/__pycache__/profiler_dcgm_impl.cpython-310.pyc,, +xformers/profiler/api.py,sha256=t-Cp6VqSEBk7Nm0zChnpJSIAKCMuY7VoYn9mySna7xQ,2685 +xformers/profiler/device_limits.py,sha256=HzPTO6bHMk7HxHelSh3A0Bk8qyuxL3-SsFYGBXdjT6c,3588 +xformers/profiler/find_slowest.py,sha256=DFHw8ybAb1eqXWjYqs5U1ZQ48CoIIqbjC8RoX2QGI_Y,6004 +xformers/profiler/profile_analyzer.py,sha256=v1TKzsE9lm5kkFoCLCXbmc3XMSG_7QD_J3QbeqmyYLc,8717 +xformers/profiler/profiler.py,sha256=sD_9eoeKttMBVfqhODw5LIzp4MYFNx8t7xC4qp5hAYw,12756 +xformers/profiler/profiler_dcgm.py,sha256=1NWMET7oVtUoBYhEFoQ-F17s1B8xmqcrL3Hjddry-H0,1153 +xformers/profiler/profiler_dcgm_impl.py,sha256=umLRJQCYOIyYHwFsyXDk9eNmbs4DUmuvAwe6tUahN6k,8472 +xformers/sparse/__init__.py,sha256=NpDMLawDg0ra3mR7LpNnkua8KOpeY6h2AL4or88rGws,317 +xformers/sparse/__pycache__/__init__.cpython-310.pyc,, +xformers/sparse/__pycache__/_csr_ops.cpython-310.pyc,, +xformers/sparse/__pycache__/blocksparse_tensor.cpython-310.pyc,, +xformers/sparse/__pycache__/csr_tensor.cpython-310.pyc,, +xformers/sparse/__pycache__/utils.cpython-310.pyc,, +xformers/sparse/_csr_ops.py,sha256=p8bGD91Y52LuYieY97ZCtlOpYFNnnPRjXDuBoK5_Bp0,4873 +xformers/sparse/blocksparse_tensor.py,sha256=5f1iIqrK_R0cza1anOIJo4CkaMIUo1WbMlJ0LjPbd8s,8894 +xformers/sparse/csr_tensor.py,sha256=TZbVB4aP0WVG2Gr8gB3orkPbNWdjeGxktxYzHAvkYfc,14191 +xformers/sparse/utils.py,sha256=f52XNuTj8gsi5YZABkYeMykMWRGmBnHjIkXM4gzXTdM,4274 +xformers/test.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198 +xformers/triton/__init__.py,sha256=BBoPvMfJjZ0Fi25JCRS8sPYUfLbHneLncV3JeGDIGHg,198 +xformers/triton/__pycache__/__init__.cpython-310.pyc,, +xformers/triton/__pycache__/vararg_kernel.cpython-310.pyc,, +xformers/triton/vararg_kernel.py,sha256=cJxRdMCIf2-fOqGKoCPOA54YjUs5d1KsN4-BbHhz9RE,6542 +xformers/utils.py,sha256=eCX-EDLXtb0pOvQAeQVwC8LiMqeBiX2NEyb89jqEVas,5064 +xformers/version.py,sha256=1LfsHAFttAgDDCXROlyBl91uXsK5xuONYMKLhXMH760,42 diff --git a/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/REQUESTED b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/WHEEL b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..c2706069fff11c40bb8ee0efb346aa2ad7a59b88 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.44.0) +Root-Is-Purelib: false +Tag: cp310-cp310-manylinux_2_28_x86_64 + diff --git a/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/top_level.txt b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..56e3c822be24e7529619f4406fbfb2ad6dfae3fd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/xformers-0.0.28.post3.dist-info/top_level.txt @@ -0,0 +1 @@ +xformers