ZTWHHH commited on
Commit
e06e815
·
verified ·
1 Parent(s): 260d6ea

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. .gitattributes +1 -0
  2. videollama2/lib/python3.10/site-packages/sklearn/__pycache__/naive_bayes.cpython-310.pyc +0 -0
  3. videollama2/lib/python3.10/site-packages/sklearn/_loss/__pycache__/__init__.cpython-310.pyc +0 -0
  4. videollama2/lib/python3.10/site-packages/sklearn/_loss/__pycache__/glm_distribution.cpython-310.pyc +0 -0
  5. videollama2/lib/python3.10/site-packages/sklearn/_loss/__pycache__/link.cpython-310.pyc +0 -0
  6. videollama2/lib/python3.10/site-packages/sklearn/_loss/__pycache__/loss.cpython-310.pyc +0 -0
  7. videollama2/lib/python3.10/site-packages/sklearn/_loss/_loss.cpython-310-x86_64-linux-gnu.so +3 -0
  8. videollama2/lib/python3.10/site-packages/sklearn/_loss/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  9. videollama2/lib/python3.10/site-packages/sklearn/_loss/tests/__pycache__/test_glm_distribution.cpython-310.pyc +0 -0
  10. videollama2/lib/python3.10/site-packages/sklearn/externals/__init__.py +5 -0
  11. videollama2/lib/python3.10/site-packages/sklearn/externals/_arff.py +1107 -0
  12. videollama2/lib/python3.10/site-packages/sklearn/impute/_knn.py +391 -0
  13. videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/__init__.py +11 -0
  14. videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/__pycache__/__init__.cpython-310.pyc +0 -0
  15. videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/__pycache__/_label_propagation.cpython-310.pyc +0 -0
  16. videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/_label_propagation.py +621 -0
  17. videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/_self_training.py +400 -0
  18. videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/tests/__init__.py +0 -0
  19. videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  20. videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/tests/__pycache__/test_label_propagation.cpython-310.pyc +0 -0
  21. videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/tests/__pycache__/test_self_training.cpython-310.pyc +0 -0
  22. videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/tests/test_label_propagation.py +216 -0
  23. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_compute_linear_combination_native.h +22 -0
  24. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cudnn_rnn_backward_native.h +22 -0
  25. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_empty_per_channel_affine_quantized_ops.h +39 -0
  26. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_floor_compositeexplicitautograd_dispatch.h +26 -0
  27. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_lerp_native.h +30 -0
  28. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_reciprocal_cuda_dispatch.h +24 -0
  29. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback.h +39 -0
  30. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_lstm_mps_ops.h +39 -0
  31. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_make_per_channel_quantized_tensor_cpu_dispatch.h +23 -0
  32. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_compute_contiguous_strides_offsets_native.h +21 -0
  33. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_get_values_copy_compositeexplicitautogradnonfunctional_dispatch.h +23 -0
  34. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_from_mask_native.h +22 -0
  35. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_strides_compositeexplicitautograd_dispatch.h +24 -0
  36. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_prelu_kernel_ops.h +28 -0
  37. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_flash_attention_backward.h +47 -0
  38. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_test_warn_in_autograd_native.h +22 -0
  39. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_to_dense_native.h +24 -0
  40. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bilinear2d_aa_compositeexplicitautogradnonfunctional_dispatch.h +24 -0
  41. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact1d_meta_dispatch.h +28 -0
  42. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/addcmul_cuda_dispatch.h +26 -0
  43. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/and_native.h +24 -0
  44. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/as_strided_copy_ops.h +39 -0
  45. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/as_strided_native.h +24 -0
  46. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/avg_pool2d_ops.h +39 -0
  47. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_or_cpu_dispatch.h +26 -0
  48. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/bucketize_ops.h +61 -0
  49. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/copy_meta_dispatch.h +23 -0
  50. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_convolution_transpose_compositeexplicitautograd_dispatch.h +26 -0
.gitattributes CHANGED
@@ -1940,3 +1940,4 @@ videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_red
1940
  videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1941
  videollama2/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1942
  videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_expected_mutual_info_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
1940
  videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1941
  videollama2/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1942
  videollama2/lib/python3.10/site-packages/sklearn/metrics/cluster/_expected_mutual_info_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1943
+ videollama2/lib/python3.10/site-packages/sklearn/_loss/_loss.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
videollama2/lib/python3.10/site-packages/sklearn/__pycache__/naive_bayes.cpython-310.pyc ADDED
Binary file (50.3 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/_loss/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (586 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/_loss/__pycache__/glm_distribution.cpython-310.pyc ADDED
Binary file (10.5 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/_loss/__pycache__/link.cpython-310.pyc ADDED
Binary file (8.45 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/_loss/__pycache__/loss.cpython-310.pyc ADDED
Binary file (29.7 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/_loss/_loss.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:616237559467732cc220de2a62e942fb993125159cecf1a37a0289203e98697e
3
+ size 2109161
videollama2/lib/python3.10/site-packages/sklearn/_loss/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (176 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/_loss/tests/__pycache__/test_glm_distribution.cpython-310.pyc ADDED
Binary file (3.49 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/externals/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+
2
+ """
3
+ External, bundled dependencies.
4
+
5
+ """
videollama2/lib/python3.10/site-packages/sklearn/externals/_arff.py ADDED
@@ -0,0 +1,1107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # Federal University of Rio Grande do Sul (UFRGS)
3
+ # Connectionist Artificial Intelligence Laboratory (LIAC)
4
+ # Renato de Pontes Pereira - rppereira@inf.ufrgs.br
5
+ # =============================================================================
6
+ # Copyright (c) 2011 Renato de Pontes Pereira, renato.ppontes at gmail dot com
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+ #
15
+ # The above copyright notice and this permission notice shall be included in
16
+ # all copies or substantial portions of the Software.
17
+ #
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+ # =============================================================================
26
+
27
+ '''
28
+ The liac-arff module implements functions to read and write ARFF files in
29
+ Python. It was created in the Connectionist Artificial Intelligence Laboratory
30
+ (LIAC), which takes place at the Federal University of Rio Grande do Sul
31
+ (UFRGS), in Brazil.
32
+
33
+ ARFF (Attribute-Relation File Format) is an file format specially created for
34
+ describe datasets which are commonly used for machine learning experiments and
35
+ software. This file format was created to be used in Weka, the best
36
+ representative software for machine learning automated experiments.
37
+
38
+ An ARFF file can be divided into two sections: header and data. The Header
39
+ describes the metadata of the dataset, including a general description of the
40
+ dataset, its name and its attributes. The source below is an example of a
41
+ header section in a XOR dataset::
42
+
43
+ %
44
+ % XOR Dataset
45
+ %
46
+ % Created by Renato Pereira
47
+ % rppereira@inf.ufrgs.br
48
+ % http://inf.ufrgs.br/~rppereira
49
+ %
50
+ %
51
+ @RELATION XOR
52
+
53
+ @ATTRIBUTE input1 REAL
54
+ @ATTRIBUTE input2 REAL
55
+ @ATTRIBUTE y REAL
56
+
57
+ The Data section of an ARFF file describes the observations of the dataset, in
58
+ the case of XOR dataset::
59
+
60
+ @DATA
61
+ 0.0,0.0,0.0
62
+ 0.0,1.0,1.0
63
+ 1.0,0.0,1.0
64
+ 1.0,1.0,0.0
65
+ %
66
+ %
67
+ %
68
+
69
+ Notice that several lines are starting with an ``%`` symbol, denoting a
70
+ comment, thus, lines with ``%`` at the beginning will be ignored, except by the
71
+ description part at the beginning of the file. The declarations ``@RELATION``,
72
+ ``@ATTRIBUTE``, and ``@DATA`` are all case insensitive and obligatory.
73
+
74
+ For more information and details about the ARFF file description, consult
75
+ http://www.cs.waikato.ac.nz/~ml/weka/arff.html
76
+
77
+
78
+ ARFF Files in Python
79
+ ~~~~~~~~~~~~~~~~~~~~
80
+
81
+ This module uses built-ins python objects to represent a deserialized ARFF
82
+ file. A dictionary is used as the container of the data and metadata of ARFF,
83
+ and have the following keys:
84
+
85
+ - **description**: (OPTIONAL) a string with the description of the dataset.
86
+ - **relation**: (OBLIGATORY) a string with the name of the dataset.
87
+ - **attributes**: (OBLIGATORY) a list of attributes with the following
88
+ template::
89
+
90
+ (attribute_name, attribute_type)
91
+
92
+ the attribute_name is a string, and attribute_type must be an string
93
+ or a list of strings.
94
+ - **data**: (OBLIGATORY) a list of data instances. Each data instance must be
95
+ a list with values, depending on the attributes.
96
+
97
+ The above keys must follow the case which were described, i.e., the keys are
98
+ case sensitive. The attribute type ``attribute_type`` must be one of these
99
+ strings (they are not case sensitive): ``NUMERIC``, ``INTEGER``, ``REAL`` or
100
+ ``STRING``. For nominal attributes, the ``atribute_type`` must be a list of
101
+ strings.
102
+
103
+ In this format, the XOR dataset presented above can be represented as a python
104
+ object as::
105
+
106
+ xor_dataset = {
107
+ 'description': 'XOR Dataset',
108
+ 'relation': 'XOR',
109
+ 'attributes': [
110
+ ('input1', 'REAL'),
111
+ ('input2', 'REAL'),
112
+ ('y', 'REAL'),
113
+ ],
114
+ 'data': [
115
+ [0.0, 0.0, 0.0],
116
+ [0.0, 1.0, 1.0],
117
+ [1.0, 0.0, 1.0],
118
+ [1.0, 1.0, 0.0]
119
+ ]
120
+ }
121
+
122
+
123
+ Features
124
+ ~~~~~~~~
125
+
126
+ This module provides several features, including:
127
+
128
+ - Read and write ARFF files using python built-in structures, such dictionaries
129
+ and lists;
130
+ - Supports `scipy.sparse.coo <http://docs.scipy
131
+ .org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.html#scipy.sparse.coo_matrix>`_
132
+ and lists of dictionaries as used by SVMLight
133
+ - Supports the following attribute types: NUMERIC, REAL, INTEGER, STRING, and
134
+ NOMINAL;
135
+ - Has an interface similar to other built-in modules such as ``json``, or
136
+ ``zipfile``;
137
+ - Supports read and write the descriptions of files;
138
+ - Supports missing values and names with spaces;
139
+ - Supports unicode values and names;
140
+ - Fully compatible with Python 2.7+, Python 3.5+, pypy and pypy3;
141
+ - Under `MIT License <http://opensource.org/licenses/MIT>`_
142
+
143
+ '''
144
+ __author__ = 'Renato de Pontes Pereira, Matthias Feurer, Joel Nothman'
145
+ __author_email__ = ('renato.ppontes@gmail.com, '
146
+ 'feurerm@informatik.uni-freiburg.de, '
147
+ 'joel.nothman@gmail.com')
148
+ __version__ = '2.4.0'
149
+
150
+ import re
151
+ import csv
152
+ from typing import TYPE_CHECKING
153
+ from typing import Optional, List, Dict, Any, Iterator, Union, Tuple
154
+
155
+ # CONSTANTS ===================================================================
156
+ _SIMPLE_TYPES = ['NUMERIC', 'REAL', 'INTEGER', 'STRING']
157
+
158
+ _TK_DESCRIPTION = '%'
159
+ _TK_COMMENT = '%'
160
+ _TK_RELATION = '@RELATION'
161
+ _TK_ATTRIBUTE = '@ATTRIBUTE'
162
+ _TK_DATA = '@DATA'
163
+
164
+ _RE_RELATION = re.compile(r'^([^\{\}%,\s]*|\".*\"|\'.*\')$', re.UNICODE)
165
+ _RE_ATTRIBUTE = re.compile(r'^(\".*\"|\'.*\'|[^\{\}%,\s]*)\s+(.+)$', re.UNICODE)
166
+ _RE_QUOTE_CHARS = re.compile(r'["\'\\\s%,\000-\031]', re.UNICODE)
167
+ _RE_ESCAPE_CHARS = re.compile(r'(?=["\'\\%])|[\n\r\t\000-\031]')
168
+ _RE_SPARSE_LINE = re.compile(r'^\s*\{.*\}\s*$', re.UNICODE)
169
+ _RE_NONTRIVIAL_DATA = re.compile('["\'{}\\s]', re.UNICODE)
170
+
171
+ ArffDenseDataType = Iterator[List]
172
+ ArffSparseDataType = Tuple[List, ...]
173
+
174
+
175
+ if TYPE_CHECKING:
176
+ # typing_extensions is available when mypy is installed
177
+ from typing_extensions import TypedDict
178
+
179
+ class ArffContainerType(TypedDict):
180
+ description: str
181
+ relation: str
182
+ attributes: List
183
+ data: Union[ArffDenseDataType, ArffSparseDataType]
184
+
185
+ else:
186
+ ArffContainerType = Dict[str, Any]
187
+
188
+
189
+ def _build_re_values():
190
+ quoted_re = r'''
191
+ " # open quote followed by zero or more of:
192
+ (?:
193
+ (?<!\\) # no additional backslash
194
+ (?:\\\\)* # maybe escaped backslashes
195
+ \\" # escaped quote
196
+ |
197
+ \\[^"] # escaping a non-quote
198
+ |
199
+ [^"\\] # non-quote char
200
+ )*
201
+ " # close quote
202
+ '''
203
+ # a value is surrounded by " or by ' or contains no quotables
204
+ value_re = r'''(?:
205
+ %s| # a value may be surrounded by "
206
+ %s| # or by '
207
+ [^,\s"'{}]+ # or may contain no characters requiring quoting
208
+ )''' % (quoted_re,
209
+ quoted_re.replace('"', "'"))
210
+
211
+ # This captures (value, error) groups. Because empty values are allowed,
212
+ # we cannot just look for empty values to handle syntax errors.
213
+ # We presume the line has had ',' prepended...
214
+ dense = re.compile(r'''(?x)
215
+ , # may follow ','
216
+ \s*
217
+ ((?=,)|$|{value_re}) # empty or value
218
+ |
219
+ (\S.*) # error
220
+ '''.format(value_re=value_re))
221
+
222
+ # This captures (key, value) groups and will have an empty key/value
223
+ # in case of syntax errors.
224
+ # It does not ensure that the line starts with '{' or ends with '}'.
225
+ sparse = re.compile(r'''(?x)
226
+ (?:^\s*\{|,) # may follow ',', or '{' at line start
227
+ \s*
228
+ (\d+) # attribute key
229
+ \s+
230
+ (%(value_re)s) # value
231
+ |
232
+ (?!}\s*$) # not an error if it's }$
233
+ (?!^\s*{\s*}\s*$) # not an error if it's ^{}$
234
+ \S.* # error
235
+ ''' % {'value_re': value_re})
236
+ return dense, sparse
237
+
238
+
239
+
240
+ _RE_DENSE_VALUES, _RE_SPARSE_KEY_VALUES = _build_re_values()
241
+
242
+
243
+ _ESCAPE_SUB_MAP = {
244
+ '\\\\': '\\',
245
+ '\\"': '"',
246
+ "\\'": "'",
247
+ '\\t': '\t',
248
+ '\\n': '\n',
249
+ '\\r': '\r',
250
+ '\\b': '\b',
251
+ '\\f': '\f',
252
+ '\\%': '%',
253
+ }
254
+ _UNESCAPE_SUB_MAP = {chr(i): '\\%03o' % i for i in range(32)}
255
+ _UNESCAPE_SUB_MAP.update({v: k for k, v in _ESCAPE_SUB_MAP.items()})
256
+ _UNESCAPE_SUB_MAP[''] = '\\'
257
+ _ESCAPE_SUB_MAP.update({'\\%d' % i: chr(i) for i in range(10)})
258
+
259
+
260
+ def _escape_sub_callback(match):
261
+ s = match.group()
262
+ if len(s) == 2:
263
+ try:
264
+ return _ESCAPE_SUB_MAP[s]
265
+ except KeyError:
266
+ raise ValueError('Unsupported escape sequence: %s' % s)
267
+ if s[1] == 'u':
268
+ return chr(int(s[2:], 16))
269
+ else:
270
+ return chr(int(s[1:], 8))
271
+
272
+
273
+ def _unquote(v):
274
+ if v[:1] in ('"', "'"):
275
+ return re.sub(r'\\([0-9]{1,3}|u[0-9a-f]{4}|.)', _escape_sub_callback,
276
+ v[1:-1])
277
+ elif v in ('?', ''):
278
+ return None
279
+ else:
280
+ return v
281
+
282
+
283
+ def _parse_values(s):
284
+ '''(INTERNAL) Split a line into a list of values'''
285
+ if not _RE_NONTRIVIAL_DATA.search(s):
286
+ # Fast path for trivial cases (unfortunately we have to handle missing
287
+ # values because of the empty string case :(.)
288
+ return [None if s in ('?', '') else s
289
+ for s in next(csv.reader([s]))]
290
+
291
+ # _RE_DENSE_VALUES tokenizes despite quoting, whitespace, etc.
292
+ values, errors = zip(*_RE_DENSE_VALUES.findall(',' + s))
293
+ if not any(errors):
294
+ return [_unquote(v) for v in values]
295
+ if _RE_SPARSE_LINE.match(s):
296
+ try:
297
+ return {int(k): _unquote(v)
298
+ for k, v in _RE_SPARSE_KEY_VALUES.findall(s)}
299
+ except ValueError:
300
+ # an ARFF syntax error in sparse data
301
+ for match in _RE_SPARSE_KEY_VALUES.finditer(s):
302
+ if not match.group(1):
303
+ raise BadLayout('Error parsing %r' % match.group())
304
+ raise BadLayout('Unknown parsing error')
305
+ else:
306
+ # an ARFF syntax error
307
+ for match in _RE_DENSE_VALUES.finditer(s):
308
+ if match.group(2):
309
+ raise BadLayout('Error parsing %r' % match.group())
310
+ raise BadLayout('Unknown parsing error')
311
+
312
+
313
+ DENSE = 0 # Constant value representing a dense matrix
314
+ COO = 1 # Constant value representing a sparse matrix in coordinate format
315
+ LOD = 2 # Constant value representing a sparse matrix in list of
316
+ # dictionaries format
317
+ DENSE_GEN = 3 # Generator of dictionaries
318
+ LOD_GEN = 4 # Generator of dictionaries
319
+ _SUPPORTED_DATA_STRUCTURES = [DENSE, COO, LOD, DENSE_GEN, LOD_GEN]
320
+
321
+
322
+ # EXCEPTIONS ==================================================================
323
+ class ArffException(Exception):
324
+ message: Optional[str] = None
325
+
326
+ def __init__(self):
327
+ self.line = -1
328
+
329
+ def __str__(self):
330
+ return self.message%self.line
331
+
332
+ class BadRelationFormat(ArffException):
333
+ '''Error raised when the relation declaration is in an invalid format.'''
334
+ message = 'Bad @RELATION format, at line %d.'
335
+
336
+ class BadAttributeFormat(ArffException):
337
+ '''Error raised when some attribute declaration is in an invalid format.'''
338
+ message = 'Bad @ATTRIBUTE format, at line %d.'
339
+
340
+ class BadDataFormat(ArffException):
341
+ '''Error raised when some data instance is in an invalid format.'''
342
+ def __init__(self, value):
343
+ super().__init__()
344
+ self.message = (
345
+ 'Bad @DATA instance format in line %d: ' +
346
+ ('%s' % value)
347
+ )
348
+
349
+ class BadAttributeType(ArffException):
350
+ '''Error raised when some invalid type is provided into the attribute
351
+ declaration.'''
352
+ message = 'Bad @ATTRIBUTE type, at line %d.'
353
+
354
+ class BadAttributeName(ArffException):
355
+ '''Error raised when an attribute name is provided twice the attribute
356
+ declaration.'''
357
+
358
+ def __init__(self, value, value2):
359
+ super().__init__()
360
+ self.message = (
361
+ ('Bad @ATTRIBUTE name %s at line' % value) +
362
+ ' %d, this name is already in use in line' +
363
+ (' %d.' % value2)
364
+ )
365
+
366
+ class BadNominalValue(ArffException):
367
+ '''Error raised when a value in used in some data instance but is not
368
+ declared into it respective attribute declaration.'''
369
+
370
+ def __init__(self, value):
371
+ super().__init__()
372
+ self.message = (
373
+ ('Data value %s not found in nominal declaration, ' % value)
374
+ + 'at line %d.'
375
+ )
376
+
377
+ class BadNominalFormatting(ArffException):
378
+ '''Error raised when a nominal value with space is not properly quoted.'''
379
+ def __init__(self, value):
380
+ super().__init__()
381
+ self.message = (
382
+ ('Nominal data value "%s" not properly quoted in line ' % value) +
383
+ '%d.'
384
+ )
385
+
386
+ class BadNumericalValue(ArffException):
387
+ '''Error raised when and invalid numerical value is used in some data
388
+ instance.'''
389
+ message = 'Invalid numerical value, at line %d.'
390
+
391
+ class BadStringValue(ArffException):
392
+ '''Error raise when a string contains space but is not quoted.'''
393
+ message = 'Invalid string value at line %d.'
394
+
395
+ class BadLayout(ArffException):
396
+ '''Error raised when the layout of the ARFF file has something wrong.'''
397
+ message = 'Invalid layout of the ARFF file, at line %d.'
398
+
399
+ def __init__(self, msg=''):
400
+ super().__init__()
401
+ if msg:
402
+ self.message = BadLayout.message + ' ' + msg.replace('%', '%%')
403
+
404
+
405
+ class BadObject(ArffException):
406
+ '''Error raised when the object representing the ARFF file has something
407
+ wrong.'''
408
+ def __init__(self, msg='Invalid object.'):
409
+ self.msg = msg
410
+
411
+ def __str__(self):
412
+ return '%s' % self.msg
413
+
414
+ # =============================================================================
415
+
416
+ # INTERNAL ====================================================================
417
+ def _unescape_sub_callback(match):
418
+ return _UNESCAPE_SUB_MAP[match.group()]
419
+
420
+
421
+ def encode_string(s):
422
+ if _RE_QUOTE_CHARS.search(s):
423
+ return "'%s'" % _RE_ESCAPE_CHARS.sub(_unescape_sub_callback, s)
424
+ return s
425
+
426
+
427
+ class EncodedNominalConversor:
428
+ def __init__(self, values):
429
+ self.values = {v: i for i, v in enumerate(values)}
430
+ self.values[0] = 0
431
+
432
+ def __call__(self, value):
433
+ try:
434
+ return self.values[value]
435
+ except KeyError:
436
+ raise BadNominalValue(value)
437
+
438
+
439
+ class NominalConversor:
440
+ def __init__(self, values):
441
+ self.values = set(values)
442
+ self.zero_value = values[0]
443
+
444
+ def __call__(self, value):
445
+ if value not in self.values:
446
+ if value == 0:
447
+ # Sparse decode
448
+ # See issue #52: nominals should take their first value when
449
+ # unspecified in a sparse matrix. Naturally, this is consistent
450
+ # with EncodedNominalConversor.
451
+ return self.zero_value
452
+ raise BadNominalValue(value)
453
+ return str(value)
454
+
455
+
456
+ class DenseGeneratorData:
457
+ '''Internal helper class to allow for different matrix types without
458
+ making the code a huge collection of if statements.'''
459
+
460
+ def decode_rows(self, stream, conversors):
461
+ for row in stream:
462
+ values = _parse_values(row)
463
+
464
+ if isinstance(values, dict):
465
+ if values and max(values) >= len(conversors):
466
+ raise BadDataFormat(row)
467
+ # XXX: int 0 is used for implicit values, not '0'
468
+ values = [values[i] if i in values else 0 for i in
469
+ range(len(conversors))]
470
+ else:
471
+ if len(values) != len(conversors):
472
+ raise BadDataFormat(row)
473
+
474
+ yield self._decode_values(values, conversors)
475
+
476
+ @staticmethod
477
+ def _decode_values(values, conversors):
478
+ try:
479
+ values = [None if value is None else conversor(value)
480
+ for conversor, value
481
+ in zip(conversors, values)]
482
+ except ValueError as exc:
483
+ if 'float: ' in str(exc):
484
+ raise BadNumericalValue()
485
+ return values
486
+
487
+ def encode_data(self, data, attributes):
488
+ '''(INTERNAL) Encodes a line of data.
489
+
490
+ Data instances follow the csv format, i.e, attribute values are
491
+ delimited by commas. After converted from csv.
492
+
493
+ :param data: a list of values.
494
+ :param attributes: a list of attributes. Used to check if data is valid.
495
+ :return: a string with the encoded data line.
496
+ '''
497
+ current_row = 0
498
+
499
+ for inst in data:
500
+ if len(inst) != len(attributes):
501
+ raise BadObject(
502
+ 'Instance %d has %d attributes, expected %d' %
503
+ (current_row, len(inst), len(attributes))
504
+ )
505
+
506
+ new_data = []
507
+ for value in inst:
508
+ if value is None or value == '' or value != value:
509
+ s = '?'
510
+ else:
511
+ s = encode_string(str(value))
512
+ new_data.append(s)
513
+
514
+ current_row += 1
515
+ yield ','.join(new_data)
516
+
517
+
518
+ class _DataListMixin:
519
+ """Mixin to return a list from decode_rows instead of a generator"""
520
+ def decode_rows(self, stream, conversors):
521
+ return list(super().decode_rows(stream, conversors))
522
+
523
+
524
+ class Data(_DataListMixin, DenseGeneratorData):
525
+ pass
526
+
527
+
528
+ class COOData:
529
+ def decode_rows(self, stream, conversors):
530
+ data, rows, cols = [], [], []
531
+ for i, row in enumerate(stream):
532
+ values = _parse_values(row)
533
+ if not isinstance(values, dict):
534
+ raise BadLayout()
535
+ if not values:
536
+ continue
537
+ row_cols, values = zip(*sorted(values.items()))
538
+ try:
539
+ values = [value if value is None else conversors[key](value)
540
+ for key, value in zip(row_cols, values)]
541
+ except ValueError as exc:
542
+ if 'float: ' in str(exc):
543
+ raise BadNumericalValue()
544
+ raise
545
+ except IndexError:
546
+ # conversor out of range
547
+ raise BadDataFormat(row)
548
+
549
+ data.extend(values)
550
+ rows.extend([i] * len(values))
551
+ cols.extend(row_cols)
552
+
553
+ return data, rows, cols
554
+
555
+ def encode_data(self, data, attributes):
556
+ num_attributes = len(attributes)
557
+ new_data = []
558
+ current_row = 0
559
+
560
+ row = data.row
561
+ col = data.col
562
+ data = data.data
563
+
564
+ # Check if the rows are sorted
565
+ if not all(row[i] <= row[i + 1] for i in range(len(row) - 1)):
566
+ raise ValueError("liac-arff can only output COO matrices with "
567
+ "sorted rows.")
568
+
569
+ for v, col, row in zip(data, col, row):
570
+ if row > current_row:
571
+ # Add empty rows if necessary
572
+ while current_row < row:
573
+ yield " ".join(["{", ','.join(new_data), "}"])
574
+ new_data = []
575
+ current_row += 1
576
+
577
+ if col >= num_attributes:
578
+ raise BadObject(
579
+ 'Instance %d has at least %d attributes, expected %d' %
580
+ (current_row, col + 1, num_attributes)
581
+ )
582
+
583
+ if v is None or v == '' or v != v:
584
+ s = '?'
585
+ else:
586
+ s = encode_string(str(v))
587
+ new_data.append("%d %s" % (col, s))
588
+
589
+ yield " ".join(["{", ','.join(new_data), "}"])
590
+
591
+ class LODGeneratorData:
592
+ def decode_rows(self, stream, conversors):
593
+ for row in stream:
594
+ values = _parse_values(row)
595
+
596
+ if not isinstance(values, dict):
597
+ raise BadLayout()
598
+ try:
599
+ yield {key: None if value is None else conversors[key](value)
600
+ for key, value in values.items()}
601
+ except ValueError as exc:
602
+ if 'float: ' in str(exc):
603
+ raise BadNumericalValue()
604
+ raise
605
+ except IndexError:
606
+ # conversor out of range
607
+ raise BadDataFormat(row)
608
+
609
+ def encode_data(self, data, attributes):
610
+ current_row = 0
611
+
612
+ num_attributes = len(attributes)
613
+ for row in data:
614
+ new_data = []
615
+
616
+ if len(row) > 0 and max(row) >= num_attributes:
617
+ raise BadObject(
618
+ 'Instance %d has %d attributes, expected %d' %
619
+ (current_row, max(row) + 1, num_attributes)
620
+ )
621
+
622
+ for col in sorted(row):
623
+ v = row[col]
624
+ if v is None or v == '' or v != v:
625
+ s = '?'
626
+ else:
627
+ s = encode_string(str(v))
628
+ new_data.append("%d %s" % (col, s))
629
+
630
+ current_row += 1
631
+ yield " ".join(["{", ','.join(new_data), "}"])
632
+
633
+ class LODData(_DataListMixin, LODGeneratorData):
634
+ pass
635
+
636
+
637
+ def _get_data_object_for_decoding(matrix_type):
638
+ if matrix_type == DENSE:
639
+ return Data()
640
+ elif matrix_type == COO:
641
+ return COOData()
642
+ elif matrix_type == LOD:
643
+ return LODData()
644
+ elif matrix_type == DENSE_GEN:
645
+ return DenseGeneratorData()
646
+ elif matrix_type == LOD_GEN:
647
+ return LODGeneratorData()
648
+ else:
649
+ raise ValueError("Matrix type %s not supported." % str(matrix_type))
650
+
651
+ def _get_data_object_for_encoding(matrix):
652
+ # Probably a scipy.sparse
653
+ if hasattr(matrix, 'format'):
654
+ if matrix.format == 'coo':
655
+ return COOData()
656
+ else:
657
+ raise ValueError('Cannot guess matrix format!')
658
+ elif isinstance(matrix[0], dict):
659
+ return LODData()
660
+ else:
661
+ return Data()
662
+
663
+ # =============================================================================
664
+
665
+ # ADVANCED INTERFACE ==========================================================
666
+ class ArffDecoder:
667
+ '''An ARFF decoder.'''
668
+
669
+ def __init__(self):
670
+ '''Constructor.'''
671
+ self._conversors = []
672
+ self._current_line = 0
673
+
674
+ def _decode_comment(self, s):
675
+ '''(INTERNAL) Decodes a comment line.
676
+
677
+ Comments are single line strings starting, obligatorily, with the ``%``
678
+ character, and can have any symbol, including whitespaces or special
679
+ characters.
680
+
681
+ This method must receive a normalized string, i.e., a string without
682
+ padding, including the "\r\n" characters.
683
+
684
+ :param s: a normalized string.
685
+ :return: a string with the decoded comment.
686
+ '''
687
+ res = re.sub(r'^\%( )?', '', s)
688
+ return res
689
+
690
+ def _decode_relation(self, s):
691
+ '''(INTERNAL) Decodes a relation line.
692
+
693
+ The relation declaration is a line with the format ``@RELATION
694
+ <relation-name>``, where ``relation-name`` is a string. The string must
695
+ start with alphabetic character and must be quoted if the name includes
696
+ spaces, otherwise this method will raise a `BadRelationFormat` exception.
697
+
698
+ This method must receive a normalized string, i.e., a string without
699
+ padding, including the "\r\n" characters.
700
+
701
+ :param s: a normalized string.
702
+ :return: a string with the decoded relation name.
703
+ '''
704
+ _, v = s.split(' ', 1)
705
+ v = v.strip()
706
+
707
+ if not _RE_RELATION.match(v):
708
+ raise BadRelationFormat()
709
+
710
+ res = str(v.strip('"\''))
711
+ return res
712
+
713
+ def _decode_attribute(self, s):
714
+ '''(INTERNAL) Decodes an attribute line.
715
+
716
+ The attribute is the most complex declaration in an arff file. All
717
+ attributes must follow the template::
718
+
719
+ @attribute <attribute-name> <datatype>
720
+
721
+ where ``attribute-name`` is a string, quoted if the name contains any
722
+ whitespace, and ``datatype`` can be:
723
+
724
+ - Numerical attributes as ``NUMERIC``, ``INTEGER`` or ``REAL``.
725
+ - Strings as ``STRING``.
726
+ - Dates (NOT IMPLEMENTED).
727
+ - Nominal attributes with format:
728
+
729
+ {<nominal-name1>, <nominal-name2>, <nominal-name3>, ...}
730
+
731
+ The nominal names follow the rules for the attribute names, i.e., they
732
+ must be quoted if the name contains whitespaces.
733
+
734
+ This method must receive a normalized string, i.e., a string without
735
+ padding, including the "\r\n" characters.
736
+
737
+ :param s: a normalized string.
738
+ :return: a tuple (ATTRIBUTE_NAME, TYPE_OR_VALUES).
739
+ '''
740
+ _, v = s.split(' ', 1)
741
+ v = v.strip()
742
+
743
+ # Verify the general structure of declaration
744
+ m = _RE_ATTRIBUTE.match(v)
745
+ if not m:
746
+ raise BadAttributeFormat()
747
+
748
+ # Extracts the raw name and type
749
+ name, type_ = m.groups()
750
+
751
+ # Extracts the final name
752
+ name = str(name.strip('"\''))
753
+
754
+ # Extracts the final type
755
+ if type_[:1] == "{" and type_[-1:] == "}":
756
+ try:
757
+ type_ = _parse_values(type_.strip('{} '))
758
+ except Exception:
759
+ raise BadAttributeType()
760
+ if isinstance(type_, dict):
761
+ raise BadAttributeType()
762
+
763
+ else:
764
+ # If not nominal, verify the type name
765
+ type_ = str(type_).upper()
766
+ if type_ not in ['NUMERIC', 'REAL', 'INTEGER', 'STRING']:
767
+ raise BadAttributeType()
768
+
769
+ return (name, type_)
770
+
771
+ def _decode(self, s, encode_nominal=False, matrix_type=DENSE):
772
+ '''Do the job the ``encode``.'''
773
+
774
+ # Make sure this method is idempotent
775
+ self._current_line = 0
776
+
777
+ # If string, convert to a list of lines
778
+ if isinstance(s, str):
779
+ s = s.strip('\r\n ').replace('\r\n', '\n').split('\n')
780
+
781
+ # Create the return object
782
+ obj: ArffContainerType = {
783
+ 'description': '',
784
+ 'relation': '',
785
+ 'attributes': [],
786
+ 'data': []
787
+ }
788
+ attribute_names = {}
789
+
790
+ # Create the data helper object
791
+ data = _get_data_object_for_decoding(matrix_type)
792
+
793
+ # Read all lines
794
+ STATE = _TK_DESCRIPTION
795
+ s = iter(s)
796
+ for row in s:
797
+ self._current_line += 1
798
+ # Ignore empty lines
799
+ row = row.strip(' \r\n')
800
+ if not row: continue
801
+
802
+ u_row = row.upper()
803
+
804
+ # DESCRIPTION -----------------------------------------------------
805
+ if u_row.startswith(_TK_DESCRIPTION) and STATE == _TK_DESCRIPTION:
806
+ obj['description'] += self._decode_comment(row) + '\n'
807
+ # -----------------------------------------------------------------
808
+
809
+ # RELATION --------------------------------------------------------
810
+ elif u_row.startswith(_TK_RELATION):
811
+ if STATE != _TK_DESCRIPTION:
812
+ raise BadLayout()
813
+
814
+ STATE = _TK_RELATION
815
+ obj['relation'] = self._decode_relation(row)
816
+ # -----------------------------------------------------------------
817
+
818
+ # ATTRIBUTE -------------------------------------------------------
819
+ elif u_row.startswith(_TK_ATTRIBUTE):
820
+ if STATE != _TK_RELATION and STATE != _TK_ATTRIBUTE:
821
+ raise BadLayout()
822
+
823
+ STATE = _TK_ATTRIBUTE
824
+
825
+ attr = self._decode_attribute(row)
826
+ if attr[0] in attribute_names:
827
+ raise BadAttributeName(attr[0], attribute_names[attr[0]])
828
+ else:
829
+ attribute_names[attr[0]] = self._current_line
830
+ obj['attributes'].append(attr)
831
+
832
+ if isinstance(attr[1], (list, tuple)):
833
+ if encode_nominal:
834
+ conversor = EncodedNominalConversor(attr[1])
835
+ else:
836
+ conversor = NominalConversor(attr[1])
837
+ else:
838
+ CONVERSOR_MAP = {'STRING': str,
839
+ 'INTEGER': lambda x: int(float(x)),
840
+ 'NUMERIC': float,
841
+ 'REAL': float}
842
+ conversor = CONVERSOR_MAP[attr[1]]
843
+
844
+ self._conversors.append(conversor)
845
+ # -----------------------------------------------------------------
846
+
847
+ # DATA ------------------------------------------------------------
848
+ elif u_row.startswith(_TK_DATA):
849
+ if STATE != _TK_ATTRIBUTE:
850
+ raise BadLayout()
851
+
852
+ break
853
+ # -----------------------------------------------------------------
854
+
855
+ # COMMENT ---------------------------------------------------------
856
+ elif u_row.startswith(_TK_COMMENT):
857
+ pass
858
+ # -----------------------------------------------------------------
859
+ else:
860
+ # Never found @DATA
861
+ raise BadLayout()
862
+
863
+ def stream():
864
+ for row in s:
865
+ self._current_line += 1
866
+ row = row.strip()
867
+ # Ignore empty lines and comment lines.
868
+ if row and not row.startswith(_TK_COMMENT):
869
+ yield row
870
+
871
+ # Alter the data object
872
+ obj['data'] = data.decode_rows(stream(), self._conversors)
873
+ if obj['description'].endswith('\n'):
874
+ obj['description'] = obj['description'][:-1]
875
+
876
+ return obj
877
+
878
+ def decode(self, s, encode_nominal=False, return_type=DENSE):
879
+ '''Returns the Python representation of a given ARFF file.
880
+
881
+ When a file object is passed as an argument, this method reads lines
882
+ iteratively, avoiding to load unnecessary information to the memory.
883
+
884
+ :param s: a string or file object with the ARFF file.
885
+ :param encode_nominal: boolean, if True perform a label encoding
886
+ while reading the .arff file.
887
+ :param return_type: determines the data structure used to store the
888
+ dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
889
+ `arff.DENSE_GEN` or `arff.LOD_GEN`.
890
+ Consult the sections on `working with sparse data`_ and `loading
891
+ progressively`_.
892
+ '''
893
+ try:
894
+ return self._decode(s, encode_nominal=encode_nominal,
895
+ matrix_type=return_type)
896
+ except ArffException as e:
897
+ e.line = self._current_line
898
+ raise e
899
+
900
+
901
+ class ArffEncoder:
902
+ '''An ARFF encoder.'''
903
+
904
+ def _encode_comment(self, s=''):
905
+ '''(INTERNAL) Encodes a comment line.
906
+
907
+ Comments are single line strings starting, obligatorily, with the ``%``
908
+ character, and can have any symbol, including whitespaces or special
909
+ characters.
910
+
911
+ If ``s`` is None, this method will simply return an empty comment.
912
+
913
+ :param s: (OPTIONAL) string.
914
+ :return: a string with the encoded comment line.
915
+ '''
916
+ if s:
917
+ return '%s %s'%(_TK_COMMENT, s)
918
+ else:
919
+ return '%s' % _TK_COMMENT
920
+
921
+ def _encode_relation(self, name):
922
+ '''(INTERNAL) Decodes a relation line.
923
+
924
+ The relation declaration is a line with the format ``@RELATION
925
+ <relation-name>``, where ``relation-name`` is a string.
926
+
927
+ :param name: a string.
928
+ :return: a string with the encoded relation declaration.
929
+ '''
930
+ for char in ' %{},':
931
+ if char in name:
932
+ name = '"%s"'%name
933
+ break
934
+
935
+ return '%s %s'%(_TK_RELATION, name)
936
+
937
+ def _encode_attribute(self, name, type_):
938
+ '''(INTERNAL) Encodes an attribute line.
939
+
940
+ The attribute follow the template::
941
+
942
+ @attribute <attribute-name> <datatype>
943
+
944
+ where ``attribute-name`` is a string, and ``datatype`` can be:
945
+
946
+ - Numerical attributes as ``NUMERIC``, ``INTEGER`` or ``REAL``.
947
+ - Strings as ``STRING``.
948
+ - Dates (NOT IMPLEMENTED).
949
+ - Nominal attributes with format:
950
+
951
+ {<nominal-name1>, <nominal-name2>, <nominal-name3>, ...}
952
+
953
+ This method must receive a the name of the attribute and its type, if
954
+ the attribute type is nominal, ``type`` must be a list of values.
955
+
956
+ :param name: a string.
957
+ :param type_: a string or a list of string.
958
+ :return: a string with the encoded attribute declaration.
959
+ '''
960
+ for char in ' %{},':
961
+ if char in name:
962
+ name = '"%s"'%name
963
+ break
964
+
965
+ if isinstance(type_, (tuple, list)):
966
+ type_tmp = ['%s' % encode_string(type_k) for type_k in type_]
967
+ type_ = '{%s}'%(', '.join(type_tmp))
968
+
969
+ return '%s %s %s'%(_TK_ATTRIBUTE, name, type_)
970
+
971
+ def encode(self, obj):
972
+ '''Encodes a given object to an ARFF file.
973
+
974
+ :param obj: the object containing the ARFF information.
975
+ :return: the ARFF file as an string.
976
+ '''
977
+ data = [row for row in self.iter_encode(obj)]
978
+
979
+ return '\n'.join(data)
980
+
981
+ def iter_encode(self, obj):
982
+ '''The iterative version of `arff.ArffEncoder.encode`.
983
+
984
+ This encodes iteratively a given object and return, one-by-one, the
985
+ lines of the ARFF file.
986
+
987
+ :param obj: the object containing the ARFF information.
988
+ :return: (yields) the ARFF file as strings.
989
+ '''
990
+ # DESCRIPTION
991
+ if obj.get('description', None):
992
+ for row in obj['description'].split('\n'):
993
+ yield self._encode_comment(row)
994
+
995
+ # RELATION
996
+ if not obj.get('relation'):
997
+ raise BadObject('Relation name not found or with invalid value.')
998
+
999
+ yield self._encode_relation(obj['relation'])
1000
+ yield ''
1001
+
1002
+ # ATTRIBUTES
1003
+ if not obj.get('attributes'):
1004
+ raise BadObject('Attributes not found.')
1005
+
1006
+ attribute_names = set()
1007
+ for attr in obj['attributes']:
1008
+ # Verify for bad object format
1009
+ if not isinstance(attr, (tuple, list)) or \
1010
+ len(attr) != 2 or \
1011
+ not isinstance(attr[0], str):
1012
+ raise BadObject('Invalid attribute declaration "%s"'%str(attr))
1013
+
1014
+ if isinstance(attr[1], str):
1015
+ # Verify for invalid types
1016
+ if attr[1] not in _SIMPLE_TYPES:
1017
+ raise BadObject('Invalid attribute type "%s"'%str(attr))
1018
+
1019
+ # Verify for bad object format
1020
+ elif not isinstance(attr[1], (tuple, list)):
1021
+ raise BadObject('Invalid attribute type "%s"'%str(attr))
1022
+
1023
+ # Verify attribute name is not used twice
1024
+ if attr[0] in attribute_names:
1025
+ raise BadObject('Trying to use attribute name "%s" for the '
1026
+ 'second time.' % str(attr[0]))
1027
+ else:
1028
+ attribute_names.add(attr[0])
1029
+
1030
+ yield self._encode_attribute(attr[0], attr[1])
1031
+ yield ''
1032
+ attributes = obj['attributes']
1033
+
1034
+ # DATA
1035
+ yield _TK_DATA
1036
+ if 'data' in obj:
1037
+ data = _get_data_object_for_encoding(obj.get('data'))
1038
+ yield from data.encode_data(obj.get('data'), attributes)
1039
+
1040
+ yield ''
1041
+
1042
+ # =============================================================================
1043
+
1044
+ # BASIC INTERFACE =============================================================
1045
+ def load(fp, encode_nominal=False, return_type=DENSE):
1046
+ '''Load a file-like object containing the ARFF document and convert it into
1047
+ a Python object.
1048
+
1049
+ :param fp: a file-like object.
1050
+ :param encode_nominal: boolean, if True perform a label encoding
1051
+ while reading the .arff file.
1052
+ :param return_type: determines the data structure used to store the
1053
+ dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
1054
+ `arff.DENSE_GEN` or `arff.LOD_GEN`.
1055
+ Consult the sections on `working with sparse data`_ and `loading
1056
+ progressively`_.
1057
+ :return: a dictionary.
1058
+ '''
1059
+ decoder = ArffDecoder()
1060
+ return decoder.decode(fp, encode_nominal=encode_nominal,
1061
+ return_type=return_type)
1062
+
1063
+ def loads(s, encode_nominal=False, return_type=DENSE):
1064
+ '''Convert a string instance containing the ARFF document into a Python
1065
+ object.
1066
+
1067
+ :param s: a string object.
1068
+ :param encode_nominal: boolean, if True perform a label encoding
1069
+ while reading the .arff file.
1070
+ :param return_type: determines the data structure used to store the
1071
+ dataset. Can be one of `arff.DENSE`, `arff.COO`, `arff.LOD`,
1072
+ `arff.DENSE_GEN` or `arff.LOD_GEN`.
1073
+ Consult the sections on `working with sparse data`_ and `loading
1074
+ progressively`_.
1075
+ :return: a dictionary.
1076
+ '''
1077
+ decoder = ArffDecoder()
1078
+ return decoder.decode(s, encode_nominal=encode_nominal,
1079
+ return_type=return_type)
1080
+
1081
+ def dump(obj, fp):
1082
+ '''Serialize an object representing the ARFF document to a given file-like
1083
+ object.
1084
+
1085
+ :param obj: a dictionary.
1086
+ :param fp: a file-like object.
1087
+ '''
1088
+ encoder = ArffEncoder()
1089
+ generator = encoder.iter_encode(obj)
1090
+
1091
+ last_row = next(generator)
1092
+ for row in generator:
1093
+ fp.write(last_row + '\n')
1094
+ last_row = row
1095
+ fp.write(last_row)
1096
+
1097
+ return fp
1098
+
1099
+ def dumps(obj):
1100
+ '''Serialize an object representing the ARFF document, returning a string.
1101
+
1102
+ :param obj: a dictionary.
1103
+ :return: a string with the ARFF document.
1104
+ '''
1105
+ encoder = ArffEncoder()
1106
+ return encoder.encode(obj)
1107
+ # =============================================================================
videollama2/lib/python3.10/site-packages/sklearn/impute/_knn.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Authors: Ashim Bhattarai <ashimb9@gmail.com>
2
+ # Thomas J Fan <thomasjpfan@gmail.com>
3
+ # License: BSD 3 clause
4
+
5
+ from numbers import Integral
6
+ import numpy as np
7
+
8
+ from ._base import _BaseImputer
9
+ from ..utils.validation import FLOAT_DTYPES
10
+ from ..metrics import pairwise_distances_chunked
11
+ from ..metrics.pairwise import _NAN_METRICS
12
+ from ..neighbors._base import _get_weights
13
+ from ..utils import is_scalar_nan
14
+ from ..utils._mask import _get_mask
15
+ from ..utils.validation import check_is_fitted
16
+ from ..utils.validation import _check_feature_names_in
17
+ from ..utils._param_validation import Hidden, Interval, StrOptions
18
+
19
+
20
+ class KNNImputer(_BaseImputer):
21
+ """Imputation for completing missing values using k-Nearest Neighbors.
22
+
23
+ Each sample's missing values are imputed using the mean value from
24
+ `n_neighbors` nearest neighbors found in the training set. Two samples are
25
+ close if the features that neither is missing are close.
26
+
27
+ Read more in the :ref:`User Guide <knnimpute>`.
28
+
29
+ .. versionadded:: 0.22
30
+
31
+ Parameters
32
+ ----------
33
+ missing_values : int, float, str, np.nan or None, default=np.nan
34
+ The placeholder for the missing values. All occurrences of
35
+ `missing_values` will be imputed. For pandas' dataframes with
36
+ nullable integer dtypes with missing values, `missing_values`
37
+ should be set to np.nan, since `pd.NA` will be converted to np.nan.
38
+
39
+ n_neighbors : int, default=5
40
+ Number of neighboring samples to use for imputation.
41
+
42
+ weights : {'uniform', 'distance'} or callable, default='uniform'
43
+ Weight function used in prediction. Possible values:
44
+
45
+ - 'uniform' : uniform weights. All points in each neighborhood are
46
+ weighted equally.
47
+ - 'distance' : weight points by the inverse of their distance.
48
+ in this case, closer neighbors of a query point will have a
49
+ greater influence than neighbors which are further away.
50
+ - callable : a user-defined function which accepts an
51
+ array of distances, and returns an array of the same shape
52
+ containing the weights.
53
+
54
+ metric : {'nan_euclidean'} or callable, default='nan_euclidean'
55
+ Distance metric for searching neighbors. Possible values:
56
+
57
+ - 'nan_euclidean'
58
+ - callable : a user-defined function which conforms to the definition
59
+ of ``_pairwise_callable(X, Y, metric, **kwds)``. The function
60
+ accepts two arrays, X and Y, and a `missing_values` keyword in
61
+ `kwds` and returns a scalar distance value.
62
+
63
+ copy : bool, default=True
64
+ If True, a copy of X will be created. If False, imputation will
65
+ be done in-place whenever possible.
66
+
67
+ add_indicator : bool, default=False
68
+ If True, a :class:`MissingIndicator` transform will stack onto the
69
+ output of the imputer's transform. This allows a predictive estimator
70
+ to account for missingness despite imputation. If a feature has no
71
+ missing values at fit/train time, the feature won't appear on the
72
+ missing indicator even if there are missing values at transform/test
73
+ time.
74
+
75
+ keep_empty_features : bool, default=False
76
+ If True, features that consist exclusively of missing values when
77
+ `fit` is called are returned in results when `transform` is called.
78
+ The imputed value is always `0`.
79
+
80
+ .. versionadded:: 1.2
81
+
82
+ Attributes
83
+ ----------
84
+ indicator_ : :class:`~sklearn.impute.MissingIndicator`
85
+ Indicator used to add binary indicators for missing values.
86
+ ``None`` if add_indicator is False.
87
+
88
+ n_features_in_ : int
89
+ Number of features seen during :term:`fit`.
90
+
91
+ .. versionadded:: 0.24
92
+
93
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
94
+ Names of features seen during :term:`fit`. Defined only when `X`
95
+ has feature names that are all strings.
96
+
97
+ .. versionadded:: 1.0
98
+
99
+ See Also
100
+ --------
101
+ SimpleImputer : Univariate imputer for completing missing values
102
+ with simple strategies.
103
+ IterativeImputer : Multivariate imputer that estimates values to impute for
104
+ each feature with missing values from all the others.
105
+
106
+ References
107
+ ----------
108
+ * Olga Troyanskaya, Michael Cantor, Gavin Sherlock, Pat Brown, Trevor
109
+ Hastie, Robert Tibshirani, David Botstein and Russ B. Altman, Missing
110
+ value estimation methods for DNA microarrays, BIOINFORMATICS Vol. 17
111
+ no. 6, 2001 Pages 520-525.
112
+
113
+ Examples
114
+ --------
115
+ >>> import numpy as np
116
+ >>> from sklearn.impute import KNNImputer
117
+ >>> X = [[1, 2, np.nan], [3, 4, 3], [np.nan, 6, 5], [8, 8, 7]]
118
+ >>> imputer = KNNImputer(n_neighbors=2)
119
+ >>> imputer.fit_transform(X)
120
+ array([[1. , 2. , 4. ],
121
+ [3. , 4. , 3. ],
122
+ [5.5, 6. , 5. ],
123
+ [8. , 8. , 7. ]])
124
+ """
125
+
126
+ _parameter_constraints: dict = {
127
+ **_BaseImputer._parameter_constraints,
128
+ "n_neighbors": [Interval(Integral, 1, None, closed="left")],
129
+ "weights": [StrOptions({"uniform", "distance"}), callable, Hidden(None)],
130
+ "metric": [StrOptions(set(_NAN_METRICS)), callable],
131
+ "copy": ["boolean"],
132
+ }
133
+
134
+ def __init__(
135
+ self,
136
+ *,
137
+ missing_values=np.nan,
138
+ n_neighbors=5,
139
+ weights="uniform",
140
+ metric="nan_euclidean",
141
+ copy=True,
142
+ add_indicator=False,
143
+ keep_empty_features=False,
144
+ ):
145
+ super().__init__(
146
+ missing_values=missing_values,
147
+ add_indicator=add_indicator,
148
+ keep_empty_features=keep_empty_features,
149
+ )
150
+ self.n_neighbors = n_neighbors
151
+ self.weights = weights
152
+ self.metric = metric
153
+ self.copy = copy
154
+
155
+ def _calc_impute(self, dist_pot_donors, n_neighbors, fit_X_col, mask_fit_X_col):
156
+ """Helper function to impute a single column.
157
+
158
+ Parameters
159
+ ----------
160
+ dist_pot_donors : ndarray of shape (n_receivers, n_potential_donors)
161
+ Distance matrix between the receivers and potential donors from
162
+ training set. There must be at least one non-nan distance between
163
+ a receiver and a potential donor.
164
+
165
+ n_neighbors : int
166
+ Number of neighbors to consider.
167
+
168
+ fit_X_col : ndarray of shape (n_potential_donors,)
169
+ Column of potential donors from training set.
170
+
171
+ mask_fit_X_col : ndarray of shape (n_potential_donors,)
172
+ Missing mask for fit_X_col.
173
+
174
+ Returns
175
+ -------
176
+ imputed_values: ndarray of shape (n_receivers,)
177
+ Imputed values for receiver.
178
+ """
179
+ # Get donors
180
+ donors_idx = np.argpartition(dist_pot_donors, n_neighbors - 1, axis=1)[
181
+ :, :n_neighbors
182
+ ]
183
+
184
+ # Get weight matrix from distance matrix
185
+ donors_dist = dist_pot_donors[
186
+ np.arange(donors_idx.shape[0])[:, None], donors_idx
187
+ ]
188
+
189
+ weight_matrix = _get_weights(donors_dist, self.weights)
190
+
191
+ # fill nans with zeros
192
+ if weight_matrix is not None:
193
+ weight_matrix[np.isnan(weight_matrix)] = 0.0
194
+
195
+ # Retrieve donor values and calculate kNN average
196
+ donors = fit_X_col.take(donors_idx)
197
+ donors_mask = mask_fit_X_col.take(donors_idx)
198
+ donors = np.ma.array(donors, mask=donors_mask)
199
+
200
+ return np.ma.average(donors, axis=1, weights=weight_matrix).data
201
+
202
+ def fit(self, X, y=None):
203
+ """Fit the imputer on X.
204
+
205
+ Parameters
206
+ ----------
207
+ X : array-like shape of (n_samples, n_features)
208
+ Input data, where `n_samples` is the number of samples and
209
+ `n_features` is the number of features.
210
+
211
+ y : Ignored
212
+ Not used, present here for API consistency by convention.
213
+
214
+ Returns
215
+ -------
216
+ self : object
217
+ The fitted `KNNImputer` class instance.
218
+ """
219
+ self._validate_params()
220
+ # Check data integrity and calling arguments
221
+ if not is_scalar_nan(self.missing_values):
222
+ force_all_finite = True
223
+ else:
224
+ force_all_finite = "allow-nan"
225
+
226
+ X = self._validate_data(
227
+ X,
228
+ accept_sparse=False,
229
+ dtype=FLOAT_DTYPES,
230
+ force_all_finite=force_all_finite,
231
+ copy=self.copy,
232
+ )
233
+
234
+ self._fit_X = X
235
+ self._mask_fit_X = _get_mask(self._fit_X, self.missing_values)
236
+ self._valid_mask = ~np.all(self._mask_fit_X, axis=0)
237
+
238
+ super()._fit_indicator(self._mask_fit_X)
239
+
240
+ return self
241
+
242
+ def transform(self, X):
243
+ """Impute all missing values in X.
244
+
245
+ Parameters
246
+ ----------
247
+ X : array-like of shape (n_samples, n_features)
248
+ The input data to complete.
249
+
250
+ Returns
251
+ -------
252
+ X : array-like of shape (n_samples, n_output_features)
253
+ The imputed dataset. `n_output_features` is the number of features
254
+ that is not always missing during `fit`.
255
+ """
256
+
257
+ check_is_fitted(self)
258
+ if not is_scalar_nan(self.missing_values):
259
+ force_all_finite = True
260
+ else:
261
+ force_all_finite = "allow-nan"
262
+ X = self._validate_data(
263
+ X,
264
+ accept_sparse=False,
265
+ dtype=FLOAT_DTYPES,
266
+ force_all_finite=force_all_finite,
267
+ copy=self.copy,
268
+ reset=False,
269
+ )
270
+
271
+ mask = _get_mask(X, self.missing_values)
272
+ mask_fit_X = self._mask_fit_X
273
+ valid_mask = self._valid_mask
274
+
275
+ X_indicator = super()._transform_indicator(mask)
276
+
277
+ # Removes columns where the training data is all nan
278
+ if not np.any(mask):
279
+ # No missing values in X
280
+ if self.keep_empty_features:
281
+ Xc = X
282
+ Xc[:, ~valid_mask] = 0
283
+ else:
284
+ Xc = X[:, valid_mask]
285
+ return Xc
286
+
287
+ row_missing_idx = np.flatnonzero(mask.any(axis=1))
288
+
289
+ non_missing_fix_X = np.logical_not(mask_fit_X)
290
+
291
+ # Maps from indices from X to indices in dist matrix
292
+ dist_idx_map = np.zeros(X.shape[0], dtype=int)
293
+ dist_idx_map[row_missing_idx] = np.arange(row_missing_idx.shape[0])
294
+
295
+ def process_chunk(dist_chunk, start):
296
+ row_missing_chunk = row_missing_idx[start : start + len(dist_chunk)]
297
+
298
+ # Find and impute missing by column
299
+ for col in range(X.shape[1]):
300
+ if not valid_mask[col]:
301
+ # column was all missing during training
302
+ continue
303
+
304
+ col_mask = mask[row_missing_chunk, col]
305
+ if not np.any(col_mask):
306
+ # column has no missing values
307
+ continue
308
+
309
+ (potential_donors_idx,) = np.nonzero(non_missing_fix_X[:, col])
310
+
311
+ # receivers_idx are indices in X
312
+ receivers_idx = row_missing_chunk[np.flatnonzero(col_mask)]
313
+
314
+ # distances for samples that needed imputation for column
315
+ dist_subset = dist_chunk[dist_idx_map[receivers_idx] - start][
316
+ :, potential_donors_idx
317
+ ]
318
+
319
+ # receivers with all nan distances impute with mean
320
+ all_nan_dist_mask = np.isnan(dist_subset).all(axis=1)
321
+ all_nan_receivers_idx = receivers_idx[all_nan_dist_mask]
322
+
323
+ if all_nan_receivers_idx.size:
324
+ col_mean = np.ma.array(
325
+ self._fit_X[:, col], mask=mask_fit_X[:, col]
326
+ ).mean()
327
+ X[all_nan_receivers_idx, col] = col_mean
328
+
329
+ if len(all_nan_receivers_idx) == len(receivers_idx):
330
+ # all receivers imputed with mean
331
+ continue
332
+
333
+ # receivers with at least one defined distance
334
+ receivers_idx = receivers_idx[~all_nan_dist_mask]
335
+ dist_subset = dist_chunk[dist_idx_map[receivers_idx] - start][
336
+ :, potential_donors_idx
337
+ ]
338
+
339
+ n_neighbors = min(self.n_neighbors, len(potential_donors_idx))
340
+ value = self._calc_impute(
341
+ dist_subset,
342
+ n_neighbors,
343
+ self._fit_X[potential_donors_idx, col],
344
+ mask_fit_X[potential_donors_idx, col],
345
+ )
346
+ X[receivers_idx, col] = value
347
+
348
+ # process in fixed-memory chunks
349
+ gen = pairwise_distances_chunked(
350
+ X[row_missing_idx, :],
351
+ self._fit_X,
352
+ metric=self.metric,
353
+ missing_values=self.missing_values,
354
+ force_all_finite=force_all_finite,
355
+ reduce_func=process_chunk,
356
+ )
357
+ for chunk in gen:
358
+ # process_chunk modifies X in place. No return value.
359
+ pass
360
+
361
+ if self.keep_empty_features:
362
+ Xc = X
363
+ Xc[:, ~valid_mask] = 0
364
+ else:
365
+ Xc = X[:, valid_mask]
366
+
367
+ return super()._concatenate_indicator(Xc, X_indicator)
368
+
369
+ def get_feature_names_out(self, input_features=None):
370
+ """Get output feature names for transformation.
371
+
372
+ Parameters
373
+ ----------
374
+ input_features : array-like of str or None, default=None
375
+ Input features.
376
+
377
+ - If `input_features` is `None`, then `feature_names_in_` is
378
+ used as feature names in. If `feature_names_in_` is not defined,
379
+ then the following input feature names are generated:
380
+ `["x0", "x1", ..., "x(n_features_in_ - 1)"]`.
381
+ - If `input_features` is an array-like, then `input_features` must
382
+ match `feature_names_in_` if `feature_names_in_` is defined.
383
+
384
+ Returns
385
+ -------
386
+ feature_names_out : ndarray of str objects
387
+ Transformed feature names.
388
+ """
389
+ input_features = _check_feature_names_in(self, input_features)
390
+ names = input_features[self._valid_mask]
391
+ return self._concatenate_indicator_feature_names_out(names, input_features)
videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The :mod:`sklearn.semi_supervised` module implements semi-supervised learning
3
+ algorithms. These algorithms utilize small amounts of labeled data and large
4
+ amounts of unlabeled data for classification tasks. This module includes Label
5
+ Propagation.
6
+ """
7
+
8
+ from ._label_propagation import LabelPropagation, LabelSpreading
9
+ from ._self_training import SelfTrainingClassifier
10
+
11
+ __all__ = ["SelfTrainingClassifier", "LabelPropagation", "LabelSpreading"]
videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (626 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/__pycache__/_label_propagation.cpython-310.pyc ADDED
Binary file (18.8 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/_label_propagation.py ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf8
2
+ """
3
+ Label propagation in the context of this module refers to a set of
4
+ semi-supervised classification algorithms. At a high level, these algorithms
5
+ work by forming a fully-connected graph between all points given and solving
6
+ for the steady-state distribution of labels at each point.
7
+
8
+ These algorithms perform very well in practice. The cost of running can be very
9
+ expensive, at approximately O(N^3) where N is the number of (labeled and
10
+ unlabeled) points. The theory (why they perform so well) is motivated by
11
+ intuitions from random walk algorithms and geometric relationships in the data.
12
+ For more information see the references below.
13
+
14
+ Model Features
15
+ --------------
16
+ Label clamping:
17
+ The algorithm tries to learn distributions of labels over the dataset given
18
+ label assignments over an initial subset. In one variant, the algorithm does
19
+ not allow for any errors in the initial assignment (hard-clamping) while
20
+ in another variant, the algorithm allows for some wiggle room for the initial
21
+ assignments, allowing them to change by a fraction alpha in each iteration
22
+ (soft-clamping).
23
+
24
+ Kernel:
25
+ A function which projects a vector into some higher dimensional space. This
26
+ implementation supports RBF and KNN kernels. Using the RBF kernel generates
27
+ a dense matrix of size O(N^2). KNN kernel will generate a sparse matrix of
28
+ size O(k*N) which will run much faster. See the documentation for SVMs for
29
+ more info on kernels.
30
+
31
+ Examples
32
+ --------
33
+ >>> import numpy as np
34
+ >>> from sklearn import datasets
35
+ >>> from sklearn.semi_supervised import LabelPropagation
36
+ >>> label_prop_model = LabelPropagation()
37
+ >>> iris = datasets.load_iris()
38
+ >>> rng = np.random.RandomState(42)
39
+ >>> random_unlabeled_points = rng.rand(len(iris.target)) < 0.3
40
+ >>> labels = np.copy(iris.target)
41
+ >>> labels[random_unlabeled_points] = -1
42
+ >>> label_prop_model.fit(iris.data, labels)
43
+ LabelPropagation(...)
44
+
45
+ Notes
46
+ -----
47
+ References:
48
+ [1] Yoshua Bengio, Olivier Delalleau, Nicolas Le Roux. In Semi-Supervised
49
+ Learning (2006), pp. 193-216
50
+
51
+ [2] Olivier Delalleau, Yoshua Bengio, Nicolas Le Roux. Efficient
52
+ Non-Parametric Function Induction in Semi-Supervised Learning. AISTAT 2005
53
+ """
54
+
55
+ # Authors: Clay Woolam <clay@woolam.org>
56
+ # Utkarsh Upadhyay <mail@musicallyut.in>
57
+ # License: BSD
58
+ from abc import ABCMeta, abstractmethod
59
+ from numbers import Integral, Real
60
+
61
+ import warnings
62
+ import numpy as np
63
+ from scipy import sparse
64
+ from scipy.sparse import csgraph
65
+
66
+ from ..base import BaseEstimator, ClassifierMixin
67
+ from ..metrics.pairwise import rbf_kernel
68
+ from ..neighbors import NearestNeighbors
69
+ from ..utils.extmath import safe_sparse_dot
70
+ from ..utils.multiclass import check_classification_targets
71
+ from ..utils.validation import check_is_fitted
72
+ from ..utils._param_validation import Interval, StrOptions
73
+ from ..exceptions import ConvergenceWarning
74
+
75
+
76
+ class BaseLabelPropagation(ClassifierMixin, BaseEstimator, metaclass=ABCMeta):
77
+ """Base class for label propagation module.
78
+
79
+ Parameters
80
+ ----------
81
+ kernel : {'knn', 'rbf'} or callable, default='rbf'
82
+ String identifier for kernel function to use or the kernel function
83
+ itself. Only 'rbf' and 'knn' strings are valid inputs. The function
84
+ passed should take two inputs, each of shape (n_samples, n_features),
85
+ and return a (n_samples, n_samples) shaped weight matrix.
86
+
87
+ gamma : float, default=20
88
+ Parameter for rbf kernel.
89
+
90
+ n_neighbors : int, default=7
91
+ Parameter for knn kernel. Need to be strictly positive.
92
+
93
+ alpha : float, default=1.0
94
+ Clamping factor.
95
+
96
+ max_iter : int, default=30
97
+ Change maximum number of iterations allowed.
98
+
99
+ tol : float, default=1e-3
100
+ Convergence tolerance: threshold to consider the system at steady
101
+ state.
102
+
103
+ n_jobs : int, default=None
104
+ The number of parallel jobs to run.
105
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
106
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
107
+ for more details.
108
+ """
109
+
110
+ _parameter_constraints: dict = {
111
+ "kernel": [StrOptions({"knn", "rbf"}), callable],
112
+ "gamma": [Interval(Real, 0, None, closed="left")],
113
+ "n_neighbors": [Interval(Integral, 0, None, closed="neither")],
114
+ "alpha": [None, Interval(Real, 0, 1, closed="neither")],
115
+ "max_iter": [Interval(Integral, 0, None, closed="neither")],
116
+ "tol": [Interval(Real, 0, None, closed="left")],
117
+ "n_jobs": [None, Integral],
118
+ }
119
+
120
+ def __init__(
121
+ self,
122
+ kernel="rbf",
123
+ *,
124
+ gamma=20,
125
+ n_neighbors=7,
126
+ alpha=1,
127
+ max_iter=30,
128
+ tol=1e-3,
129
+ n_jobs=None,
130
+ ):
131
+
132
+ self.max_iter = max_iter
133
+ self.tol = tol
134
+
135
+ # kernel parameters
136
+ self.kernel = kernel
137
+ self.gamma = gamma
138
+ self.n_neighbors = n_neighbors
139
+
140
+ # clamping factor
141
+ self.alpha = alpha
142
+
143
+ self.n_jobs = n_jobs
144
+
145
+ def _get_kernel(self, X, y=None):
146
+ if self.kernel == "rbf":
147
+ if y is None:
148
+ return rbf_kernel(X, X, gamma=self.gamma)
149
+ else:
150
+ return rbf_kernel(X, y, gamma=self.gamma)
151
+ elif self.kernel == "knn":
152
+ if self.nn_fit is None:
153
+ self.nn_fit = NearestNeighbors(
154
+ n_neighbors=self.n_neighbors, n_jobs=self.n_jobs
155
+ ).fit(X)
156
+ if y is None:
157
+ return self.nn_fit.kneighbors_graph(
158
+ self.nn_fit._fit_X, self.n_neighbors, mode="connectivity"
159
+ )
160
+ else:
161
+ return self.nn_fit.kneighbors(y, return_distance=False)
162
+ elif callable(self.kernel):
163
+ if y is None:
164
+ return self.kernel(X, X)
165
+ else:
166
+ return self.kernel(X, y)
167
+
168
+ @abstractmethod
169
+ def _build_graph(self):
170
+ raise NotImplementedError(
171
+ "Graph construction must be implemented to fit a label propagation model."
172
+ )
173
+
174
+ def predict(self, X):
175
+ """Perform inductive inference across the model.
176
+
177
+ Parameters
178
+ ----------
179
+ X : array-like of shape (n_samples, n_features)
180
+ The data matrix.
181
+
182
+ Returns
183
+ -------
184
+ y : ndarray of shape (n_samples,)
185
+ Predictions for input data.
186
+ """
187
+ # Note: since `predict` does not accept semi-supervised labels as input,
188
+ # `fit(X, y).predict(X) != fit(X, y).transduction_`.
189
+ # Hence, `fit_predict` is not implemented.
190
+ # See https://github.com/scikit-learn/scikit-learn/pull/24898
191
+ probas = self.predict_proba(X)
192
+ return self.classes_[np.argmax(probas, axis=1)].ravel()
193
+
194
+ def predict_proba(self, X):
195
+ """Predict probability for each possible outcome.
196
+
197
+ Compute the probability estimates for each single sample in X
198
+ and each possible outcome seen during training (categorical
199
+ distribution).
200
+
201
+ Parameters
202
+ ----------
203
+ X : array-like of shape (n_samples, n_features)
204
+ The data matrix.
205
+
206
+ Returns
207
+ -------
208
+ probabilities : ndarray of shape (n_samples, n_classes)
209
+ Normalized probability distributions across
210
+ class labels.
211
+ """
212
+ check_is_fitted(self)
213
+
214
+ X_2d = self._validate_data(
215
+ X,
216
+ accept_sparse=["csc", "csr", "coo", "dok", "bsr", "lil", "dia"],
217
+ reset=False,
218
+ )
219
+ weight_matrices = self._get_kernel(self.X_, X_2d)
220
+ if self.kernel == "knn":
221
+ probabilities = np.array(
222
+ [
223
+ np.sum(self.label_distributions_[weight_matrix], axis=0)
224
+ for weight_matrix in weight_matrices
225
+ ]
226
+ )
227
+ else:
228
+ weight_matrices = weight_matrices.T
229
+ probabilities = safe_sparse_dot(weight_matrices, self.label_distributions_)
230
+ normalizer = np.atleast_2d(np.sum(probabilities, axis=1)).T
231
+ probabilities /= normalizer
232
+ return probabilities
233
+
234
+ def fit(self, X, y):
235
+ """Fit a semi-supervised label propagation model to X.
236
+
237
+ The input samples (labeled and unlabeled) are provided by matrix X,
238
+ and target labels are provided by matrix y. We conventionally apply the
239
+ label -1 to unlabeled samples in matrix y in a semi-supervised
240
+ classification.
241
+
242
+ Parameters
243
+ ----------
244
+ X : array-like of shape (n_samples, n_features)
245
+ Training data, where `n_samples` is the number of samples
246
+ and `n_features` is the number of features.
247
+
248
+ y : array-like of shape (n_samples,)
249
+ Target class values with unlabeled points marked as -1.
250
+ All unlabeled samples will be transductively assigned labels
251
+ internally, which are stored in `transduction_`.
252
+
253
+ Returns
254
+ -------
255
+ self : object
256
+ Returns the instance itself.
257
+ """
258
+ self._validate_params()
259
+ X, y = self._validate_data(X, y)
260
+ self.X_ = X
261
+ check_classification_targets(y)
262
+
263
+ # actual graph construction (implementations should override this)
264
+ graph_matrix = self._build_graph()
265
+
266
+ # label construction
267
+ # construct a categorical distribution for classification only
268
+ classes = np.unique(y)
269
+ classes = classes[classes != -1]
270
+ self.classes_ = classes
271
+
272
+ n_samples, n_classes = len(y), len(classes)
273
+
274
+ y = np.asarray(y)
275
+ unlabeled = y == -1
276
+
277
+ # initialize distributions
278
+ self.label_distributions_ = np.zeros((n_samples, n_classes))
279
+ for label in classes:
280
+ self.label_distributions_[y == label, classes == label] = 1
281
+
282
+ y_static = np.copy(self.label_distributions_)
283
+ if self._variant == "propagation":
284
+ # LabelPropagation
285
+ y_static[unlabeled] = 0
286
+ else:
287
+ # LabelSpreading
288
+ y_static *= 1 - self.alpha
289
+
290
+ l_previous = np.zeros((self.X_.shape[0], n_classes))
291
+
292
+ unlabeled = unlabeled[:, np.newaxis]
293
+ if sparse.isspmatrix(graph_matrix):
294
+ graph_matrix = graph_matrix.tocsr()
295
+
296
+ for self.n_iter_ in range(self.max_iter):
297
+ if np.abs(self.label_distributions_ - l_previous).sum() < self.tol:
298
+ break
299
+
300
+ l_previous = self.label_distributions_
301
+ self.label_distributions_ = safe_sparse_dot(
302
+ graph_matrix, self.label_distributions_
303
+ )
304
+
305
+ if self._variant == "propagation":
306
+ normalizer = np.sum(self.label_distributions_, axis=1)[:, np.newaxis]
307
+ normalizer[normalizer == 0] = 1
308
+ self.label_distributions_ /= normalizer
309
+ self.label_distributions_ = np.where(
310
+ unlabeled, self.label_distributions_, y_static
311
+ )
312
+ else:
313
+ # clamp
314
+ self.label_distributions_ = (
315
+ np.multiply(self.alpha, self.label_distributions_) + y_static
316
+ )
317
+ else:
318
+ warnings.warn(
319
+ "max_iter=%d was reached without convergence." % self.max_iter,
320
+ category=ConvergenceWarning,
321
+ )
322
+ self.n_iter_ += 1
323
+
324
+ normalizer = np.sum(self.label_distributions_, axis=1)[:, np.newaxis]
325
+ normalizer[normalizer == 0] = 1
326
+ self.label_distributions_ /= normalizer
327
+
328
+ # set the transduction item
329
+ transduction = self.classes_[np.argmax(self.label_distributions_, axis=1)]
330
+ self.transduction_ = transduction.ravel()
331
+ return self
332
+
333
+
334
+ class LabelPropagation(BaseLabelPropagation):
335
+ """Label Propagation classifier.
336
+
337
+ Read more in the :ref:`User Guide <label_propagation>`.
338
+
339
+ Parameters
340
+ ----------
341
+ kernel : {'knn', 'rbf'} or callable, default='rbf'
342
+ String identifier for kernel function to use or the kernel function
343
+ itself. Only 'rbf' and 'knn' strings are valid inputs. The function
344
+ passed should take two inputs, each of shape (n_samples, n_features),
345
+ and return a (n_samples, n_samples) shaped weight matrix.
346
+
347
+ gamma : float, default=20
348
+ Parameter for rbf kernel.
349
+
350
+ n_neighbors : int, default=7
351
+ Parameter for knn kernel which need to be strictly positive.
352
+
353
+ max_iter : int, default=1000
354
+ Change maximum number of iterations allowed.
355
+
356
+ tol : float, 1e-3
357
+ Convergence tolerance: threshold to consider the system at steady
358
+ state.
359
+
360
+ n_jobs : int, default=None
361
+ The number of parallel jobs to run.
362
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
363
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
364
+ for more details.
365
+
366
+ Attributes
367
+ ----------
368
+ X_ : ndarray of shape (n_samples, n_features)
369
+ Input array.
370
+
371
+ classes_ : ndarray of shape (n_classes,)
372
+ The distinct labels used in classifying instances.
373
+
374
+ label_distributions_ : ndarray of shape (n_samples, n_classes)
375
+ Categorical distribution for each item.
376
+
377
+ transduction_ : ndarray of shape (n_samples)
378
+ Label assigned to each item during :term:`fit`.
379
+
380
+ n_features_in_ : int
381
+ Number of features seen during :term:`fit`.
382
+
383
+ .. versionadded:: 0.24
384
+
385
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
386
+ Names of features seen during :term:`fit`. Defined only when `X`
387
+ has feature names that are all strings.
388
+
389
+ .. versionadded:: 1.0
390
+
391
+ n_iter_ : int
392
+ Number of iterations run.
393
+
394
+ See Also
395
+ --------
396
+ BaseLabelPropagation : Base class for label propagation module.
397
+ LabelSpreading : Alternate label propagation strategy more robust to noise.
398
+
399
+ References
400
+ ----------
401
+ Xiaojin Zhu and Zoubin Ghahramani. Learning from labeled and unlabeled data
402
+ with label propagation. Technical Report CMU-CALD-02-107, Carnegie Mellon
403
+ University, 2002 http://pages.cs.wisc.edu/~jerryzhu/pub/CMU-CALD-02-107.pdf
404
+
405
+ Examples
406
+ --------
407
+ >>> import numpy as np
408
+ >>> from sklearn import datasets
409
+ >>> from sklearn.semi_supervised import LabelPropagation
410
+ >>> label_prop_model = LabelPropagation()
411
+ >>> iris = datasets.load_iris()
412
+ >>> rng = np.random.RandomState(42)
413
+ >>> random_unlabeled_points = rng.rand(len(iris.target)) < 0.3
414
+ >>> labels = np.copy(iris.target)
415
+ >>> labels[random_unlabeled_points] = -1
416
+ >>> label_prop_model.fit(iris.data, labels)
417
+ LabelPropagation(...)
418
+ """
419
+
420
+ _variant = "propagation"
421
+
422
+ _parameter_constraints: dict = {**BaseLabelPropagation._parameter_constraints}
423
+ _parameter_constraints.pop("alpha")
424
+
425
+ def __init__(
426
+ self,
427
+ kernel="rbf",
428
+ *,
429
+ gamma=20,
430
+ n_neighbors=7,
431
+ max_iter=1000,
432
+ tol=1e-3,
433
+ n_jobs=None,
434
+ ):
435
+ super().__init__(
436
+ kernel=kernel,
437
+ gamma=gamma,
438
+ n_neighbors=n_neighbors,
439
+ max_iter=max_iter,
440
+ tol=tol,
441
+ n_jobs=n_jobs,
442
+ alpha=None,
443
+ )
444
+
445
+ def _build_graph(self):
446
+ """Matrix representing a fully connected graph between each sample
447
+
448
+ This basic implementation creates a non-stochastic affinity matrix, so
449
+ class distributions will exceed 1 (normalization may be desired).
450
+ """
451
+ if self.kernel == "knn":
452
+ self.nn_fit = None
453
+ affinity_matrix = self._get_kernel(self.X_)
454
+ normalizer = affinity_matrix.sum(axis=0)
455
+ if sparse.isspmatrix(affinity_matrix):
456
+ affinity_matrix.data /= np.diag(np.array(normalizer))
457
+ else:
458
+ affinity_matrix /= normalizer[:, np.newaxis]
459
+ return affinity_matrix
460
+
461
+ def fit(self, X, y):
462
+ """Fit a semi-supervised label propagation model to X.
463
+
464
+ Parameters
465
+ ----------
466
+ X : array-like of shape (n_samples, n_features)
467
+ Training data, where `n_samples` is the number of samples
468
+ and `n_features` is the number of features.
469
+
470
+ y : array-like of shape (n_samples,)
471
+ Target class values with unlabeled points marked as -1.
472
+ All unlabeled samples will be transductively assigned labels
473
+ internally, which are stored in `transduction_`.
474
+
475
+ Returns
476
+ -------
477
+ self : object
478
+ Returns the instance itself.
479
+ """
480
+ return super().fit(X, y)
481
+
482
+
483
+ class LabelSpreading(BaseLabelPropagation):
484
+ """LabelSpreading model for semi-supervised learning.
485
+
486
+ This model is similar to the basic Label Propagation algorithm,
487
+ but uses affinity matrix based on the normalized graph Laplacian
488
+ and soft clamping across the labels.
489
+
490
+ Read more in the :ref:`User Guide <label_propagation>`.
491
+
492
+ Parameters
493
+ ----------
494
+ kernel : {'knn', 'rbf'} or callable, default='rbf'
495
+ String identifier for kernel function to use or the kernel function
496
+ itself. Only 'rbf' and 'knn' strings are valid inputs. The function
497
+ passed should take two inputs, each of shape (n_samples, n_features),
498
+ and return a (n_samples, n_samples) shaped weight matrix.
499
+
500
+ gamma : float, default=20
501
+ Parameter for rbf kernel.
502
+
503
+ n_neighbors : int, default=7
504
+ Parameter for knn kernel which is a strictly positive integer.
505
+
506
+ alpha : float, default=0.2
507
+ Clamping factor. A value in (0, 1) that specifies the relative amount
508
+ that an instance should adopt the information from its neighbors as
509
+ opposed to its initial label.
510
+ alpha=0 means keeping the initial label information; alpha=1 means
511
+ replacing all initial information.
512
+
513
+ max_iter : int, default=30
514
+ Maximum number of iterations allowed.
515
+
516
+ tol : float, default=1e-3
517
+ Convergence tolerance: threshold to consider the system at steady
518
+ state.
519
+
520
+ n_jobs : int, default=None
521
+ The number of parallel jobs to run.
522
+ ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
523
+ ``-1`` means using all processors. See :term:`Glossary <n_jobs>`
524
+ for more details.
525
+
526
+ Attributes
527
+ ----------
528
+ X_ : ndarray of shape (n_samples, n_features)
529
+ Input array.
530
+
531
+ classes_ : ndarray of shape (n_classes,)
532
+ The distinct labels used in classifying instances.
533
+
534
+ label_distributions_ : ndarray of shape (n_samples, n_classes)
535
+ Categorical distribution for each item.
536
+
537
+ transduction_ : ndarray of shape (n_samples,)
538
+ Label assigned to each item during :term:`fit`.
539
+
540
+ n_features_in_ : int
541
+ Number of features seen during :term:`fit`.
542
+
543
+ .. versionadded:: 0.24
544
+
545
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
546
+ Names of features seen during :term:`fit`. Defined only when `X`
547
+ has feature names that are all strings.
548
+
549
+ .. versionadded:: 1.0
550
+
551
+ n_iter_ : int
552
+ Number of iterations run.
553
+
554
+ See Also
555
+ --------
556
+ LabelPropagation : Unregularized graph based semi-supervised learning.
557
+
558
+ References
559
+ ----------
560
+ `Dengyong Zhou, Olivier Bousquet, Thomas Navin Lal, Jason Weston,
561
+ Bernhard Schoelkopf. Learning with local and global consistency (2004)
562
+ <https://citeseerx.ist.psu.edu/doc_view/pid/d74c37aabf2d5cae663007cbd8718175466aea8c>`_
563
+
564
+ Examples
565
+ --------
566
+ >>> import numpy as np
567
+ >>> from sklearn import datasets
568
+ >>> from sklearn.semi_supervised import LabelSpreading
569
+ >>> label_prop_model = LabelSpreading()
570
+ >>> iris = datasets.load_iris()
571
+ >>> rng = np.random.RandomState(42)
572
+ >>> random_unlabeled_points = rng.rand(len(iris.target)) < 0.3
573
+ >>> labels = np.copy(iris.target)
574
+ >>> labels[random_unlabeled_points] = -1
575
+ >>> label_prop_model.fit(iris.data, labels)
576
+ LabelSpreading(...)
577
+ """
578
+
579
+ _variant = "spreading"
580
+
581
+ _parameter_constraints: dict = {**BaseLabelPropagation._parameter_constraints}
582
+ _parameter_constraints["alpha"] = [Interval(Real, 0, 1, closed="neither")]
583
+
584
+ def __init__(
585
+ self,
586
+ kernel="rbf",
587
+ *,
588
+ gamma=20,
589
+ n_neighbors=7,
590
+ alpha=0.2,
591
+ max_iter=30,
592
+ tol=1e-3,
593
+ n_jobs=None,
594
+ ):
595
+
596
+ # this one has different base parameters
597
+ super().__init__(
598
+ kernel=kernel,
599
+ gamma=gamma,
600
+ n_neighbors=n_neighbors,
601
+ alpha=alpha,
602
+ max_iter=max_iter,
603
+ tol=tol,
604
+ n_jobs=n_jobs,
605
+ )
606
+
607
+ def _build_graph(self):
608
+ """Graph matrix for Label Spreading computes the graph laplacian"""
609
+ # compute affinity matrix (or gram matrix)
610
+ if self.kernel == "knn":
611
+ self.nn_fit = None
612
+ n_samples = self.X_.shape[0]
613
+ affinity_matrix = self._get_kernel(self.X_)
614
+ laplacian = csgraph.laplacian(affinity_matrix, normed=True)
615
+ laplacian = -laplacian
616
+ if sparse.isspmatrix(laplacian):
617
+ diag_mask = laplacian.row == laplacian.col
618
+ laplacian.data[diag_mask] = 0.0
619
+ else:
620
+ laplacian.flat[:: n_samples + 1] = 0.0 # set diag to 0.0
621
+ return laplacian
videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/_self_training.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from numbers import Integral, Real
3
+
4
+ import numpy as np
5
+
6
+ from ..base import MetaEstimatorMixin, clone, BaseEstimator
7
+ from ..utils._param_validation import HasMethods, Interval, StrOptions
8
+ from ..utils.validation import check_is_fitted
9
+ from ..utils.metaestimators import available_if
10
+ from ..utils import safe_mask
11
+
12
+ __all__ = ["SelfTrainingClassifier"]
13
+
14
+ # Authors: Oliver Rausch <rauscho@ethz.ch>
15
+ # Patrice Becker <beckerp@ethz.ch>
16
+ # License: BSD 3 clause
17
+
18
+
19
+ def _estimator_has(attr):
20
+ """Check if `self.base_estimator_ `or `self.base_estimator_` has `attr`."""
21
+ return lambda self: (
22
+ hasattr(self.base_estimator_, attr)
23
+ if hasattr(self, "base_estimator_")
24
+ else hasattr(self.base_estimator, attr)
25
+ )
26
+
27
+
28
+ class SelfTrainingClassifier(MetaEstimatorMixin, BaseEstimator):
29
+ """Self-training classifier.
30
+
31
+ This :term:`metaestimator` allows a given supervised classifier to function as a
32
+ semi-supervised classifier, allowing it to learn from unlabeled data. It
33
+ does this by iteratively predicting pseudo-labels for the unlabeled data
34
+ and adding them to the training set.
35
+
36
+ The classifier will continue iterating until either max_iter is reached, or
37
+ no pseudo-labels were added to the training set in the previous iteration.
38
+
39
+ Read more in the :ref:`User Guide <self_training>`.
40
+
41
+ Parameters
42
+ ----------
43
+ base_estimator : estimator object
44
+ An estimator object implementing `fit` and `predict_proba`.
45
+ Invoking the `fit` method will fit a clone of the passed estimator,
46
+ which will be stored in the `base_estimator_` attribute.
47
+
48
+ threshold : float, default=0.75
49
+ The decision threshold for use with `criterion='threshold'`.
50
+ Should be in [0, 1). When using the `'threshold'` criterion, a
51
+ :ref:`well calibrated classifier <calibration>` should be used.
52
+
53
+ criterion : {'threshold', 'k_best'}, default='threshold'
54
+ The selection criterion used to select which labels to add to the
55
+ training set. If `'threshold'`, pseudo-labels with prediction
56
+ probabilities above `threshold` are added to the dataset. If `'k_best'`,
57
+ the `k_best` pseudo-labels with highest prediction probabilities are
58
+ added to the dataset. When using the 'threshold' criterion, a
59
+ :ref:`well calibrated classifier <calibration>` should be used.
60
+
61
+ k_best : int, default=10
62
+ The amount of samples to add in each iteration. Only used when
63
+ `criterion='k_best'`.
64
+
65
+ max_iter : int or None, default=10
66
+ Maximum number of iterations allowed. Should be greater than or equal
67
+ to 0. If it is `None`, the classifier will continue to predict labels
68
+ until no new pseudo-labels are added, or all unlabeled samples have
69
+ been labeled.
70
+
71
+ verbose : bool, default=False
72
+ Enable verbose output.
73
+
74
+ Attributes
75
+ ----------
76
+ base_estimator_ : estimator object
77
+ The fitted estimator.
78
+
79
+ classes_ : ndarray or list of ndarray of shape (n_classes,)
80
+ Class labels for each output. (Taken from the trained
81
+ `base_estimator_`).
82
+
83
+ transduction_ : ndarray of shape (n_samples,)
84
+ The labels used for the final fit of the classifier, including
85
+ pseudo-labels added during fit.
86
+
87
+ labeled_iter_ : ndarray of shape (n_samples,)
88
+ The iteration in which each sample was labeled. When a sample has
89
+ iteration 0, the sample was already labeled in the original dataset.
90
+ When a sample has iteration -1, the sample was not labeled in any
91
+ iteration.
92
+
93
+ n_features_in_ : int
94
+ Number of features seen during :term:`fit`.
95
+
96
+ .. versionadded:: 0.24
97
+
98
+ feature_names_in_ : ndarray of shape (`n_features_in_`,)
99
+ Names of features seen during :term:`fit`. Defined only when `X`
100
+ has feature names that are all strings.
101
+
102
+ .. versionadded:: 1.0
103
+
104
+ n_iter_ : int
105
+ The number of rounds of self-training, that is the number of times the
106
+ base estimator is fitted on relabeled variants of the training set.
107
+
108
+ termination_condition_ : {'max_iter', 'no_change', 'all_labeled'}
109
+ The reason that fitting was stopped.
110
+
111
+ - `'max_iter'`: `n_iter_` reached `max_iter`.
112
+ - `'no_change'`: no new labels were predicted.
113
+ - `'all_labeled'`: all unlabeled samples were labeled before `max_iter`
114
+ was reached.
115
+
116
+ See Also
117
+ --------
118
+ LabelPropagation : Label propagation classifier.
119
+ LabelSpreading : Label spreading model for semi-supervised learning.
120
+
121
+ References
122
+ ----------
123
+ :doi:`David Yarowsky. 1995. Unsupervised word sense disambiguation rivaling
124
+ supervised methods. In Proceedings of the 33rd annual meeting on
125
+ Association for Computational Linguistics (ACL '95). Association for
126
+ Computational Linguistics, Stroudsburg, PA, USA, 189-196.
127
+ <10.3115/981658.981684>`
128
+
129
+ Examples
130
+ --------
131
+ >>> import numpy as np
132
+ >>> from sklearn import datasets
133
+ >>> from sklearn.semi_supervised import SelfTrainingClassifier
134
+ >>> from sklearn.svm import SVC
135
+ >>> rng = np.random.RandomState(42)
136
+ >>> iris = datasets.load_iris()
137
+ >>> random_unlabeled_points = rng.rand(iris.target.shape[0]) < 0.3
138
+ >>> iris.target[random_unlabeled_points] = -1
139
+ >>> svc = SVC(probability=True, gamma="auto")
140
+ >>> self_training_model = SelfTrainingClassifier(svc)
141
+ >>> self_training_model.fit(iris.data, iris.target)
142
+ SelfTrainingClassifier(...)
143
+ """
144
+
145
+ _estimator_type = "classifier"
146
+
147
+ _parameter_constraints: dict = {
148
+ # We don't require `predic_proba` here to allow passing a meta-estimator
149
+ # that only exposes `predict_proba` after fitting.
150
+ "base_estimator": [HasMethods(["fit"])],
151
+ "threshold": [Interval(Real, 0.0, 1.0, closed="left")],
152
+ "criterion": [StrOptions({"threshold", "k_best"})],
153
+ "k_best": [Interval(Integral, 1, None, closed="left")],
154
+ "max_iter": [Interval(Integral, 0, None, closed="left"), None],
155
+ "verbose": ["verbose"],
156
+ }
157
+
158
+ def __init__(
159
+ self,
160
+ base_estimator,
161
+ threshold=0.75,
162
+ criterion="threshold",
163
+ k_best=10,
164
+ max_iter=10,
165
+ verbose=False,
166
+ ):
167
+ self.base_estimator = base_estimator
168
+ self.threshold = threshold
169
+ self.criterion = criterion
170
+ self.k_best = k_best
171
+ self.max_iter = max_iter
172
+ self.verbose = verbose
173
+
174
+ def fit(self, X, y):
175
+ """
176
+ Fit self-training classifier using `X`, `y` as training data.
177
+
178
+ Parameters
179
+ ----------
180
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
181
+ Array representing the data.
182
+
183
+ y : {array-like, sparse matrix} of shape (n_samples,)
184
+ Array representing the labels. Unlabeled samples should have the
185
+ label -1.
186
+
187
+ Returns
188
+ -------
189
+ self : object
190
+ Fitted estimator.
191
+ """
192
+ self._validate_params()
193
+
194
+ # we need row slicing support for sparce matrices, but costly finiteness check
195
+ # can be delegated to the base estimator.
196
+ X, y = self._validate_data(
197
+ X, y, accept_sparse=["csr", "csc", "lil", "dok"], force_all_finite=False
198
+ )
199
+
200
+ self.base_estimator_ = clone(self.base_estimator)
201
+
202
+ if y.dtype.kind in ["U", "S"]:
203
+ raise ValueError(
204
+ "y has dtype string. If you wish to predict on "
205
+ "string targets, use dtype object, and use -1"
206
+ " as the label for unlabeled samples."
207
+ )
208
+
209
+ has_label = y != -1
210
+
211
+ if np.all(has_label):
212
+ warnings.warn("y contains no unlabeled samples", UserWarning)
213
+
214
+ if self.criterion == "k_best" and (
215
+ self.k_best > X.shape[0] - np.sum(has_label)
216
+ ):
217
+ warnings.warn(
218
+ "k_best is larger than the amount of unlabeled "
219
+ "samples. All unlabeled samples will be labeled in "
220
+ "the first iteration",
221
+ UserWarning,
222
+ )
223
+
224
+ self.transduction_ = np.copy(y)
225
+ self.labeled_iter_ = np.full_like(y, -1)
226
+ self.labeled_iter_[has_label] = 0
227
+
228
+ self.n_iter_ = 0
229
+
230
+ while not np.all(has_label) and (
231
+ self.max_iter is None or self.n_iter_ < self.max_iter
232
+ ):
233
+ self.n_iter_ += 1
234
+ self.base_estimator_.fit(
235
+ X[safe_mask(X, has_label)], self.transduction_[has_label]
236
+ )
237
+
238
+ # Predict on the unlabeled samples
239
+ prob = self.base_estimator_.predict_proba(X[safe_mask(X, ~has_label)])
240
+ pred = self.base_estimator_.classes_[np.argmax(prob, axis=1)]
241
+ max_proba = np.max(prob, axis=1)
242
+
243
+ # Select new labeled samples
244
+ if self.criterion == "threshold":
245
+ selected = max_proba > self.threshold
246
+ else:
247
+ n_to_select = min(self.k_best, max_proba.shape[0])
248
+ if n_to_select == max_proba.shape[0]:
249
+ selected = np.ones_like(max_proba, dtype=bool)
250
+ else:
251
+ # NB these are indices, not a mask
252
+ selected = np.argpartition(-max_proba, n_to_select)[:n_to_select]
253
+
254
+ # Map selected indices into original array
255
+ selected_full = np.nonzero(~has_label)[0][selected]
256
+
257
+ # Add newly labeled confident predictions to the dataset
258
+ self.transduction_[selected_full] = pred[selected]
259
+ has_label[selected_full] = True
260
+ self.labeled_iter_[selected_full] = self.n_iter_
261
+
262
+ if selected_full.shape[0] == 0:
263
+ # no changed labels
264
+ self.termination_condition_ = "no_change"
265
+ break
266
+
267
+ if self.verbose:
268
+ print(
269
+ f"End of iteration {self.n_iter_},"
270
+ f" added {selected_full.shape[0]} new labels."
271
+ )
272
+
273
+ if self.n_iter_ == self.max_iter:
274
+ self.termination_condition_ = "max_iter"
275
+ if np.all(has_label):
276
+ self.termination_condition_ = "all_labeled"
277
+
278
+ self.base_estimator_.fit(
279
+ X[safe_mask(X, has_label)], self.transduction_[has_label]
280
+ )
281
+ self.classes_ = self.base_estimator_.classes_
282
+ return self
283
+
284
+ @available_if(_estimator_has("predict"))
285
+ def predict(self, X):
286
+ """Predict the classes of `X`.
287
+
288
+ Parameters
289
+ ----------
290
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
291
+ Array representing the data.
292
+
293
+ Returns
294
+ -------
295
+ y : ndarray of shape (n_samples,)
296
+ Array with predicted labels.
297
+ """
298
+ check_is_fitted(self)
299
+ X = self._validate_data(
300
+ X,
301
+ accept_sparse=True,
302
+ force_all_finite=False,
303
+ reset=False,
304
+ )
305
+ return self.base_estimator_.predict(X)
306
+
307
+ @available_if(_estimator_has("predict_proba"))
308
+ def predict_proba(self, X):
309
+ """Predict probability for each possible outcome.
310
+
311
+ Parameters
312
+ ----------
313
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
314
+ Array representing the data.
315
+
316
+ Returns
317
+ -------
318
+ y : ndarray of shape (n_samples, n_features)
319
+ Array with prediction probabilities.
320
+ """
321
+ check_is_fitted(self)
322
+ X = self._validate_data(
323
+ X,
324
+ accept_sparse=True,
325
+ force_all_finite=False,
326
+ reset=False,
327
+ )
328
+ return self.base_estimator_.predict_proba(X)
329
+
330
+ @available_if(_estimator_has("decision_function"))
331
+ def decision_function(self, X):
332
+ """Call decision function of the `base_estimator`.
333
+
334
+ Parameters
335
+ ----------
336
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
337
+ Array representing the data.
338
+
339
+ Returns
340
+ -------
341
+ y : ndarray of shape (n_samples, n_features)
342
+ Result of the decision function of the `base_estimator`.
343
+ """
344
+ check_is_fitted(self)
345
+ X = self._validate_data(
346
+ X,
347
+ accept_sparse=True,
348
+ force_all_finite=False,
349
+ reset=False,
350
+ )
351
+ return self.base_estimator_.decision_function(X)
352
+
353
+ @available_if(_estimator_has("predict_log_proba"))
354
+ def predict_log_proba(self, X):
355
+ """Predict log probability for each possible outcome.
356
+
357
+ Parameters
358
+ ----------
359
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
360
+ Array representing the data.
361
+
362
+ Returns
363
+ -------
364
+ y : ndarray of shape (n_samples, n_features)
365
+ Array with log prediction probabilities.
366
+ """
367
+ check_is_fitted(self)
368
+ X = self._validate_data(
369
+ X,
370
+ accept_sparse=True,
371
+ force_all_finite=False,
372
+ reset=False,
373
+ )
374
+ return self.base_estimator_.predict_log_proba(X)
375
+
376
+ @available_if(_estimator_has("score"))
377
+ def score(self, X, y):
378
+ """Call score on the `base_estimator`.
379
+
380
+ Parameters
381
+ ----------
382
+ X : {array-like, sparse matrix} of shape (n_samples, n_features)
383
+ Array representing the data.
384
+
385
+ y : array-like of shape (n_samples,)
386
+ Array representing the labels.
387
+
388
+ Returns
389
+ -------
390
+ score : float
391
+ Result of calling score on the `base_estimator`.
392
+ """
393
+ check_is_fitted(self)
394
+ X = self._validate_data(
395
+ X,
396
+ accept_sparse=True,
397
+ force_all_finite=False,
398
+ reset=False,
399
+ )
400
+ return self.base_estimator_.score(X, y)
videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/tests/__init__.py ADDED
File without changes
videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (186 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/tests/__pycache__/test_label_propagation.cpython-310.pyc ADDED
Binary file (6.95 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/tests/__pycache__/test_self_training.cpython-310.pyc ADDED
Binary file (7.97 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/semi_supervised/tests/test_label_propagation.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ test the label propagation module """
2
+
3
+ import numpy as np
4
+ import pytest
5
+ import warnings
6
+
7
+ from scipy.sparse import issparse
8
+ from sklearn.semi_supervised import _label_propagation as label_propagation
9
+ from sklearn.metrics.pairwise import rbf_kernel
10
+ from sklearn.model_selection import train_test_split
11
+ from sklearn.neighbors import NearestNeighbors
12
+ from sklearn.datasets import make_classification
13
+ from sklearn.exceptions import ConvergenceWarning
14
+ from sklearn.utils._testing import (
15
+ assert_allclose,
16
+ assert_array_equal,
17
+ )
18
+
19
+ ESTIMATORS = [
20
+ (label_propagation.LabelPropagation, {"kernel": "rbf"}),
21
+ (label_propagation.LabelPropagation, {"kernel": "knn", "n_neighbors": 2}),
22
+ (
23
+ label_propagation.LabelPropagation,
24
+ {"kernel": lambda x, y: rbf_kernel(x, y, gamma=20)},
25
+ ),
26
+ (label_propagation.LabelSpreading, {"kernel": "rbf"}),
27
+ (label_propagation.LabelSpreading, {"kernel": "knn", "n_neighbors": 2}),
28
+ (
29
+ label_propagation.LabelSpreading,
30
+ {"kernel": lambda x, y: rbf_kernel(x, y, gamma=20)},
31
+ ),
32
+ ]
33
+
34
+
35
+ @pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
36
+ def test_fit_transduction(global_dtype, Estimator, parameters):
37
+ samples = np.asarray([[1.0, 0.0], [0.0, 2.0], [1.0, 3.0]], dtype=global_dtype)
38
+ labels = [0, 1, -1]
39
+ clf = Estimator(**parameters).fit(samples, labels)
40
+ assert clf.transduction_[2] == 1
41
+
42
+
43
+ @pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
44
+ def test_distribution(global_dtype, Estimator, parameters):
45
+ if parameters["kernel"] == "knn":
46
+ pytest.skip(
47
+ "Unstable test for this configuration: changes in k-NN ordering break it."
48
+ )
49
+ samples = np.asarray([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], dtype=global_dtype)
50
+ labels = [0, 1, -1]
51
+ clf = Estimator(**parameters).fit(samples, labels)
52
+ assert_allclose(clf.label_distributions_[2], [0.5, 0.5], atol=1e-2)
53
+
54
+
55
+ @pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
56
+ def test_predict(global_dtype, Estimator, parameters):
57
+ samples = np.asarray([[1.0, 0.0], [0.0, 2.0], [1.0, 3.0]], dtype=global_dtype)
58
+ labels = [0, 1, -1]
59
+ clf = Estimator(**parameters).fit(samples, labels)
60
+ assert_array_equal(clf.predict([[0.5, 2.5]]), np.array([1]))
61
+
62
+
63
+ @pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
64
+ def test_predict_proba(global_dtype, Estimator, parameters):
65
+ samples = np.asarray([[1.0, 0.0], [0.0, 1.0], [1.0, 2.5]], dtype=global_dtype)
66
+ labels = [0, 1, -1]
67
+ clf = Estimator(**parameters).fit(samples, labels)
68
+ assert_allclose(clf.predict_proba([[1.0, 1.0]]), np.array([[0.5, 0.5]]))
69
+
70
+
71
+ @pytest.mark.parametrize("alpha", [0.1, 0.3, 0.5, 0.7, 0.9])
72
+ @pytest.mark.parametrize("Estimator, parameters", ESTIMATORS)
73
+ def test_label_spreading_closed_form(global_dtype, Estimator, parameters, alpha):
74
+ n_classes = 2
75
+ X, y = make_classification(n_classes=n_classes, n_samples=200, random_state=0)
76
+ X = X.astype(global_dtype, copy=False)
77
+ y[::3] = -1
78
+
79
+ gamma = 0.1
80
+ clf = label_propagation.LabelSpreading(gamma=gamma).fit(X, y)
81
+ # adopting notation from Zhou et al (2004):
82
+ S = clf._build_graph()
83
+ Y = np.zeros((len(y), n_classes + 1), dtype=X.dtype)
84
+ Y[np.arange(len(y)), y] = 1
85
+ Y = Y[:, :-1]
86
+
87
+ expected = np.dot(np.linalg.inv(np.eye(len(S), dtype=S.dtype) - alpha * S), Y)
88
+ expected /= expected.sum(axis=1)[:, np.newaxis]
89
+
90
+ clf = label_propagation.LabelSpreading(
91
+ max_iter=100, alpha=alpha, tol=1e-10, gamma=gamma
92
+ )
93
+ clf.fit(X, y)
94
+
95
+ assert_allclose(expected, clf.label_distributions_)
96
+
97
+
98
+ def test_label_propagation_closed_form(global_dtype):
99
+ n_classes = 2
100
+ X, y = make_classification(n_classes=n_classes, n_samples=200, random_state=0)
101
+ X = X.astype(global_dtype, copy=False)
102
+ y[::3] = -1
103
+ Y = np.zeros((len(y), n_classes + 1))
104
+ Y[np.arange(len(y)), y] = 1
105
+ unlabelled_idx = Y[:, (-1,)].nonzero()[0]
106
+ labelled_idx = (Y[:, (-1,)] == 0).nonzero()[0]
107
+
108
+ clf = label_propagation.LabelPropagation(max_iter=100, tol=1e-10, gamma=0.1)
109
+ clf.fit(X, y)
110
+ # adopting notation from Zhu et al 2002
111
+ T_bar = clf._build_graph()
112
+ Tuu = T_bar[tuple(np.meshgrid(unlabelled_idx, unlabelled_idx, indexing="ij"))]
113
+ Tul = T_bar[tuple(np.meshgrid(unlabelled_idx, labelled_idx, indexing="ij"))]
114
+ Y = Y[:, :-1]
115
+ Y_l = Y[labelled_idx, :]
116
+ Y_u = np.dot(np.dot(np.linalg.inv(np.eye(Tuu.shape[0]) - Tuu), Tul), Y_l)
117
+
118
+ expected = Y.copy()
119
+ expected[unlabelled_idx, :] = Y_u
120
+ expected /= expected.sum(axis=1)[:, np.newaxis]
121
+
122
+ assert_allclose(expected, clf.label_distributions_, atol=1e-4)
123
+
124
+
125
+ def test_convergence_speed():
126
+ # This is a non-regression test for #5774
127
+ X = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 2.5]])
128
+ y = np.array([0, 1, -1])
129
+ mdl = label_propagation.LabelSpreading(kernel="rbf", max_iter=5000)
130
+ mdl.fit(X, y)
131
+
132
+ # this should converge quickly:
133
+ assert mdl.n_iter_ < 10
134
+ assert_array_equal(mdl.predict(X), [0, 1, 1])
135
+
136
+
137
+ def test_convergence_warning():
138
+ # This is a non-regression test for #5774
139
+ X = np.array([[1.0, 0.0], [0.0, 1.0], [1.0, 2.5]])
140
+ y = np.array([0, 1, -1])
141
+ mdl = label_propagation.LabelSpreading(kernel="rbf", max_iter=1)
142
+ warn_msg = "max_iter=1 was reached without convergence."
143
+ with pytest.warns(ConvergenceWarning, match=warn_msg):
144
+ mdl.fit(X, y)
145
+ assert mdl.n_iter_ == mdl.max_iter
146
+
147
+ mdl = label_propagation.LabelPropagation(kernel="rbf", max_iter=1)
148
+ with pytest.warns(ConvergenceWarning, match=warn_msg):
149
+ mdl.fit(X, y)
150
+ assert mdl.n_iter_ == mdl.max_iter
151
+
152
+ mdl = label_propagation.LabelSpreading(kernel="rbf", max_iter=500)
153
+ with warnings.catch_warnings():
154
+ warnings.simplefilter("error", ConvergenceWarning)
155
+ mdl.fit(X, y)
156
+
157
+ mdl = label_propagation.LabelPropagation(kernel="rbf", max_iter=500)
158
+ with warnings.catch_warnings():
159
+ warnings.simplefilter("error", ConvergenceWarning)
160
+ mdl.fit(X, y)
161
+
162
+
163
+ @pytest.mark.parametrize(
164
+ "LabelPropagationCls",
165
+ [label_propagation.LabelSpreading, label_propagation.LabelPropagation],
166
+ )
167
+ def test_label_propagation_non_zero_normalizer(LabelPropagationCls):
168
+ # check that we don't divide by zero in case of null normalizer
169
+ # non-regression test for
170
+ # https://github.com/scikit-learn/scikit-learn/pull/15946
171
+ # https://github.com/scikit-learn/scikit-learn/issues/9292
172
+ X = np.array([[100.0, 100.0], [100.0, 100.0], [0.0, 0.0], [0.0, 0.0]])
173
+ y = np.array([0, 1, -1, -1])
174
+ mdl = LabelPropagationCls(kernel="knn", max_iter=100, n_neighbors=1)
175
+ with warnings.catch_warnings():
176
+ warnings.simplefilter("error", RuntimeWarning)
177
+ mdl.fit(X, y)
178
+
179
+
180
+ def test_predict_sparse_callable_kernel(global_dtype):
181
+ # This is a non-regression test for #15866
182
+
183
+ # Custom sparse kernel (top-K RBF)
184
+ def topk_rbf(X, Y=None, n_neighbors=10, gamma=1e-5):
185
+ nn = NearestNeighbors(n_neighbors=10, metric="euclidean", n_jobs=2)
186
+ nn.fit(X)
187
+ W = -1 * nn.kneighbors_graph(Y, mode="distance").power(2) * gamma
188
+ np.exp(W.data, out=W.data)
189
+ assert issparse(W)
190
+ return W.T
191
+
192
+ n_classes = 4
193
+ n_samples = 500
194
+ n_test = 10
195
+ X, y = make_classification(
196
+ n_classes=n_classes,
197
+ n_samples=n_samples,
198
+ n_features=20,
199
+ n_informative=20,
200
+ n_redundant=0,
201
+ n_repeated=0,
202
+ random_state=0,
203
+ )
204
+ X = X.astype(global_dtype)
205
+
206
+ X_train, X_test, y_train, y_test = train_test_split(
207
+ X, y, test_size=n_test, random_state=0
208
+ )
209
+
210
+ model = label_propagation.LabelSpreading(kernel=topk_rbf)
211
+ model.fit(X_train, y_train)
212
+ assert model.score(X_test, y_test) >= 0.9
213
+
214
+ model = label_propagation.LabelPropagation(kernel=topk_rbf)
215
+ model.fit(X_train, y_train)
216
+ assert model.score(X_test, y_test) >= 0.9
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_compute_linear_combination_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor _compute_linear_combination(const at::Tensor & input, const at::Tensor & coefficients);
20
+ TORCH_API at::Tensor & _compute_linear_combination_out(const at::Tensor & input, const at::Tensor & coefficients, at::Tensor & out);
21
+ } // namespace native
22
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_cudnn_rnn_backward_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API void _cudnn_rnn_backward_out_symint(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, const at::Tensor & output, const ::std::optional<at::Tensor> & grad_output, const ::std::optional<at::Tensor> & grad_hy, const ::std::optional<at::Tensor> & grad_cy, int64_t mode, c10::SymInt hidden_size, c10::SymInt proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, c10::SymIntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state, const at::Tensor & reserve, ::std::array<bool,4> output_mask, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::TensorList out3);
20
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor,at::Tensor,::std::vector<at::Tensor>> _cudnn_rnn_backward(const at::Tensor & input, at::TensorList weight, int64_t weight_stride0, const at::Tensor & weight_buf, const at::Tensor & hx, const ::std::optional<at::Tensor> & cx, const at::Tensor & output, const ::std::optional<at::Tensor> & grad_output, const ::std::optional<at::Tensor> & grad_hy, const ::std::optional<at::Tensor> & grad_cy, int64_t mode, int64_t hidden_size, int64_t proj_size, int64_t num_layers, bool batch_first, double dropout, bool train, bool bidirectional, at::IntArrayRef batch_sizes, const ::std::optional<at::Tensor> & dropout_state, const at::Tensor & reserve, ::std::array<bool,4> output_mask);
21
+ } // namespace native
22
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_empty_per_channel_affine_quantized_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _empty_per_channel_affine_quantized {
18
+ using schema = at::Tensor (c10::SymIntArrayRef, const at::Tensor &, const at::Tensor &, int64_t, ::std::optional<at::ScalarType>, ::std::optional<at::Layout>, ::std::optional<at::Device>, ::std::optional<bool>, ::std::optional<at::MemoryFormat>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_empty_per_channel_affine_quantized")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_empty_per_channel_affine_quantized(SymInt[] size, *, Tensor scales, Tensor zero_points, int axis, ScalarType? dtype=None, Layout? layout=None, Device? device=None, bool? pin_memory=None, MemoryFormat? memory_format=contiguous_format) -> Tensor")
24
+ static at::Tensor call(c10::SymIntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, ::std::optional<at::ScalarType> dtype, ::std::optional<at::Layout> layout, ::std::optional<at::Device> device, ::std::optional<bool> pin_memory, ::std::optional<at::MemoryFormat> memory_format);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymIntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, ::std::optional<at::ScalarType> dtype, ::std::optional<at::Layout> layout, ::std::optional<at::Device> device, ::std::optional<bool> pin_memory, ::std::optional<at::MemoryFormat> memory_format);
26
+ };
27
+
28
+ struct TORCH_API _empty_per_channel_affine_quantized_out {
29
+ using schema = at::Tensor & (c10::SymIntArrayRef, const at::Tensor &, const at::Tensor &, int64_t, ::std::optional<at::MemoryFormat>, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_empty_per_channel_affine_quantized")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_empty_per_channel_affine_quantized.out(SymInt[] size, *, Tensor scales, Tensor zero_points, int axis, MemoryFormat? memory_format=contiguous_format, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(c10::SymIntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, ::std::optional<at::MemoryFormat> memory_format, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, c10::SymIntArrayRef size, const at::Tensor & scales, const at::Tensor & zero_points, int64_t axis, ::std::optional<at::MemoryFormat> memory_format, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_floor_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API ::std::vector<at::Tensor> _foreach_floor(at::TensorList self);
21
+ TORCH_API void _foreach_floor_out(at::TensorList out, at::TensorList self);
22
+ TORCH_API void _foreach_floor_outf(at::TensorList self, at::TensorList out);
23
+ TORCH_API void _foreach_floor_(at::TensorList self);
24
+
25
+ } // namespace compositeexplicitautograd
26
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_lerp_native.h ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_ternary_lerp_slow(at::TensorList self, at::TensorList tensors1, at::TensorList weights);
20
+ TORCH_API void _foreach_lerp_List_out(at::TensorList self, at::TensorList tensors1, at::TensorList weights, at::TensorList out);
21
+ TORCH_API void foreach_tensor_ternary_lerp_slow_(at::TensorList self, at::TensorList tensors1, at::TensorList weights);
22
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_lerp_ternary_cuda(at::TensorList self, at::TensorList tensors1, at::TensorList weights);
23
+ TORCH_API void foreach_tensor_lerp_ternary_cuda_(at::TensorList self, at::TensorList tensors1, at::TensorList weights);
24
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_lerp_list_kernel_slow(at::TensorList self, at::TensorList tensors1, const at::Scalar & weight);
25
+ TORCH_API void _foreach_lerp_Scalar_out(at::TensorList self, at::TensorList tensors1, const at::Scalar & weight, at::TensorList out);
26
+ TORCH_API void foreach_tensor_lerp_list_kernel_slow_(at::TensorList self, at::TensorList tensors1, const at::Scalar & weight);
27
+ TORCH_API ::std::vector<at::Tensor> foreach_tensor_lerp_list_cuda(at::TensorList self, at::TensorList tensors1, const at::Scalar & weight);
28
+ TORCH_API void foreach_tensor_lerp_list_cuda_(at::TensorList self, at::TensorList tensors1, const at::Scalar & weight);
29
+ } // namespace native
30
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_foreach_reciprocal_cuda_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API ::std::vector<at::Tensor> _foreach_reciprocal(at::TensorList self);
21
+ TORCH_API void _foreach_reciprocal_(at::TensorList self);
22
+
23
+ } // namespace cuda
24
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_grid_sampler_2d_cpu_fallback.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_grid_sampler_2d_cpu_fallback_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_grid_sampler_2d_cpu_fallback(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners) -> Tensor
26
+ inline at::Tensor _grid_sampler_2d_cpu_fallback(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners) {
27
+ return at::_ops::_grid_sampler_2d_cpu_fallback::call(input, grid, interpolation_mode, padding_mode, align_corners);
28
+ }
29
+
30
+ // aten::_grid_sampler_2d_cpu_fallback.out(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, *, Tensor(a!) out) -> Tensor(a!)
31
+ inline at::Tensor & _grid_sampler_2d_cpu_fallback_out(at::Tensor & out, const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners) {
32
+ return at::_ops::_grid_sampler_2d_cpu_fallback_out::call(input, grid, interpolation_mode, padding_mode, align_corners, out);
33
+ }
34
+ // aten::_grid_sampler_2d_cpu_fallback.out(Tensor input, Tensor grid, int interpolation_mode, int padding_mode, bool align_corners, *, Tensor(a!) out) -> Tensor(a!)
35
+ inline at::Tensor & _grid_sampler_2d_cpu_fallback_outf(const at::Tensor & input, const at::Tensor & grid, int64_t interpolation_mode, int64_t padding_mode, bool align_corners, at::Tensor & out) {
36
+ return at::_ops::_grid_sampler_2d_cpu_fallback_out::call(input, grid, interpolation_mode, padding_mode, align_corners, out);
37
+ }
38
+
39
+ }
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_lstm_mps_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _lstm_mps {
18
+ using schema = ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> (const at::Tensor &, at::TensorList, at::TensorList, bool, int64_t, double, bool, bool, bool);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_lstm_mps")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_lstm_mps(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor)")
24
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> call(const at::Tensor & input, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first);
25
+ static ::std::tuple<at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor,at::Tensor> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first);
26
+ };
27
+
28
+ struct TORCH_API _lstm_mps_out {
29
+ using schema = ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> (const at::Tensor &, at::TensorList, at::TensorList, bool, int64_t, double, bool, bool, bool, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_lstm_mps")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_lstm_mps.out(Tensor input, Tensor[] hx, Tensor[] params, bool has_biases, int num_layers, float dropout, bool train, bool bidirectional, bool batch_first, *, Tensor(a!) out0, Tensor(b!) out1, Tensor(c!) out2, Tensor(d!) out3, Tensor(e!) out4, Tensor(f!) out5) -> (Tensor(a!), Tensor(b!), Tensor(c!), Tensor(d!), Tensor(e!), Tensor(f!))")
35
+ static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> call(const at::Tensor & input, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4, at::Tensor & out5);
36
+ static ::std::tuple<at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &,at::Tensor &> redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & input, at::TensorList hx, at::TensorList params, bool has_biases, int64_t num_layers, double dropout, bool train, bool bidirectional, bool batch_first, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2, at::Tensor & out3, at::Tensor & out4, at::Tensor & out5);
37
+ };
38
+
39
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_make_per_channel_quantized_tensor_cpu_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor _make_per_channel_quantized_tensor(const at::Tensor & self, const at::Tensor & scale, const at::Tensor & zero_point, int64_t axis);
21
+
22
+ } // namespace cpu
23
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_compute_contiguous_strides_offsets_native.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API ::std::tuple<at::Tensor,at::Tensor> _nested_compute_contiguous_strides_offsets(const at::Tensor & nested_size);
20
+ } // namespace native
21
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_get_values_copy_compositeexplicitautogradnonfunctional_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor _nested_get_values_copy(const at::Tensor & self);
21
+
22
+ } // namespace compositeexplicitautogradnonfunctional
23
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_from_mask_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & _nested_tensor_from_mask_out(const at::Tensor & t, const at::Tensor & mask, bool mask_check, at::Tensor & out);
20
+ TORCH_API at::Tensor NestedTensor_nested_tensor_from_mask(const at::Tensor & t, const at::Tensor & mask, bool mask_check=true);
21
+ } // namespace native
22
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_nested_tensor_strides_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & _nested_tensor_strides_out(at::Tensor & out, const at::Tensor & self);
21
+ TORCH_API at::Tensor & _nested_tensor_strides_outf(const at::Tensor & self, at::Tensor & out);
22
+
23
+ } // namespace compositeexplicitautograd
24
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_prelu_kernel_ops.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API _prelu_kernel {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_prelu_kernel")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_prelu_kernel(Tensor self, Tensor weight) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & weight);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight);
26
+ };
27
+
28
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_flash_attention_backward.h ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Function.h
4
+
5
+ #include <ATen/Context.h>
6
+ #include <ATen/DeviceGuard.h>
7
+ #include <ATen/TensorUtils.h>
8
+ #include <ATen/TracerMode.h>
9
+ #include <ATen/core/Generator.h>
10
+ #include <ATen/core/Reduction.h>
11
+ #include <ATen/core/Tensor.h>
12
+ #include <c10/core/Scalar.h>
13
+ #include <c10/core/Storage.h>
14
+ #include <c10/core/TensorOptions.h>
15
+ #include <c10/util/Deprecated.h>
16
+ #include <optional>
17
+
18
+
19
+
20
+ #include <ATen/ops/_scaled_dot_product_flash_attention_backward_ops.h>
21
+
22
+ namespace at {
23
+
24
+
25
+ // aten::_scaled_dot_product_flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value)
26
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_flash_attention_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, ::std::optional<double> scale=::std::nullopt) {
27
+ return at::_ops::_scaled_dot_product_flash_attention_backward::call(grad_out, query, key, value, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale);
28
+ }
29
+ namespace symint {
30
+ template <typename T, typename = std::enable_if_t<std::is_same<T, int64_t>::value>>
31
+ ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_flash_attention_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, int64_t max_q, int64_t max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, ::std::optional<double> scale=::std::nullopt) {
32
+ return at::_ops::_scaled_dot_product_flash_attention_backward::call(grad_out, query, key, value, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale);
33
+ }
34
+ }
35
+
36
+ // aten::_scaled_dot_product_flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value)
37
+ inline ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_flash_attention_backward_symint(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, ::std::optional<double> scale=::std::nullopt) {
38
+ return at::_ops::_scaled_dot_product_flash_attention_backward::call(grad_out, query, key, value, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale);
39
+ }
40
+ namespace symint {
41
+ template <typename T, typename = std::enable_if_t<std::is_same<T, c10::SymInt>::value>>
42
+ ::std::tuple<at::Tensor,at::Tensor,at::Tensor> _scaled_dot_product_flash_attention_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, const at::Tensor & cum_seq_q, const at::Tensor & cum_seq_k, c10::SymInt max_q, c10::SymInt max_k, double dropout_p, bool is_causal, const at::Tensor & philox_seed, const at::Tensor & philox_offset, ::std::optional<double> scale=::std::nullopt) {
43
+ return at::_ops::_scaled_dot_product_flash_attention_backward::call(grad_out, query, key, value, out, logsumexp, cum_seq_q, cum_seq_k, max_q, max_k, dropout_p, is_causal, philox_seed, philox_offset, scale);
44
+ }
45
+ }
46
+
47
+ }
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_test_warn_in_autograd_native.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor _test_warn_in_autograd(const at::Tensor & self);
20
+ TORCH_API at::Tensor & _test_warn_in_autograd_out(const at::Tensor & self, at::Tensor & out);
21
+ } // namespace native
22
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_to_dense_native.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor & _to_dense_out(const at::Tensor & self, ::std::optional<at::ScalarType> dtype, ::std::optional<bool> masked_grad, at::Tensor & out);
20
+ TORCH_API at::Tensor sparse_to_dense(const at::Tensor & self, ::std::optional<at::ScalarType> dtype=::std::nullopt, ::std::optional<bool> masked_grad=::std::nullopt);
21
+ TORCH_API at::Tensor sparse_compressed_to_dense(const at::Tensor & self, ::std::optional<at::ScalarType> dtype=::std::nullopt, ::std::optional<bool> masked_grad=::std::nullopt);
22
+ TORCH_API at::Tensor mkldnn_to_dense(const at::Tensor & self, ::std::optional<at::ScalarType> dtype=::std::nullopt, ::std::optional<bool> masked_grad=::std::nullopt);
23
+ } // namespace native
24
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bilinear2d_aa_compositeexplicitautogradnonfunctional_dispatch.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor _upsample_bilinear2d_aa(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt);
21
+ TORCH_API at::Tensor _upsample_bilinear2d_aa_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, ::std::optional<double> scales_h=::std::nullopt, ::std::optional<double> scales_w=::std::nullopt);
22
+
23
+ } // namespace compositeexplicitautogradnonfunctional
24
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact1d_meta_dispatch.h ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor _upsample_nearest_exact1d(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional<double> scales=::std::nullopt);
21
+ TORCH_API at::Tensor _upsample_nearest_exact1d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional<double> scales=::std::nullopt);
22
+ TORCH_API at::Tensor & _upsample_nearest_exact1d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, ::std::optional<double> scales=::std::nullopt);
23
+ TORCH_API at::Tensor & _upsample_nearest_exact1d_outf(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional<double> scales, at::Tensor & out);
24
+ TORCH_API at::Tensor & _upsample_nearest_exact1d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional<double> scales=::std::nullopt);
25
+ TORCH_API at::Tensor & _upsample_nearest_exact1d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional<double> scales, at::Tensor & out);
26
+
27
+ } // namespace meta
28
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/addcmul_cuda_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cuda {
19
+
20
+ TORCH_API at::Tensor addcmul(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1);
21
+ TORCH_API at::Tensor & addcmul_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1);
22
+ TORCH_API at::Tensor & addcmul_outf(const at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value, at::Tensor & out);
23
+ TORCH_API at::Tensor & addcmul_(at::Tensor & self, const at::Tensor & tensor1, const at::Tensor & tensor2, const at::Scalar & value=1);
24
+
25
+ } // namespace cuda
26
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/and_native.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor __and__(const at::Tensor & self, const at::Scalar & other);
20
+ TORCH_API at::Tensor & __iand__(at::Tensor & self, const at::Scalar & other);
21
+ TORCH_API at::Tensor __and__(const at::Tensor & self, const at::Tensor & other);
22
+ TORCH_API at::Tensor & __iand__(at::Tensor & self, const at::Tensor & other);
23
+ } // namespace native
24
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/as_strided_copy_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API as_strided_copy {
18
+ using schema = at::Tensor (const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, ::std::optional<c10::SymInt>);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::as_strided_copy")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "as_strided_copy(Tensor self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional<c10::SymInt> storage_offset);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional<c10::SymInt> storage_offset);
26
+ };
27
+
28
+ struct TORCH_API as_strided_copy_out {
29
+ using schema = at::Tensor & (const at::Tensor &, c10::SymIntArrayRef, c10::SymIntArrayRef, ::std::optional<c10::SymInt>, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::as_strided_copy")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "as_strided_copy.out(Tensor self, SymInt[] size, SymInt[] stride, SymInt? storage_offset=None, *, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional<c10::SymInt> storage_offset, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional<c10::SymInt> storage_offset, at::Tensor & out);
37
+ };
38
+
39
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/as_strided_native.h ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from NativeFunction.h
4
+
5
+ #include <c10/core/Scalar.h>
6
+ #include <c10/core/Storage.h>
7
+ #include <c10/core/TensorOptions.h>
8
+ #include <c10/util/Deprecated.h>
9
+ #include <optional>
10
+ #include <c10/core/QScheme.h>
11
+ #include <ATen/core/Reduction.h>
12
+ #include <ATen/core/Tensor.h>
13
+ #include <tuple>
14
+ #include <vector>
15
+
16
+
17
+ namespace at {
18
+ namespace native {
19
+ TORCH_API at::Tensor as_strided_tensorimpl(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional<int64_t> storage_offset=::std::nullopt);
20
+ TORCH_API at::Tensor as_strided_tensorimpl_meta_symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional<c10::SymInt> storage_offset=::std::nullopt);
21
+ TORCH_API at::Tensor as_strided_qtensorimpl(const at::Tensor & self, at::IntArrayRef size, at::IntArrayRef stride, ::std::optional<int64_t> storage_offset=::std::nullopt);
22
+ TORCH_API const at::Tensor & as_strided__symint(const at::Tensor & self, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, ::std::optional<c10::SymInt> storage_offset=::std::nullopt);
23
+ } // namespace native
24
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/avg_pool2d_ops.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API avg_pool2d_out {
18
+ using schema = at::Tensor & (const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool, bool, ::std::optional<int64_t>, at::Tensor &);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::avg_pool2d")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "avg_pool2d.out(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None, *, Tensor(a!) out) -> Tensor(a!)")
24
+ static at::Tensor & call(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, bool ceil_mode, bool count_include_pad, ::std::optional<int64_t> divisor_override, at::Tensor & out);
25
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, bool ceil_mode, bool count_include_pad, ::std::optional<int64_t> divisor_override, at::Tensor & out);
26
+ };
27
+
28
+ struct TORCH_API avg_pool2d {
29
+ using schema = at::Tensor (const at::Tensor &, at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, bool, bool, ::std::optional<int64_t>);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::avg_pool2d")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "avg_pool2d(Tensor self, int[2] kernel_size, int[2] stride=[], int[2] padding=0, bool ceil_mode=False, bool count_include_pad=True, int? divisor_override=None) -> Tensor")
35
+ static at::Tensor call(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, bool ceil_mode, bool count_include_pad, ::std::optional<int64_t> divisor_override);
36
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride, at::IntArrayRef padding, bool ceil_mode, bool count_include_pad, ::std::optional<int64_t> divisor_override);
37
+ };
38
+
39
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_or_cpu_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace cpu {
19
+
20
+ TORCH_API at::Tensor bitwise_or(const at::Tensor & self, const at::Tensor & other);
21
+ TORCH_API at::Tensor & bitwise_or_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other);
22
+ TORCH_API at::Tensor & bitwise_or_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out);
23
+ TORCH_API at::Tensor & bitwise_or_(at::Tensor & self, const at::Tensor & other);
24
+
25
+ } // namespace cpu
26
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/bucketize_ops.h ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // @generated by torchgen/gen.py from Operator.h
4
+
5
+ #include <tuple>
6
+ #include <vector>
7
+
8
+ // Forward declarations of any types needed in the operator signatures.
9
+ // We can't directly include these classes because it will cause circular include dependencies.
10
+ // This file is included by TensorBody.h, which defines the Tensor class.
11
+ #include <ATen/core/ATen_fwd.h>
12
+
13
+ namespace at {
14
+ namespace _ops {
15
+
16
+
17
+ struct TORCH_API bucketize_Tensor {
18
+ using schema = at::Tensor (const at::Tensor &, const at::Tensor &, bool, bool);
19
+ using ptr_schema = schema*;
20
+ // See Note [static constexpr char* members for windows NVCC]
21
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bucketize")
22
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor")
23
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bucketize.Tensor(Tensor self, Tensor boundaries, *, bool out_int32=False, bool right=False) -> Tensor")
24
+ static at::Tensor call(const at::Tensor & self, const at::Tensor & boundaries, bool out_int32, bool right);
25
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & boundaries, bool out_int32, bool right);
26
+ };
27
+
28
+ struct TORCH_API bucketize_Tensor_out {
29
+ using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, bool, bool, at::Tensor &);
30
+ using ptr_schema = schema*;
31
+ // See Note [static constexpr char* members for windows NVCC]
32
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bucketize")
33
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Tensor_out")
34
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bucketize.Tensor_out(Tensor self, Tensor boundaries, *, bool out_int32=False, bool right=False, Tensor(a!) out) -> Tensor(a!)")
35
+ static at::Tensor & call(const at::Tensor & self, const at::Tensor & boundaries, bool out_int32, bool right, at::Tensor & out);
36
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & boundaries, bool out_int32, bool right, at::Tensor & out);
37
+ };
38
+
39
+ struct TORCH_API bucketize_Scalar {
40
+ using schema = at::Tensor (const at::Scalar &, const at::Tensor &, bool, bool);
41
+ using ptr_schema = schema*;
42
+ // See Note [static constexpr char* members for windows NVCC]
43
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bucketize")
44
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar")
45
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bucketize.Scalar(Scalar self, Tensor boundaries, *, bool out_int32=False, bool right=False) -> Tensor")
46
+ static at::Tensor call(const at::Scalar & self, const at::Tensor & boundaries, bool out_int32, bool right);
47
+ static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & boundaries, bool out_int32, bool right);
48
+ };
49
+
50
+ struct TORCH_API bucketize_Scalar_out {
51
+ using schema = at::Tensor & (const at::Scalar &, const at::Tensor &, bool, bool, at::Tensor &);
52
+ using ptr_schema = schema*;
53
+ // See Note [static constexpr char* members for windows NVCC]
54
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::bucketize")
55
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "Scalar_out")
56
+ STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "bucketize.Scalar_out(Scalar self, Tensor boundaries, *, bool out_int32=False, bool right=False, Tensor(a!) out) -> Tensor(a!)")
57
+ static at::Tensor & call(const at::Scalar & self, const at::Tensor & boundaries, bool out_int32, bool right, at::Tensor & out);
58
+ static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Scalar & self, const at::Tensor & boundaries, bool out_int32, bool right, at::Tensor & out);
59
+ };
60
+
61
+ }} // namespace at::_ops
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/copy_meta_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace meta {
19
+
20
+ TORCH_API at::Tensor copy(const at::Tensor & self, const at::Tensor & src, bool non_blocking=false);
21
+
22
+ } // namespace meta
23
+ } // namespace at
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/cudnn_convolution_transpose_compositeexplicitautograd_dispatch.h ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautograd {
19
+
20
+ TORCH_API at::Tensor & cudnn_convolution_transpose_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic, bool allow_tf32);
21
+ TORCH_API at::Tensor & cudnn_convolution_transpose_outf(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef padding, at::IntArrayRef output_padding, at::IntArrayRef stride, at::IntArrayRef dilation, int64_t groups, bool benchmark, bool deterministic, bool allow_tf32, at::Tensor & out);
22
+ TORCH_API at::Tensor & cudnn_convolution_transpose_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, bool allow_tf32);
23
+ TORCH_API at::Tensor & cudnn_convolution_transpose_symint_outf(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef padding, c10::SymIntArrayRef output_padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, bool benchmark, bool deterministic, bool allow_tf32, at::Tensor & out);
24
+
25
+ } // namespace compositeexplicitautograd
26
+ } // namespace at