ZTWHHH commited on
Commit
e1453cc
·
verified ·
1 Parent(s): 71bc75d

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc +0 -0
  2. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc +0 -0
  3. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc +0 -0
  4. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc +0 -0
  5. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc +0 -0
  6. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc +0 -0
  7. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_spfuncs.cpython-310.pyc +0 -0
  8. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc +0 -0
  9. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc +0 -0
  10. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc +0 -0
  11. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc +0 -0
  12. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc +0 -0
  13. parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc +0 -0
  14. parrot/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py +562 -0
  15. parrot/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py +81 -0
  16. parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/minres.cpython-310.pyc +0 -0
  17. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/BinaryOps.h +129 -0
  18. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/DispatchStub.h +315 -0
  19. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/GridSampler.h +298 -0
  20. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/GridSamplerUtils.h +109 -0
  21. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/Math.h +0 -0
  22. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/MaxPooling.h +42 -0
  23. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/NonEmptyUtils.h +27 -0
  24. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/Padding.h +62 -0
  25. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/PointwiseOps.h +28 -0
  26. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/Pow.h +69 -0
  27. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/ReduceAllOps.h +16 -0
  28. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/ReduceOps.h +56 -0
  29. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/ResizeCommon.h +75 -0
  30. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/SparseTensorUtils.h +184 -0
  31. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/TensorFactories.h +140 -0
  32. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/TriangularOpsUtils.h +57 -0
  33. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/AffineQuantizer.h +130 -0
  34. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/FakeQuantAffine.h +67 -0
  35. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/IndexKernel.h +14 -0
  36. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/PackedParams.h +147 -0
  37. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/cpu/QuantUtils.h +239 -0
  38. videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/cpu/init_qnnpack.h +13 -0
  39. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/bbp_pi.cpython-310.pyc +0 -0
  40. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/continued_fraction.cpython-310.pyc +0 -0
  41. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc +0 -0
  43. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc +0 -0
  45. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc +0 -0
  46. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc +0 -0
  47. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc +0 -0
  48. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc +0 -0
  49. vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc +0 -0
  50. vllm/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py +190 -0
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_construct.cpython-310.pyc ADDED
Binary file (42.8 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_data.cpython-310.pyc ADDED
Binary file (15.8 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_dia.cpython-310.pyc ADDED
Binary file (15.2 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_extract.cpython-310.pyc ADDED
Binary file (4.97 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_lil.cpython-310.pyc ADDED
Binary file (18.6 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_matrix.cpython-310.pyc ADDED
Binary file (4.21 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/_spfuncs.cpython-310.pyc ADDED
Binary file (1.81 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/base.cpython-310.pyc ADDED
Binary file (770 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/bsr.cpython-310.pyc ADDED
Binary file (771 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/compressed.cpython-310.pyc ADDED
Binary file (934 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/csc.cpython-310.pyc ADDED
Binary file (635 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/dia.cpython-310.pyc ADDED
Binary file (691 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/__pycache__/sparsetools.cpython-310.pyc ADDED
Binary file (632 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/sparse/csgraph/_laplacian.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Laplacian of a compressed-sparse graph
3
+ """
4
+
5
+ import numpy as np
6
+ from scipy.sparse import issparse
7
+ from scipy.sparse.linalg import LinearOperator
8
+ from scipy.sparse._sputils import convert_pydata_sparse_to_scipy, is_pydata_spmatrix
9
+
10
+
11
+ ###############################################################################
12
+ # Graph laplacian
13
+ def laplacian(
14
+ csgraph,
15
+ normed=False,
16
+ return_diag=False,
17
+ use_out_degree=False,
18
+ *,
19
+ copy=True,
20
+ form="array",
21
+ dtype=None,
22
+ symmetrized=False,
23
+ ):
24
+ """
25
+ Return the Laplacian of a directed graph.
26
+
27
+ Parameters
28
+ ----------
29
+ csgraph : array_like or sparse matrix, 2 dimensions
30
+ compressed-sparse graph, with shape (N, N).
31
+ normed : bool, optional
32
+ If True, then compute symmetrically normalized Laplacian.
33
+ Default: False.
34
+ return_diag : bool, optional
35
+ If True, then also return an array related to vertex degrees.
36
+ Default: False.
37
+ use_out_degree : bool, optional
38
+ If True, then use out-degree instead of in-degree.
39
+ This distinction matters only if the graph is asymmetric.
40
+ Default: False.
41
+ copy: bool, optional
42
+ If False, then change `csgraph` in place if possible,
43
+ avoiding doubling the memory use.
44
+ Default: True, for backward compatibility.
45
+ form: 'array', or 'function', or 'lo'
46
+ Determines the format of the output Laplacian:
47
+
48
+ * 'array' is a numpy array;
49
+ * 'function' is a pointer to evaluating the Laplacian-vector
50
+ or Laplacian-matrix product;
51
+ * 'lo' results in the format of the `LinearOperator`.
52
+
53
+ Choosing 'function' or 'lo' always avoids doubling
54
+ the memory use, ignoring `copy` value.
55
+ Default: 'array', for backward compatibility.
56
+ dtype: None or one of numeric numpy dtypes, optional
57
+ The dtype of the output. If ``dtype=None``, the dtype of the
58
+ output matches the dtype of the input csgraph, except for
59
+ the case ``normed=True`` and integer-like csgraph, where
60
+ the output dtype is 'float' allowing accurate normalization,
61
+ but dramatically increasing the memory use.
62
+ Default: None, for backward compatibility.
63
+ symmetrized: bool, optional
64
+ If True, then the output Laplacian is symmetric/Hermitian.
65
+ The symmetrization is done by ``csgraph + csgraph.T.conj``
66
+ without dividing by 2 to preserve integer dtypes if possible
67
+ prior to the construction of the Laplacian.
68
+ The symmetrization will increase the memory footprint of
69
+ sparse matrices unless the sparsity pattern is symmetric or
70
+ `form` is 'function' or 'lo'.
71
+ Default: False, for backward compatibility.
72
+
73
+ Returns
74
+ -------
75
+ lap : ndarray, or sparse matrix, or `LinearOperator`
76
+ The N x N Laplacian of csgraph. It will be a NumPy array (dense)
77
+ if the input was dense, or a sparse matrix otherwise, or
78
+ the format of a function or `LinearOperator` if
79
+ `form` equals 'function' or 'lo', respectively.
80
+ diag : ndarray, optional
81
+ The length-N main diagonal of the Laplacian matrix.
82
+ For the normalized Laplacian, this is the array of square roots
83
+ of vertex degrees or 1 if the degree is zero.
84
+
85
+ Notes
86
+ -----
87
+ The Laplacian matrix of a graph is sometimes referred to as the
88
+ "Kirchhoff matrix" or just the "Laplacian", and is useful in many
89
+ parts of spectral graph theory.
90
+ In particular, the eigen-decomposition of the Laplacian can give
91
+ insight into many properties of the graph, e.g.,
92
+ is commonly used for spectral data embedding and clustering.
93
+
94
+ The constructed Laplacian doubles the memory use if ``copy=True`` and
95
+ ``form="array"`` which is the default.
96
+ Choosing ``copy=False`` has no effect unless ``form="array"``
97
+ or the matrix is sparse in the ``coo`` format, or dense array, except
98
+ for the integer input with ``normed=True`` that forces the float output.
99
+
100
+ Sparse input is reformatted into ``coo`` if ``form="array"``,
101
+ which is the default.
102
+
103
+ If the input adjacency matrix is not symmetric, the Laplacian is
104
+ also non-symmetric unless ``symmetrized=True`` is used.
105
+
106
+ Diagonal entries of the input adjacency matrix are ignored and
107
+ replaced with zeros for the purpose of normalization where ``normed=True``.
108
+ The normalization uses the inverse square roots of row-sums of the input
109
+ adjacency matrix, and thus may fail if the row-sums contain
110
+ negative or complex with a non-zero imaginary part values.
111
+
112
+ The normalization is symmetric, making the normalized Laplacian also
113
+ symmetric if the input csgraph was symmetric.
114
+
115
+ References
116
+ ----------
117
+ .. [1] Laplacian matrix. https://en.wikipedia.org/wiki/Laplacian_matrix
118
+
119
+ Examples
120
+ --------
121
+ >>> import numpy as np
122
+ >>> from scipy.sparse import csgraph
123
+
124
+ Our first illustration is the symmetric graph
125
+
126
+ >>> G = np.arange(4) * np.arange(4)[:, np.newaxis]
127
+ >>> G
128
+ array([[0, 0, 0, 0],
129
+ [0, 1, 2, 3],
130
+ [0, 2, 4, 6],
131
+ [0, 3, 6, 9]])
132
+
133
+ and its symmetric Laplacian matrix
134
+
135
+ >>> csgraph.laplacian(G)
136
+ array([[ 0, 0, 0, 0],
137
+ [ 0, 5, -2, -3],
138
+ [ 0, -2, 8, -6],
139
+ [ 0, -3, -6, 9]])
140
+
141
+ The non-symmetric graph
142
+
143
+ >>> G = np.arange(9).reshape(3, 3)
144
+ >>> G
145
+ array([[0, 1, 2],
146
+ [3, 4, 5],
147
+ [6, 7, 8]])
148
+
149
+ has different row- and column sums, resulting in two varieties
150
+ of the Laplacian matrix, using an in-degree, which is the default
151
+
152
+ >>> L_in_degree = csgraph.laplacian(G)
153
+ >>> L_in_degree
154
+ array([[ 9, -1, -2],
155
+ [-3, 8, -5],
156
+ [-6, -7, 7]])
157
+
158
+ or alternatively an out-degree
159
+
160
+ >>> L_out_degree = csgraph.laplacian(G, use_out_degree=True)
161
+ >>> L_out_degree
162
+ array([[ 3, -1, -2],
163
+ [-3, 8, -5],
164
+ [-6, -7, 13]])
165
+
166
+ Constructing a symmetric Laplacian matrix, one can add the two as
167
+
168
+ >>> L_in_degree + L_out_degree.T
169
+ array([[ 12, -4, -8],
170
+ [ -4, 16, -12],
171
+ [ -8, -12, 20]])
172
+
173
+ or use the ``symmetrized=True`` option
174
+
175
+ >>> csgraph.laplacian(G, symmetrized=True)
176
+ array([[ 12, -4, -8],
177
+ [ -4, 16, -12],
178
+ [ -8, -12, 20]])
179
+
180
+ that is equivalent to symmetrizing the original graph
181
+
182
+ >>> csgraph.laplacian(G + G.T)
183
+ array([[ 12, -4, -8],
184
+ [ -4, 16, -12],
185
+ [ -8, -12, 20]])
186
+
187
+ The goal of normalization is to make the non-zero diagonal entries
188
+ of the Laplacian matrix to be all unit, also scaling off-diagonal
189
+ entries correspondingly. The normalization can be done manually, e.g.,
190
+
191
+ >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]])
192
+ >>> L, d = csgraph.laplacian(G, return_diag=True)
193
+ >>> L
194
+ array([[ 2, -1, -1],
195
+ [-1, 2, -1],
196
+ [-1, -1, 2]])
197
+ >>> d
198
+ array([2, 2, 2])
199
+ >>> scaling = np.sqrt(d)
200
+ >>> scaling
201
+ array([1.41421356, 1.41421356, 1.41421356])
202
+ >>> (1/scaling)*L*(1/scaling)
203
+ array([[ 1. , -0.5, -0.5],
204
+ [-0.5, 1. , -0.5],
205
+ [-0.5, -0.5, 1. ]])
206
+
207
+ Or using ``normed=True`` option
208
+
209
+ >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True)
210
+ >>> L
211
+ array([[ 1. , -0.5, -0.5],
212
+ [-0.5, 1. , -0.5],
213
+ [-0.5, -0.5, 1. ]])
214
+
215
+ which now instead of the diagonal returns the scaling coefficients
216
+
217
+ >>> d
218
+ array([1.41421356, 1.41421356, 1.41421356])
219
+
220
+ Zero scaling coefficients are substituted with 1s, where scaling
221
+ has thus no effect, e.g.,
222
+
223
+ >>> G = np.array([[0, 0, 0], [0, 0, 1], [0, 1, 0]])
224
+ >>> G
225
+ array([[0, 0, 0],
226
+ [0, 0, 1],
227
+ [0, 1, 0]])
228
+ >>> L, d = csgraph.laplacian(G, return_diag=True, normed=True)
229
+ >>> L
230
+ array([[ 0., -0., -0.],
231
+ [-0., 1., -1.],
232
+ [-0., -1., 1.]])
233
+ >>> d
234
+ array([1., 1., 1.])
235
+
236
+ Only the symmetric normalization is implemented, resulting
237
+ in a symmetric Laplacian matrix if and only if its graph is symmetric
238
+ and has all non-negative degrees, like in the examples above.
239
+
240
+ The output Laplacian matrix is by default a dense array or a sparse matrix
241
+ inferring its shape, format, and dtype from the input graph matrix:
242
+
243
+ >>> G = np.array([[0, 1, 1], [1, 0, 1], [1, 1, 0]]).astype(np.float32)
244
+ >>> G
245
+ array([[0., 1., 1.],
246
+ [1., 0., 1.],
247
+ [1., 1., 0.]], dtype=float32)
248
+ >>> csgraph.laplacian(G)
249
+ array([[ 2., -1., -1.],
250
+ [-1., 2., -1.],
251
+ [-1., -1., 2.]], dtype=float32)
252
+
253
+ but can alternatively be generated matrix-free as a LinearOperator:
254
+
255
+ >>> L = csgraph.laplacian(G, form="lo")
256
+ >>> L
257
+ <3x3 _CustomLinearOperator with dtype=float32>
258
+ >>> L(np.eye(3))
259
+ array([[ 2., -1., -1.],
260
+ [-1., 2., -1.],
261
+ [-1., -1., 2.]])
262
+
263
+ or as a lambda-function:
264
+
265
+ >>> L = csgraph.laplacian(G, form="function")
266
+ >>> L
267
+ <function _laplace.<locals>.<lambda> at 0x0000012AE6F5A598>
268
+ >>> L(np.eye(3))
269
+ array([[ 2., -1., -1.],
270
+ [-1., 2., -1.],
271
+ [-1., -1., 2.]])
272
+
273
+ The Laplacian matrix is used for
274
+ spectral data clustering and embedding
275
+ as well as for spectral graph partitioning.
276
+ Our final example illustrates the latter
277
+ for a noisy directed linear graph.
278
+
279
+ >>> from scipy.sparse import diags, random
280
+ >>> from scipy.sparse.linalg import lobpcg
281
+
282
+ Create a directed linear graph with ``N=35`` vertices
283
+ using a sparse adjacency matrix ``G``:
284
+
285
+ >>> N = 35
286
+ >>> G = diags(np.ones(N-1), 1, format="csr")
287
+
288
+ Fix a random seed ``rng`` and add a random sparse noise to the graph ``G``:
289
+
290
+ >>> rng = np.random.default_rng()
291
+ >>> G += 1e-2 * random(N, N, density=0.1, random_state=rng)
292
+
293
+ Set initial approximations for eigenvectors:
294
+
295
+ >>> X = rng.random((N, 2))
296
+
297
+ The constant vector of ones is always a trivial eigenvector
298
+ of the non-normalized Laplacian to be filtered out:
299
+
300
+ >>> Y = np.ones((N, 1))
301
+
302
+ Alternating (1) the sign of the graph weights allows determining
303
+ labels for spectral max- and min- cuts in a single loop.
304
+ Since the graph is undirected, the option ``symmetrized=True``
305
+ must be used in the construction of the Laplacian.
306
+ The option ``normed=True`` cannot be used in (2) for the negative weights
307
+ here as the symmetric normalization evaluates square roots.
308
+ The option ``form="lo"`` in (2) is matrix-free, i.e., guarantees
309
+ a fixed memory footprint and read-only access to the graph.
310
+ Calling the eigenvalue solver ``lobpcg`` (3) computes the Fiedler vector
311
+ that determines the labels as the signs of its components in (5).
312
+ Since the sign in an eigenvector is not deterministic and can flip,
313
+ we fix the sign of the first component to be always +1 in (4).
314
+
315
+ >>> for cut in ["max", "min"]:
316
+ ... G = -G # 1.
317
+ ... L = csgraph.laplacian(G, symmetrized=True, form="lo") # 2.
318
+ ... _, eves = lobpcg(L, X, Y=Y, largest=False, tol=1e-2) # 3.
319
+ ... eves *= np.sign(eves[0, 0]) # 4.
320
+ ... print(cut + "-cut labels:\\n", 1 * (eves[:, 0]>0)) # 5.
321
+ max-cut labels:
322
+ [1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1]
323
+ min-cut labels:
324
+ [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
325
+
326
+ As anticipated for a (slightly noisy) linear graph,
327
+ the max-cut strips all the edges of the graph coloring all
328
+ odd vertices into one color and all even vertices into another one,
329
+ while the balanced min-cut partitions the graph
330
+ in the middle by deleting a single edge.
331
+ Both determined partitions are optimal.
332
+ """
333
+ is_pydata_sparse = is_pydata_spmatrix(csgraph)
334
+ if is_pydata_sparse:
335
+ pydata_sparse_cls = csgraph.__class__
336
+ csgraph = convert_pydata_sparse_to_scipy(csgraph)
337
+ if csgraph.ndim != 2 or csgraph.shape[0] != csgraph.shape[1]:
338
+ raise ValueError('csgraph must be a square matrix or array')
339
+
340
+ if normed and (
341
+ np.issubdtype(csgraph.dtype, np.signedinteger)
342
+ or np.issubdtype(csgraph.dtype, np.uint)
343
+ ):
344
+ csgraph = csgraph.astype(np.float64)
345
+
346
+ if form == "array":
347
+ create_lap = (
348
+ _laplacian_sparse if issparse(csgraph) else _laplacian_dense
349
+ )
350
+ else:
351
+ create_lap = (
352
+ _laplacian_sparse_flo
353
+ if issparse(csgraph)
354
+ else _laplacian_dense_flo
355
+ )
356
+
357
+ degree_axis = 1 if use_out_degree else 0
358
+
359
+ lap, d = create_lap(
360
+ csgraph,
361
+ normed=normed,
362
+ axis=degree_axis,
363
+ copy=copy,
364
+ form=form,
365
+ dtype=dtype,
366
+ symmetrized=symmetrized,
367
+ )
368
+ if is_pydata_sparse:
369
+ lap = pydata_sparse_cls.from_scipy_sparse(lap)
370
+ if return_diag:
371
+ return lap, d
372
+ return lap
373
+
374
+
375
+ def _setdiag_dense(m, d):
376
+ step = len(d) + 1
377
+ m.flat[::step] = d
378
+
379
+
380
+ def _laplace(m, d):
381
+ return lambda v: v * d[:, np.newaxis] - m @ v
382
+
383
+
384
+ def _laplace_normed(m, d, nd):
385
+ laplace = _laplace(m, d)
386
+ return lambda v: nd[:, np.newaxis] * laplace(v * nd[:, np.newaxis])
387
+
388
+
389
+ def _laplace_sym(m, d):
390
+ return (
391
+ lambda v: v * d[:, np.newaxis]
392
+ - m @ v
393
+ - np.transpose(np.conjugate(np.transpose(np.conjugate(v)) @ m))
394
+ )
395
+
396
+
397
+ def _laplace_normed_sym(m, d, nd):
398
+ laplace_sym = _laplace_sym(m, d)
399
+ return lambda v: nd[:, np.newaxis] * laplace_sym(v * nd[:, np.newaxis])
400
+
401
+
402
+ def _linearoperator(mv, shape, dtype):
403
+ return LinearOperator(matvec=mv, matmat=mv, shape=shape, dtype=dtype)
404
+
405
+
406
+ def _laplacian_sparse_flo(graph, normed, axis, copy, form, dtype, symmetrized):
407
+ # The keyword argument `copy` is unused and has no effect here.
408
+ del copy
409
+
410
+ if dtype is None:
411
+ dtype = graph.dtype
412
+
413
+ graph_sum = np.asarray(graph.sum(axis=axis)).ravel()
414
+ graph_diagonal = graph.diagonal()
415
+ diag = graph_sum - graph_diagonal
416
+ if symmetrized:
417
+ graph_sum += np.asarray(graph.sum(axis=1 - axis)).ravel()
418
+ diag = graph_sum - graph_diagonal - graph_diagonal
419
+
420
+ if normed:
421
+ isolated_node_mask = diag == 0
422
+ w = np.where(isolated_node_mask, 1, np.sqrt(diag))
423
+ if symmetrized:
424
+ md = _laplace_normed_sym(graph, graph_sum, 1.0 / w)
425
+ else:
426
+ md = _laplace_normed(graph, graph_sum, 1.0 / w)
427
+ if form == "function":
428
+ return md, w.astype(dtype, copy=False)
429
+ elif form == "lo":
430
+ m = _linearoperator(md, shape=graph.shape, dtype=dtype)
431
+ return m, w.astype(dtype, copy=False)
432
+ else:
433
+ raise ValueError(f"Invalid form: {form!r}")
434
+ else:
435
+ if symmetrized:
436
+ md = _laplace_sym(graph, graph_sum)
437
+ else:
438
+ md = _laplace(graph, graph_sum)
439
+ if form == "function":
440
+ return md, diag.astype(dtype, copy=False)
441
+ elif form == "lo":
442
+ m = _linearoperator(md, shape=graph.shape, dtype=dtype)
443
+ return m, diag.astype(dtype, copy=False)
444
+ else:
445
+ raise ValueError(f"Invalid form: {form!r}")
446
+
447
+
448
+ def _laplacian_sparse(graph, normed, axis, copy, form, dtype, symmetrized):
449
+ # The keyword argument `form` is unused and has no effect here.
450
+ del form
451
+
452
+ if dtype is None:
453
+ dtype = graph.dtype
454
+
455
+ needs_copy = False
456
+ if graph.format in ('lil', 'dok'):
457
+ m = graph.tocoo()
458
+ else:
459
+ m = graph
460
+ if copy:
461
+ needs_copy = True
462
+
463
+ if symmetrized:
464
+ m += m.T.conj()
465
+
466
+ w = np.asarray(m.sum(axis=axis)).ravel() - m.diagonal()
467
+ if normed:
468
+ m = m.tocoo(copy=needs_copy)
469
+ isolated_node_mask = (w == 0)
470
+ w = np.where(isolated_node_mask, 1, np.sqrt(w))
471
+ m.data /= w[m.row]
472
+ m.data /= w[m.col]
473
+ m.data *= -1
474
+ m.setdiag(1 - isolated_node_mask)
475
+ else:
476
+ if m.format == 'dia':
477
+ m = m.copy()
478
+ else:
479
+ m = m.tocoo(copy=needs_copy)
480
+ m.data *= -1
481
+ m.setdiag(w)
482
+
483
+ return m.astype(dtype, copy=False), w.astype(dtype)
484
+
485
+
486
+ def _laplacian_dense_flo(graph, normed, axis, copy, form, dtype, symmetrized):
487
+
488
+ if copy:
489
+ m = np.array(graph)
490
+ else:
491
+ m = np.asarray(graph)
492
+
493
+ if dtype is None:
494
+ dtype = m.dtype
495
+
496
+ graph_sum = m.sum(axis=axis)
497
+ graph_diagonal = m.diagonal()
498
+ diag = graph_sum - graph_diagonal
499
+ if symmetrized:
500
+ graph_sum += m.sum(axis=1 - axis)
501
+ diag = graph_sum - graph_diagonal - graph_diagonal
502
+
503
+ if normed:
504
+ isolated_node_mask = diag == 0
505
+ w = np.where(isolated_node_mask, 1, np.sqrt(diag))
506
+ if symmetrized:
507
+ md = _laplace_normed_sym(m, graph_sum, 1.0 / w)
508
+ else:
509
+ md = _laplace_normed(m, graph_sum, 1.0 / w)
510
+ if form == "function":
511
+ return md, w.astype(dtype, copy=False)
512
+ elif form == "lo":
513
+ m = _linearoperator(md, shape=graph.shape, dtype=dtype)
514
+ return m, w.astype(dtype, copy=False)
515
+ else:
516
+ raise ValueError(f"Invalid form: {form!r}")
517
+ else:
518
+ if symmetrized:
519
+ md = _laplace_sym(m, graph_sum)
520
+ else:
521
+ md = _laplace(m, graph_sum)
522
+ if form == "function":
523
+ return md, diag.astype(dtype, copy=False)
524
+ elif form == "lo":
525
+ m = _linearoperator(md, shape=graph.shape, dtype=dtype)
526
+ return m, diag.astype(dtype, copy=False)
527
+ else:
528
+ raise ValueError(f"Invalid form: {form!r}")
529
+
530
+
531
+ def _laplacian_dense(graph, normed, axis, copy, form, dtype, symmetrized):
532
+
533
+ if form != "array":
534
+ raise ValueError(f'{form!r} must be "array"')
535
+
536
+ if dtype is None:
537
+ dtype = graph.dtype
538
+
539
+ if copy:
540
+ m = np.array(graph)
541
+ else:
542
+ m = np.asarray(graph)
543
+
544
+ if dtype is None:
545
+ dtype = m.dtype
546
+
547
+ if symmetrized:
548
+ m += m.T.conj()
549
+ np.fill_diagonal(m, 0)
550
+ w = m.sum(axis=axis)
551
+ if normed:
552
+ isolated_node_mask = (w == 0)
553
+ w = np.where(isolated_node_mask, 1, np.sqrt(w))
554
+ m /= w
555
+ m /= w[:, np.newaxis]
556
+ m *= -1
557
+ _setdiag_dense(m, 1 - isolated_node_mask)
558
+ else:
559
+ m *= -1
560
+ _setdiag_dense(m, w)
561
+
562
+ return m.astype(dtype, copy=False), w.astype(dtype, copy=False)
parrot/lib/python3.10/site-packages/scipy/sparse/csgraph/tests/test_traversal.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pytest
3
+ from numpy.testing import assert_array_almost_equal
4
+ from scipy.sparse import csr_array
5
+ from scipy.sparse.csgraph import (breadth_first_tree, depth_first_tree,
6
+ csgraph_to_dense, csgraph_from_dense)
7
+
8
+
9
+ def test_graph_breadth_first():
10
+ csgraph = np.array([[0, 1, 2, 0, 0],
11
+ [1, 0, 0, 0, 3],
12
+ [2, 0, 0, 7, 0],
13
+ [0, 0, 7, 0, 1],
14
+ [0, 3, 0, 1, 0]])
15
+ csgraph = csgraph_from_dense(csgraph, null_value=0)
16
+
17
+ bfirst = np.array([[0, 1, 2, 0, 0],
18
+ [0, 0, 0, 0, 3],
19
+ [0, 0, 0, 7, 0],
20
+ [0, 0, 0, 0, 0],
21
+ [0, 0, 0, 0, 0]])
22
+
23
+ for directed in [True, False]:
24
+ bfirst_test = breadth_first_tree(csgraph, 0, directed)
25
+ assert_array_almost_equal(csgraph_to_dense(bfirst_test),
26
+ bfirst)
27
+
28
+
29
+ def test_graph_depth_first():
30
+ csgraph = np.array([[0, 1, 2, 0, 0],
31
+ [1, 0, 0, 0, 3],
32
+ [2, 0, 0, 7, 0],
33
+ [0, 0, 7, 0, 1],
34
+ [0, 3, 0, 1, 0]])
35
+ csgraph = csgraph_from_dense(csgraph, null_value=0)
36
+
37
+ dfirst = np.array([[0, 1, 0, 0, 0],
38
+ [0, 0, 0, 0, 3],
39
+ [0, 0, 0, 0, 0],
40
+ [0, 0, 7, 0, 0],
41
+ [0, 0, 0, 1, 0]])
42
+
43
+ for directed in [True, False]:
44
+ dfirst_test = depth_first_tree(csgraph, 0, directed)
45
+ assert_array_almost_equal(csgraph_to_dense(dfirst_test),
46
+ dfirst)
47
+
48
+
49
+ def test_graph_breadth_first_trivial_graph():
50
+ csgraph = np.array([[0]])
51
+ csgraph = csgraph_from_dense(csgraph, null_value=0)
52
+
53
+ bfirst = np.array([[0]])
54
+
55
+ for directed in [True, False]:
56
+ bfirst_test = breadth_first_tree(csgraph, 0, directed)
57
+ assert_array_almost_equal(csgraph_to_dense(bfirst_test),
58
+ bfirst)
59
+
60
+
61
+ def test_graph_depth_first_trivial_graph():
62
+ csgraph = np.array([[0]])
63
+ csgraph = csgraph_from_dense(csgraph, null_value=0)
64
+
65
+ bfirst = np.array([[0]])
66
+
67
+ for directed in [True, False]:
68
+ bfirst_test = depth_first_tree(csgraph, 0, directed)
69
+ assert_array_almost_equal(csgraph_to_dense(bfirst_test),
70
+ bfirst)
71
+
72
+
73
+ @pytest.mark.parametrize('directed', [True, False])
74
+ @pytest.mark.parametrize('tree_func', [breadth_first_tree, depth_first_tree])
75
+ def test_int64_indices(tree_func, directed):
76
+ # See https://github.com/scipy/scipy/issues/18716
77
+ g = csr_array(([1], np.array([[0], [1]], dtype=np.int64)), shape=(2, 2))
78
+ assert g.indices.dtype == np.int64
79
+ tree = tree_func(g, 0, directed=directed)
80
+ assert_array_almost_equal(csgraph_to_dense(tree), [[0, 1], [0, 0]])
81
+
parrot/lib/python3.10/site-packages/scipy/sparse/linalg/_isolve/__pycache__/minres.cpython-310.pyc ADDED
Binary file (7.41 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/BinaryOps.h ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/TensorBase.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/util/TypeSafeSignMath.h>
7
+ #if defined(__CUDA_ARCH__)
8
+ #include <c10/cuda/CUDAMathCompat.h>
9
+ #define compat_copysign c10::cuda::compat::copysign
10
+ #elif defined(__HIPCC__)
11
+ #include <c10/hip/HIPMathCompat.h>
12
+ #define compat_copysign c10::hip::compat::copysign
13
+ #else
14
+ #include <c10/util/copysign.h>
15
+ #define compat_copysign c10::copysign
16
+ #endif
17
+
18
+
19
+ namespace at {
20
+ struct TensorIterator;
21
+ struct TensorIteratorBase;
22
+ }
23
+
24
+ namespace at::native {
25
+
26
+ inline void alpha_check(const ScalarType dtype, const Scalar& alpha) {
27
+ TORCH_CHECK(! alpha.isBoolean() || dtype == ScalarType::Bool,
28
+ "Boolean alpha only supported for Boolean results.");
29
+ TORCH_CHECK(isFloatingType(dtype) || isComplexType(dtype)
30
+ || alpha.isIntegral(true),
31
+ "For integral input tensors, argument alpha must not be a floating point number.");
32
+ TORCH_CHECK(isComplexType(dtype) || !alpha.isComplex(),
33
+ "For non-complex input tensors, argument alpha must not be a complex number.")
34
+ }
35
+
36
+ // Basic checking for all sub functions.
37
+ inline void sub_check(const TensorBase& self, const TensorBase& other) {
38
+ TORCH_CHECK(self.scalar_type() != kBool || other.scalar_type() != kBool,
39
+ "Subtraction, the `-` operator, with two bool tensors is not supported. "
40
+ "Use the `^` or `logical_xor()` operator instead.")
41
+ TORCH_CHECK(self.scalar_type() != kBool && other.scalar_type() != kBool,
42
+ "Subtraction, the `-` operator, with a bool tensor is not supported. "
43
+ "If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
44
+ }
45
+
46
+ inline void sub_check(const TensorBase& self, const Scalar& scalar) {
47
+ TORCH_CHECK(self.scalar_type() != kBool || !scalar.isBoolean(),
48
+ "Subtraction, the `-` operator, with two bool tensors is not supported. "
49
+ "Use the `^` or `logical_xor()` operator instead.")
50
+ TORCH_CHECK(self.scalar_type() != kBool && !scalar.isBoolean(),
51
+ "Subtraction, the `-` operator, with a bool tensor is not supported. "
52
+ "If you are trying to invert a mask, use the `~` or `logical_not()` operator instead.");
53
+ }
54
+
55
+ using structured_binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
56
+ using structured_binary_fn_double = void(*)(TensorIteratorBase&, double);
57
+ using structured_binary_fn = void(*)(TensorIteratorBase&);
58
+
59
+ using binary_fn_alpha = void(*)(TensorIteratorBase&, const Scalar& alpha);
60
+ using binary_fn_double = void(*)(TensorIterator&, double);
61
+ using binary_fn = void(*)(TensorIterator&);
62
+ using binary_clamp_fn_alpha =
63
+ void(*)(TensorIterator&, const Scalar& alpha, const Scalar& min_val, const Scalar& max_val);
64
+
65
+ // NB: codegenned
66
+ DECLARE_DISPATCH(structured_binary_fn_alpha, add_stub);
67
+
68
+ DECLARE_DISPATCH(binary_clamp_fn_alpha, add_clamp_stub);
69
+ DECLARE_DISPATCH(structured_binary_fn_alpha, sub_stub);
70
+ DECLARE_DISPATCH(structured_binary_fn, mul_stub);
71
+ DECLARE_DISPATCH(structured_binary_fn, div_true_stub);
72
+ DECLARE_DISPATCH(structured_binary_fn, div_floor_stub);
73
+ DECLARE_DISPATCH(structured_binary_fn, div_trunc_stub);
74
+ DECLARE_DISPATCH(structured_binary_fn, atan2_stub);
75
+ DECLARE_DISPATCH(structured_binary_fn, remainder_stub);
76
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_and_stub);
77
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_or_stub);
78
+ DECLARE_DISPATCH(structured_binary_fn, bitwise_xor_stub);
79
+ DECLARE_DISPATCH(structured_binary_fn, lshift_stub);
80
+ DECLARE_DISPATCH(structured_binary_fn, rshift_stub);
81
+ DECLARE_DISPATCH(binary_fn, logical_xor_stub);
82
+ DECLARE_DISPATCH(binary_fn, logical_and_stub);
83
+ DECLARE_DISPATCH(binary_fn, logical_or_stub);
84
+ DECLARE_DISPATCH(structured_binary_fn, lt_stub);
85
+ DECLARE_DISPATCH(structured_binary_fn, le_stub);
86
+ DECLARE_DISPATCH(structured_binary_fn, gt_stub);
87
+ DECLARE_DISPATCH(structured_binary_fn, ge_stub);
88
+ DECLARE_DISPATCH(structured_binary_fn, eq_stub);
89
+ DECLARE_DISPATCH(structured_binary_fn, ne_stub);
90
+ DECLARE_DISPATCH(binary_fn, max_elementwise_stub);
91
+ DECLARE_DISPATCH(binary_fn, min_elementwise_stub);
92
+ DECLARE_DISPATCH(structured_binary_fn, maximum_stub);
93
+ DECLARE_DISPATCH(structured_binary_fn, minimum_stub);
94
+ DECLARE_DISPATCH(structured_binary_fn, fmax_stub);
95
+ DECLARE_DISPATCH(structured_binary_fn, fmin_stub);
96
+ DECLARE_DISPATCH(structured_binary_fn_double, smooth_l1_stub);
97
+ DECLARE_DISPATCH(binary_fn_double, huber_stub);
98
+ DECLARE_DISPATCH(structured_binary_fn, sigmoid_backward_stub);
99
+ DECLARE_DISPATCH(binary_fn_alpha, logit_backward_stub);
100
+ DECLARE_DISPATCH(structured_binary_fn, tanh_backward_stub);
101
+ DECLARE_DISPATCH(structured_binary_fn, mse_stub);
102
+ DECLARE_DISPATCH(structured_binary_fn, fmod_stub);
103
+ DECLARE_DISPATCH(structured_binary_fn, logaddexp_stub);
104
+ DECLARE_DISPATCH(structured_binary_fn, logaddexp2_stub);
105
+ DECLARE_DISPATCH(structured_binary_fn, gcd_stub);
106
+ DECLARE_DISPATCH(structured_binary_fn, lcm_stub);
107
+ DECLARE_DISPATCH(structured_binary_fn, hypot_stub);
108
+ DECLARE_DISPATCH(structured_binary_fn, igamma_stub);
109
+ DECLARE_DISPATCH(structured_binary_fn, igammac_stub);
110
+ DECLARE_DISPATCH(structured_binary_fn, nextafter_stub);
111
+ DECLARE_DISPATCH(structured_binary_fn, heaviside_stub);
112
+ DECLARE_DISPATCH(structured_binary_fn, copysign_stub);
113
+ DECLARE_DISPATCH(structured_binary_fn, xlogy_stub);
114
+ DECLARE_DISPATCH(structured_binary_fn, xlog1py_stub);
115
+ DECLARE_DISPATCH(structured_binary_fn, zeta_stub);
116
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_t_stub);
117
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_u_stub);
118
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_v_stub);
119
+ DECLARE_DISPATCH(structured_binary_fn, chebyshev_polynomial_w_stub);
120
+ DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_h_stub);
121
+ DECLARE_DISPATCH(structured_binary_fn, hermite_polynomial_he_stub);
122
+ DECLARE_DISPATCH(structured_binary_fn, laguerre_polynomial_l_stub);
123
+ DECLARE_DISPATCH(structured_binary_fn, legendre_polynomial_p_stub);
124
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_t_stub);
125
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_u_stub);
126
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_v_stub);
127
+ DECLARE_DISPATCH(structured_binary_fn, shifted_chebyshev_polynomial_w_stub);
128
+
129
+ } // namespace at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/DispatchStub.h ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <c10/core/DeviceType.h>
4
+ #include <c10/macros/Macros.h>
5
+
6
+ #include <atomic>
7
+ #include <utility>
8
+
9
+ // Implements instruction set specific function dispatch.
10
+ //
11
+ // Kernels that may make use of specialized instruction sets (e.g. AVX2) are
12
+ // compiled multiple times with different compiler flags (e.g. -mavx2). A
13
+ // DispatchStub contains a table of function pointers for a kernel. At runtime,
14
+ // the fastest available kernel is chosen based on the features reported by
15
+ // cpuinfo.
16
+ //
17
+ // Example:
18
+ //
19
+ // In native/MyKernel.h:
20
+ // using fn_type = void(*)(const Tensor& x);
21
+ // DECLARE_DISPATCH(fn_type, stub);
22
+ //
23
+ // In native/MyKernel.cpp
24
+ // DEFINE_DISPATCH(stub);
25
+ //
26
+ // In native/cpu/MyKernel.cpp:
27
+ // namespace {
28
+ // // use anonymous namespace so that different cpu versions won't conflict
29
+ // void kernel(const Tensor& x) { ... }
30
+ // }
31
+ // REGISTER_DISPATCH(stub, &kernel);
32
+ //
33
+ // To call:
34
+ // stub(kCPU, tensor);
35
+ //
36
+ // TODO: CPU instruction set selection should be folded into whatever
37
+ // the main dispatch mechanism is.
38
+
39
+ // ignore warnings about DispatchStub::DEFAULT, AVX, AVX2 defined elsewhere
40
+ C10_CLANG_DIAGNOSTIC_PUSH()
41
+ C10_CLANG_DIAGNOSTIC_IGNORE("-Wundefined-var-template")
42
+
43
+ namespace at::native {
44
+
45
+ enum class CPUCapability {
46
+ DEFAULT = 0,
47
+ #if defined(HAVE_VSX_CPU_DEFINITION)
48
+ VSX = 1,
49
+ #elif defined(HAVE_ZVECTOR_CPU_DEFINITION)
50
+ ZVECTOR = 1,
51
+ #else
52
+ AVX2 = 1,
53
+ AVX512 = 2,
54
+ #endif
55
+ NUM_OPTIONS
56
+ };
57
+
58
+ CPUCapability get_cpu_capability();
59
+
60
+ template <typename FnPtr, typename T>
61
+ struct DispatchStub;
62
+
63
+ /**
64
+ * The sole purpose of this class is to outline methods that don't need to be
65
+ * specialized or otherwise inlined and duplicated (by the compiler due to
66
+ * template expansion), since it causes size bloat if there are a significant
67
+ * number of specialization of the DispatchStub<> class.
68
+ */
69
+ struct TORCH_API DispatchStubImpl {
70
+ void* get_call_ptr(
71
+ c10::DeviceType device_type
72
+ , void *DEFAULT
73
+ #ifdef HAVE_AVX512_CPU_DEFINITION
74
+ , void *AVX512
75
+ #endif
76
+ #ifdef HAVE_AVX2_CPU_DEFINITION
77
+ , void *AVX2
78
+ #endif
79
+ #ifdef HAVE_VSX_CPU_DEFINITION
80
+ , void *VSX
81
+ #endif
82
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
83
+ , void *ZVECTOR
84
+ #endif
85
+ );
86
+
87
+ /**
88
+ * The CPU Dispatch actual method is chosen in decreasing order of preference by
89
+ * DispatchStubImpl::choose_cpu_impl() in case none is found by
90
+ * DispatchStubImpl::get_call_ptr() in cpu_dispatch_ptr.
91
+ */
92
+ void* choose_cpu_impl(
93
+ void *DEFAULT
94
+ #ifdef HAVE_AVX512_CPU_DEFINITION
95
+ , void *AVX512
96
+ #endif
97
+ #ifdef HAVE_AVX2_CPU_DEFINITION
98
+ , void *AVX2
99
+ #endif
100
+ #ifdef HAVE_VSX_CPU_DEFINITION
101
+ , void *VSX
102
+ #endif
103
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
104
+ , void *ZVECTOR
105
+ #endif
106
+ );
107
+
108
+ // Fixing dispatch error in Windows debug builds.
109
+ // See https://github.com/pytorch/pytorch/issues/22681 for more details.
110
+ #if defined(_MSC_VER) && defined(_DEBUG)
111
+ std::atomic<void*> cpu_dispatch_ptr;
112
+ void* cuda_dispatch_ptr;
113
+ void* hip_dispatch_ptr;
114
+ void* mps_dispatch_ptr;
115
+ void* privateuse1_dispatch_ptr;
116
+ #else
117
+ std::atomic<void*> cpu_dispatch_ptr{nullptr};
118
+ void* cuda_dispatch_ptr = nullptr;
119
+ void* hip_dispatch_ptr = nullptr;
120
+ void* mps_dispatch_ptr = nullptr;
121
+ void* privateuse1_dispatch_ptr = nullptr;
122
+ #endif
123
+ };
124
+
125
+ template <typename rT, typename T, typename... Args>
126
+ struct DispatchStub<rT (*)(Args...), T> {
127
+ using FnPtr = rT (*) (Args...);
128
+
129
+ DispatchStub() = default;
130
+ DispatchStub(const DispatchStub&) = delete;
131
+ DispatchStub& operator=(const DispatchStub&) = delete;
132
+
133
+ private:
134
+ FnPtr get_call_ptr(c10::DeviceType device_type) {
135
+ return reinterpret_cast<FnPtr>(
136
+ impl.get_call_ptr(device_type
137
+ , reinterpret_cast<void*>(DEFAULT)
138
+ #ifdef HAVE_AVX512_CPU_DEFINITION
139
+ , reinterpret_cast<void*>(AVX512)
140
+ #endif
141
+ #ifdef HAVE_AVX2_CPU_DEFINITION
142
+ , reinterpret_cast<void*>(AVX2)
143
+ #endif
144
+ #ifdef HAVE_VSX_CPU_DEFINITION
145
+ , reinterpret_cast<void*>(VSX)
146
+ #endif
147
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
148
+ , reinterpret_cast<void*>(ZVECTOR)
149
+ #endif
150
+ )
151
+ );
152
+ }
153
+
154
+ public:
155
+ template <typename... ArgTypes>
156
+ rT operator()(c10::DeviceType device_type, ArgTypes&&... args) {
157
+ FnPtr call_ptr = get_call_ptr(device_type);
158
+ return (*call_ptr)(std::forward<ArgTypes>(args)...);
159
+ }
160
+
161
+ void set_cuda_dispatch_ptr(FnPtr fn_ptr) {
162
+ impl.cuda_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
163
+ }
164
+
165
+ void set_hip_dispatch_ptr(FnPtr fn_ptr) {
166
+ impl.hip_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
167
+ }
168
+
169
+ void set_mps_dispatch_ptr(FnPtr fn_ptr) {
170
+ impl.mps_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
171
+ }
172
+
173
+ void set_privateuse1_dispatch_ptr(FnPtr fn_ptr) {
174
+ impl.privateuse1_dispatch_ptr = reinterpret_cast<void*>(fn_ptr);
175
+ }
176
+
177
+ static TORCH_API FnPtr DEFAULT;
178
+ #ifdef HAVE_AVX512_CPU_DEFINITION
179
+ static TORCH_API FnPtr AVX512;
180
+ #endif
181
+ #ifdef HAVE_AVX2_CPU_DEFINITION
182
+ static TORCH_API FnPtr AVX2;
183
+ #endif
184
+ #ifdef HAVE_VSX_CPU_DEFINITION
185
+ static TORCH_API FnPtr VSX;
186
+ #endif
187
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
188
+ static TORCH_API FnPtr ZVECTOR;
189
+ #endif
190
+ private:
191
+ DispatchStubImpl impl;
192
+ };
193
+
194
+ namespace {
195
+ template <typename DispatchStub>
196
+ struct RegisterCUDADispatch {
197
+ RegisterCUDADispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
198
+ stub.set_cuda_dispatch_ptr(value);
199
+ }
200
+ };
201
+
202
+ template <typename DispatchStub>
203
+ struct RegisterMPSDispatch {
204
+ RegisterMPSDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
205
+ stub.set_mps_dispatch_ptr(value);
206
+ }
207
+ };
208
+
209
+ template <typename DispatchStub>
210
+ struct RegisterHIPDispatch {
211
+ RegisterHIPDispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
212
+ // TODO: make this point at hip_dispatch_ptr
213
+ stub.set_cuda_dispatch_ptr(value);
214
+ }
215
+ };
216
+
217
+ template <typename DispatchStub>
218
+ struct RegisterPRIVATEUSE1Dispatch {
219
+ RegisterPRIVATEUSE1Dispatch(DispatchStub &stub, typename DispatchStub::FnPtr value) {
220
+ stub.set_privateuse1_dispatch_ptr(value);
221
+ }
222
+ };
223
+
224
+ } // anonymous namespace
225
+ // Compiler will complain if you put things like std::tuple<Tensor, Tensor> in
226
+ // the `fn` argument of DECLARE_DISPATCH. Some possible workarounds, e.g.,
227
+ // adding parentheses and using helper struct to get rid of the parentheses, do
228
+ // not work with MSVC. So do a `using`-declaration if you need to pass in such
229
+ // `fn`, e.g., grid_sampler_2d_backward_cpu_kernel in GridSampleKernel.h.
230
+ #define DECLARE_DISPATCH(fn, name) \
231
+ struct name : DispatchStub<fn, name> { \
232
+ name() = default; \
233
+ name(const name&) = delete; \
234
+ name& operator=(const name&) = delete; \
235
+ }; \
236
+ extern TORCH_API struct name name
237
+
238
+ #define DEFINE_DISPATCH(name) struct name name
239
+
240
+ #define REGISTER_ARCH_DISPATCH(name, arch, fn) \
241
+ template <> name::FnPtr TORCH_API DispatchStub<name::FnPtr, struct name>::arch = fn;
242
+
243
+ #ifdef HAVE_AVX512_CPU_DEFINITION
244
+ #define REGISTER_AVX512_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, AVX512, fn)
245
+ #else
246
+ #define REGISTER_AVX512_DISPATCH(name, fn)
247
+ #endif
248
+
249
+ #ifdef HAVE_AVX2_CPU_DEFINITION
250
+ #define REGISTER_AVX2_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, AVX2, fn)
251
+ #else
252
+ #define REGISTER_AVX2_DISPATCH(name, fn)
253
+ #endif
254
+
255
+ #ifdef HAVE_VSX_CPU_DEFINITION
256
+ #define REGISTER_VSX_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, VSX, fn)
257
+ #else
258
+ #define REGISTER_VSX_DISPATCH(name, fn)
259
+ #endif
260
+
261
+ #ifdef HAVE_ZVECTOR_CPU_DEFINITION
262
+ #define REGISTER_ZVECTOR_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, ZVECTOR, fn)
263
+ #else
264
+ #define REGISTER_ZVECTOR_DISPATCH(name, fn)
265
+ #endif
266
+
267
+ // Macro to register the same kernel for all CPU arch types. This is useful
268
+ // if a kernel does not benefit from being recompiled across different arch types.
269
+ #define REGISTER_ALL_CPU_DISPATCH(name, fn) \
270
+ REGISTER_ARCH_DISPATCH(name, DEFAULT, fn) \
271
+ REGISTER_AVX512_DISPATCH(name, fn) \
272
+ REGISTER_AVX2_DISPATCH(name, fn) \
273
+ REGISTER_VSX_DISPATCH(name, fn) \
274
+ REGISTER_ZVECTOR_DISPATCH(name, fn)
275
+
276
+ #define REGISTER_NO_CPU_DISPATCH(name) \
277
+ REGISTER_ALL_CPU_DISPATCH(name, nullptr)
278
+
279
+ #define REGISTER_CUDA_DISPATCH(name, fn) \
280
+ static RegisterCUDADispatch<struct name> name ## __register(name, fn);
281
+
282
+ #define REGISTER_HIP_DISPATCH(name, fn) \
283
+ static RegisterHIPDispatch<struct name> name ## __register(name, fn);
284
+
285
+ #define REGISTER_MPS_DISPATCH(name, fn) \
286
+ static RegisterMPSDispatch<struct name> name ## __register(name, fn);
287
+
288
+ #define REGISTER_PRIVATEUSE1_DISPATCH(name, fn) \
289
+ static RegisterPRIVATEUSE1Dispatch<struct name> name ## __register(name, fn);
290
+
291
+ // NB: This macro must be used in an actual 'cu' file; if you try using
292
+ // it from a 'cpp' file it will not work!
293
+ #if defined(__CUDACC__)
294
+ #define REGISTER_DISPATCH(name, fn) REGISTER_CUDA_DISPATCH(name, fn)
295
+ #elif defined(__HIPCC__)
296
+ // TODO: cut this over to HIP dispatch once we stop pretending that CUDA
297
+ // is HIP in the PyTorch HIPify build.
298
+ #define REGISTER_DISPATCH(name, fn) REGISTER_CUDA_DISPATCH(name, fn)
299
+ // #define REGISTER_DISPATCH(name, fn) REGISTER_HIP_DISPATCH(name, fn)
300
+ #elif defined(__OBJC__) && defined(USE_MPS)
301
+ // NB: this macro must be used from a 'mm' file in order to dispatch a MPS kernel
302
+ #define REGISTER_DISPATCH(name, fn) REGISTER_MPS_DISPATCH(name, fn)
303
+ #elif defined(CPU_CAPABILITY)
304
+ // REGISTER_DISPATCH now dispatches an AVX512 kernel to nullptr but registers other dispatches.
305
+ // ALSO_REGISTER_AVX512_DISPATCH should be used for ensuring AVX512 dispatch, among others.
306
+ #ifdef CPU_CAPABILITY_AVX512
307
+ #define REGISTER_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, nullptr)
308
+ #else
309
+ #define REGISTER_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
310
+ #endif
311
+ #define ALSO_REGISTER_AVX512_DISPATCH(name, fn) REGISTER_ARCH_DISPATCH(name, CPU_CAPABILITY, fn)
312
+ #endif
313
+ } // namespace at::native
314
+
315
+ C10_CLANG_DIAGNOSTIC_POP()
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/GridSampler.h ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <algorithm>
4
+ #include <cmath>
5
+ #include <cstdint>
6
+ #include <utility>
7
+
8
+ #include <ATen/native/GridSamplerUtils.h>
9
+
10
+ namespace at::native {
11
+
12
+ using detail::GridSamplerInterpolation;
13
+ using detail::GridSamplerPadding;
14
+
15
+ // Unnormalizes a coordinate from the -1 to +1 scale to its pixel index value,
16
+ // where we view each pixel as an area between (idx - 0.5) and (idx + 0.5).
17
+ // if align_corners: -1 and +1 get sent to the centers of the corner pixels
18
+ // -1 --> 0
19
+ // +1 --> (size - 1)
20
+ // scale_factor = (size - 1) / 2
21
+ // if not align_corners: -1 and +1 get sent to the image edges
22
+ // -1 --> -0.5
23
+ // +1 --> (size - 1) + 0.5 == size - 0.5
24
+ // scale_factor = size / 2
25
+ template <typename scalar_t>
26
+ static inline scalar_t grid_sampler_unnormalize(scalar_t coord, int64_t size,
27
+ bool align_corners) {
28
+ if (align_corners) {
29
+ // unnormalize coord from [-1, 1] to [0, size - 1]
30
+ return ((coord + 1) / 2) * (size - 1);
31
+ } else {
32
+ // unnormalize coord from [-1, 1] to [-0.5, size - 0.5]
33
+ return ((coord + 1) * size - 1) / 2;
34
+ }
35
+ }
36
+
37
+ // grid_sampler_unnormalize_set_grad works the same as grid_sampler_unnormalize
38
+ // except that it also returns the `d output / d input` via pointer argument
39
+ // `grad_in`.
40
+ // This is useful in the backward pass of grid_sampler.
41
+ template <typename scalar_t>
42
+ static inline scalar_t grid_sampler_unnormalize_set_grad(scalar_t coord, int64_t size,
43
+ bool align_corners, scalar_t *grad_in) {
44
+ if (align_corners) {
45
+ // unnormalize coord from [-1, 1] to [0, size - 1]
46
+ *grad_in = static_cast<scalar_t>(size - 1) / 2;
47
+ return ((coord + 1) / 2) * (size - 1);
48
+ } else {
49
+ // unnormalize coord from [-1, 1] to [-0.5, size - 0.5]
50
+ *grad_in = static_cast<scalar_t>(size) / 2;
51
+ return ((coord + 1) * size - 1) / 2;
52
+ }
53
+ }
54
+
55
+ // Clips coordinates to between 0 and clip_limit - 1
56
+ template<typename scalar_t>
57
+ static inline scalar_t clip_coordinates(scalar_t in, int64_t clip_limit) {
58
+ return std::min(static_cast<scalar_t>(clip_limit - 1), std::max(in, static_cast<scalar_t>(0)));
59
+ }
60
+
61
+ // clip_coordinates_set_grad works similarly to clip_coordinates except that
62
+ // it also returns the `d output / d input` via pointer argument `grad_in`.
63
+ // This is useful in the backward pass of grid_sampler.
64
+ template<typename scalar_t>
65
+ static inline scalar_t clip_coordinates_set_grad(scalar_t in, int64_t clip_limit,
66
+ scalar_t *grad_in) {
67
+ // Note that it is important for the gradient calculation that borders
68
+ // are considered out of bounds.
69
+ if (in <= static_cast<scalar_t>(0)) {
70
+ *grad_in = static_cast<scalar_t>(0);
71
+ return static_cast<scalar_t>(0);
72
+ } else {
73
+ scalar_t max = static_cast<scalar_t>(clip_limit - 1);
74
+ if (in >= max) {
75
+ *grad_in = static_cast<scalar_t>(0);
76
+ return max;
77
+ } else {
78
+ *grad_in = static_cast<scalar_t>(1);
79
+ return in;
80
+ }
81
+ }
82
+ }
83
+
84
+ // Reflects coordinates until they fall between low and high (inclusive).
85
+ // The bounds are passed as twice their value so that half-integer values
86
+ // can be represented as ints.
87
+ template<typename scalar_t>
88
+ static inline scalar_t reflect_coordinates(scalar_t in, int64_t twice_low,
89
+ int64_t twice_high) {
90
+ if (twice_low == twice_high) {
91
+ return static_cast<scalar_t>(0);
92
+ }
93
+ scalar_t min = static_cast<scalar_t>(twice_low) / 2;
94
+ scalar_t span = static_cast<scalar_t>(twice_high - twice_low) / 2;
95
+ in = std::fabs(in - min);
96
+ // `fmod` returns same sign as `in`, which is positive after the `fabs` above.
97
+ scalar_t extra = std::fmod(in, span);
98
+ int flips = static_cast<int>(std::floor(in / span));
99
+ if (flips % 2 == 0) {
100
+ return extra + min;
101
+ } else {
102
+ return span - extra + min;
103
+ }
104
+ }
105
+
106
+ // reflect_coordinates_set_grad works similarly to reflect_coordinates except
107
+ // that it also returns the `d output / d input` via pointer argument
108
+ // `grad_in`.
109
+ // This is useful in the backward pass of grid_sampler.
110
+ template<typename scalar_t>
111
+ static inline scalar_t reflect_coordinates_set_grad(scalar_t in, int64_t twice_low,
112
+ int64_t twice_high, scalar_t *grad_in) {
113
+ if (twice_low == twice_high) {
114
+ *grad_in = static_cast<scalar_t>(0);
115
+ return static_cast<scalar_t>(0);
116
+ }
117
+ int grad_in_mult_;
118
+ scalar_t min = static_cast<scalar_t>(twice_low) / 2;
119
+ scalar_t span = static_cast<scalar_t>(twice_high - twice_low) / 2;
120
+ in = in - min;
121
+ if (in < static_cast<scalar_t>(0)) {
122
+ grad_in_mult_ = -1;
123
+ in = -in;
124
+ } else {
125
+ grad_in_mult_ = 1;
126
+ }
127
+ // `fmod` returns same sign as `in`, which is positive after the `if` above.
128
+ scalar_t extra = std::fmod(in, span);
129
+ int flips = static_cast<int>(std::floor(in / span));
130
+ if (flips % 2 == 0) {
131
+ *grad_in = static_cast<scalar_t>(grad_in_mult_);
132
+ return extra + min;
133
+ } else {
134
+ *grad_in = static_cast<scalar_t>(-grad_in_mult_);
135
+ return span - extra + min;
136
+ }
137
+ }
138
+
139
+ // Mapping the out-of-boundary points back into boundary
140
+ // This would only affect padding_mode=border or reflection
141
+ template<typename scalar_t>
142
+ static inline scalar_t compute_coordinates(scalar_t coord, int64_t size,
143
+ GridSamplerPadding padding_mode,
144
+ bool align_corners) {
145
+ if (padding_mode == GridSamplerPadding::Border) {
146
+ // clip coordinates to image borders
147
+ coord = clip_coordinates(coord, size);
148
+ } else if (padding_mode == GridSamplerPadding::Reflection) {
149
+ // reflect coordinates by image borders
150
+ if (align_corners) {
151
+ coord = reflect_coordinates(coord, 0, 2*(size - 1));
152
+ } else {
153
+ coord = reflect_coordinates(coord, -1, 2*size - 1);
154
+ }
155
+ // clip coordinates to image borders
156
+ coord = clip_coordinates(coord, size);
157
+ }
158
+ return coord;
159
+ }
160
+
161
+ // Computes the pixel source index value for a grid coordinate
162
+ template <typename scalar_t>
163
+ static inline scalar_t grid_sampler_compute_source_index(
164
+ scalar_t coord,
165
+ int64_t size,
166
+ GridSamplerPadding padding_mode,
167
+ bool align_corners) {
168
+ coord = grid_sampler_unnormalize(coord, size, align_corners);
169
+ coord = compute_coordinates(coord, size, padding_mode, align_corners);
170
+ return coord;
171
+ }
172
+
173
+ // grid_sampler_compute_source_index_set_grad works similarly to
174
+ // grid_sampler_compute_source_index except that it also returns the
175
+ // `d output / d input` via pointer argument `grad_in`.
176
+ // This is useful in the backward pass of grid_sampler.
177
+ template <typename scalar_t>
178
+ static inline scalar_t grid_sampler_compute_source_index_set_grad(
179
+ scalar_t coord,
180
+ int64_t size,
181
+ GridSamplerPadding padding_mode,
182
+ bool align_corners,
183
+ scalar_t *grad_in) {
184
+ scalar_t grad_clip, grad_refl;
185
+ coord = grid_sampler_unnormalize_set_grad(coord, size, align_corners, grad_in);
186
+ if (padding_mode == GridSamplerPadding::Border) {
187
+ // clip coordinates to image borders
188
+ coord = clip_coordinates_set_grad(coord, size, &grad_clip);
189
+ *grad_in = (*grad_in) * grad_clip;
190
+ } else if (padding_mode == GridSamplerPadding::Reflection) {
191
+ // reflect coordinates by image borders
192
+ if (align_corners) {
193
+ coord = reflect_coordinates_set_grad(coord, 0, 2*(size - 1), &grad_refl);
194
+ } else {
195
+ coord = reflect_coordinates_set_grad(coord, -1, 2*size - 1, &grad_refl);
196
+ }
197
+ // clip coordinates to image borders
198
+ coord = clip_coordinates_set_grad(coord, size, &grad_clip);
199
+ *grad_in = (*grad_in) * grad_refl * grad_clip;
200
+ }
201
+ return coord;
202
+ }
203
+
204
+ static inline bool within_bounds_2d(int64_t h, int64_t w, int64_t H, int64_t W) {
205
+ return h >= 0 && h < H && w >= 0 && w < W;
206
+ }
207
+
208
+ static inline bool within_bounds_3d(int64_t d, int64_t h, int64_t w, int64_t D, int64_t H, int64_t W) {
209
+ return d >= 0 && d < D && h >= 0 && h < H && w >= 0 && w < W;
210
+ }
211
+
212
+ template<typename scalar_t>
213
+ static inline scalar_t get_value_bounded(
214
+ scalar_t* data,
215
+ scalar_t x,
216
+ scalar_t y,
217
+ int64_t W,
218
+ int64_t H,
219
+ int64_t sW,
220
+ int64_t sH,
221
+ GridSamplerPadding padding_mode,
222
+ bool align_corners) {
223
+
224
+ x = compute_coordinates(x, W, padding_mode, align_corners);
225
+ y = compute_coordinates(y, H, padding_mode, align_corners);
226
+
227
+ int64_t ix = static_cast<int64_t>(x);
228
+ int64_t iy = static_cast<int64_t>(y);
229
+
230
+ if (within_bounds_2d(iy, ix, H, W)) {
231
+ return data[iy * sH + ix * sW];
232
+ }
233
+ return static_cast<scalar_t>(0);
234
+ }
235
+
236
+ template<typename scalar_t>
237
+ static inline void safe_add_2d(scalar_t *data, int64_t h, int64_t w,
238
+ int64_t sH, int64_t sW, int64_t H, int64_t W,
239
+ scalar_t delta) {
240
+ if (within_bounds_2d(h, w, H, W)) {
241
+ data[h * sH + w * sW] += delta;
242
+ }
243
+ }
244
+
245
+ template<typename scalar_t>
246
+ static inline void safe_add_3d(scalar_t *data, int64_t d, int64_t h, int64_t w,
247
+ int64_t sD, int64_t sH, int64_t sW,
248
+ int64_t D, int64_t H, int64_t W,
249
+ scalar_t delta) {
250
+ if (within_bounds_3d(d, h, w, D, H, W)) {
251
+ data[d * sD + h * sH + w * sW] += delta;
252
+ }
253
+ }
254
+
255
+ template<typename scalar_t>
256
+ static inline void add_value_bounded(
257
+ scalar_t* data,
258
+ scalar_t x,
259
+ scalar_t y,
260
+ int64_t W,
261
+ int64_t H,
262
+ int64_t sW,
263
+ int64_t sH,
264
+ scalar_t delta,
265
+ GridSamplerPadding padding_mode,
266
+ bool align_corners) {
267
+
268
+ x = compute_coordinates(x, W, padding_mode, align_corners);
269
+ y = compute_coordinates(y, H, padding_mode, align_corners);
270
+
271
+ int64_t ix = static_cast<int64_t>(x);
272
+ int64_t iy = static_cast<int64_t>(y);
273
+
274
+ safe_add_2d(data, iy, ix, sH, sW, H, W, delta);
275
+ }
276
+
277
+ // Calculate the differential of the cubic convolution, i.e. `d coeff / d x`
278
+ template<typename scalar_t>
279
+ static inline void get_cubic_coefficients_grad(
280
+ scalar_t coeffs[4],
281
+ scalar_t t) {
282
+
283
+ // Must be the same as forward calculation in
284
+ // aten/src/ATen/native/UpSample.h:get_cubic_upsample_coefficients
285
+ scalar_t A = -0.75;
286
+
287
+ scalar_t x;
288
+ x = -1 - t; // 1 < x = |-1 - tx| < 2
289
+ coeffs[0] = (-3 * A * x - 10 * A ) * x - 8 * A;
290
+ x = -t; // x = |0 - tx| <= 1
291
+ coeffs[1] = (-3 * (A + 2) * x - 2 * (A + 3)) * x;
292
+ x = 1 - t; // x = |1 - tx| <= 1
293
+ coeffs[2] = (3 * (A + 2) * x - 2 * (A + 3)) * x;
294
+ x = 2 - t; // 1 < x = |2 - tx| < 2
295
+ coeffs[3] = (3 * A * x - 10 * A) * x + 8 * A;
296
+ }
297
+
298
+ } // namespace at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/GridSamplerUtils.h ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // See NOTE: [Tensor vs. TensorBase]
4
+ // https://github.com/pytorch/pytorch/pull/66979
5
+ #include <ATen/core/TensorBase.h>
6
+ #include <ATen/native/TensorProperties.h>
7
+ #include <ATen/native/CanUse32BitIndexMath.h>
8
+
9
+ namespace at::native {
10
+
11
+ namespace detail {
12
+
13
+ enum class GridSamplerInterpolation {Bilinear, Nearest, Bicubic};
14
+ enum class GridSamplerPadding {Zeros, Border, Reflection};
15
+
16
+ } // namespace detail
17
+
18
+ using detail::GridSamplerInterpolation;
19
+ using detail::GridSamplerPadding;
20
+
21
+ namespace {
22
+
23
+ // See NOTE [ grid_sampler Native Functions ].
24
+ void check_grid_sampler_common(
25
+ const TensorBase& input,
26
+ const TensorBase& grid
27
+ ) {
28
+ auto input_opt = input.options();
29
+ auto grid_opt = grid.options();
30
+
31
+ TORCH_CHECK(
32
+ input.defined(),
33
+ "grid_sampler(): expected input to not be undefined");
34
+ TORCH_CHECK(
35
+ grid.defined(),
36
+ "grid_sampler(): expected grid to not be undefined");
37
+ TORCH_CHECK(
38
+ input_opt.device() == grid_opt.device(),
39
+ "grid_sampler(): expected input and grid to be on same device, but input "
40
+ "is on ", input_opt.device(), " and grid is on ", grid_opt.device());
41
+ TORCH_CHECK(
42
+ input_opt.layout() == kStrided && grid_opt.layout() == kStrided,
43
+ "grid_sampler(): expected input and grid to have torch.strided layout, but "
44
+ "input has ", input_opt.layout(), " and grid has ", grid_opt.layout());
45
+ TORCH_CHECK(
46
+ input.size(0) == grid.size(0),
47
+ "grid_sampler(): expected grid and input to have same batch size, but got "
48
+ "input with sizes ", input.sizes(), " and grid with sizes ", grid.sizes());
49
+ TORCH_CHECK(
50
+ grid.size(-1) == input.dim() - 2,
51
+ "grid_sampler(): expected grid to have size ", input.dim() - 2, " in last "
52
+ "dimension, but got grid with sizes ", grid.sizes());
53
+
54
+ for (const auto i : c10::irange(2, input.dim())) {
55
+ TORCH_CHECK(input.size(i) > 0,
56
+ "grid_sampler(): expected input to have non-empty spatial dimensions, "
57
+ "but input has sizes ", input.sizes(), " with dimension ", i, " being "
58
+ "empty");
59
+ }
60
+ }
61
+
62
+ // See NOTE [ grid_sampler Native Functions ].
63
+ void check_grid_sampler_2d(
64
+ const TensorBase& input,
65
+ const TensorBase& grid
66
+ ) {
67
+ TORCH_CHECK(
68
+ input.dim() == 4 && input.dim() == grid.dim(),
69
+ "grid_sampler(): expected 4D input and grid with same number of "
70
+ "dimensions, but got input with sizes ", input.sizes(),
71
+ " and grid with sizes ", grid.sizes());
72
+ }
73
+
74
+ // See NOTE [ grid_sampler Native Functions ].
75
+ void check_grid_sampler_3d(
76
+ const TensorBase& input,
77
+ const TensorBase& grid,
78
+ int64_t interpolation_mode
79
+ ) {
80
+ TORCH_CHECK(
81
+ input.dim() == 5 && input.dim() == grid.dim(),
82
+ "grid_sampler(): expected 5D input and grid with same number of "
83
+ "dimensions, but got input with sizes ", input.sizes(),
84
+ " and grid with sizes ", grid.sizes());
85
+ TORCH_CHECK(
86
+ !(input.dim() == 5 &&
87
+ static_cast<GridSamplerInterpolation>(interpolation_mode) ==
88
+ GridSamplerInterpolation::Bicubic),
89
+ "grid_sampler(): bicubic interpolation only supports 4D input");
90
+ }
91
+
92
+ // See NOTE [ grid_sampler Native Functions ].
93
+ // cudnn does not support inputs larger than 1024.
94
+ bool cond_cudnn_grid_sampler(
95
+ const TensorBase& input,
96
+ const TensorBase& grid
97
+ ) {
98
+ return (
99
+ at::native::cudnn_is_acceptable(input) &&
100
+ at::native::cudnn_is_acceptable(grid) &&
101
+ at::native::canUse32BitIndexMath(input) &&
102
+ at::native::canUse32BitIndexMath(grid) &&
103
+ input.dim() == 4 &&
104
+ input.sym_size(1) <= 1024);
105
+ }
106
+
107
+ } // anonymous namespace
108
+
109
+ } // namespace at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/Math.h ADDED
The diff for this file is too large to render. See raw diff
 
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/MaxPooling.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/Parallel.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+
7
+ namespace at::native {
8
+
9
+ // TODO(Heitor) Template by dimension
10
+ struct PoolingParams1D {
11
+ int64_t NB; // Number of batches
12
+ int64_t NC; // Number of channels
13
+ int64_t IW; // Input width
14
+ int64_t OW; // Output width
15
+ int64_t KW; // Kernel width
16
+ int64_t SJ; // Column stride
17
+ int64_t PJ; // Column padding
18
+ int64_t DJ; // Column dilation
19
+
20
+ // Return index of input element for the given kernel and output index
21
+ inline int64_t index(int64_t kj, int64_t oj) const {
22
+ return oj * SJ + kj * DJ - PJ;
23
+ }
24
+
25
+ // Return index of first output within bounds for this kernel index
26
+ inline int64_t valid_output_start(int64_t kj) const {
27
+ int64_t ij = index(kj, 0);;
28
+ return ij < 0 ? at::divup(-ij, SJ) : 0;
29
+ }
30
+
31
+ // Return index one past last output within bounds for this kernel index
32
+ inline int64_t valid_output_end(int64_t kj) const {
33
+ int64_t ij = index(kj, OW - 1);
34
+ return ij >= IW ? OW - at::divup(ij - (IW - 1), SJ) : OW;
35
+ }
36
+ };
37
+
38
+ using pooling_fn = void (*)(Tensor&, const Tensor&, const PoolingParams1D&);
39
+
40
+ DECLARE_DISPATCH(pooling_fn, max_pool1d_stub);
41
+
42
+ } // namespace at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/NonEmptyUtils.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/TensorBase.h>
2
+ #include <algorithm>
3
+ #include <vector>
4
+
5
+ namespace at::native {
6
+
7
+ inline int64_t ensure_nonempty_dim(int64_t dim) {
8
+ return std::max<int64_t>(dim, 1);
9
+ }
10
+
11
+ inline int64_t ensure_nonempty_size(const TensorBase &t, int64_t dim) {
12
+ return t.dim() == 0 ? 1 : t.size(dim);
13
+ }
14
+
15
+ inline int64_t ensure_nonempty_stride(const TensorBase &t, int64_t dim) {
16
+ return t.dim() == 0 ? 1 : t.stride(dim);
17
+ }
18
+
19
+ using IdxVec = std::vector<int64_t>;
20
+ inline IdxVec ensure_nonempty_vec(IdxVec vec) {
21
+ if (vec.empty()) {
22
+ vec.push_back(1);
23
+ }
24
+ return vec;
25
+ }
26
+
27
+ } // namespace at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/Padding.h ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/DispatchStub.h>
5
+
6
+ namespace at::native {
7
+
8
+ using padding_fn = void (*)(const Tensor&, const Tensor&, IntArrayRef);
9
+
10
+ // reflection padding
11
+ DECLARE_DISPATCH(padding_fn, reflection_pad1d_kernel);
12
+ DECLARE_DISPATCH(padding_fn, reflection_pad1d_backward_kernel);
13
+ DECLARE_DISPATCH(padding_fn, reflection_pad2d_kernel);
14
+ DECLARE_DISPATCH(padding_fn, reflection_pad2d_backward_kernel);
15
+ DECLARE_DISPATCH(padding_fn, reflection_pad3d_kernel);
16
+ DECLARE_DISPATCH(padding_fn, reflection_pad3d_backward_kernel);
17
+
18
+ // replication padding
19
+ DECLARE_DISPATCH(padding_fn, replication_pad1d_kernel);
20
+ DECLARE_DISPATCH(padding_fn, replication_pad1d_backward_kernel);
21
+ DECLARE_DISPATCH(padding_fn, replication_pad2d_kernel);
22
+ DECLARE_DISPATCH(padding_fn, replication_pad2d_backward_kernel);
23
+ DECLARE_DISPATCH(padding_fn, replication_pad3d_kernel);
24
+ DECLARE_DISPATCH(padding_fn, replication_pad3d_backward_kernel);
25
+
26
+ namespace padding {
27
+
28
+ template <int dim>
29
+ static inline void check_valid_input(const Tensor& input, IntArrayRef padding) {
30
+
31
+ TORCH_CHECK(padding.size() == 2 * dim,
32
+ "padding size is expected to be ", 2 * dim,
33
+ ", but got: ", padding.size());
34
+
35
+ int input_dim = input.dim();
36
+
37
+ bool is_batch_mode = input_dim == (dim + 2);
38
+
39
+ bool valid_batch_mode = is_batch_mode;
40
+ bool valid_non_batch_mode = !is_batch_mode;
41
+
42
+ if (is_batch_mode) {
43
+ // allow batch size of 0-dim.
44
+ for (const auto d : c10::irange(1, input_dim)) {
45
+ valid_batch_mode = valid_batch_mode && input.size(d) != 0;
46
+ }
47
+ } else {
48
+ for (const auto d : c10::irange(0, input_dim)) {
49
+ valid_non_batch_mode = valid_non_batch_mode && input.size(d) != 0;
50
+ }
51
+ }
52
+
53
+ // allow empty batch size but not other dimensions.
54
+ TORCH_CHECK(valid_batch_mode || valid_non_batch_mode,
55
+ "Expected ", dim + 1, "D or ", dim + 2,
56
+ "D (batch mode) tensor with possibly 0 batch size and other non-zero dimensions for input, but got: ",
57
+ input.sizes());
58
+ }
59
+
60
+ } // namespace padding
61
+
62
+ } // at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/PointwiseOps.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Ternary and higher-order pointwise operations
2
+ #pragma once
3
+
4
+ #include <ATen/native/DispatchStub.h>
5
+
6
+ namespace c10 {
7
+ class Scalar;
8
+ }
9
+
10
+ namespace at {
11
+
12
+ struct TensorIterator;
13
+ struct TensorIteratorBase;
14
+
15
+ namespace native {
16
+
17
+ using pointwise_fn = void (*)(TensorIterator&, const Scalar& scalar);
18
+ using structured_pointwise_fn = void (*)(TensorIteratorBase&, const Scalar& scalar);
19
+ using pointwise_fn_double = void (*)(TensorIterator&, const Scalar&, double);
20
+
21
+ DECLARE_DISPATCH(structured_pointwise_fn, addcmul_stub);
22
+ DECLARE_DISPATCH(structured_pointwise_fn, addcdiv_stub);
23
+ DECLARE_DISPATCH(pointwise_fn_double, smooth_l1_backward_stub);
24
+ DECLARE_DISPATCH(pointwise_fn_double, huber_backward_stub);
25
+ DECLARE_DISPATCH(pointwise_fn, mse_backward_stub);
26
+
27
+ } // namespace native
28
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/Pow.h ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace c10 {
6
+ class Scalar;
7
+ }
8
+
9
+ namespace at {
10
+
11
+ struct TensorIterator;
12
+ struct TensorIteratorBase;
13
+
14
+ namespace native {
15
+
16
+ #if defined(__CUDACC__) || defined(__HIPCC__)
17
+ #define HOST_DEVICE __host__ __device__
18
+ #else
19
+ #define HOST_DEVICE
20
+ #endif
21
+
22
+ // integral power in pytorch allows for negative exponents, giving truncated integral results.
23
+ // e.g. since 2**-1==0.5, the truncated integral result is zero. 1**negative_exponent is the
24
+ // only non-zero result.
25
+ template <class T,
26
+ typename std::enable_if<std::is_integral<T>::value, T>::type* = nullptr>
27
+ static inline HOST_DEVICE __ubsan_ignore_signed_int_overflow__ T powi_impl(T a, T b) {
28
+ T result = 1;
29
+ while (b) {
30
+ if (b & 1) {
31
+ result *= a;
32
+ }
33
+ b /= 2;
34
+ a *= a;
35
+ }
36
+ return result;
37
+ }
38
+
39
+ template <class T,
40
+ typename std::enable_if<std::is_integral<T>::value && !std::is_signed<T>::value, T>::type* = nullptr>
41
+ static inline HOST_DEVICE T powi(T a, T b) {
42
+ return powi_impl(a, b);
43
+ }
44
+
45
+ template <class T,
46
+ typename std::enable_if<std::is_integral<T>::value && std::is_signed<T>::value, T>::type* = nullptr>
47
+ static inline HOST_DEVICE T powi(T a, T b) {
48
+ if ( b < 0 ) {
49
+ if ( a == 1 ) {
50
+ return 1;
51
+ } else if ( a == -1 ) {
52
+ auto negative = (-b) % static_cast<T>(2);
53
+ return negative ? -1 : 1;
54
+ } else {
55
+ return 0;
56
+ }
57
+ }
58
+ return powi_impl(a, b);
59
+ }
60
+
61
+ using pow_tensor_tensor_fn = void (*)(TensorIteratorBase&);
62
+ using pow_tensor_scalar_fn = void (*)(TensorIteratorBase&, const c10::Scalar&);
63
+
64
+ DECLARE_DISPATCH(pow_tensor_tensor_fn, pow_tensor_tensor_stub);
65
+ DECLARE_DISPATCH(pow_tensor_scalar_fn, pow_tensor_scalar_stub);
66
+
67
+ } // namespace native
68
+
69
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/ReduceAllOps.h ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+
5
+ namespace at {
6
+ class Tensor;
7
+ }
8
+
9
+ namespace at::native {
10
+
11
+ using reduce_all_fn = void (*)(Tensor & result, const Tensor & self);
12
+ using reduce_min_max_fn = void (*)(Tensor & max_result, Tensor & min_result, const Tensor & self);
13
+ DECLARE_DISPATCH(reduce_all_fn, min_all_stub);
14
+ DECLARE_DISPATCH(reduce_all_fn, max_all_stub);
15
+
16
+ } // namespace at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/ReduceOps.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/native/DispatchStub.h>
4
+ #include <c10/util/ArrayRef.h>
5
+ #include <c10/util/Optional.h>
6
+
7
+ namespace c10 {
8
+ class Scalar;
9
+ }
10
+
11
+ namespace at {
12
+ struct TensorIterator;
13
+ class Tensor;
14
+ }
15
+
16
+ namespace at::native {
17
+
18
+ using reduce_fn = void(*)(TensorIterator &);
19
+
20
+ DECLARE_DISPATCH(reduce_fn, sum_stub);
21
+ DECLARE_DISPATCH(reduce_fn, nansum_stub);
22
+ DECLARE_DISPATCH(reduce_fn, prod_stub);
23
+ DECLARE_DISPATCH(reduce_fn, mean_stub);
24
+ DECLARE_DISPATCH(reduce_fn, and_stub);
25
+ DECLARE_DISPATCH(reduce_fn, or_stub);
26
+ DECLARE_DISPATCH(reduce_fn, min_values_stub);
27
+ DECLARE_DISPATCH(reduce_fn, max_values_stub);
28
+ DECLARE_DISPATCH(reduce_fn, argmax_stub);
29
+ DECLARE_DISPATCH(reduce_fn, argmin_stub);
30
+
31
+ using reduce_std_var_function =
32
+ void (*)(TensorIterator&, double correction, bool take_sqrt);
33
+ DECLARE_DISPATCH(reduce_std_var_function, std_var_stub);
34
+
35
+ using reduce_norm_fn =
36
+ void (*)(Tensor&, const Tensor&, const c10::Scalar&, c10::optional<int64_t>);
37
+ DECLARE_DISPATCH(reduce_norm_fn, norm_kernel);
38
+
39
+ using reduce_fn_flag = void(*)(TensorIterator &, const c10::Scalar&);
40
+ DECLARE_DISPATCH(reduce_fn_flag, norm_stub);
41
+
42
+ using structured_cum_fn = void (*)(const Tensor&, const Tensor&, int64_t);
43
+ using cum_fn = void (*)(Tensor&, const Tensor&, int64_t);
44
+ DECLARE_DISPATCH(structured_cum_fn, cumsum_stub);
45
+ DECLARE_DISPATCH(structured_cum_fn, cumprod_stub);
46
+ DECLARE_DISPATCH(cum_fn, logcumsumexp_stub);
47
+
48
+ DECLARE_DISPATCH(void (*)(const Tensor&, int64_t, bool, Tensor&, Tensor&), aminmax_stub);
49
+ DECLARE_DISPATCH(void (*)(const Tensor&, Tensor&, Tensor&), aminmax_allreduce_stub);
50
+
51
+ // Used in cuda/Normalization.cu
52
+ TORCH_API std::tuple<Tensor&,Tensor&> var_mean_out(
53
+ Tensor &result1, Tensor &result2, const Tensor &self, IntArrayRef dim,
54
+ int64_t correction, bool keepdim);
55
+
56
+ } // namespace at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/ResizeCommon.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/native/TensorFactories.h>
5
+ #include <ATen/NamedTensorUtils.h>
6
+ #include <c10/util/irange.h>
7
+
8
+ #ifndef AT_PER_OPERATOR_HEADERS
9
+ #include <ATen/NativeFunctions.h>
10
+ #else
11
+ #include <ATen/ops/empty.h>
12
+ #endif
13
+
14
+ namespace at::native {
15
+
16
+ template <typename T>
17
+ inline T storage_size_for(ArrayRef<T> size, ArrayRef<T> stride) {
18
+ TORCH_INTERNAL_ASSERT_DEBUG_ONLY(size.size() == stride.size(),
19
+ "storage_size_for(size, stride) requires that size and stride ",
20
+ "have the same size as a precondition.");
21
+ T storage_size = 1;
22
+ for (const auto dim : c10::irange(size.size())) {
23
+ if (size[dim] == 0) {
24
+ storage_size = 0;
25
+ break;
26
+ }
27
+ storage_size += (size[dim] - 1) * stride[dim];
28
+ }
29
+ return storage_size;
30
+ }
31
+
32
+ inline const Tensor& resize_named_tensor_(
33
+ const Tensor& self,
34
+ IntArrayRef size,
35
+ c10::optional<MemoryFormat> optional_memory_format) {
36
+ TORCH_INTERNAL_ASSERT(self.has_names());
37
+ TORCH_CHECK(
38
+ self.sizes() == size,
39
+ "Cannot resize named tensor with resize_ or resize_as_ (tried to resize "
40
+ "Tensor",
41
+ self.names(),
42
+ " with size ",
43
+ self.sizes(),
44
+ " to ",
45
+ size,
46
+ "). This may be caused by passing a named tensor ",
47
+ "as an `out=` argument; please ensure that the sizes are the same. ");
48
+ TORCH_CHECK(
49
+ !optional_memory_format.has_value(),
50
+ "Unsupported memory format for named tensor resize ",
51
+ optional_memory_format.value());
52
+ return self;
53
+ }
54
+
55
+ // For deterministic output, fill new elements that were added after a storage
56
+ // resize with NaN or MAX_INT. `old_storage_nbytes` is the size of the storage
57
+ // before the resize happened.
58
+ inline const Tensor& fill_resize_deterministic_(const Tensor& tensor, int64_t old_storage_nbytes) {
59
+ const at::Storage& storage = tensor.unsafeGetTensorImpl()->unsafe_storage();
60
+ int64_t new_storage_nbytes = storage.nbytes();
61
+ int64_t old_storage_numel = old_storage_nbytes / tensor.itemsize();
62
+ int64_t new_storage_numel = new_storage_nbytes / tensor.itemsize();
63
+ if (new_storage_numel > old_storage_numel) {
64
+ at::Tensor tensor_view = at::empty({}, at::TensorOptions().dtype(tensor.scalar_type()).device(tensor.device()));
65
+ tensor_view.set_(
66
+ storage,
67
+ /*storage_offset=*/old_storage_numel,
68
+ /*size=*/{new_storage_numel - old_storage_numel},
69
+ /*stride=*/{1});
70
+ at::native::fill_empty_deterministic_(tensor_view);
71
+ }
72
+ return tensor;
73
+ }
74
+
75
+ } // namespace at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/SparseTensorUtils.h ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/Parallel.h>
4
+ #include <ATen/SparseTensorImpl.h>
5
+ #include <ATen/core/Tensor.h>
6
+
7
+ #ifndef AT_PER_OPERATOR_HEADERS
8
+ #include <ATen/Functions.h>
9
+ #else
10
+ #include <ATen/ops/empty.h>
11
+ #include <ATen/ops/tensor.h>
12
+ #endif
13
+
14
+ namespace at::sparse {
15
+
16
+ // Just for documentary purposes
17
+ using SparseTensor = Tensor;
18
+ using SparseType = Type;
19
+
20
+ // This is an internal utility function for getting at the SparseTensorImpl,
21
+ // so that we can write sparse tensor specific accessors for special fields
22
+ // in SparseTensor. You should only use this for writing low level
23
+ // setters/getters for SparseTensorImpl fields; otherwise, you should use
24
+ // the low level setters/getters that were implemented using this.
25
+ //
26
+ // This may be called repeatedly, so make sure it's pretty cheap.
27
+ inline SparseTensorImpl* get_sparse_impl(const SparseTensor& self) {
28
+ TORCH_INTERNAL_ASSERT(
29
+ self.is_sparse(), "_internal_get_SparseTensorImpl: not a sparse tensor");
30
+ return static_cast<SparseTensorImpl*>(self.unsafeGetTensorImpl());
31
+ }
32
+
33
+ // Takes indices and values and directly puts them into the sparse tensor, no
34
+ // copy. This used to be called THSTensor_(_move)
35
+ inline void alias_into_sparse(
36
+ const SparseTensor& self,
37
+ const Tensor& indices,
38
+ const Tensor& values) {
39
+ get_sparse_impl(self)->set_indices_and_values_unsafe(indices, values);
40
+ }
41
+
42
+ // Take indices and values and makes a (data) copy of them to put into the
43
+ // sparse indices/values. This used to be called THSTensor_(_set)
44
+ inline void copy_into_sparse(
45
+ const SparseTensor& self,
46
+ const Tensor& indices,
47
+ const Tensor& values,
48
+ bool non_blocking) {
49
+ alias_into_sparse(
50
+ self,
51
+ indices.to(self._indices().options(), non_blocking, /*copy=*/true),
52
+ values.to(self._values().options(), non_blocking, /*copy=*/true));
53
+ }
54
+
55
+ // TODO: put this into the public API
56
+ inline bool is_same_tensor(const Tensor& lhs, const Tensor& rhs) {
57
+ return lhs.unsafeGetTensorImpl() == rhs.unsafeGetTensorImpl();
58
+ }
59
+
60
+ inline bool is_same_density(const SparseTensor& self, const SparseTensor& src) {
61
+ return self.sparse_dim() == src.sparse_dim() &&
62
+ self.dense_dim() == src.dense_dim();
63
+ }
64
+
65
+ // Give us a new values tensor, with the same dimensionality
66
+ // as 'values' but with a new number of non-zero elements.
67
+ // TODO: Expose this for real in ATen, some day?
68
+ // NB: Doesn't preserve data.
69
+ inline Tensor new_values_with_size_of(const Tensor& values, int64_t nnz) {
70
+ std::vector<int64_t> size = values.sizes().vec();
71
+ size[0] = nnz;
72
+ return at::empty(size, values.options());
73
+ }
74
+
75
+ // NOTE [ Flatten Sparse Indices ]
76
+ // This helper function flattens a sparse indices tensor (a Tensor) into a 1D
77
+ // indices tensor. E.g.,
78
+ // input = [[2, 4, 0],
79
+ // [3, 1, 10]]
80
+ // full_size = [2, 12]
81
+ // output = [ 2 * 12 + 3, 4 * 12 + 1, 0 * 12 + 10 ] = [27, 49, 10]
82
+ //
83
+ // In other words, assuming that each `indices[i, :]` is a valid index to a
84
+ // tensor `t` of shape `full_size`. This returns the corresponding indices to
85
+ // the flattened tensor `t.reshape( prod(full_size[:indices.size(0)]), -1 )`.
86
+ // if forceClone is true, the result will forced to be a clone of self.
87
+ // if force_clone is true, the result will forced to be a clone of self.
88
+ TORCH_API Tensor flatten_indices(
89
+ const Tensor& indices,
90
+ IntArrayRef full_size,
91
+ bool force_clone = false);
92
+
93
+ // Flatten sparse tensor's indices from nD to 1D, similar to NOTE [ Flatten
94
+ // Sparse Indices ], except this one allows partial flatten: only flatten on
95
+ // specified dims. Note that the flatten indices might be uncoalesced if
96
+ // dims_to_flatten.size() < sparse_dim. Also if input indices is already
97
+ // coalesced, the flattened indices will also be sorted.
98
+ //
99
+ // args:
100
+ // indices: sparse tensor indices
101
+ // sizes: sparse tensor sizes
102
+ // dims_to_flatten: a list of dim index to flatten
103
+ //
104
+ // Ex1:
105
+ // indices = [[2, 4, 0],
106
+ // [3, 1, 3]]
107
+ // sizes = [2, 12]
108
+ // dims_to_flatten = [0, 1]
109
+ // new_indices = [ 2 * 12 + 3, 4 * 12 + 1, 0 * 12 + 3 ] = [27, 49, 3]
110
+ //
111
+ // Ex2:
112
+ // dims_to_flatten = [1]
113
+ // new_indices = [ 3, 1, 3 ] # uncoalesced
114
+ TORCH_API Tensor flatten_indices_by_dims(
115
+ const Tensor& indices,
116
+ const IntArrayRef& sizes,
117
+ const IntArrayRef& dims_to_flatten);
118
+
119
+ // Find the CSR representation for a row `indices` from the COO format
120
+ TORCH_API Tensor coo_to_csr(const int64_t* indices, int64_t dim, int64_t nnz);
121
+
122
+ TORCH_API Tensor zeros_like_with_indices(const Tensor& t);
123
+
124
+ template <size_t static_shape_max_len>
125
+ class TensorGeometryHolder {
126
+ using geometry_holder_t = std::array<int64_t, static_shape_max_len>;
127
+
128
+ public:
129
+ explicit TensorGeometryHolder(
130
+ IntArrayRef sizes,
131
+ IntArrayRef strides,
132
+ TensorOptions options = {}) {
133
+ std::copy(sizes.begin(), sizes.end(), t_sizes.begin());
134
+ std::copy(strides.begin(), strides.end(), t_strides.begin());
135
+ }
136
+
137
+ explicit TensorGeometryHolder(const Tensor& t)
138
+ : TensorGeometryHolder(t.sizes(), t.strides()) {}
139
+
140
+ auto operator*() const {
141
+ return std::make_tuple(t_sizes, t_strides);
142
+ }
143
+
144
+ private:
145
+ geometry_holder_t t_sizes;
146
+ geometry_holder_t t_strides;
147
+ };
148
+
149
+ template <>
150
+ class TensorGeometryHolder<0> {
151
+ using geometry_holder_t = Tensor;
152
+
153
+ public:
154
+ explicit TensorGeometryHolder(
155
+ IntArrayRef sizes,
156
+ IntArrayRef strides,
157
+ TensorOptions options) {
158
+ const int64_t t_ndims = sizes.size();
159
+ const auto cpu_options = TensorOptions(options).dtype(kLong).device(kCPU);
160
+ Tensor t_sizes_and_strides_cpu = at::empty({2, t_ndims}, cpu_options);
161
+ t_sizes_and_strides_cpu.select(0, 0).copy_(at::tensor(sizes, cpu_options));
162
+ t_sizes_and_strides_cpu.select(0, 1).copy_(
163
+ at::tensor(strides, cpu_options));
164
+ const Tensor t_sizes_and_strides =
165
+ t_sizes_and_strides_cpu.to(options.device());
166
+ t_sizes = t_sizes_and_strides.select(0, 0);
167
+ t_strides = t_sizes_and_strides.select(0, 1);
168
+ }
169
+
170
+ explicit TensorGeometryHolder(const Tensor& t)
171
+ : TensorGeometryHolder(t.sizes(), t.strides(), t.options()) {}
172
+
173
+ auto operator*() const {
174
+ return std::make_tuple(
175
+ t_sizes.template data_ptr<int64_t>(),
176
+ t_strides.template data_ptr<int64_t>());
177
+ }
178
+
179
+ private:
180
+ geometry_holder_t t_sizes;
181
+ geometry_holder_t t_strides;
182
+ };
183
+
184
+ } // namespace at::sparse
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/TensorFactories.h ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/EmptyTensor.h>
5
+ #include <ATen/TensorIterator.h>
6
+ #include <ATen/Dispatch.h>
7
+ #include <ATen/native/DispatchStub.h>
8
+
9
+ #ifndef AT_PER_OPERATOR_HEADERS
10
+ #include <ATen/Functions.h>
11
+ #else
12
+ #include <ATen/ops/scalar_tensor.h>
13
+ #endif
14
+
15
+ namespace at::native {
16
+ // Different combinations of row, col, and offset can lead to two cases:
17
+ //
18
+ // Case 1 - Trapezoid (Triangle as a special case): row + offset <= col
19
+ // Example A: offset > 0
20
+ // 1 1 0 0 0
21
+ // 1 1 1 0 0
22
+ // 1 1 1 1 0
23
+ // Example B: offset <= 0
24
+ // 0 0 0
25
+ // 1 0 0
26
+ // 1 1 0
27
+ // In this case, we calculate the number of elements in the first row and
28
+ // last row of the tril respectively, and then compute the tril size.
29
+ //
30
+ // Case 2 - Trapezoid + Rectangle: row + offset > col
31
+ // Example:
32
+ // 1 1 0
33
+ // 1 1 1
34
+ // 1 1 1
35
+ // In this case, we first calculate the size of top trapezoid, and then
36
+ // calculate the size of the bottom rectangle.
37
+ inline int64_t get_tril_size(int64_t row, int64_t col, int64_t offset) {
38
+ // If either dimension is 0 then the there is no tril
39
+ if (row == 0 || col == 0) {
40
+ return 0;
41
+ }
42
+ // number of elements in the first row of the tril
43
+ auto m_first_row = offset > 0 ?
44
+ std::min<int64_t>(col, 1 + offset) : // upper bounded by col
45
+ row + offset > 0; // either 0 or 1
46
+ // number of elements in the last row of the tril, bounded by [0, col]
47
+ auto m_last_row = std::max<int64_t>(0, std::min<int64_t>(col, row + offset));
48
+ // number of rows, bounded by [0, row]
49
+ auto n_row_all = std::max<int64_t>(0, std::min<int64_t>(row, row + offset));
50
+ auto n_row_trapezoid = (m_last_row - m_first_row + 1);
51
+
52
+ // calculate # of elements in the top trapezoid
53
+ auto tril_size = (m_first_row + m_last_row) * n_row_trapezoid >> 1;
54
+
55
+ // calculate # of elements in the bottom rectangle if there is any
56
+ auto diff_row = n_row_all - n_row_trapezoid;
57
+ if (diff_row > 0) {
58
+ tril_size += diff_row * col;
59
+ }
60
+
61
+ return tril_size;
62
+ }
63
+
64
+ inline void check_args(
65
+ int64_t row, int64_t col, c10::optional<Layout> layout_opt) {
66
+ TORCH_CHECK(row >= 0, "row must be non-negative, got", row);
67
+ TORCH_CHECK(col >= 0, "col must be non-negative, got", col);
68
+ if (layout_opt.has_value()) {
69
+ TORCH_CHECK(
70
+ *layout_opt == at::kStrided,
71
+ "only support layout=torch.strided, got",
72
+ *layout_opt)
73
+ }
74
+ }
75
+
76
+ using at::check_size_nonnegative;
77
+
78
+ // assumes maximum value in created tensor is n-1 (e.g., torch.randperm(n))
79
+ inline void check_supported_max_int_with_precision(int64_t n, const Tensor& tensor) {
80
+ // match defined() to behavior of checks below
81
+ TORCH_CHECK(at::scalar_tensor(n>0?n-1:n, tensor.options()).defined(),
82
+ "n is too large for result tensor type: '", tensor.toString(), "'");
83
+
84
+ // Ensure sufficient precision for floating point representation.
85
+ switch (tensor.scalar_type()) {
86
+ case at::ScalarType::Half:
87
+ TORCH_CHECK(n <= (int64_t(1) << 11) + 1, "n cannot be greater than 2049 for Half type.");
88
+ break;
89
+ case at::ScalarType::Float:
90
+ TORCH_CHECK(n <= (int64_t(1) << 24) + 1, "n cannot be greater than 2^24+1 for Float type.");
91
+ break;
92
+ case at::ScalarType::Double: // Unlikely to happen, but doesn't hurt to check
93
+ TORCH_CHECK(n <= (int64_t(1) << 53) + 1, "n cannot be greater than 2^53+1 for Double type.");
94
+ break;
95
+ default:
96
+ break;
97
+ }
98
+ }
99
+
100
+ // Called by `empty*` functions when deterministic algorithms are enabled to
101
+ // fill the tensor with NaN if it is floating point or complex type, or fill
102
+ // with max value if it is integer type
103
+ inline Tensor& fill_empty_deterministic_(Tensor& tensor) {
104
+ if (tensor.is_floating_point() || tensor.is_complex()) {
105
+ AT_DISPATCH_FLOATING_AND_COMPLEX_TYPES_AND2(
106
+ kBFloat16, kHalf, tensor.scalar_type(), "fill_empty_deterministic_", [&]() {
107
+ tensor.fill_(std::numeric_limits<scalar_t>::quiet_NaN());
108
+ });
109
+ } else {
110
+ AT_DISPATCH_INTEGRAL_TYPES_AND(
111
+ kBool, tensor.scalar_type(), "fill_empty_deterministic_", [&]() {
112
+ tensor.fill_(std::numeric_limits<scalar_t>::max());
113
+ });
114
+ }
115
+ return tensor;
116
+ }
117
+
118
+ // The ZeroTensor allocator ignores whatever allocation is requested and always
119
+ // gives you nullptr
120
+ struct ZeroTensorAllocator final : public at::Allocator {
121
+ ZeroTensorAllocator(at::Device device) : device_(device) {};
122
+ ~ZeroTensorAllocator() override = default;
123
+ static void deleter(void* const pointer) {
124
+ TORCH_INTERNAL_ASSERT(!pointer);
125
+ }
126
+ DataPtr allocate(const size_t /*nbytes*/) const override {
127
+ return {nullptr, nullptr, &deleter, device_};
128
+ }
129
+ DeleterFnPtr raw_deleter() const override {
130
+ return deleter;
131
+ }
132
+ at::Device device_;
133
+ };
134
+
135
+ using binary_fn = void (*)(TensorIterator&);
136
+
137
+ DECLARE_DISPATCH(binary_fn, complex_stub);
138
+ DECLARE_DISPATCH(binary_fn, polar_stub);
139
+
140
+ } // namespace at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/TriangularOpsUtils.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include <ATen/core/Tensor.h>
2
+ #include <ATen/native/LinearAlgebraUtils.h>
3
+
4
+ namespace at::native {
5
+
6
+ /*
7
+ * Given batches of matrices with arbitrary batch dim,
8
+ * computes the number of batches for Triu and Tril. This ignores stride 0 dimension
9
+ */
10
+ static inline int64_t batchCountTrilTriu(const Tensor& batched_matrices) {
11
+ int64_t result = 1;
12
+ for (int64_t i = 0; i < batched_matrices.ndimension() - 2; i++) {
13
+ if (batched_matrices.stride(i) != 0) {
14
+ result *= batched_matrices.size(i);
15
+ }
16
+ }
17
+ return result;
18
+ }
19
+
20
+ /* Checks a necessary property for the triu and tril implementations, hence the name.
21
+ * Here batch contiguity is checked for tensors with greater than 4 dimensions.
22
+ * Contiguous tensors and tensors with less than 3 dimensions pass this check
23
+ */
24
+ static inline std::tuple<bool, Tensor> checkTrilTriuBatchContiguous(const Tensor& tensor, bool allow_zero_stride) {
25
+ // Complete contiguity is the most desired property, which is why
26
+ // we return true if the tensor is contiguous
27
+ if (tensor.is_contiguous()) {
28
+ auto default_strides_for_size = batched_matrix_contiguous_strides(tensor.sizes());
29
+ if (tensor.strides() == default_strides_for_size) {
30
+ return std::make_tuple(true, tensor);
31
+ } else {
32
+ return std::make_tuple(false, tensor.as_strided(tensor.sizes(), default_strides_for_size));
33
+ }
34
+ }
35
+
36
+ int64_t dims = tensor.dim();
37
+
38
+ // Tensors with dimension less than 4 are handled by default
39
+ if (allow_zero_stride && dims <= 3) {
40
+ return std::make_tuple(true, tensor);
41
+ }
42
+
43
+ int64_t expected_stride = tensor.size(-1) * tensor.size(-2);
44
+ for (int64_t i = dims - 3; i >= 0; i--) {
45
+ // Skip trivial dimension;
46
+ if (allow_zero_stride && i == 0 && (tensor.stride(i) == 0 || tensor.size(i) == 1)) {
47
+ continue;
48
+ }
49
+ if (expected_stride != tensor.stride(i)) {
50
+ return std::make_tuple(false, tensor.contiguous());
51
+ }
52
+ expected_stride *= tensor.size(i);
53
+ }
54
+ return std::make_tuple(true, tensor);
55
+ }
56
+
57
+ } // namespace at::native
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/AffineQuantizer.h ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/Dispatch.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+ #include <ATen/native/quantized/AffineQuantizerBase.h>
7
+
8
+ namespace at {
9
+ namespace native {
10
+
11
+ Tensor& quantize_tensor_per_tensor_affine(
12
+ const Tensor& rtensor,
13
+ Tensor& qtensor,
14
+ double scale,
15
+ int64_t zero_point);
16
+ Tensor& quantize_tensor_per_channel_affine(
17
+ const Tensor& rtensor,
18
+ Tensor& qtensor,
19
+ Tensor scales,
20
+ Tensor zero_points,
21
+ int64_t axis);
22
+
23
+ Tensor& quantize_tensor_per_channel_float_qparams(
24
+ const Tensor& rtensor,
25
+ Tensor& qtensor,
26
+ Tensor scales,
27
+ Tensor zero_points,
28
+ int64_t axis);
29
+
30
+ Tensor& dequantize_tensor_per_tensor_affine(
31
+ const Tensor& qtensor,
32
+ Tensor& rtensor,
33
+ double scale,
34
+ int64_t zero_point);
35
+ Tensor& dequantize_tensor_per_channel_affine(
36
+ const Tensor& qtensor,
37
+ Tensor& rtensor,
38
+ Tensor scales,
39
+ Tensor zero_points,
40
+ int64_t axis);
41
+ Tensor& dequantize_tensor_per_channel_float_qparams(
42
+ const Tensor& qtensor,
43
+ Tensor& rtensor,
44
+ Tensor scales,
45
+ Tensor zero_points,
46
+ int64_t axis);
47
+
48
+ using quantize_tensor_per_tensor_affine_fn =
49
+ void (*)(const Tensor& rtensor, Tensor& qtensor, double scale, int64_t zero_point);
50
+
51
+ using quantize_tensor_per_channel_affine_fn = void (*)(
52
+ const Tensor& rtensor,
53
+ Tensor& qtensor,
54
+ const Tensor& scales,
55
+ const Tensor& zero_points,
56
+ int64_t axis);
57
+
58
+ using quantize_tensor_per_channel_float_qparams_fn = void (*)(
59
+ const Tensor& rtensor,
60
+ Tensor& qtensor,
61
+ const Tensor& scales,
62
+ const Tensor& zero_points,
63
+ int64_t axis);
64
+
65
+ using dequantize_tensor_per_tensor_affine_fn =
66
+ void (*)(const Tensor& qtensor, Tensor& rtensor, double scale, int64_t zero_point);
67
+
68
+ using dequantize_tensor_per_channel_affine_fn = void (*)(
69
+ const Tensor& qtensor,
70
+ Tensor& rtensor,
71
+ const Tensor& scales,
72
+ const Tensor& zero_points,
73
+ int64_t axis);
74
+
75
+ using dequantize_tensor_per_channel_float_qparams_fn = void (*)(
76
+ const Tensor& qtensor,
77
+ Tensor& rtensor,
78
+ const Tensor& scales,
79
+ const Tensor& zero_points,
80
+ int64_t axis);
81
+
82
+ using quantize_tensor_per_tensor_affine_sub_byte_fn =
83
+ void (*)(const Tensor& rtensor, Tensor& qtensor, float scale, float zero_point);
84
+
85
+ using dequantize_tensor_per_tensor_affine_sub_byte_fn =
86
+ void (*)(const Tensor& qtensor, Tensor& rtensor, float scale, float zero_point);
87
+
88
+ DECLARE_DISPATCH(
89
+ quantize_tensor_per_tensor_affine_fn,
90
+ quantize_tensor_per_tensor_affine_stub);
91
+ DECLARE_DISPATCH(
92
+ quantize_tensor_per_channel_affine_fn,
93
+ quantize_tensor_per_channel_affine_stub);
94
+ DECLARE_DISPATCH(
95
+ quantize_tensor_per_channel_float_qparams_fn,
96
+ quantize_tensor_per_channel_float_qparams_stub);
97
+
98
+ DECLARE_DISPATCH(
99
+ dequantize_tensor_per_tensor_affine_fn,
100
+ dequantize_tensor_per_tensor_affine_stub);
101
+ DECLARE_DISPATCH(
102
+ dequantize_tensor_per_channel_affine_fn,
103
+ dequantize_tensor_per_channel_affine_stub);
104
+ DECLARE_DISPATCH(
105
+ dequantize_tensor_per_channel_float_qparams_fn,
106
+ dequantize_tensor_per_channel_float_qparams_stub);
107
+
108
+ DECLARE_DISPATCH(
109
+ quantize_tensor_per_tensor_affine_sub_byte_fn,
110
+ quantize_tensor_per_tensor_affine_sub_byte_stub);
111
+
112
+ DECLARE_DISPATCH(
113
+ dequantize_tensor_per_tensor_affine_sub_byte_fn,
114
+ dequantize_tensor_per_tensor_affine_sub_byte_stub);
115
+
116
+ template <typename T>
117
+ TORCH_API Tensor quantize_tensor(
118
+ Tensor rtensor,
119
+ Tensor qtensor,
120
+ double scale,
121
+ int64_t zero_point);
122
+ template <typename T>
123
+ TORCH_API Tensor dequantize_tensor(
124
+ Tensor qtensor,
125
+ Tensor rtensor,
126
+ double scale,
127
+ int64_t zero_point);
128
+
129
+ } // namespace native
130
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/FakeQuantAffine.h ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/Dispatch.h>
5
+ #include <ATen/native/DispatchStub.h>
6
+
7
+ namespace at {
8
+
9
+ struct TensorIterator;
10
+
11
+ namespace native {
12
+
13
+ using fake_quant_tensor_cachemask_fn = void (*)(
14
+ Tensor& output,
15
+ Tensor& mask,
16
+ const Tensor& input,
17
+ float sc,
18
+ int64_t z_point,
19
+ int64_t quant_min,
20
+ int64_t quant_max);
21
+
22
+ using fake_quant_tensor_cachemask_tensor_qparams_fn = void (*)(
23
+ Tensor& output,
24
+ Tensor& mask,
25
+ const Tensor& input,
26
+ const Tensor& sc,
27
+ const Tensor& z_point,
28
+ const Tensor& fake_quant_enabled,
29
+ int64_t quant_min,
30
+ int64_t quant_max);
31
+
32
+ using fake_quant_learnable_grad_tensor_fn = void (*)(
33
+ TensorIterator& iter,
34
+ float scale,
35
+ float inv_scale,
36
+ int64_t zero_point,
37
+ int64_t quant_min,
38
+ int64_t quant_max,
39
+ float grad_factor);
40
+
41
+ DECLARE_DISPATCH(fake_quant_tensor_cachemask_fn, fake_quant_tensor_cachemask_stub);
42
+ DECLARE_DISPATCH(fake_quant_tensor_cachemask_tensor_qparams_fn, fake_quant_tensor_cachemask_tensor_qparams_stub);
43
+ DECLARE_DISPATCH(fake_quant_learnable_grad_tensor_fn, fake_quant_grad_learnable_tensor_stub);
44
+
45
+ using fake_quant_per_channel_fn = void (*)(
46
+ TensorIterator &iter,
47
+ int64_t quant_min,
48
+ int64_t quant_max);
49
+
50
+ using fake_quant_per_channel_cachemask_fn = void (*)(
51
+ TensorIterator &iter,
52
+ TensorIterator &iter_mask,
53
+ int64_t quant_min,
54
+ int64_t quant_max);
55
+
56
+ DECLARE_DISPATCH(fake_quant_per_channel_cachemask_fn, fake_quant_per_channel_cachemask_stub);
57
+
58
+ using fake_quant_learnable_per_channel_fn = void (*)(
59
+ TensorIterator &iter,
60
+ int64_t quant_min,
61
+ int64_t quant_max,
62
+ float grad_factor);
63
+
64
+ DECLARE_DISPATCH(fake_quant_learnable_per_channel_fn, fake_quant_grad_learnable_channel_stub);
65
+
66
+ } // namespace native
67
+ } // namespace at
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/IndexKernel.h ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #include <ATen/native/TensorIterator.h>
3
+
4
+ namespace at {
5
+ namespace native {
6
+ using masked_fill_kernel_quantized_fn = void(*)(TensorIterator& iter, const Scalar& value, double scale, int zero_point);
7
+ using index_put_kernel_quantized_fn = void(*)(TensorIterator& iter, IntArrayRef index_size, IntArrayRef index_stride, bool accumulate, double scale, int zero_point);
8
+
9
+ DECLARE_DISPATCH(masked_fill_kernel_quantized_fn, masked_fill_kernel_quantized_stub);
10
+ DECLARE_DISPATCH(index_put_kernel_quantized_fn, index_put_kernel_quantized_stub);
11
+
12
+
13
+ } // native
14
+ } // at
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/PackedParams.h ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/core/ivalue.h>
5
+
6
+ struct LinearPackedParamsBase : public torch::jit::CustomClassHolder {
7
+ virtual at::Tensor apply(
8
+ at::Tensor input,
9
+ double output_scale,
10
+ int64_t output_zero_point) = 0;
11
+ virtual at::Tensor apply_relu(
12
+ at::Tensor input,
13
+ double output_scale,
14
+ int64_t output_zero_point) = 0;
15
+
16
+ // out variant of LinearPackedParamsBase::apply
17
+ virtual at::Tensor& apply_out(
18
+ const at::Tensor& /*input*/,
19
+ double /*output_scale*/,
20
+ int64_t /*output_zero_point*/,
21
+ at::Tensor& output) {
22
+ throw std::runtime_error(
23
+ "apply_out is not implemented for this packed "
24
+ "parameter type");
25
+ return output;
26
+ }
27
+
28
+ virtual at::Tensor& apply_relu_out(
29
+ const at::Tensor& /*input*/,
30
+ double /*output_scale*/,
31
+ int64_t /*output_zero_point*/,
32
+ at::Tensor& output) {
33
+ throw std::runtime_error(
34
+ "apply_relu_out is not implemented for this packed "
35
+ "parameter type");
36
+ return output;
37
+ }
38
+
39
+ // Corresponding pattern (the ops with `*` are part of the pattern that
40
+ // represents the computation of quantized::linear_with_input_q_dq_qweight_dq_output_fp32):
41
+ // input -> q* -> dq* -> linear* ->
42
+ // qweight -> dq* /
43
+ //
44
+ // After fusion:
45
+ // input -> quantized::linear_with_input_q_dq_qweight_dq_output_fp32* ->
46
+ // qweight /
47
+ //
48
+ // Additional Note: the weight is packed as well
49
+ // Params:
50
+ // X: float32 Tensor, will be quantized to quint8 in the op
51
+ // W_prepack: packed qint8 quantized weight and bias
52
+ // Returns:
53
+ // Y: float32 Tensor
54
+ virtual at::Tensor apply_with_input_q_dq_qweight_dq_output_fp32(
55
+ at::Tensor input,
56
+ double input_scale,
57
+ int64_t input_zero_point) {
58
+ throw std::runtime_error(
59
+ "apply_with_input_q_dq_qweight_dq_output_fp32 is not implemented for this packed "
60
+ "parameter type");
61
+ return {};
62
+ }
63
+
64
+ // Corresponding pattern (the ops with `*` are part of the pattern that
65
+ // represents the computation of quantized::linear_with_input_q_dq_qweight_dq_relu_output_fp32):
66
+ // input -> q* -> dq* -> linear* -> relu* ->
67
+ // qweight -> dq* /
68
+ //
69
+ // After fusion:
70
+ // input -> quantized::linear_with_input_q_dq_qweight_dq_relu_output_fp32* ->
71
+ // qweight /
72
+ //
73
+ // Additional Note: the weight is packed as well
74
+ // Params:
75
+ // input: float32 Tensor, will be quantized to quint8 in the op
76
+ // Returns:
77
+ // float32 Tensor
78
+ virtual at::Tensor apply_with_input_q_dq_qweight_dq_relu_output_fp32(
79
+ at::Tensor input,
80
+ double input_scale,
81
+ int64_t input_zero_point) {
82
+ throw std::runtime_error(
83
+ "apply_with_input_q_dq_qweight_dq_relu_output_fp32 is not implemented for this packed "
84
+ "parameter type");
85
+ return {};
86
+ }
87
+
88
+ virtual at::Tensor apply_dynamic(
89
+ at::Tensor input,
90
+ bool reduce_range = false) = 0;
91
+ virtual at::Tensor apply_dynamic_relu(
92
+ at::Tensor input,
93
+ bool reduce_range = false) = 0;
94
+
95
+ virtual at::Tensor& apply_dynamic_out(
96
+ const at::Tensor& /* input */,
97
+ at::Tensor& output,
98
+ bool /* reduce_range */) {
99
+ throw std::runtime_error(
100
+ "apply_dynamic_out is not implemented for this packed "
101
+ "parameter type");
102
+ return output;
103
+ }
104
+ virtual at::Tensor& apply_dynamic_relu_out(
105
+ const at::Tensor& /* input */,
106
+ at::Tensor& output,
107
+ bool /* reduce_range */) {
108
+ throw std::runtime_error(
109
+ "apply_dynamic_relu_out is not implemented for this packed "
110
+ "parameter type");
111
+ return output;
112
+ }
113
+
114
+ virtual std::tuple<at::Tensor, c10::optional<at::Tensor>> unpack() = 0;
115
+
116
+ virtual c10::optional<at::Tensor> bias() = 0;
117
+
118
+ virtual void set_bias(c10::optional<at::Tensor> /*bias*/) {
119
+ throw std::runtime_error(
120
+ "set_bias is not implemented for this packed "
121
+ "parameter type");
122
+ }
123
+ };
124
+
125
+ template <int kSpatialDim = 2>
126
+ struct ConvPackedParamsBase : public torch::jit::CustomClassHolder {
127
+ virtual at::Tensor apply(
128
+ const at::Tensor& input,
129
+ double output_scale,
130
+ int64_t output_zero_point) = 0;
131
+ virtual at::Tensor apply_relu(
132
+ const at::Tensor& input,
133
+ double output_scale,
134
+ int64_t output_zero_point) = 0;
135
+ virtual at::Tensor apply_dynamic(
136
+ const at::Tensor& input,
137
+ bool reduce_range) = 0;
138
+
139
+ virtual std::tuple<at::Tensor, c10::optional<at::Tensor>> unpack() = 0;
140
+
141
+ virtual torch::List<int64_t> stride() const = 0;
142
+ virtual torch::List<int64_t> padding() const = 0;
143
+ virtual torch::List<int64_t> output_padding() const = 0;
144
+ virtual torch::List<int64_t> dilation() const = 0;
145
+ virtual int64_t groups() const = 0;
146
+ virtual bool transpose() const = 0;
147
+ };
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/cpu/QuantUtils.h ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/core/Tensor.h>
4
+ #include <ATen/core/List.h>
5
+ #include <ATen/TensorOperators.h>
6
+ #include <c10/util/irange.h>
7
+ #include <algorithm>
8
+ #include <cmath>
9
+
10
+ #ifndef AT_PER_OPERATOR_HEADERS
11
+ #include <ATen/Functions.h>
12
+ #include <ATen/NativeFunctions.h>
13
+ #else
14
+ #include <ATen/ops/quantize_per_tensor_native.h>
15
+ #include <ATen/ops/quantize_per_channel_native.h>
16
+ #include <ATen/ops/zeros.h>
17
+ #endif
18
+
19
+ namespace quant_utils {
20
+ namespace {
21
+ float RawUint16ToFp16(unsigned short value) {
22
+ // Convert raw 16 bits half precision floating point number
23
+ // to single precision floating point number.
24
+ const unsigned short sign_bits = value >> 15;
25
+ const unsigned short exponent_bits = value >> 10 & 0x1f;
26
+ const unsigned short significand_bits = value & 0x3ff;
27
+
28
+ const float sign = sign_bits ? -1 : 1;
29
+ const float significand =
30
+ 1 + significand_bits * 0.0009765625f; // 0.0009765625f = 0x1p-10 = 2^-10;
31
+ const float exponent = exponent_bits - 0xf;
32
+
33
+ return sign * std::ldexp(significand, exponent);
34
+ }
35
+
36
+ template <typename T>
37
+ bool CheckAndSaturate(T max_val, T* element) {
38
+ if (*element > max_val) {
39
+ *element = max_val;
40
+ return true;
41
+ }
42
+ if (*element < -max_val) {
43
+ *element = -max_val;
44
+ return true;
45
+ }
46
+ return false;
47
+ }
48
+ }
49
+ using namespace std;
50
+ // A structure to hold quantization parameters 'scale' and 'zero_point'.
51
+ // The meaning of these values is as the constants in the quantization equation
52
+ //
53
+ // real_value = scale * (quantized_value - zero_point)
54
+ //
55
+ // In other words, 'zero_point' is the quantized value that corresponds
56
+ // to the real value 0, and 'scale' is the difference of real values
57
+ // corresponding to consecutive quantized values.
58
+ struct TensorQuantizationParams {
59
+ double scale;
60
+ std::int32_t zero_point;
61
+ int precision;
62
+ };
63
+
64
+ // Use fp16_min as the small scale cutoff because we don't want to use scales in
65
+ // fp16 subnormal range. This is to be consistent with Glow and FakeLowP
66
+ // implementation for NNPI.
67
+ constexpr float SMALL_SCALE_THRESHOLD = 6.1e-5f;
68
+
69
+ // Following implementation should be identical to fbgemm::ChooseQuantizationParams
70
+ inline TensorQuantizationParams ChooseQuantizationParams(
71
+ float min,
72
+ float max,
73
+ int32_t qmin,
74
+ int32_t qmax,
75
+ bool preserve_sparsity = false,
76
+ bool force_scale_power_of_two = false,
77
+ bool reduce_range = false) {
78
+ TORCH_CHECK(
79
+ min <= max,
80
+ "In ChooseQuantizationParams, min should be less than or equal to max");
81
+
82
+ if (reduce_range) {
83
+ qmin = qmin/2;
84
+ qmax = qmax/2;
85
+ }
86
+ if (min < 0 && max > 0 && preserve_sparsity) {
87
+ int symmetric_qmin = -((qmax - qmin) / 2 + 1);
88
+ int symmetric_qmax = (qmax - qmin) / 2;
89
+ double max_scale =
90
+ std::max(fabs(min / symmetric_qmin), fabs(max / symmetric_qmax));
91
+ min = max_scale * symmetric_qmin;
92
+ max = max_scale * symmetric_qmax;
93
+ }
94
+
95
+ // We extend the [min, max] interval to ensure that it contains 0.
96
+ // Otherwise, we would not meet the requirement that 0 be an exactly
97
+ // representable value.
98
+ min = std::min(min, 0.f);
99
+ max = std::max(max, 0.f);
100
+
101
+ TORCH_CHECK(
102
+ qmin < qmax,
103
+ "In ChooseQuantizationParams, qmin should be less than qmax");
104
+
105
+ // Use double precision for intermediate computation but use single precision
106
+ // in final number to reflect the actual number used during quantization.
107
+ double scale = (static_cast<double>(max) - min) / (qmax - qmin);
108
+ // If scale is 0 or too small so its reciprocal is infinity, we arbitrary
109
+ // adjust the scale to 0.1 . We want to avoid scale's reciprocal being
110
+ // infinity because some of fbgemm code pre-computes scale's reciprocal to do
111
+ // multiplication instead of division in the time critical part of code.
112
+ if (float(scale) == 0.0f || std::isinf(1.0f / float(scale))) {
113
+ scale = 0.1;
114
+ }
115
+ TORCH_CHECK(scale > 0, "quantization scale should be > 0");
116
+
117
+ if (force_scale_power_of_two) {
118
+ if (scale < 1) {
119
+ scale = 1.0 / (1 << static_cast<int>(floor(log(1.0 / scale) / log(2))));
120
+ } else {
121
+ scale = 1 << static_cast<int>(ceil(log(scale) / log(2)));
122
+ }
123
+ }
124
+
125
+ // Cut off small scale
126
+ if (scale < SMALL_SCALE_THRESHOLD) {
127
+ float org_scale = scale;
128
+ scale = SMALL_SCALE_THRESHOLD;
129
+ // Adjust the min and max based on the new scale
130
+ if (min == 0.0f) {
131
+ max = SMALL_SCALE_THRESHOLD * (qmax - qmin);
132
+ } else if (max == 0.0f) {
133
+ min = -SMALL_SCALE_THRESHOLD * (qmax - qmin);
134
+ } else {
135
+ float amplifier = SMALL_SCALE_THRESHOLD / org_scale;
136
+ min *= amplifier;
137
+ max *= amplifier;
138
+ }
139
+ }
140
+
141
+ // Zero-point computation.
142
+ // First the initial floating-point computation. The zero-point can be
143
+ // determined from solving an affine equation for any known pair
144
+ // (real value, corresponding quantized value).
145
+ // We know two such pairs: (rmin, qmin) and (rmax, qmax).
146
+ // The arithmetic error on the zero point computed from either pair
147
+ // will be roughly machine_epsilon * (sum of absolute values of terms)
148
+ // so we want to use the variant that adds the smaller terms.
149
+ double zero_point_from_min = qmin - min / static_cast<double>(scale);
150
+ double zero_point_from_max = qmax - max / static_cast<double>(scale);
151
+ double zero_point_from_min_error =
152
+ std::abs(qmin) - std::abs(min / static_cast<double>(scale));
153
+ double zero_point_from_max_error =
154
+ std::abs(qmax) - std::abs(max / static_cast<double>(scale));
155
+ double initial_zero_point =
156
+ zero_point_from_min_error < zero_point_from_max_error
157
+ ? zero_point_from_min
158
+ : zero_point_from_max;
159
+
160
+ // for symmetric quantization (preserve_sparsity == true), we force zero_point
161
+ // to be a middle value between qmin and qmax.
162
+ // If either min or max is 0, then we just use 0 as zero_point.
163
+ if (min < 0 && max > 0 && preserve_sparsity) {
164
+ initial_zero_point = static_cast<double>(qmin + qmax) / 2;
165
+ }
166
+
167
+ // Now we need to nudge the zero point to be an integer
168
+ // (our zero points are integer, and this is motivated by the requirement
169
+ // to be able to represent the real value "0" exactly as a quantized value,
170
+ // which is required in multiple places, for example in Im2col with zero
171
+ // padding).
172
+ int32_t nudged_zero_point = 0;
173
+ if (initial_zero_point < qmin) {
174
+ nudged_zero_point = qmin;
175
+ } else if (initial_zero_point > qmax) {
176
+ nudged_zero_point = qmax;
177
+ } else {
178
+ nudged_zero_point = nearbyint(initial_zero_point);
179
+ }
180
+
181
+ TensorQuantizationParams result;
182
+ result.scale = scale;
183
+ result.zero_point = nudged_zero_point;
184
+ return result;
185
+ }
186
+
187
+ // This function helps to convert the Conv1D dimensions usable by the Conv2d op.
188
+ constexpr int64_t kConv1dSqueezeDim = 0;
189
+ static C10_UNUSED torch::List<int64_t> MakeArgForConv1d(const torch::List<int64_t>& arg,
190
+ int64_t base_value) {
191
+ TORCH_CHECK(!arg.empty(), "Argument must have elements.");
192
+ torch::List<int64_t> result({arg.get(0), base_value});
193
+ if (arg.size() == 1) {
194
+ result[1] = arg.get(0);
195
+ } else {
196
+ result[1] = arg.get(1);
197
+ }
198
+ result[kConv1dSqueezeDim] = base_value;
199
+ return result;
200
+ }
201
+
202
+ // The range for using FP16 quantization of weights requires that the elements
203
+ // should be in the range of [5.96e-8, 65504]. If it is out of range, then the
204
+ // number will be saturated to max or min representable values by FP16.
205
+ inline void HandleWeightsSaturation(int64_t N, float* weight) {
206
+ const float kFp16Max = RawUint16ToFp16(0x7BFF);
207
+ bool found_out_of_range = false;
208
+ for (const auto i : c10::irange(N)) {
209
+ bool saturate = CheckAndSaturate<float>(kFp16Max, weight + i);
210
+ if (saturate) {
211
+ found_out_of_range = true;
212
+ }
213
+ }
214
+ if (found_out_of_range) {
215
+ TORCH_WARN("FOUND weight out of range ");
216
+ }
217
+ }
218
+
219
+ // Util function for quantizing bias.
220
+ inline at::Tensor QuantizeBias(
221
+ bool is_per_channel,
222
+ const at::Tensor& bias,
223
+ const at::Tensor& weight_contig,
224
+ double input_scale) {
225
+ at::Tensor qbias;
226
+ if (is_per_channel) {
227
+ auto bias_quant_scales =
228
+ weight_contig.q_per_channel_scales() * input_scale;
229
+ auto bias_zp = at::zeros(bias_quant_scales.sizes(), c10::kInt);
230
+ qbias = at::native::quantize_per_channel(
231
+ bias, bias_quant_scales, bias_zp, 0, c10::kQInt32);
232
+ } else {
233
+ qbias = at::native::quantize_per_tensor(
234
+ bias, weight_contig.q_scale() * input_scale, 0, c10::kQInt32);
235
+ }
236
+ return qbias;
237
+ }
238
+
239
+ } // namespace quant_utils
videollama2/lib/python3.10/site-packages/torch/include/ATen/native/quantized/cpu/init_qnnpack.h ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #ifdef USE_PYTORCH_QNNPACK
4
+
5
+ namespace at {
6
+ namespace native {
7
+
8
+ void initQNNPACK();
9
+
10
+ } // namespace native
11
+ } // namespace at
12
+
13
+ #endif
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/bbp_pi.cpython-310.pyc ADDED
Binary file (5.71 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/continued_fraction.cpython-310.pyc ADDED
Binary file (9.73 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/digits.cpython-310.pyc ADDED
Binary file (4.02 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/ecm.cpython-310.pyc ADDED
Binary file (9.95 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/egyptian_fraction.cpython-310.pyc ADDED
Binary file (6.52 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/generate.cpython-310.pyc ADDED
Binary file (30.5 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/multinomial.cpython-310.pyc ADDED
Binary file (4.49 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/partitions_.cpython-310.pyc ADDED
Binary file (6.69 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/primetest.cpython-310.pyc ADDED
Binary file (18.8 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/qs.cpython-310.pyc ADDED
Binary file (15.5 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/__pycache__/residue_ntheory.cpython-310.pyc ADDED
Binary file (46.5 kB). View file
 
vllm/lib/python3.10/site-packages/sympy/ntheory/bbp_pi.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ This implementation is a heavily modified fixed point implementation of
3
+ BBP_formula for calculating the nth position of pi. The original hosted
4
+ at: https://web.archive.org/web/20151116045029/http://en.literateprograms.org/Pi_with_the_BBP_formula_(Python)
5
+
6
+ # Permission is hereby granted, free of charge, to any person obtaining
7
+ # a copy of this software and associated documentation files (the
8
+ # "Software"), to deal in the Software without restriction, including
9
+ # without limitation the rights to use, copy, modify, merge, publish,
10
+ # distribute, sub-license, and/or sell copies of the Software, and to
11
+ # permit persons to whom the Software is furnished to do so, subject to
12
+ # the following conditions:
13
+ #
14
+ # The above copyright notice and this permission notice shall be
15
+ # included in all copies or substantial portions of the Software.
16
+ #
17
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20
+ # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21
+ # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22
+ # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23
+ # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
+
25
+ Modifications:
26
+
27
+ 1.Once the nth digit and desired number of digits is selected, the
28
+ number of digits of working precision is calculated to ensure that
29
+ the hexadecimal digits returned are accurate. This is calculated as
30
+
31
+ int(math.log(start + prec)/math.log(16) + prec + 3)
32
+ --------------------------------------- --------
33
+ / /
34
+ number of hex digits additional digits
35
+
36
+ This was checked by the following code which completed without
37
+ errors (and dig are the digits included in the test_bbp.py file):
38
+
39
+ for i in range(0,1000):
40
+ for j in range(1,1000):
41
+ a, b = pi_hex_digits(i, j), dig[i:i+j]
42
+ if a != b:
43
+ print('%s\n%s'%(a,b))
44
+
45
+ Deceasing the additional digits by 1 generated errors, so '3' is
46
+ the smallest additional precision needed to calculate the above
47
+ loop without errors. The following trailing 10 digits were also
48
+ checked to be accurate (and the times were slightly faster with
49
+ some of the constant modifications that were made):
50
+
51
+ >> from time import time
52
+ >> t=time();pi_hex_digits(10**2-10 + 1, 10), time()-t
53
+ ('e90c6cc0ac', 0.0)
54
+ >> t=time();pi_hex_digits(10**4-10 + 1, 10), time()-t
55
+ ('26aab49ec6', 0.17100000381469727)
56
+ >> t=time();pi_hex_digits(10**5-10 + 1, 10), time()-t
57
+ ('a22673c1a5', 4.7109999656677246)
58
+ >> t=time();pi_hex_digits(10**6-10 + 1, 10), time()-t
59
+ ('9ffd342362', 59.985999822616577)
60
+ >> t=time();pi_hex_digits(10**7-10 + 1, 10), time()-t
61
+ ('c1a42e06a1', 689.51800012588501)
62
+
63
+ 2. The while loop to evaluate whether the series has converged quits
64
+ when the addition amount `dt` has dropped to zero.
65
+
66
+ 3. the formatting string to convert the decimal to hexadecimal is
67
+ calculated for the given precision.
68
+
69
+ 4. pi_hex_digits(n) changed to have coefficient to the formula in an
70
+ array (perhaps just a matter of preference).
71
+
72
+ '''
73
+
74
+ from sympy.utilities.misc import as_int
75
+
76
+
77
+ def _series(j, n, prec=14):
78
+
79
+ # Left sum from the bbp algorithm
80
+ s = 0
81
+ D = _dn(n, prec)
82
+ D4 = 4 * D
83
+ d = j
84
+ for k in range(n + 1):
85
+ s += (pow(16, n - k, d) << D4) // d
86
+ d += 8
87
+
88
+ # Right sum iterates to infinity for full precision, but we
89
+ # stop at the point where one iteration is beyond the precision
90
+ # specified.
91
+
92
+ t = 0
93
+ k = n + 1
94
+ e = D4 - 4 # 4*(D + n - k)
95
+ d = 8 * k + j
96
+ while True:
97
+ dt = (1 << e) // d
98
+ if not dt:
99
+ break
100
+ t += dt
101
+ # k += 1
102
+ e -= 4
103
+ d += 8
104
+ total = s + t
105
+
106
+ return total
107
+
108
+
109
+ def pi_hex_digits(n, prec=14):
110
+ """Returns a string containing ``prec`` (default 14) digits
111
+ starting at the nth digit of pi in hex. Counting of digits
112
+ starts at 0 and the decimal is not counted, so for n = 0 the
113
+ returned value starts with 3; n = 1 corresponds to the first
114
+ digit past the decimal point (which in hex is 2).
115
+
116
+ Parameters
117
+ ==========
118
+
119
+ n : non-negative integer
120
+ prec : non-negative integer. default = 14
121
+
122
+ Returns
123
+ =======
124
+
125
+ str : Returns a string containing ``prec`` digits
126
+ starting at the nth digit of pi in hex.
127
+ If ``prec`` = 0, returns empty string.
128
+
129
+ Raises
130
+ ======
131
+
132
+ ValueError
133
+ If ``n`` < 0 or ``prec`` < 0.
134
+ Or ``n`` or ``prec`` is not an integer.
135
+
136
+ Examples
137
+ ========
138
+
139
+ >>> from sympy.ntheory.bbp_pi import pi_hex_digits
140
+ >>> pi_hex_digits(0)
141
+ '3243f6a8885a30'
142
+ >>> pi_hex_digits(0, 3)
143
+ '324'
144
+
145
+ These are consistent with the following results
146
+
147
+ >>> import math
148
+ >>> hex(int(math.pi * 2**((14-1)*4)))
149
+ '0x3243f6a8885a30'
150
+ >>> hex(int(math.pi * 2**((3-1)*4)))
151
+ '0x324'
152
+
153
+ References
154
+ ==========
155
+
156
+ .. [1] http://www.numberworld.org/digits/Pi/
157
+ """
158
+ n, prec = as_int(n), as_int(prec)
159
+ if n < 0:
160
+ raise ValueError('n cannot be negative')
161
+ if prec < 0:
162
+ raise ValueError('prec cannot be negative')
163
+ if prec == 0:
164
+ return ''
165
+
166
+ # main of implementation arrays holding formulae coefficients
167
+ n -= 1
168
+ a = [4, 2, 1, 1]
169
+ j = [1, 4, 5, 6]
170
+
171
+ #formulae
172
+ D = _dn(n, prec)
173
+ x = + (a[0]*_series(j[0], n, prec)
174
+ - a[1]*_series(j[1], n, prec)
175
+ - a[2]*_series(j[2], n, prec)
176
+ - a[3]*_series(j[3], n, prec)) & (16**D - 1)
177
+
178
+ s = ("%0" + "%ix" % prec) % (x // 16**(D - prec))
179
+ return s
180
+
181
+
182
+ def _dn(n, prec):
183
+ # controller for n dependence on precision
184
+ # n = starting digit index
185
+ # prec = the number of total digits to compute
186
+ n += 1 # because we subtract 1 for _series
187
+
188
+ # assert int(math.log(n + prec)/math.log(16)) ==\
189
+ # ((n + prec).bit_length() - 1) // 4
190
+ return ((n + prec).bit_length() - 1) // 4 + prec + 3