ZTWHHH commited on
Commit
e3665ef
·
verified ·
1 Parent(s): 0aedc79

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. videollama2/lib/python3.10/site-packages/torch/ao/__pycache__/__init__.cpython-310.pyc +0 -0
  2. videollama2/lib/python3.10/site-packages/torch/ao/nn/qat/dynamic/__pycache__/__init__.cpython-310.pyc +0 -0
  3. videollama2/lib/python3.10/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/__init__.cpython-310.pyc +0 -0
  4. videollama2/lib/python3.10/site-packages/torch/ao/ns/__pycache__/__init__.cpython-310.pyc +0 -0
  5. videollama2/lib/python3.10/site-packages/torch/ao/ns/__pycache__/_numeric_suite.cpython-310.pyc +0 -0
  6. videollama2/lib/python3.10/site-packages/torch/ao/ns/__pycache__/_numeric_suite_fx.cpython-310.pyc +0 -0
  7. videollama2/lib/python3.10/site-packages/torch/ao/ns/_numeric_suite.py +526 -0
  8. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__init__.py +0 -0
  9. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/graph_passes.cpython-310.pyc +0 -0
  10. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/utils.cpython-310.pyc +0 -0
  11. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/weight_utils.cpython-310.pyc +0 -0
  12. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/graph_matcher.py +460 -0
  13. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/graph_passes.py +950 -0
  14. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/mappings.py +761 -0
  15. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/n_shadows_utils.py +1312 -0
  16. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/ns_types.py +64 -0
  17. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/pattern_utils.py +200 -0
  18. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/qconfig_multi_mapping.py +243 -0
  19. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/utils.py +533 -0
  20. videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/weight_utils.py +275 -0
  21. videollama2/lib/python3.10/site-packages/torch/include/dnnl_threadpool.h +22 -0
  22. videollama2/lib/python3.10/site-packages/torch/include/dnnl_types.h +22 -0
  23. videollama2/lib/python3.10/site-packages/torch/include/dnnl_version.h +22 -0
  24. videollama2/lib/python3.10/site-packages/torch/include/fp16.h +11 -0
  25. videollama2/lib/python3.10/site-packages/torch/include/libshm.h +46 -0
  26. videollama2/lib/python3.10/site-packages/torch/include/psimd.h +1384 -0
  27. videollama2/lib/python3.10/site-packages/torch/include/qnnpack.h +336 -0
  28. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/api.h +47 -0
  29. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/builder.h +33 -0
  30. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/chunked_array.h +283 -0
  31. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/device_allocation_type_set.h +97 -0
  32. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/extension_type.h +168 -0
  33. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/memory_pool.h +296 -0
  34. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/stl_iterator.h +304 -0
  35. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/type.h +2629 -0
  36. vllm/lib/python3.10/site-packages/pyarrow/include/arrow/visit_array_inline.h +64 -0
  37. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/api/io.h +20 -0
  38. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/api/reader.h +35 -0
  39. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/api/schema.h +21 -0
  40. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/api/writer.h +25 -0
  41. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/reader.h +379 -0
  42. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/schema.h +184 -0
  43. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/test_util.h +528 -0
  44. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/writer.h +178 -0
  45. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/benchmark_util.h +47 -0
  46. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/encoding.h +448 -0
  47. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/crypto_factory.h +152 -0
  48. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/encryption.h +518 -0
  49. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_material_store.h +57 -0
  50. vllm/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_unwrapper.h +94 -0
videollama2/lib/python3.10/site-packages/torch/ao/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (471 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/nn/qat/dynamic/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (204 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/nn/qat/dynamic/modules/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (247 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (168 Bytes). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/__pycache__/_numeric_suite.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/__pycache__/_numeric_suite_fx.cpython-310.pyc ADDED
Binary file (26.1 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/_numeric_suite.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.ao.nn.quantized as nnq
4
+ import torch.ao.nn.quantized.dynamic as nnqd
5
+ from torch.ao.quantization import prepare
6
+ from typing import Dict, List, Optional, Any, Union, Callable, Set
7
+
8
+ from torch.ao.quantization.quantization_mappings import (
9
+ get_default_compare_output_module_list,
10
+ )
11
+
12
+ NON_LEAF_MODULE_TO_ADD_OBSERVER_ALLOW_LIST = {
13
+ nnqd.Linear,
14
+ nnq.Linear,
15
+ nnqd.LSTM,
16
+ nn.LSTM,
17
+ }
18
+
19
+
20
+ def _find_match(
21
+ str_list: Union[Dict[str, Any], List[str]], key_str: str,
22
+ postfix: str,
23
+ ) -> Optional[str]:
24
+ split_str = key_str.split(".")
25
+ if split_str[-1] == postfix:
26
+ match_string = "".join(key_str.split(".")[0:-1])
27
+ for s2 in str_list:
28
+ pattern1 = "".join(s2.split(".")[0:-1])
29
+ pattern2 = "".join(s2.split(".")[0:-2])
30
+ if match_string == pattern1:
31
+ return s2
32
+ if match_string == pattern2:
33
+ return s2
34
+
35
+ # For matching "fc.weight" and "fc._packed_params._packed_params"
36
+ if postfix == "_packed_params":
37
+ match_string = "".join(key_str.split(".")[0:-2])
38
+ if len(match_string) == 0:
39
+ return None
40
+ for s2 in str_list:
41
+ pattern1 = "".join(s2.split(".")[0:-1])
42
+ pattern2 = "".join(s2.split(".")[0:-2])
43
+ if match_string == pattern1:
44
+ return s2
45
+ if match_string == pattern2:
46
+ return s2
47
+ return None
48
+ else:
49
+ return None
50
+
51
+
52
+ def compare_weights(
53
+ float_dict: Dict[str, Any], quantized_dict: Dict[str, Any]
54
+ ) -> Dict[str, Dict[str, torch.Tensor]]:
55
+ r"""Compare the weights of the float module with its corresponding quantized
56
+ module. Return a dict with key corresponding to module names and each entry being
57
+ a dictionary with two keys 'float' and 'quantized', containing the float and
58
+ quantized weights. This dict can be used to compare and compute the quantization
59
+ error of the weights of float and quantized models.
60
+
61
+ Example usage::
62
+
63
+ wt_compare_dict = compare_weights(
64
+ float_model.state_dict(), qmodel.state_dict())
65
+ for key in wt_compare_dict:
66
+ print(
67
+ key,
68
+ compute_error(
69
+ wt_compare_dict[key]['float'],
70
+ wt_compare_dict[key]['quantized'].dequantize()
71
+ )
72
+ )
73
+
74
+ Args:
75
+ float_dict: state dict of the float model
76
+ quantized_dict: state dict of the quantized model
77
+
78
+ Return:
79
+ weight_dict: dict with key corresponding to module names and each entry being
80
+ a dictionary with two keys 'float' and 'quantized', containing the float and
81
+ quantized weights
82
+ """
83
+ torch._C._log_api_usage_once("quantization_api._numeric_suite.compare_weights")
84
+ weight_dict: Dict[str, Dict] = {}
85
+ for key in quantized_dict:
86
+ match_key = _find_match(float_dict, key, "weight")
87
+ if match_key is not None:
88
+ weight_dict[key] = {}
89
+ weight_dict[key]["float"] = float_dict[match_key]
90
+ weight_dict[key]["quantized"] = quantized_dict[key]
91
+ continue
92
+
93
+ # For matching "fc.weight" and "fc._packed_params._packed_params"
94
+ match_key = _find_match(float_dict, key, "_packed_params")
95
+ if match_key is not None:
96
+ weight_dict[key] = {}
97
+ weight_dict[key]["float"] = float_dict[match_key]
98
+ weight_dict[key]["quantized"] = quantized_dict[key][0]
99
+
100
+ # For LSTM
101
+ split_str = key.split(".")
102
+ if split_str[-1] == "param" and split_str[-3] == "_all_weight_values":
103
+ layer = split_str[-2]
104
+ module_name = ".".join(split_str[:-3])
105
+ float_weight_ih_key = module_name + ".weight_ih_l" + layer
106
+ float_weight_hh_key = module_name + ".weight_hh_l" + layer
107
+ if float_weight_ih_key in float_dict and float_weight_hh_key in float_dict:
108
+ weight_dict[key] = {}
109
+ weight_dict[key]["float"] = float_dict[float_weight_ih_key]
110
+ weight_dict[key]["quantized"] = (
111
+ quantized_dict[key].__getstate__()[0][4][0].__getstate__()[0][0]
112
+ )
113
+ weight_dict[key]["float"] = float_dict[float_weight_hh_key]
114
+ weight_dict[key]["quantized"] = (
115
+ quantized_dict[key].__getstate__()[0][4][1].__getstate__()[0][0]
116
+ )
117
+
118
+ return weight_dict
119
+
120
+
121
+ def _get_logger_dict_helper(
122
+ mod: nn.Module, target_dict: Dict[str, Any],
123
+ prefix: str = "",
124
+ ) -> None:
125
+ r"""This is the helper function for get_logger_dict
126
+
127
+ Args:
128
+ mod: module we want to save all logger stats
129
+ prefix: prefix for the current module
130
+ target_dict: the dictionary used to save all logger stats
131
+ """
132
+
133
+ def get_prefix(prefix):
134
+ return prefix if prefix == "" else prefix + "."
135
+
136
+ for name, child in mod.named_children():
137
+ if isinstance(child, Logger):
138
+ target_dict[get_prefix(prefix) + "stats"] = child.stats
139
+ break
140
+
141
+ for name, child in mod.named_children():
142
+ module_prefix = get_prefix(prefix) + name if prefix else name
143
+ _get_logger_dict_helper(child, target_dict, module_prefix)
144
+
145
+
146
+ def get_logger_dict(mod: nn.Module, prefix: str = "") -> Dict[str, Dict]:
147
+ r"""Traverse the modules and save all logger stats into target dict.
148
+ This is mainly used for quantization accuracy debug.
149
+
150
+ Type of loggers supported:
151
+ ShadowLogger: used to log the outputs of the quantized module and its matching float shadow module,
152
+ OutputLogger: used to log the outputs of the modules
153
+
154
+ Args:
155
+ mod: module we want to save all logger stats
156
+ prefix: prefix for the current module
157
+
158
+ Return:
159
+ target_dict: the dictionary used to save all logger stats
160
+
161
+ """
162
+ torch._C._log_api_usage_once("quantization_api._numeric_suite.get_logger_dict")
163
+
164
+ target_dict: Dict[str, Dict] = {}
165
+ _get_logger_dict_helper(mod, target_dict, prefix)
166
+ return target_dict
167
+
168
+
169
+ class Logger(nn.Module):
170
+ r"""Base class for stats logging
171
+ """
172
+
173
+ def __init__(self):
174
+ super().__init__()
175
+ self.stats = {}
176
+ # We only insert observer if the op is quantized with static quantization,
177
+ # which is identified by activation_observer.dtype == quint8. This is needed
178
+ # when attaching Logger as observer for FX mode
179
+ self.dtype = torch.quint8
180
+
181
+ def forward(self, x):
182
+ """
183
+ """ # blank docblock to make autodoc happy
184
+ pass
185
+
186
+
187
+ class ShadowLogger(Logger):
188
+ r"""Class used in Shadow module to record the outputs of the original and
189
+ shadow modules.
190
+ """
191
+
192
+ def __init__(self):
193
+ super().__init__()
194
+ self.stats["float"] = []
195
+ self.stats["quantized"] = []
196
+
197
+ def forward(self, x, y):
198
+ """
199
+ """ # blank docblock to make autodoc happy
200
+ if len(x) > 1:
201
+ x = x[0]
202
+ if len(y) > 1:
203
+ y = y[0]
204
+ self.stats["quantized"].append(x.detach())
205
+ self.stats["float"].append(y.detach())
206
+
207
+
208
+ class OutputLogger(Logger):
209
+ r"""Class used to log the outputs of the module
210
+ """
211
+
212
+ def __init__(self):
213
+ super().__init__()
214
+ self.stats["tensor_val"] = []
215
+
216
+
217
+ def forward(self, x):
218
+ """
219
+ """ # blank docblock to make autodoc happy
220
+ self.stats["tensor_val"].append(x)
221
+ return x
222
+
223
+
224
+ def _convert_tuple_to_list(t: Any) -> Any:
225
+ return [_convert_tuple_to_list(x) for x in t] if type(t) is tuple else t
226
+
227
+
228
+ def _dequantize_tensor_list(t: Any) -> Any:
229
+ return (
230
+ [_dequantize_tensor_list(x) for x in t]
231
+ if type(t) is list
232
+ else t.dequantize()
233
+ if t.is_quantized
234
+ else t
235
+ )
236
+
237
+
238
+ class Shadow(nn.Module):
239
+ r"""Shadow module attaches the float module to its matching quantized module
240
+ as the shadow. Then it uses Logger module to process the outputs of both
241
+ modules.
242
+
243
+ Args:
244
+ q_module: module quantized from float_module that we want to shadow
245
+ float_module: float module used to shadow q_module
246
+ logger_cls: type of logger used to process the outputs of q_module and
247
+ float_module. ShadowLogger or custom loggers can be used.
248
+ """
249
+
250
+ def __init__(self, q_module, float_module, logger_cls):
251
+ super().__init__()
252
+ self.orig_module = q_module
253
+ self.shadow_module = float_module
254
+ self.dequant = nnq.DeQuantize()
255
+ self.logger = logger_cls()
256
+
257
+ def forward(self, *x) -> torch.Tensor:
258
+ """
259
+ """ # blank docblock to make autodoc happy
260
+ xl = _convert_tuple_to_list(x)
261
+ output = self.orig_module(*xl)
262
+ xl_float = _dequantize_tensor_list(xl)
263
+ shadow_output = self.shadow_module(*xl_float)
264
+ self.logger(output, shadow_output)
265
+ return output
266
+
267
+ def add(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
268
+ """
269
+ """ # blank docblock to make autodoc happy
270
+ output = self.orig_module.add(x, y)
271
+ x = x.dequantize()
272
+ y = y.dequantize()
273
+ shadow_output = self.shadow_module.add(x, y)
274
+ self.logger(output, shadow_output)
275
+ return output
276
+
277
+ def add_scalar(self, x: torch.Tensor, y: float) -> torch.Tensor:
278
+ """
279
+ """ # blank docblock to make autodoc happy
280
+ output = self.orig_module.add_scalar(x, y)
281
+ x = x.dequantize()
282
+ shadow_output = self.shadow_module.add_scalar(x, y)
283
+ self.logger(output, shadow_output)
284
+ return output
285
+
286
+ def mul(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
287
+ """
288
+ """ # blank docblock to make autodoc happy
289
+ output = self.orig_module.mul(x, y)
290
+ x = x.dequantize()
291
+ y = y.dequantize()
292
+ shadow_output = self.shadow_module.mul(x, y)
293
+ self.logger(output, shadow_output)
294
+ return output
295
+
296
+ def mul_scalar(self, x: torch.Tensor, y: float) -> torch.Tensor:
297
+ """
298
+ """ # blank docblock to make autodoc happy
299
+ output = self.orig_module.mul_scalar(x, y)
300
+ x = x.dequantize()
301
+ shadow_output = self.shadow_module.mul_scalar(x, y)
302
+ self.logger(output, shadow_output)
303
+ return output
304
+
305
+ def cat(self, x: List[torch.Tensor], dim: int = 0) -> torch.Tensor:
306
+ """
307
+ """ # blank docblock to make autodoc happy
308
+ output = self.orig_module.cat(x, dim)
309
+ x = [y.dequantize() for y in x]
310
+ shadow_output = self.shadow_module.cat(x, dim)
311
+ self.logger(output, shadow_output)
312
+ return output
313
+
314
+ def add_relu(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
315
+ """
316
+ """ # blank docblock to make autodoc happy
317
+ output = self.orig_module.add_relu(x, y)
318
+ x = x.dequantize()
319
+ y = y.dequantize()
320
+ shadow_output = self.shadow_module.add_relu(x, y)
321
+ self.logger(output, shadow_output)
322
+ return output
323
+
324
+
325
+ def prepare_model_with_stubs(
326
+ float_module: nn.Module, q_module: nn.Module,
327
+ module_swap_list: Set[type], logger_cls: Callable,
328
+ ) -> None:
329
+ r"""Prepare the model by attaching the float module to its matching quantized
330
+ module as the shadow if the float module type is in module_swap_list.
331
+
332
+ Example usage::
333
+
334
+ prepare_model_with_stubs(float_model, q_model, module_swap_list, Logger)
335
+ q_model(data)
336
+ ob_dict = get_logger_dict(q_model)
337
+
338
+ Args:
339
+ float_module: float module used to generate the q_module
340
+ q_module: module quantized from float_module
341
+ module_swap_list: list of float module types to attach the shadow
342
+ logger_cls: type of logger to be used in shadow module to process the outputs of
343
+ quantized module and its float shadow module
344
+ """
345
+ torch._C._log_api_usage_once("quantization_api._numeric_suite.prepare_model_with_stubs")
346
+
347
+ float_module_children = {}
348
+ for name, mod in float_module.named_children():
349
+ float_module_children[name] = mod
350
+
351
+ reassign = {}
352
+ for name, mod in q_module.named_children():
353
+
354
+ if name not in float_module_children:
355
+ continue
356
+
357
+ float_mod = float_module_children[name]
358
+
359
+ if type(float_mod) not in module_swap_list:
360
+ prepare_model_with_stubs(float_mod, mod, module_swap_list, logger_cls)
361
+
362
+ # Insert shadow module only if the module is not of the same type as
363
+ # the floating point module
364
+ if type(float_mod) in module_swap_list and not _is_identical_module_type(mod, float_mod):
365
+ reassign[name] = Shadow(mod, float_mod, logger_cls)
366
+
367
+ for key, value in reassign.items():
368
+ q_module._modules[key] = value
369
+
370
+ def _is_identical_module_type(mod1, mod2):
371
+ # Compare if two modules have the same dtype
372
+ mod1_module_types = [type(mod) for mod in mod1.modules()]
373
+ mod2_module_types = [type(mod) for mod in mod2.modules()]
374
+ return mod1_module_types == mod2_module_types
375
+
376
+
377
+
378
+ def compare_model_stub(
379
+ float_model: nn.Module, q_model: nn.Module, module_swap_list: Set[type],
380
+ *data, logger_cls=ShadowLogger
381
+ ) -> Dict[str, Dict]:
382
+ r"""Compare quantized module in a model with its floating point counterpart,
383
+ feeding both of them the same input. Return a dict with key corresponding to
384
+ module names and each entry being a dictionary with two keys 'float' and
385
+ 'quantized', containing the output tensors of quantized and its matching
386
+ float shadow module. This dict can be used to compare and compute the module
387
+ level quantization error.
388
+
389
+ This function first call prepare_model_with_stubs() to swap the quantized
390
+ module that we want to compare with the Shadow module, which takes quantized
391
+ module, corresponding float module and logger as input, and creates a forward
392
+ path inside to make the float module to shadow quantized module sharing the
393
+ same input. The logger can be customizable, default logger is ShadowLogger
394
+ and it will save the outputs of the quantized module and float module that
395
+ can be used to compute the module level quantization error.
396
+
397
+ Example usage::
398
+
399
+ module_swap_list = [torchvision.models.quantization.resnet.QuantizableBasicBlock]
400
+ ob_dict = compare_model_stub(float_model,qmodel,module_swap_list, data)
401
+ for key in ob_dict:
402
+ print(key, compute_error(ob_dict[key]['float'], ob_dict[key]['quantized'].dequantize()))
403
+
404
+ Args:
405
+ float_model: float model used to generate the q_model
406
+ q_model: model quantized from float_model
407
+ module_swap_list: list of float module types at which shadow modules will
408
+ be attached.
409
+ data: input data used to run the prepared q_model
410
+ logger_cls: type of logger to be used in shadow module to process the outputs of
411
+ quantized module and its float shadow module
412
+ """
413
+ torch._C._log_api_usage_once("quantization_api._numeric_suite.compare_model_stub")
414
+ prepare_model_with_stubs(float_model, q_model, module_swap_list, logger_cls)
415
+ q_model(*data)
416
+ ob_dict = get_logger_dict(q_model)
417
+ return ob_dict
418
+
419
+
420
+ def get_matching_activations(
421
+ float_module: nn.Module, q_module: nn.Module,
422
+ ) -> Dict[str, Dict[str, torch.Tensor]]:
423
+ r"""Find the matching activation between float and quantized modules.
424
+
425
+ Args:
426
+ float_module: float module used to generate the q_module
427
+ q_module: module quantized from float_module
428
+
429
+ Return:
430
+ act_dict: dict with key corresponding to quantized module names and each
431
+ entry being a dictionary with two keys 'float' and 'quantized', containing
432
+ the matching float and quantized activations
433
+ """
434
+ torch._C._log_api_usage_once("quantization_api._numeric_suite.get_matching_activations")
435
+ float_dict = get_logger_dict(float_module)
436
+ quantized_dict = get_logger_dict(q_module)
437
+ act_dict: Dict[str, Dict] = {}
438
+ for key in quantized_dict:
439
+ if len(quantized_dict[key]["tensor_val"]) == 0:
440
+ continue
441
+ match_key = _find_match(sorted(float_dict, reverse=True), key, "stats")
442
+ if match_key is not None:
443
+ act_dict[key] = {}
444
+ act_dict[key]["float"] = float_dict[match_key]["tensor_val"]
445
+ act_dict[key]["quantized"] = quantized_dict[key]["tensor_val"]
446
+ return act_dict
447
+
448
+
449
+ def prepare_model_outputs(
450
+ float_module: nn.Module,
451
+ q_module: nn.Module,
452
+ logger_cls=OutputLogger,
453
+ allow_list=None
454
+ ) -> None:
455
+ r"""Prepare the model by attaching the logger to both float module
456
+ and quantized module if they are in the allow_list.
457
+
458
+ Args:
459
+ float_module: float module used to generate the q_module
460
+ q_module: module quantized from float_module
461
+ logger_cls: type of logger to be attached to float_module and q_module
462
+ allow_list: list of module types to attach logger
463
+ """
464
+ torch._C._log_api_usage_once("quantization_api._numeric_suite.prepare_model_outputs")
465
+ if allow_list is None:
466
+ allow_list = get_default_compare_output_module_list()
467
+
468
+ qconfig_debug = torch.ao.quantization.QConfig(activation=logger_cls, weight=None)
469
+ float_module.qconfig = qconfig_debug # type: ignore[assignment]
470
+ prepare(float_module, inplace=True, allow_list=allow_list, prepare_custom_config_dict={})
471
+ q_module.qconfig = qconfig_debug # type: ignore[assignment]
472
+ prepare(
473
+ q_module,
474
+ inplace=True,
475
+ allow_list=allow_list,
476
+ observer_non_leaf_module_list=NON_LEAF_MODULE_TO_ADD_OBSERVER_ALLOW_LIST,
477
+ prepare_custom_config_dict={}
478
+ )
479
+
480
+
481
+ def compare_model_outputs(
482
+ float_model: nn.Module,
483
+ q_model: nn.Module,
484
+ *data,
485
+ logger_cls=OutputLogger,
486
+ allow_list=None
487
+ ) -> Dict[str, Dict[str, torch.Tensor]]:
488
+ r"""Compare output activations between float and quantized models at
489
+ corresponding locations for the same input. Return a dict with key corresponding
490
+ to quantized module names and each entry being a dictionary with two keys
491
+ 'float' and 'quantized', containing the activations of quantized model and
492
+ float model at matching locations. This dict can be used to compare and
493
+ compute the propagation quantization error.
494
+
495
+ Example usage::
496
+
497
+ act_compare_dict = compare_model_outputs(float_model, qmodel, data)
498
+ for key in act_compare_dict:
499
+ print(
500
+ key,
501
+ compute_error(
502
+ act_compare_dict[key]['float'],
503
+ act_compare_dict[key]['quantized'].dequantize()
504
+ )
505
+ )
506
+
507
+ Args:
508
+ float_model: float model used to generate the q_model
509
+ q_model: model quantized from float_model
510
+ data: input data used to run the prepared float_model and q_model
511
+ logger_cls: type of logger to be attached to float_module and q_module
512
+ allow_list: list of module types to attach logger
513
+
514
+ Return:
515
+ act_compare_dict: dict with key corresponding to quantized module names
516
+ and each entry being a dictionary with two keys 'float' and 'quantized',
517
+ containing the matching float and quantized activations
518
+ """
519
+ torch._C._log_api_usage_once("quantization_api._numeric_suite.compare_model_outputs")
520
+ if allow_list is None:
521
+ allow_list = get_default_compare_output_module_list()
522
+ prepare_model_outputs(float_model, q_model, logger_cls, allow_list)
523
+ float_model(*data)
524
+ q_model(*data)
525
+ act_compare_dict = get_matching_activations(float_model, q_model)
526
+ return act_compare_dict
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__init__.py ADDED
File without changes
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/graph_passes.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/utils.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/__pycache__/weight_utils.cpython-310.pyc ADDED
Binary file (6.84 kB). View file
 
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/graph_matcher.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import enum
3
+
4
+ import torch
5
+ toq = torch.ops.quantized
6
+
7
+ from torch.fx import GraphModule
8
+ from torch.fx.graph import Graph, Node
9
+
10
+ from torch.ao.quantization.utils import getattr_from_fqn
11
+ from .ns_types import NSSubgraph, NSNodeTargetType
12
+ from .mappings import (
13
+ get_base_name_to_sets_of_related_ops,
14
+ get_unmatchable_types_map,
15
+ )
16
+ from .pattern_utils import (
17
+ get_type_a_related_to_b,
18
+ get_reversed_fusions,
19
+ end_node_matches_reversed_fusion,
20
+ )
21
+ from torch.ao.quantization import (
22
+ ObserverBase,
23
+ FakeQuantizeBase,
24
+ )
25
+
26
+ from typing import Dict, Tuple, List, Optional, Set, Any
27
+
28
+ def _get_output_nodes(g: Graph) -> List[Node]:
29
+ return [n for n in g.nodes if n.op == 'output']
30
+
31
+ class _NSGraphMatchableSubgraphsIterator:
32
+ """
33
+ Iterates through the graph of gm, starting with the output nodes
34
+ and continuing backwards.
35
+ 1. Returns matchable subgraphs, in order. A subgraph is defined by
36
+ (start_node, end_node).
37
+ 2. Skips over non-matchable subgraphs
38
+ """
39
+ def __init__(
40
+ self,
41
+ gm: GraphModule,
42
+ non_matchable_functions: Set[NSNodeTargetType],
43
+ non_matchable_modules: Set[NSNodeTargetType],
44
+ non_matchable_methods: Set[NSNodeTargetType],
45
+ ):
46
+ self.gm: GraphModule = gm
47
+ self.non_matchable_functions: Set[NSNodeTargetType] = non_matchable_functions
48
+ self.non_matchable_modules: Set[NSNodeTargetType] = non_matchable_modules
49
+ self.non_matchable_methods: Set[NSNodeTargetType] = non_matchable_methods
50
+ self.seen_nodes: Set[Node] = set()
51
+ self.stack: List[Node] = []
52
+ for start_node in _get_output_nodes(self.gm.graph):
53
+ self.stack.append(start_node)
54
+
55
+ def __iter__(self):
56
+ return self
57
+
58
+ def __next__(self) -> NSSubgraph:
59
+ """
60
+ Returns the next matchable subgraph.
61
+ """
62
+ while len(self.stack) > 0:
63
+ cur_end_node = self.stack.pop()
64
+ if cur_end_node in self.seen_nodes:
65
+ continue
66
+
67
+ # for subgraphs which are single nodes, start_node == end_node
68
+ # for subgraphs with more than one node, start node != end_node
69
+ cur_start_node = cur_end_node
70
+ # Subgraphs like linear-relu have the base node as the start node.
71
+ # Subgraphs like dequantize-linear-relu-to(torch.float16) have the
72
+ # base node as the second node.
73
+ # The cur_base_op_node var will move to the actual node during
74
+ # the fusion matching later in this code block.
75
+ cur_base_op_node = cur_end_node
76
+
77
+ # Check for potential fusions. For now, we are greedy
78
+ # and always skip all non-base nodes of a fusion. For example,
79
+ # if we match linear-relu backwards, we will always skip the
80
+ # relu node and attempt to match the linear node. This can
81
+ # be made configurable later if needed.
82
+ for _reverse_fusion_ops, base_op_idx in get_reversed_fusions():
83
+ is_match = end_node_matches_reversed_fusion(
84
+ cur_end_node, _reverse_fusion_ops, self.gm, self.seen_nodes)
85
+ if is_match:
86
+ # navigate to the base node
87
+ for rev_fusion_idx in range(len(_reverse_fusion_ops) - 1):
88
+ self.seen_nodes.add(cur_start_node)
89
+ # for now, assume that there are no other nodes
90
+ # which need to be added to the stack
91
+ cur_start_node = cur_start_node.args[0] # type: ignore[assignment]
92
+ # if the base op index matches the current node, set it
93
+ rev_base_op_idx = \
94
+ len(_reverse_fusion_ops) - 2 - base_op_idx
95
+ if rev_fusion_idx == rev_base_op_idx:
96
+ cur_base_op_node = cur_start_node
97
+ break
98
+
99
+ self.seen_nodes.add(cur_start_node)
100
+ # add args of previous nodes to stack
101
+ for arg in cur_start_node.all_input_nodes:
102
+ self._recursively_add_node_arg_to_stack(arg)
103
+
104
+ # skip unmatchable nodes
105
+ # note: this check is done on the start_node, i.e.
106
+ # if we are matching linear-relu in reverse, this would do the matchable
107
+ # check on the linear
108
+ if not self._is_matchable(cur_base_op_node):
109
+ continue
110
+
111
+ # If an observer or a fake_quant was not matched as a part of
112
+ # a pattern of multiple nodes, ignore it. One case where this is
113
+ # relevant is an observer on a graph input, which was added because
114
+ # it is necessary for the next node.
115
+ if cur_end_node.op == 'call_module' and cur_start_node is cur_end_node:
116
+ maybe_obs = getattr_from_fqn(self.gm, cur_end_node.target) # type: ignore[arg-type]
117
+ if isinstance(maybe_obs, (ObserverBase, FakeQuantizeBase)):
118
+ continue
119
+
120
+ return NSSubgraph(
121
+ start_node=cur_start_node, end_node=cur_end_node,
122
+ base_op_node=cur_base_op_node)
123
+
124
+ raise StopIteration
125
+
126
+ def _recursively_add_node_arg_to_stack(self, arg: Any) -> None:
127
+ """
128
+ Adds all of the nodes in this arg to the stack, properly navigating
129
+ through list, dicts and tuples.
130
+ """
131
+ if isinstance(arg, Node):
132
+ self.stack.append(arg)
133
+ elif isinstance(arg, torch.fx.immutable_collections.immutable_list) or type(arg) is tuple:
134
+ for inner_arg in arg:
135
+ self._recursively_add_node_arg_to_stack(inner_arg)
136
+ elif isinstance(arg, torch.fx.immutable_collections.immutable_dict):
137
+ for value in arg.values():
138
+ self._recursively_add_node_arg_to_stack(value)
139
+
140
+ def _is_matchable(self, node: Node) -> bool:
141
+ if node.op == 'call_function':
142
+ return node.target not in self.non_matchable_functions
143
+ elif node.op == 'call_module':
144
+ assert isinstance(node.target, str)
145
+ target_mod = getattr_from_fqn(self.gm, node.target)
146
+ return not \
147
+ any(isinstance(target_mod, t) # type: ignore[arg-type]
148
+ for t in self.non_matchable_modules)
149
+ elif node.op == 'call_method':
150
+ return node.target not in self.non_matchable_methods
151
+ else:
152
+ return False
153
+
154
+ class GraphMatchingException(Exception):
155
+ """
156
+ Exception raised when two graphs cannot be matched.
157
+ """
158
+ pass
159
+
160
+ class SubgraphTypeRelationship(enum.Enum):
161
+ # same type, known
162
+ # example: F.linear and F.linear, or nn.Conv2d and nn.Conv2d
163
+ EQUAL = enum.auto()
164
+ # same type, but the type is not known to Numerical Suite
165
+ # (user defined type, etc).
166
+ EQUAL_BUT_UKNOWN = enum.auto()
167
+ # known, same subgraph_relationship set, but not the same type
168
+ # example: F.linear and toq.linear
169
+ RELATED_BUT_NOT_EQUAL = enum.auto()
170
+ # not related
171
+ NOT_RELATED = enum.auto()
172
+
173
+ def _get_subgraph_relationship_type(
174
+ subgraph_a: NSSubgraph,
175
+ subgraph_b: NSSubgraph,
176
+ gm_a: GraphModule,
177
+ gm_b: GraphModule,
178
+ type_a_related_to_b: Set[Tuple[NSNodeTargetType, NSNodeTargetType]],
179
+ ) -> SubgraphTypeRelationship:
180
+ node_a = subgraph_a.base_op_node
181
+ node_b = subgraph_b.base_op_node
182
+
183
+ # TODO(next): make this code handle matching by what is before the base op
184
+ if node_a.op != node_b.op:
185
+ if not (
186
+ node_a.op in ('call_function', 'call_method') and
187
+ node_b.op in ('call_function', 'call_method')
188
+ ):
189
+ return SubgraphTypeRelationship.NOT_RELATED
190
+
191
+ if node_a.op in ('call_function', 'call_method'):
192
+ key = (node_a.target, node_b.target)
193
+
194
+ if key not in type_a_related_to_b:
195
+ if node_a.target == node_b.target:
196
+ return SubgraphTypeRelationship.EQUAL_BUT_UKNOWN
197
+ else:
198
+ return SubgraphTypeRelationship.NOT_RELATED
199
+ # after this point, we are dealing with known types
200
+
201
+ if node_a.target == node_b.target:
202
+ node_a_has_prev = subgraph_a.base_op_node == subgraph_a.start_node
203
+ node_b_has_prev = subgraph_b.base_op_node == subgraph_b.start_node
204
+ if node_a_has_prev and (not node_b_has_prev):
205
+ return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
206
+ elif (not node_a_has_prev) and node_b_has_prev:
207
+ return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
208
+ elif (not node_a_has_prev) and (not node_b_has_prev):
209
+ return SubgraphTypeRelationship.EQUAL
210
+ else:
211
+ # TODO(future PR): check for matches start_op_node and base_op_node
212
+ return SubgraphTypeRelationship.EQUAL
213
+
214
+ if key in type_a_related_to_b:
215
+ return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
216
+ else:
217
+ return SubgraphTypeRelationship.NOT_RELATED
218
+ elif node_a.op == 'call_module':
219
+ assert (subgraph_a.base_op_node == subgraph_a.start_node and
220
+ subgraph_b.base_op_node == subgraph_b.start_node), \
221
+ "Matching call_module patterns where base_op_node != start_node is not supported yet"
222
+ # for call_module, we need to look up the modules to do the type check
223
+ assert isinstance(node_a.target, str)
224
+ mod_a = getattr_from_fqn(gm_a, node_a.target)
225
+ assert isinstance(node_b.target, str)
226
+ mod_b = getattr_from_fqn(gm_b, node_b.target)
227
+
228
+ key = (type(mod_a), type(mod_b))
229
+
230
+ if key not in type_a_related_to_b:
231
+ if type(mod_a) == type(mod_b):
232
+ return SubgraphTypeRelationship.EQUAL_BUT_UKNOWN
233
+ else:
234
+ return SubgraphTypeRelationship.NOT_RELATED
235
+ elif type(mod_a) == type(mod_b):
236
+ return SubgraphTypeRelationship.EQUAL
237
+ else:
238
+ return SubgraphTypeRelationship.RELATED_BUT_NOT_EQUAL
239
+
240
+ return SubgraphTypeRelationship.NOT_RELATED
241
+
242
+ def _get_name_for_subgraph(
243
+ subgraph_a: NSSubgraph,
244
+ gm_a: GraphModule,
245
+ base_name_to_sets_of_related_ops: Dict[str, Set[NSNodeTargetType]],
246
+ existing_names: Set[str],
247
+ ) -> str:
248
+ """
249
+ Returns a unique name for a subgraph. This name is based on two things:
250
+ 1. the name of the set containing the underlying type of the base op in the
251
+ subgraph (i.e. 'torch.nn.functional.linear' if this is related to a linear op)
252
+ 2. the number of previous subgraphs with related underlying type of the base op
253
+
254
+ For example, in the graph
255
+
256
+ linear0 -> relu0 -> linear1 -> relu1
257
+
258
+ The subgraphs are (linear0, relu0) and (linear1, relu1). If we iterate
259
+ from the output node backwards, the name given to (linear1, relu1) will be
260
+ `base_op_torch.nn.functional.linear_0`, and the name given to (linear0, relu0)
261
+ will be `base_op_torch.nn.functional.linear_1`.
262
+
263
+ Why are we not just using the node name? Answer: because of two requirements:
264
+ A. fusions must be supported
265
+ B. some Numeric Suite APIs can be called without having all of the models in memory
266
+
267
+ For example, let's say we need to match nodes of
268
+
269
+ (1) ... -> linear0 -> relu0 -> ...
270
+
271
+ And
272
+
273
+ (2) ... -> linear_relu0 -> ...
274
+
275
+ Without being able to inspect them together. With the current naming scheme, if
276
+ we iterate through both of these graphs in the same order, and assuming the rest
277
+ of the graphs match, both of these subgraphs will get the same name without
278
+ (1) and (2) knowing anything about each other.
279
+ """
280
+ target_type = _get_node_target_type(subgraph_a.base_op_node, gm_a)
281
+ target_base_type = None
282
+ for base_name, sets_of_related_ops in base_name_to_sets_of_related_ops.items():
283
+ if target_type in sets_of_related_ops:
284
+ target_base_type = base_name
285
+ target_base_name = 'base_op_' + str(target_base_type)
286
+ counter = 0
287
+ proposed_name = target_base_name + '_' + str(counter)
288
+ while proposed_name in existing_names:
289
+ counter += 1
290
+ proposed_name = target_base_name + '_' + str(counter)
291
+ existing_names.add(proposed_name)
292
+ return proposed_name
293
+
294
+ def _get_node_target_type(node: Node, gm: GraphModule) -> Optional[NSNodeTargetType]:
295
+ if node.op in ('call_function', 'call_method'):
296
+ return node.target
297
+ elif node.op == 'call_module':
298
+ assert isinstance(node.target, str)
299
+ mod = getattr_from_fqn(gm, node.target)
300
+ return type(mod)
301
+ return None
302
+
303
+ def get_matching_subgraph_pairs(
304
+ gm_a: GraphModule,
305
+ gm_b: GraphModule,
306
+ base_name_to_sets_of_related_ops: Optional[Dict[str, Set[NSNodeTargetType]]] = None,
307
+ unmatchable_types_map: Optional[Dict[str, Set[NSNodeTargetType]]] = None,
308
+ ) -> Dict[str, Tuple[NSSubgraph, NSSubgraph]]:
309
+ """
310
+ Matches matchable subgraphs of graph_a to graph_b.
311
+
312
+ For a node, "matchable" is defined as a node which is not an observer,
313
+ fake_quants, quant or dequant.
314
+
315
+ A subgraph can contain one or more nodes. A subgraph is matchable if
316
+ at least one node inside of it is matchable. Currently, all nodes in
317
+ a subgraph must be matchable (because we assume no observers will be
318
+ inserted in the middle of a fusion).
319
+
320
+ A subgraph is defined by (start_node, end_node). We assume that only
321
+ start_node and end_node are linked with the surrounding graph, all other
322
+ nodes in a subgraph are self-contained.
323
+
324
+ A pair of nodes is "related" if both nodes represent the same mathematical
325
+ operation across different quantization flavors. For example,
326
+ `F.linear` and `torch.ops.quantized.linear` are related, and
327
+ `F.linear` and `torch.nn.Conv` are not related.
328
+
329
+ For each matchable pair of nodes node_a and node_b, they will match
330
+ if node_a and node_b are related.
331
+
332
+ For graphs A and B, they will match iff:
333
+ 1. the number of matchable subgraphs in A and B is equivalent
334
+ 2. when iterating through the matchable subgraphs of A and B in the same order, each
335
+ corresponding pair of base nodes is related.
336
+
337
+ This enables us to find the corresponding subgraphs between
338
+ graphs of related models. For example, if we had two graphs such as:
339
+
340
+ graph_a: x0 -> conv_0 (type: nn.Conv2d) -> obs_0 -> x1
341
+ w -/
342
+ b -/
343
+
344
+ graph_b: x0 -> quant_0 -> qconv_0 (type: nnq.Conv2d) -> dequant_0 -> x1
345
+ packed_params_0 -/
346
+
347
+ This function will return the following result:
348
+ {
349
+ 'conv_0': ( # the name of the node in graph_b
350
+ (conv_0, conv_0), # (start_node_a, end_node_a)
351
+ (qconv_0, qconv_0), # (start_node_b, end_node_b)
352
+ ),
353
+ }
354
+
355
+ Or, if we have a fusion pattern,
356
+
357
+ graph_a: x0 -> linear_0 -> relu_0 -> obs_0 -> x1
358
+ w -/
359
+ b -/
360
+
361
+ graph_b: x0 -> quant_0 -> linear_relu_0 -> dequant_0 -> x1
362
+ packed_params_0 -/
363
+
364
+ This function will return the following result:
365
+ {
366
+ 'linear_relu_0': ( # the name of the node in graph_b
367
+ (linear_0, relu_0), # (start_node_a, end_node_a)
368
+ (linear_relu_0, linear_relu_0), # (start_node_b, end_node_b)
369
+ ),
370
+ }
371
+ """
372
+ if unmatchable_types_map is None:
373
+ unmatchable_types_map = get_unmatchable_types_map()
374
+ non_matchable_functions = unmatchable_types_map['funs_unmatchable']
375
+ non_matchable_modules = unmatchable_types_map['mods_unmatchable']
376
+ non_matchable_methods = unmatchable_types_map['meths_unmatchable']
377
+
378
+ graph_a_iterator = _NSGraphMatchableSubgraphsIterator(
379
+ gm_a, non_matchable_functions, non_matchable_modules,
380
+ non_matchable_methods)
381
+ graph_b_iterator = _NSGraphMatchableSubgraphsIterator(
382
+ gm_b, non_matchable_functions, non_matchable_modules,
383
+ non_matchable_methods)
384
+ results = collections.OrderedDict()
385
+ if base_name_to_sets_of_related_ops is None:
386
+ base_name_to_sets_of_related_ops = get_base_name_to_sets_of_related_ops()
387
+ type_a_related_to_b = \
388
+ get_type_a_related_to_b(base_name_to_sets_of_related_ops)
389
+
390
+ existing_names_a: Set[str] = set()
391
+ existing_names_b: Set[str] = set()
392
+
393
+ while True:
394
+ # fetch the next subgraphs from a and b
395
+ cur_subgraph_a, cur_subgraph_b = None, None
396
+ try:
397
+ cur_subgraph_a = next(graph_a_iterator)
398
+ except StopIteration:
399
+ pass
400
+ try:
401
+ cur_subgraph_b = next(graph_b_iterator)
402
+ except StopIteration:
403
+ pass
404
+
405
+ # look up types of a and b for useful error messages
406
+ type_start_a, type_start_b = None, None
407
+ if cur_subgraph_a is not None:
408
+ type_start_a = _get_node_target_type(cur_subgraph_a.start_node, gm_a)
409
+ if cur_subgraph_b is not None:
410
+ type_start_b = _get_node_target_type(cur_subgraph_b.start_node, gm_b)
411
+
412
+ # check for results and determine what to do next
413
+ if cur_subgraph_a is not None and cur_subgraph_b is not None:
414
+ # both nodes were fetched, check for subgraph_relationship
415
+ # note: subgraph_relationship is checked on the start node, i.e.
416
+ # if a linear-relu pattern is checked, we would check for subgraph_relationship
417
+ # of the linear
418
+ subgraph_relationship = _get_subgraph_relationship_type(
419
+ cur_subgraph_a, cur_subgraph_b,
420
+ gm_a, gm_b, type_a_related_to_b)
421
+ if subgraph_relationship == SubgraphTypeRelationship.NOT_RELATED:
422
+ msg = f"""
423
+ The subgraphs
424
+ ({cur_subgraph_a}, {type_start_a}) and
425
+ ({cur_subgraph_b}, {type_start_b})
426
+ are not related. Please ensure that the two models you pass in have the same number
427
+ of subgraphs, and each pair of subgraphs is related to each other."""
428
+ raise GraphMatchingException(msg)
429
+ elif subgraph_relationship == SubgraphTypeRelationship.EQUAL_BUT_UKNOWN:
430
+ # skip matching but unknown types
431
+ continue
432
+ key_name_a = _get_name_for_subgraph(
433
+ cur_subgraph_a, gm_a, base_name_to_sets_of_related_ops,
434
+ existing_names_a)
435
+ key_name_b = _get_name_for_subgraph(
436
+ cur_subgraph_b, gm_b, base_name_to_sets_of_related_ops,
437
+ existing_names_b)
438
+ assert key_name_a == key_name_b, \
439
+ f"Subgraph names {key_name_a} and {key_name_b} do not match"
440
+ results[key_name_a] = (cur_subgraph_a, cur_subgraph_b)
441
+ continue
442
+ elif cur_subgraph_a is None and cur_subgraph_b is None:
443
+ # we reached the end of both graphs
444
+ break
445
+ else:
446
+ # only one node was fetched, no match possible, throw error
447
+ msg = f"""
448
+ Attempting to match
449
+ ({cur_subgraph_a}, {type_start_a}) and
450
+ ({cur_subgraph_b}, {type_start_b}),
451
+ one of which is empty. Please ensure that the two models you pass in have the same number
452
+ of subgraphs."""
453
+ raise GraphMatchingException(msg)
454
+
455
+ # The subgraph pairs are originally created by traversing the two graphs
456
+ # from the outputs to the inputs. Reverse the results to return the
457
+ # subgraphs in their order of execution.
458
+ results = collections.OrderedDict(reversed(list(results.items())))
459
+
460
+ return results
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/graph_passes.py ADDED
@@ -0,0 +1,950 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch.fx import GraphModule, map_arg
3
+ from torch.fx.graph import Graph, Node
4
+ from torch.ao.quantization.fx.utils import get_new_attr_name_with_prefix
5
+
6
+ from .utils import (
7
+ get_node_first_input_and_output_type,
8
+ getattr_from_fqn,
9
+ NodeInputOrOutputType,
10
+ return_first_non_observer_node,
11
+ get_number_of_non_param_args,
12
+ get_target_type_str,
13
+ get_arg_indices_of_inputs_to_log,
14
+ get_node_input_qparams,
15
+ op_type_supports_shadowing,
16
+ get_normalized_nth_input,
17
+ )
18
+
19
+ from .ns_types import (
20
+ NSSingleResultValuesType,
21
+ NSSubgraph,
22
+ NSNodeTargetType,
23
+ )
24
+ from torch.ao.ns.fx.mappings import (
25
+ get_node_type_to_io_type_map,
26
+ )
27
+ from torch.ao.quantization.observer import _is_activation_post_process
28
+
29
+ from typing import Dict, Tuple, Callable, List, Any, Union, Optional, Set
30
+
31
+ def _maybe_get_fqn(node: Node, gm: GraphModule) -> Optional[str]:
32
+ fqn = None
33
+ if hasattr(gm, '_node_name_to_scope'):
34
+ # fqn on observers is not present, because they do not
35
+ # exist when the fqns are created during tracing. If this is
36
+ # an observer, get the fqn of the node being observed.
37
+ node_to_use_for_fqn = node
38
+ if node.op == 'call_module':
39
+ assert isinstance(node.target, str)
40
+ module = getattr_from_fqn(gm, node.target)
41
+ if _is_activation_post_process(module):
42
+ node_to_use_for_fqn = get_normalized_nth_input(node, gm, 0)
43
+ fqn = gm._node_name_to_scope[node_to_use_for_fqn.name][0] # type: ignore[index]
44
+ return fqn # type: ignore[return-value]
45
+
46
+ def _insert_logger_after_node(
47
+ node: Node,
48
+ gm: GraphModule,
49
+ logger_cls: Callable,
50
+ logger_node_name_suffix: str,
51
+ ref_node_name: str,
52
+ model_name: str,
53
+ ref_name: str,
54
+ ref_node_target_type: str,
55
+ results_type: str,
56
+ index_within_arg: int,
57
+ index_of_arg: int,
58
+ fqn: Optional[str],
59
+ ) -> Node:
60
+ """
61
+ Given a starting graph of
62
+
63
+ prev_node -> node -> next_node
64
+
65
+ This function creates a new logger_cls obj and adds it
66
+ after node, resulting in
67
+
68
+ prev_node -> node -> logger_obj -> next_node
69
+ """
70
+ # create new name
71
+ logger_node_name = \
72
+ get_new_attr_name_with_prefix(node.name + logger_node_name_suffix)(gm)
73
+ target_type = get_target_type_str(node, gm)
74
+ # create the logger object
75
+ logger_obj = logger_cls(
76
+ ref_node_name, node.name, model_name, ref_name, target_type,
77
+ ref_node_target_type,
78
+ results_type, index_within_arg, index_of_arg, fqn)
79
+ # attach the logger object to the parent module
80
+ setattr(gm, logger_node_name, logger_obj)
81
+ logger_node = node.graph.create_node(
82
+ 'call_module', logger_node_name, (node,), {})
83
+ return logger_node
84
+
85
+ def add_loggers_to_model(
86
+ gm: GraphModule,
87
+ node_to_instrument_inputs_to_ref_node_name: Dict[Node, Tuple[str, str]],
88
+ node_to_instrument_outputs_to_ref_node_name: Dict[Node, Tuple[str, str]],
89
+ logger_cls: Callable,
90
+ model_name: str,
91
+ ) -> GraphModule:
92
+ """
93
+ Takes the graph of gm, adds loggers to the output
94
+ of each node in nodes_to_instrument. Returns a GraphModule with the new
95
+ graph.
96
+ """
97
+
98
+ new_graph = Graph()
99
+ env: Dict[str, Any] = {}
100
+ modules = dict(gm.named_modules())
101
+
102
+ def load_arg(a):
103
+ return map_arg(a, lambda node: env[node.name])
104
+
105
+ for node in gm.graph.nodes:
106
+ if node.op == 'output':
107
+ new_graph.output(map_arg(get_normalized_nth_input(node, gm, 0), load_arg))
108
+ continue
109
+
110
+ if (
111
+ (node in node_to_instrument_inputs_to_ref_node_name) or
112
+ (node in node_to_instrument_outputs_to_ref_node_name)
113
+ ):
114
+ fqn = _maybe_get_fqn(node, gm)
115
+
116
+ if node in node_to_instrument_inputs_to_ref_node_name:
117
+ ref_name, ref_node_type = node_to_instrument_inputs_to_ref_node_name[node]
118
+ # Ops such add and mul are special because either
119
+ # one or two of the first two arguments can be tensors,
120
+ # and if one argument is a tensor it can be first or
121
+ # second (x + 1 versus 1 + x).
122
+ arg_indices_to_log = get_arg_indices_of_inputs_to_log(node)
123
+ for node_arg_idx in arg_indices_to_log:
124
+ node_arg = get_normalized_nth_input(node, gm, node_arg_idx)
125
+ if type(node_arg) == Node:
126
+ # create a single input logger
127
+ prev_node = env[node_arg.name]
128
+ env[node_arg.name] = _insert_logger_after_node(
129
+ prev_node, gm, logger_cls, '_ns_logger_', node.name,
130
+ model_name, ref_name, ref_node_type,
131
+ NSSingleResultValuesType.NODE_INPUT.value,
132
+ index_within_arg=0, index_of_arg=node_arg_idx,
133
+ fqn=fqn)
134
+ elif type(node_arg) == torch.fx.immutable_collections.immutable_list:
135
+ # create N input loggers, one for each node
136
+ for arg_idx, arg in enumerate(node_arg): # type: ignore[var-annotated, arg-type]
137
+ prev_node = env[arg.name]
138
+ env[prev_node.name] = _insert_logger_after_node(
139
+ prev_node, gm, logger_cls, '_ns_logger_', node.name,
140
+ model_name, ref_name, ref_node_type,
141
+ NSSingleResultValuesType.NODE_INPUT.value,
142
+ index_within_arg=arg_idx, index_of_arg=node_arg_idx,
143
+ fqn=fqn)
144
+ else:
145
+ pass
146
+
147
+ # ensure env is populated with base node
148
+ # Note: runs for both inputs and outputs
149
+ env[node.name] = new_graph.node_copy(node, load_arg)
150
+
151
+ if node in node_to_instrument_outputs_to_ref_node_name:
152
+ ref_name, ref_node_type = node_to_instrument_outputs_to_ref_node_name[node]
153
+ # add the logger after the base node
154
+ env[node.name] = _insert_logger_after_node(
155
+ env[node.name], gm, logger_cls, '_ns_logger_', node.name,
156
+ model_name, ref_name, ref_node_type,
157
+ NSSingleResultValuesType.NODE_OUTPUT.value,
158
+ index_within_arg=0, index_of_arg=0, fqn=fqn)
159
+
160
+ else:
161
+ env[node.name] = new_graph.node_copy(node, load_arg)
162
+
163
+ new_gm = GraphModule(gm, new_graph)
164
+ return new_gm
165
+
166
+ def _insert_quantize_per_tensor_node(
167
+ prev_node_c: Node,
168
+ node_a: Node,
169
+ gm_b: GraphModule,
170
+ graph_c: Graph,
171
+ scale: Union[torch.Tensor, float],
172
+ zero_point: Union[torch.Tensor, int],
173
+ dtype_cast_name: str,
174
+ ) -> Node:
175
+ # copy scale
176
+ scale_node_name = \
177
+ get_new_attr_name_with_prefix(
178
+ node_a.name + '_input_scale_')(gm_b)
179
+ setattr(gm_b, scale_node_name, scale)
180
+ scale_node = graph_c.create_node(
181
+ 'get_attr', scale_node_name, (), {}, scale_node_name)
182
+ # copy zero_point
183
+ zero_point_node_name = \
184
+ get_new_attr_name_with_prefix(
185
+ node_a.name + '_input_zero_point_')(gm_b)
186
+ setattr(gm_b, zero_point_node_name, zero_point)
187
+ zero_point_node = graph_c.create_node(
188
+ 'get_attr', zero_point_node_name, (), {}, zero_point_node_name)
189
+ # create the quantize_per_tensor call
190
+ return graph_c.create_node(
191
+ 'call_function', torch.quantize_per_tensor,
192
+ (prev_node_c, scale_node, zero_point_node, torch.quint8), {},
193
+ dtype_cast_name)
194
+
195
+ def _insert_dtype_cast_after_node(
196
+ node_a: Node,
197
+ node_c: Node,
198
+ prev_node_c: Union[Node, List[Node]],
199
+ gm_a: GraphModule,
200
+ gm_b: GraphModule,
201
+ graph_c: Graph,
202
+ node_name_prefix: str,
203
+ logger_cls: Callable,
204
+ node_type_to_io_type_map: Dict[str, Set[NSNodeTargetType]],
205
+ ) -> Union[Node, List[Node]]:
206
+ """
207
+ Given a starting graph C (derived from graph B) of
208
+
209
+ ... -> prev_node_c -> node_c -> ...
210
+
211
+ And a corresponding related node_a, inserts the correct dtype
212
+ cast node after prev_node_c to cast into the dtype expected
213
+ by node_a, resulting in:
214
+
215
+ dtype_cast
216
+ /
217
+ ... -> prev_node_c -> node_c -> ...
218
+
219
+ For example, if node_c is an int8 op and node_a is an fp32 op, this function
220
+ will insert a dequant.
221
+ """
222
+ dtype_cast_op = None
223
+ dtype_cast_mod_cls = None
224
+ dtype_cast_method = None
225
+ dtype_cast_method_dtype = None
226
+ dtype_cast_scale = None
227
+ dtype_cast_zero_point = None
228
+ node_input_type_a, _node_output_type_a = \
229
+ get_node_first_input_and_output_type(
230
+ node_a, gm_a, logger_cls, node_type_to_io_type_map)
231
+ node_input_type_c, _node_output_type_c = \
232
+ get_node_first_input_and_output_type(
233
+ node_c, gm_b, logger_cls, node_type_to_io_type_map)
234
+
235
+ if (
236
+ (node_input_type_a == NodeInputOrOutputType.FP32 and
237
+ node_input_type_c == NodeInputOrOutputType.INT8) or
238
+ (node_input_type_a == NodeInputOrOutputType.FP32 and
239
+ node_input_type_c == NodeInputOrOutputType.FP16) or
240
+ # TODO(future PR): determine the actual dtype of node_c,
241
+ # the current code only works because dequantize works with
242
+ # multiple input dtypes.
243
+ (node_input_type_a == NodeInputOrOutputType.FP32 and
244
+ node_input_type_c == NodeInputOrOutputType.FP32_OR_INT8)
245
+ ):
246
+ dtype_cast_op = torch.dequantize
247
+ elif (
248
+ node_input_type_a == node_input_type_c and
249
+ node_input_type_a != NodeInputOrOutputType.UNKNOWN
250
+ ):
251
+ dtype_cast_mod_cls = torch.nn.Identity
252
+ elif (
253
+ node_input_type_a == NodeInputOrOutputType.INT8 and
254
+ node_input_type_c == NodeInputOrOutputType.FP32
255
+ ):
256
+ # int8 shadows fp32, the dtype cast needs to quantize to int8
257
+ # with the right qparams.
258
+ node_a_input_qparams = get_node_input_qparams(
259
+ node_a, gm_a, node_type_to_io_type_map)
260
+ if node_a_input_qparams is not None:
261
+ dtype_cast_op = torch.quantize_per_tensor # type: ignore[assignment]
262
+ dtype_cast_scale, dtype_cast_zero_point = node_a_input_qparams
263
+ elif (
264
+ node_input_type_a == NodeInputOrOutputType.FP16 and
265
+ node_input_type_c == NodeInputOrOutputType.FP32
266
+ ):
267
+ dtype_cast_method = 'to'
268
+ dtype_cast_method_dtype = torch.float16
269
+ else:
270
+ raise AssertionError(
271
+ f"dtype cast from {node_input_type_c} {node_c.format_node()} to " +
272
+ f"{node_input_type_a} {node_a.format_node()} needs to be implemented")
273
+
274
+ if isinstance(prev_node_c, Node):
275
+ new_dtype_cast_name = \
276
+ get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
277
+ if dtype_cast_op:
278
+ if dtype_cast_scale is not None and dtype_cast_zero_point is not None:
279
+ return _insert_quantize_per_tensor_node(
280
+ prev_node_c, node_a, gm_b, graph_c, dtype_cast_scale,
281
+ dtype_cast_zero_point, new_dtype_cast_name)
282
+ else:
283
+ return graph_c.create_node(
284
+ 'call_function', dtype_cast_op, (prev_node_c,), {},
285
+ new_dtype_cast_name)
286
+ elif dtype_cast_method:
287
+ return graph_c.create_node(
288
+ 'call_method', dtype_cast_method,
289
+ (prev_node_c, dtype_cast_method_dtype), {}, new_dtype_cast_name)
290
+ else:
291
+ assert dtype_cast_mod_cls
292
+ dtype_cast_mod = dtype_cast_mod_cls()
293
+ setattr(gm_b, new_dtype_cast_name, dtype_cast_mod)
294
+ return graph_c.create_node(
295
+ 'call_module', new_dtype_cast_name, (prev_node_c,), {},
296
+ new_dtype_cast_name)
297
+ elif isinstance(prev_node_c, list):
298
+ results = []
299
+ for prev_node_c_inner in prev_node_c:
300
+ new_dtype_cast_name = \
301
+ get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
302
+ if dtype_cast_op:
303
+ # TODO(future PR): add handling for quantize_per_tensor
304
+ new_dtype_cast_node = graph_c.create_node(
305
+ 'call_function', dtype_cast_op, (prev_node_c_inner,), {},
306
+ new_dtype_cast_name)
307
+ results.append(new_dtype_cast_node)
308
+ else:
309
+ assert dtype_cast_mod_cls
310
+ dtype_cast_mod = dtype_cast_mod_cls()
311
+ setattr(gm_b, new_dtype_cast_name, dtype_cast_mod)
312
+ new_dtype_cast_node = graph_c.create_node(
313
+ 'call_module', new_dtype_cast_name, (prev_node_c_inner,), {},
314
+ new_dtype_cast_name)
315
+ results.append(new_dtype_cast_node)
316
+ return results
317
+ else:
318
+ raise AssertionError(f"type f{type(prev_node_c)} is not handled")
319
+
320
+ # TODO(future PR): look into using copy_node API instead
321
+ def _copy_node_from_a_to_c(
322
+ node_a: Node,
323
+ gm_a: GraphModule,
324
+ gm_b: GraphModule,
325
+ graph_c: Graph,
326
+ ) -> Node:
327
+ """
328
+ Simple copy of node_a to graph_c.
329
+ """
330
+ if node_a.op == 'get_attr':
331
+ node_a_copy_name = \
332
+ get_new_attr_name_with_prefix(node_a.name + '_shadow_copy_')(gm_b)
333
+ node_a_obj = getattr_from_fqn(gm_a, node_a.target) # type: ignore[arg-type]
334
+ if torch.is_tensor(node_a_obj):
335
+ node_a_obj = node_a_obj.detach()
336
+ setattr(gm_b, node_a_copy_name, node_a_obj)
337
+ node_a_copy = graph_c.create_node(
338
+ node_a.op, node_a_copy_name, (), {}, node_a_copy_name)
339
+ return node_a_copy
340
+ elif node_a.op == 'call_method':
341
+ assert node_a.target in ('dequantize', 'to'), \
342
+ f"target {node_a.target} is not implemented"
343
+ if node_a.target == 'dequantize':
344
+ arg_copy = _copy_node_from_a_to_c(
345
+ get_normalized_nth_input(node_a, gm_a, 0),
346
+ gm_a, gm_b, graph_c) # type: ignore[arg-type]
347
+ node_a_copy_name = \
348
+ get_new_attr_name_with_prefix(node_a.name + '_shadow_copy_')(gm_b)
349
+ node_a_copy = graph_c.create_node(
350
+ node_a.op, node_a.target, (arg_copy,), {}, node_a_copy_name)
351
+ return node_a_copy
352
+ else: # to
353
+ arg_copy = _copy_node_from_a_to_c(
354
+ get_normalized_nth_input(node_a, gm_a, 0), gm_a, gm_b, graph_c) # type: ignore[arg-type]
355
+ node_a_copy_name = \
356
+ get_new_attr_name_with_prefix(node_a.name + '_shadow_copy_')(gm_b)
357
+ node_a_copy = graph_c.create_node(
358
+ node_a.op, node_a.target,
359
+ (arg_copy, get_normalized_nth_input(node_a, gm_a, 1)),
360
+ {}, node_a_copy_name)
361
+ return node_a_copy
362
+
363
+ else:
364
+ raise AssertionError(
365
+ f"handling of node {node_a.format_node()} with op {node_a.op} is not implemented")
366
+
367
+ def _can_insert_copy_of_subgraph_a(
368
+ subgraph_a: NSSubgraph,
369
+ gm_a: GraphModule,
370
+ num_non_param_args_node_a: int,
371
+ ) -> bool:
372
+ """
373
+ This function returns `False` if the input subgraph cannot be copied by
374
+ `_insert_copy_of_subgraph_a_after_input_node_c`. This usually means
375
+ that there is a corner case logic for which copy is not yet implemented.
376
+ """
377
+ # populate the list of nodes we need to check
378
+ nodes = []
379
+ cur_node = subgraph_a.end_node
380
+ while cur_node != subgraph_a.start_node:
381
+ nodes.append(cur_node)
382
+ cur_node = get_normalized_nth_input(cur_node, gm_a, 0) # type: ignore[assignment]
383
+ nodes.append(cur_node)
384
+ nodes.reverse()
385
+
386
+ def _can_insert(node_a_arg, gm_a):
387
+ if isinstance(node_a_arg, Node):
388
+ arg_a = return_first_non_observer_node(node_a_arg, gm_a)
389
+ if arg_a.op == 'call_method':
390
+ return arg_a.target in ('dequantize', 'to')
391
+ elif arg_a.op == 'get_attr':
392
+ return True
393
+ else:
394
+ return False
395
+ elif isinstance(node_a_arg, (list, tuple)):
396
+ for el in node_a_arg:
397
+ if not isinstance(el, Node):
398
+ return False
399
+ return True
400
+
401
+ # For each node, check if we handle the copy behavior. This follows the
402
+ # logic in `_insert_copy_of_subgraph_a_after_input_node_c`.
403
+ for node_a in nodes:
404
+
405
+ local_num_non_param_args_node_a = num_non_param_args_node_a \
406
+ if node_a is nodes[0] else 1
407
+
408
+ norm_args_kwargs = node_a.normalized_arguments(
409
+ gm_a, normalize_to_only_use_kwargs=True)
410
+ if norm_args_kwargs is not None:
411
+ norm_args, norm_kwargs = norm_args_kwargs
412
+ else:
413
+ norm_args, norm_kwargs = node_a.args, node_a.kwargs
414
+
415
+ cur_idx = 0
416
+
417
+ while cur_idx < len(norm_args):
418
+ if cur_idx == 0:
419
+ pass
420
+ elif cur_idx == 1 and local_num_non_param_args_node_a == 2:
421
+ pass
422
+ else:
423
+ if not _can_insert(norm_args[cur_idx], gm_a):
424
+ return False
425
+ cur_idx += 1
426
+
427
+ for kwarg_val in norm_kwargs.values():
428
+ # stitch the inputs from base graph
429
+ if cur_idx == 0:
430
+ pass
431
+ elif cur_idx == 1 and local_num_non_param_args_node_a == 2:
432
+ pass
433
+ else:
434
+ if not _can_insert(kwarg_val, gm_a):
435
+ return False
436
+ cur_idx += 1
437
+
438
+ return True
439
+
440
+ def _insert_copy_of_subgraph_a_after_input_node_c(
441
+ input_node_c: Union[Node, List[Node]],
442
+ input_node_c_2: Optional[Union[Node, List[Node]]],
443
+ subgraph_a: NSSubgraph,
444
+ gm_a: GraphModule,
445
+ gm_b: GraphModule,
446
+ node_name_prefix: str,
447
+ ) -> Node:
448
+ """
449
+ TODO(before land): real docblock
450
+ """
451
+ if isinstance(input_node_c, Node):
452
+ graph_c = input_node_c.graph
453
+ else:
454
+ assert isinstance(input_node_c, list)
455
+ graph_c = input_node_c[0].graph
456
+
457
+ # create a sequential list of the subgraphs' nodes from start to end,
458
+ # because we need to add the nodes to graph C in non-reverse order
459
+ nodes_of_a = [subgraph_a.end_node]
460
+ cur_node = subgraph_a.end_node
461
+ while cur_node != subgraph_a.start_node:
462
+ cur_node = get_normalized_nth_input(cur_node, gm_a, 0) # type: ignore[assignment]
463
+ nodes_of_a.insert(0, cur_node)
464
+
465
+ # go through nodes of a in order, and insert them into the graph of c
466
+ # sequentially
467
+ cur_node_a = nodes_of_a[0]
468
+ cur_node_c = _insert_copy_of_node_a_after_input_node_c(
469
+ input_node_c,
470
+ input_node_c_2,
471
+ cur_node_a,
472
+ gm_a,
473
+ gm_b,
474
+ node_name_prefix)
475
+ for cur_idx_a in range(1, len(nodes_of_a)):
476
+ cur_node_a = nodes_of_a[cur_idx_a]
477
+ prev_node_c = cur_node_c # previous added node is the input to next node
478
+ cur_node_c = _insert_copy_of_node_a_after_input_node_c(
479
+ prev_node_c,
480
+ # TODO(future PR): enable multiple inputs for nodes which are not at start of subgraph
481
+ None,
482
+ cur_node_a,
483
+ gm_a,
484
+ gm_b,
485
+ node_name_prefix)
486
+ # return the last inserted node
487
+ return cur_node_c
488
+
489
+
490
+ def _insert_copy_of_node_a_after_input_node_c(
491
+ input_node_c: Union[Node, List[Node]],
492
+ input_node_c_2: Optional[Union[Node, List[Node]]],
493
+ node_a: Node,
494
+ gm_a: GraphModule,
495
+ gm_b: GraphModule,
496
+ node_name_prefix: str,
497
+ ) -> Node:
498
+ """
499
+ Assume that node_a from graph_a has
500
+ args (input, (input2)?, arg1, ...), and
501
+ kwargs {kw0: kwarg0, ...}
502
+
503
+ Note: input2 is optional. If it equals to None, we assume that the op
504
+ has a single non-param input. If it is specified, we assume that the op
505
+ has two non-param inputs.
506
+
507
+ Copies the underlying values of arg1..argn and kwarg0..kwargn into gm_b,
508
+ and creates the corresponding nodes in graph_c. Note: observers are ignored,
509
+ so if an arg is an observer we navigate up until we find a non-observer parent.
510
+
511
+ If node_a is a call_module, points the module pointed to by node_a to gm_b.
512
+
513
+ Creates the copy of node_a in graph_c, with input as the first arg,
514
+ and all other args and kwargs pointing to the copies of the objects
515
+ in gm_b created above.
516
+
517
+ An example in pictures:
518
+
519
+ graph A:
520
+ ========
521
+
522
+ input -------------> node_a
523
+ / / /
524
+ (input_2)?----------/ / /
525
+ / /
526
+ weight -> weight_obs /
527
+ /
528
+ bias ----------------
529
+
530
+ graph C (derived from B):
531
+ =========================
532
+
533
+ input_node_c --> node_a_copy
534
+ / / /
535
+ (input_node_c_2)? / /
536
+ / /
537
+ weight_copy ----/ /
538
+ /
539
+ bias_copy ------/
540
+ """
541
+ if isinstance(input_node_c, Node):
542
+ graph_c = input_node_c.graph
543
+ else:
544
+ assert isinstance(input_node_c, list)
545
+ graph_c = input_node_c[0].graph
546
+
547
+ norm_args_kwargs = node_a.normalized_arguments(
548
+ gm_a, normalize_to_only_use_kwargs=True)
549
+ if norm_args_kwargs is not None:
550
+ norm_args, norm_kwargs = norm_args_kwargs
551
+ else:
552
+ norm_args, norm_kwargs = node_a.args, node_a.kwargs
553
+
554
+ new_args = []
555
+ new_kwargs = {}
556
+
557
+ def _copy_arg(arg):
558
+ # copy the other inputs from the other graph
559
+ if isinstance(arg, Node):
560
+ arg = return_first_non_observer_node(arg, gm_a)
561
+ arg = _copy_node_from_a_to_c(arg, gm_a, gm_b, graph_c)
562
+ return arg
563
+ elif isinstance(arg, (int, float, torch.dtype)):
564
+ return arg
565
+ elif isinstance(kwarg_val, (list, tuple)):
566
+ for el in kwarg_val:
567
+ assert not isinstance(el, Node), \
568
+ "handling of Node inside list is not implemented"
569
+ return arg
570
+ else:
571
+ raise AssertionError(
572
+ f"handling for kwarg of type {type(kwarg_val)} is not implemented")
573
+
574
+ cur_idx = 0
575
+
576
+ while cur_idx < len(norm_args):
577
+ if cur_idx == 0:
578
+ new_arg = input_node_c
579
+ elif cur_idx == 1 and input_node_c_2 is not None:
580
+ new_arg = input_node_c_2
581
+ else:
582
+ new_arg = _copy_arg(norm_args[cur_idx])
583
+ new_args.append(new_arg)
584
+ cur_idx += 1
585
+
586
+ for kwarg_name, kwarg_val in norm_kwargs.items():
587
+ # stitch the inputs from base graph
588
+ if cur_idx == 0:
589
+ new_kwargs[kwarg_name] = input_node_c
590
+ elif cur_idx == 1 and input_node_c_2 is not None:
591
+ new_kwargs[kwarg_name] = input_node_c_2
592
+ else:
593
+ new_kwargs[kwarg_name] = _copy_arg(kwarg_val)
594
+ cur_idx += 1
595
+
596
+ new_args = tuple(new_args) # type: ignore[assignment]
597
+
598
+ node_a_shadows_c_name = \
599
+ get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
600
+
601
+ if node_a.op == 'call_module':
602
+ # if target is a module, we point to the module from gm_b
603
+ new_mod_copy_name = \
604
+ get_new_attr_name_with_prefix(node_name_prefix)(gm_b)
605
+ # fetch the corresponding module from gm_a
606
+ assert isinstance(node_a.target, str)
607
+ mod_a = getattr_from_fqn(gm_a, node_a.target)
608
+ setattr(gm_b, new_mod_copy_name, mod_a)
609
+ node_a_shadows_c = graph_c.create_node(
610
+ node_a.op, new_mod_copy_name, new_args,
611
+ new_kwargs, node_a_shadows_c_name)
612
+ return node_a_shadows_c
613
+ else:
614
+ assert node_a.op in ('call_function', 'call_method')
615
+ node_a_shadows_c = graph_c.create_node(
616
+ node_a.op, node_a.target, new_args,
617
+ new_kwargs, node_a_shadows_c_name)
618
+ return node_a_shadows_c
619
+
620
+ def create_a_shadows_b(
621
+ name_a: str,
622
+ gm_a: GraphModule,
623
+ name_b: str,
624
+ gm_b: GraphModule,
625
+ matched_subgraph_pairs: Dict[str, Tuple[NSSubgraph, NSSubgraph]],
626
+ logger_cls: Callable,
627
+ should_log_inputs: bool,
628
+ node_type_to_io_type_map: Optional[Dict[str, Set[NSNodeTargetType]]] = None,
629
+ ) -> GraphModule:
630
+ """
631
+ Creates a new GraphModule consisting of the graph of C, with the meaningful
632
+ nodes of A shadowing the corresponding nodes of B. For example,
633
+
634
+ Graph A:
635
+ a0 -> op0_fp32 -> a1 -> op1_fp32 -> a2
636
+
637
+ Graph B:
638
+ b0 -> op0_int8 -> b1 -> op1_int8 -> b2
639
+
640
+ matched_node_pairs: {'op0': (op0_fp32, op0_int8), 'op1': (op1_fp32, op1_int8)}
641
+
642
+ Graph C (A shadows B):
643
+
644
+ / dequant0 -> op0_fp32 -> logger_a_0 / dequant_1 -> op1_fp32 -> logger_a_1
645
+ / /
646
+ b0 -------------> op0_int8 -> logger_b_0 --------------> op1_int8 -> logger_b_1
647
+
648
+ In a nutshell, this function does the following for each node pair:
649
+ * copies the necessary attributes and modules from gm_a to gm_b,
650
+ keeping names unique
651
+ * adds a dtype cast op (dequant, quant, etc)
652
+ * adds a copy of node_a in gm_b's graph
653
+ * adds loggers to the outputs of node_a and node_b
654
+ """
655
+
656
+ if node_type_to_io_type_map is None:
657
+ node_type_to_io_type_map = get_node_type_to_io_type_map()
658
+
659
+ # graph_c is the graph created from copying the nodes of graph_b and inserting
660
+ # the shadows with the nodes copied from graph_a
661
+ graph_c = Graph()
662
+ env_c: Dict[str, Any] = {}
663
+ modules = dict(gm_b.named_modules())
664
+
665
+ def load_arg(a):
666
+ return map_arg(a, lambda node: env_c[node.name])
667
+
668
+ start_node_b_to_matched_subgraph_a_and_name = {}
669
+ end_node_b_to_matched_subgraph_a_and_name = {}
670
+ for match_name, match in matched_subgraph_pairs.items():
671
+ subgraph_a, subgraph_b = match
672
+ ref_node_type_a = get_target_type_str(subgraph_a.base_op_node, gm_a)
673
+ ref_node_type_b = get_target_type_str(subgraph_b.base_op_node, gm_b)
674
+ start_node_b_to_matched_subgraph_a_and_name[subgraph_b.start_node] = \
675
+ (subgraph_a, match_name, ref_node_type_a, ref_node_type_b)
676
+ end_node_b_to_matched_subgraph_a_and_name[subgraph_b.end_node] = \
677
+ (subgraph_a, match_name, ref_node_type_a, ref_node_type_b)
678
+
679
+ for node_b in gm_b.graph.nodes:
680
+ if node_b.op == 'output':
681
+ graph_c.output(map_arg(node_b.args[0], load_arg))
682
+ continue
683
+
684
+ # calculate the flags to determine what to do with this node
685
+ node_b_is_start_node = node_b in start_node_b_to_matched_subgraph_a_and_name
686
+ node_b_is_end_node = node_b in end_node_b_to_matched_subgraph_a_and_name
687
+
688
+ if (node_b_is_start_node or node_b_is_end_node):
689
+
690
+ if node_b_is_start_node:
691
+ subgraph_a, ref_name, ref_node_type_a, ref_node_type_b = \
692
+ start_node_b_to_matched_subgraph_a_and_name[node_b]
693
+ else:
694
+ assert node_b_is_end_node
695
+ subgraph_a, ref_name, ref_node_type_a, ref_node_type_b = \
696
+ end_node_b_to_matched_subgraph_a_and_name[node_b]
697
+
698
+ all_op_types_support_shadowing = (
699
+ op_type_supports_shadowing(subgraph_a.start_node) and
700
+ op_type_supports_shadowing(node_b)
701
+ )
702
+ if not all_op_types_support_shadowing:
703
+ print(
704
+ f'skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}' +
705
+ f', start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}' +
706
+ ', unsupported')
707
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
708
+ continue
709
+
710
+ # For both start_node and end_node verify that we know how to do
711
+ # the dtype cast. If we do not, skip.
712
+ node_input_type_a, node_output_type_a = \
713
+ get_node_first_input_and_output_type(
714
+ subgraph_a.start_node, gm_a, logger_cls,
715
+ node_type_to_io_type_map)
716
+ node_input_type_b, node_output_type_b = \
717
+ get_node_first_input_and_output_type(
718
+ node_b, gm_b, logger_cls,
719
+ node_type_to_io_type_map)
720
+ node_io_types_known_a_and_b = (
721
+ node_input_type_a != NodeInputOrOutputType.UNKNOWN and
722
+ node_output_type_a != NodeInputOrOutputType.UNKNOWN and
723
+ node_input_type_b != NodeInputOrOutputType.UNKNOWN and
724
+ node_output_type_b != NodeInputOrOutputType.UNKNOWN
725
+ )
726
+ if not node_io_types_known_a_and_b:
727
+ print(
728
+ f'skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}' +
729
+ f', start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}' +
730
+ ', unknown dtype cast')
731
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
732
+ continue
733
+
734
+ # If we are shadowing from fp32 to int8, we need to insert
735
+ # quantize_per_tensor call with qparams from the previous node.
736
+ # Only do this if we are able to infer these qparams from the graph.
737
+ if (
738
+ node_input_type_a == NodeInputOrOutputType.INT8 and
739
+ node_input_type_b == NodeInputOrOutputType.FP32
740
+ ):
741
+ node_a_input_qparams = get_node_input_qparams(
742
+ subgraph_a.start_node, gm_a, node_type_to_io_type_map)
743
+ if not node_a_input_qparams:
744
+ print(
745
+ f'skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}' +
746
+ f', start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}' +
747
+ ', unknown input qparams')
748
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
749
+ continue
750
+
751
+ num_non_param_args_node_a = \
752
+ get_number_of_non_param_args(subgraph_a.start_node, gm_a)
753
+ if not _can_insert_copy_of_subgraph_a(subgraph_a, gm_a, num_non_param_args_node_a):
754
+ print(
755
+ f'skipping shadow loggers for node_b: {get_target_type_str(node_b, gm_b)}' +
756
+ f', start_node_a: {get_target_type_str(subgraph_a.start_node, gm_a)}' +
757
+ ', unhandled logic in subgraph copy')
758
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
759
+ continue
760
+
761
+ fqn_base_a = _maybe_get_fqn(subgraph_a.base_op_node, gm_a)
762
+ fqn_base_b = _maybe_get_fqn(subgraph_b.base_op_node, gm_b)
763
+
764
+ if node_b_is_start_node:
765
+
766
+ # if necessary, log the input of node_c
767
+ if should_log_inputs:
768
+ prev_node_b = get_normalized_nth_input(node_b, gm_b, 0)
769
+ if isinstance(prev_node_b, Node):
770
+ prev_node_c = env_c[prev_node_b.name]
771
+ env_c[prev_node_c.name] = _insert_logger_after_node(
772
+ prev_node_c, gm_b, logger_cls, '_ns_logger_b_inp_',
773
+ node_b.name, name_b, ref_name, ref_node_type_b,
774
+ NSSingleResultValuesType.NODE_INPUT.value,
775
+ index_within_arg=0, index_of_arg=0,
776
+ fqn=fqn_base_b)
777
+ elif isinstance(prev_node_b, list):
778
+ # first, save the prev_node instances, because they
779
+ # will be overwritten in the env after the first logger
780
+ # is added
781
+ prev_node_c_list = [env_c[arg.name] for arg in prev_node_b]
782
+
783
+ for arg_idx, arg in enumerate(prev_node_b):
784
+ prev_node_c = prev_node_c_list[arg_idx]
785
+ env_c[prev_node_c.name] = _insert_logger_after_node(
786
+ prev_node_c, gm_b, logger_cls, '_ns_logger_b_inp_',
787
+ node_b.name, name_b, ref_name, ref_node_type_b,
788
+ NSSingleResultValuesType.NODE_INPUT.value,
789
+ index_within_arg=arg_idx, index_of_arg=0,
790
+ fqn=fqn_base_b)
791
+ else:
792
+ # logging of inputs which are not lists is not supported yet
793
+ raise AssertionError(f"type {type(prev_node_b)} is not handled yet")
794
+ # subgraph so far:
795
+ #
796
+ # (prev_node_c)+ -> (logger_c_input)?
797
+
798
+ # Note: this if statement is always True, spelling it out to clarify code
799
+ # intent.
800
+ if node_b_is_start_node or node_b_is_end_node:
801
+ # ensure env_c is populated with base node
802
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
803
+ node_c = env_c[node_b.name]
804
+
805
+ # after this point,
806
+ #
807
+ # node_a is the original node from graph_a, with parent module gm_a
808
+ # node_b is the original node from graph_b, with parent module gm_b
809
+ # node_c is the copy of node_b in graph_c
810
+ #
811
+ # subgraph so far:
812
+ #
813
+ # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
814
+
815
+ if node_b_is_start_node:
816
+
817
+ # cast dtype from the dtype of node_c's input to the dtype of
818
+ # node_a's input (dequant, etc)
819
+ # prev_node_c = node_c.args[0]
820
+ prev_node_c = get_normalized_nth_input(node_c, gm_b, 0)
821
+ if should_log_inputs:
822
+ # skip the input logger when inserting a dtype cast
823
+ if isinstance(prev_node_c, Node):
824
+ prev_node_c = get_normalized_nth_input(node_c, gm_b, 0)
825
+ elif isinstance(prev_node_c, list):
826
+ prev_node_c = [get_normalized_nth_input(arg, gm_b, 0) for arg in prev_node_c]
827
+ dtype_cast_node = _insert_dtype_cast_after_node(
828
+ subgraph_a.start_node, node_c, prev_node_c, gm_a, gm_b, graph_c,
829
+ node_b.name + '_dtype_cast_', logger_cls,
830
+ node_type_to_io_type_map)
831
+ # note: not inserting to env_c because all nodes which use the dtype
832
+ # casts are copied from graph_a
833
+ #
834
+ # subgraph so far:
835
+ #
836
+ # (dtype_cast_node)+
837
+ # /
838
+ # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
839
+
840
+ # if input logging is enabled, log the input to the subgraph
841
+ if should_log_inputs:
842
+ # TODO: explain this
843
+ ref_node_name = ''
844
+ if isinstance(dtype_cast_node, Node):
845
+ dtype_cast_node = _insert_logger_after_node(
846
+ dtype_cast_node, gm_b, logger_cls, '_ns_logger_a_inp_',
847
+ ref_node_name, name_a, ref_name, ref_node_type_a,
848
+ NSSingleResultValuesType.NODE_INPUT.value,
849
+ index_within_arg=0, index_of_arg=0,
850
+ fqn=fqn_base_a)
851
+ input_logger: Union[Node, List[Node]] = dtype_cast_node
852
+ else:
853
+ assert isinstance(dtype_cast_node, list)
854
+ new_loggers = []
855
+ for dtype_cast_idx, dtype_cast_node_inner in enumerate(dtype_cast_node):
856
+ dtype_cast_logger = _insert_logger_after_node(
857
+ dtype_cast_node_inner, gm_b, logger_cls, '_ns_logger_a_inp_',
858
+ ref_node_name, name_a, ref_name, ref_node_type_a,
859
+ NSSingleResultValuesType.NODE_INPUT.value,
860
+ index_within_arg=dtype_cast_idx,
861
+ index_of_arg=0,
862
+ fqn=fqn_base_a)
863
+ new_loggers.append(dtype_cast_logger)
864
+ dtype_cast_node = new_loggers
865
+ input_logger = dtype_cast_node
866
+ # subgraph so far:
867
+ #
868
+ # (dtype_cast_node)+ -> (logger_a_input)?
869
+ # /
870
+ # prev_node_c -> (logger_c_input)? -> node_start_c
871
+
872
+ # hook up the new mod_a copy to be in the graph, receiving the
873
+ # same inputs as mod_b does, with dtype cast to match a
874
+ # Some ops, such as LSTMs, have two non-param inputs. If we have
875
+ # such an op, pass the second param as well. Note: dtype casting
876
+ # for the second param is not implemented yet, it can be added
877
+ # later if there is a use case.
878
+ node_c_second_non_param_arg = None
879
+ num_non_param_args_node_a = get_number_of_non_param_args(subgraph_a.start_node, gm_a)
880
+ if num_non_param_args_node_a == 2:
881
+ # node_c_second_non_param_arg = node_c.args[1]
882
+ node_c_second_non_param_arg = get_normalized_nth_input(node_c, gm_b, 1)
883
+ node_a_shadows_c = _insert_copy_of_subgraph_a_after_input_node_c(
884
+ dtype_cast_node, node_c_second_non_param_arg,
885
+ subgraph_a, gm_a, gm_b, node_c.name + '_shadow_copy_')
886
+ env_c[node_a_shadows_c.name] = node_a_shadows_c
887
+ # subgraph so far:
888
+ #
889
+ # dtype_cast_node -> (logger_a_input)? -> subgraph_a_copy(args/kwargs not shown)
890
+ # /
891
+ # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
892
+
893
+ if should_log_inputs:
894
+ # When we created the input logger, we left the ref_node_name
895
+ # as an empty string, because the subgraph copy did not exist
896
+ # yet. Now that the subgraph copy exists, we modify this name
897
+ # to its true value.
898
+ # Note: the alternative to this is to create the input logger
899
+ # after creating the subgraph, which is slightly more
900
+ # complicated. This is the lesser of two evils.
901
+ # input_logger = env_c[dtype_cast_node.name]
902
+ # Find the first node in the subgraph
903
+ cur_node = node_a_shadows_c
904
+ while get_normalized_nth_input(cur_node, gm_b, 0) != input_logger:
905
+ cur_node = get_normalized_nth_input(cur_node, gm_b, 0) # type: ignore[assignment]
906
+ if isinstance(input_logger, Node):
907
+ input_logger_mod = getattr(gm_b, input_logger.name)
908
+ input_logger_mod.ref_node_name = cur_node.name
909
+ else:
910
+ assert isinstance(input_logger, list)
911
+ for input_logger_inner in input_logger:
912
+ input_logger_mod = getattr(gm_b, input_logger_inner.name)
913
+ input_logger_mod.ref_node_name = cur_node.name
914
+
915
+ # hook up a logger to the mod_a copy
916
+ env_c[node_a_shadows_c.name] = _insert_logger_after_node(
917
+ env_c[node_a_shadows_c.name], gm_b, logger_cls, '_ns_logger_a_',
918
+ node_a_shadows_c.name, name_a, ref_name, ref_node_type_a,
919
+ NSSingleResultValuesType.NODE_OUTPUT.value,
920
+ index_within_arg=0, index_of_arg=0,
921
+ fqn=fqn_base_a)
922
+ # subgraph so far:
923
+ #
924
+ # dtype_cast_node -> (logger_a_input)? -> subgraph_a_copy -> logger_a
925
+ # /
926
+ # (prev_node_c)+ -> (logger_c_input)? -> node_start_c
927
+
928
+ if node_b_is_end_node:
929
+
930
+ # hook up a logger to the mod_b copy
931
+ env_c[node_b.name] = _insert_logger_after_node(
932
+ env_c[node_b.name], gm_b, logger_cls, '_ns_logger_b_',
933
+ node_b.name, name_b, ref_name, ref_node_type_b,
934
+ NSSingleResultValuesType.NODE_OUTPUT.value,
935
+ index_within_arg=0, index_of_arg=0,
936
+ fqn=fqn_base_b)
937
+ # subgraph so far:
938
+ #
939
+ # dtype_cast_node -> (logger_a_input)? -> subgraph_a_copy -> logger_a
940
+ # /
941
+ # (prev_node_c+) -> (logger_c_input)? -> node_start_c -> ... -> node_end_c -> logger_c
942
+ #
943
+ # Note: node_start_c may be the same node as node_end_c, or they
944
+ # may have nodes inbetween.
945
+
946
+ else:
947
+ env_c[node_b.name] = graph_c.node_copy(node_b, load_arg)
948
+
949
+ gm_c = GraphModule(gm_b, graph_c)
950
+ return gm_c
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/mappings.py ADDED
@@ -0,0 +1,761 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ toq = torch.ops.quantized
7
+
8
+ import torch.ao.nn.quantized as nnq
9
+ import torch.ao.nn.quantized.dynamic as nnqd
10
+ import torch.ao.nn.intrinsic.quantized as nniq
11
+ import torch.ao.nn.intrinsic.quantized.dynamic as nniqd
12
+ import torch.ao.nn.intrinsic.qat as nniqat
13
+ import torch.ao.nn.intrinsic as nni
14
+ import torch.ao.nn.qat as nnqat
15
+ import torch.ao.nn.qat.dynamic as nnqatd
16
+ from torch.ao.quantization.backend_config import get_native_backend_config
17
+ import torch.ao.quantization.fx._lower_to_native_backend as \
18
+ _lower_to_native_backend
19
+ import torch.ao.quantization.quantization_mappings as quantization_mappings
20
+
21
+ from .ns_types import NSNodeTargetType
22
+
23
+ from typing import Callable, Dict, List, Optional, Set, Tuple
24
+
25
+
26
+ def get_base_name_to_sets_of_related_ops() -> Dict[str, Set[NSNodeTargetType]]:
27
+ # note: this set is modified below by items from backend_config
28
+ sets_of_related_ops: List[Set[NSNodeTargetType]] = [
29
+ # conv modules
30
+ {
31
+ nn.Conv1d,
32
+ },
33
+ {
34
+ nn.Conv2d,
35
+ },
36
+ {
37
+ nn.Conv3d,
38
+ },
39
+ # conv functionals
40
+ {
41
+ F.conv1d,
42
+ },
43
+ {
44
+ F.conv2d,
45
+ },
46
+ {
47
+ F.conv3d,
48
+ },
49
+ # linear modules
50
+ {
51
+ nn.Linear,
52
+ },
53
+ # linear functionals
54
+ {
55
+ F.linear,
56
+ },
57
+ # average pool
58
+ {
59
+ nn.AvgPool1d,
60
+ torch.avg_pool1d,
61
+ },
62
+ {
63
+ nn.AvgPool2d,
64
+ torch._C._nn.avg_pool2d,
65
+ },
66
+ {
67
+ nn.AvgPool3d,
68
+ torch._C._nn.avg_pool3d,
69
+ },
70
+ # adaptive average pool
71
+ {
72
+ nn.AdaptiveAvgPool1d,
73
+ F.adaptive_avg_pool1d,
74
+ },
75
+ {
76
+ nn.AdaptiveAvgPool2d,
77
+ F.adaptive_avg_pool2d,
78
+ },
79
+ {
80
+ nn.AdaptiveAvgPool3d,
81
+ F.adaptive_avg_pool3d,
82
+ },
83
+ # LSTM
84
+ {
85
+ nn.LSTM,
86
+ },
87
+ # add
88
+ {
89
+ torch.add,
90
+ operator.add, # x + y
91
+ },
92
+ # cat
93
+ {
94
+ torch.cat,
95
+ },
96
+ # mul
97
+ {
98
+ torch.mul,
99
+ operator.mul,
100
+ },
101
+ # relu
102
+ {
103
+ F.relu,
104
+ nn.ReLU,
105
+ 'relu',
106
+ 'relu_',
107
+ torch.relu,
108
+ },
109
+ # maxpool
110
+ {
111
+ nn.MaxPool1d,
112
+ F.max_pool1d,
113
+ },
114
+ {
115
+ nn.MaxPool2d,
116
+ F.max_pool2d,
117
+ },
118
+ {
119
+ nn.MaxPool3d,
120
+ F.max_pool3d,
121
+ },
122
+ # sigmoid
123
+ {
124
+ torch.sigmoid,
125
+ 'sigmoid',
126
+ 'sigmoid_',
127
+ nn.Sigmoid,
128
+ F.sigmoid,
129
+ },
130
+ # BatchNorm
131
+ {
132
+ nn.BatchNorm2d,
133
+ },
134
+ {
135
+ nn.BatchNorm3d,
136
+ },
137
+ # ConvTranspose
138
+ {
139
+ nn.ConvTranspose1d,
140
+ },
141
+ {
142
+ nn.ConvTranspose2d,
143
+ },
144
+ {
145
+ nn.ConvTranspose3d,
146
+ },
147
+ # functional transposed conv
148
+ {
149
+ F.conv_transpose1d,
150
+ },
151
+ {
152
+ F.conv_transpose2d,
153
+ },
154
+ {
155
+ F.conv_transpose3d,
156
+ },
157
+ # ELU
158
+ {
159
+ nn.ELU,
160
+ },
161
+ # Embedding
162
+ {
163
+ nn.Embedding,
164
+ },
165
+ # EmbeddingBag
166
+ {
167
+ nn.EmbeddingBag,
168
+ },
169
+ # GroupNorm
170
+ {
171
+ nn.GroupNorm,
172
+ },
173
+ # Hardswish
174
+ {
175
+ nn.Hardswish,
176
+ },
177
+ # InstanceNorm
178
+ {
179
+ nn.InstanceNorm1d,
180
+ },
181
+ {
182
+ nn.InstanceNorm2d,
183
+ },
184
+ {
185
+ nn.InstanceNorm3d,
186
+ },
187
+ # LayerNorm
188
+ {
189
+ nn.LayerNorm,
190
+ },
191
+ # LeakyReLU
192
+ {
193
+ nn.LeakyReLU,
194
+ },
195
+ # ReLU6
196
+ {
197
+ nn.ReLU6,
198
+ F.relu6,
199
+ },
200
+ # F.elu
201
+ {
202
+ F.elu,
203
+ },
204
+ # F.hardswish
205
+ {
206
+ F.hardswish,
207
+ },
208
+ # F.group_norm
209
+ {
210
+ F.group_norm,
211
+ },
212
+ # F.instance_norm
213
+ {
214
+ F.instance_norm,
215
+ },
216
+ # F.layer_norm
217
+ {
218
+ F.layer_norm,
219
+ },
220
+ # F.leaky_relu
221
+ {
222
+ F.leaky_relu,
223
+ },
224
+ # F.silu
225
+ {
226
+ nn.SiLU,
227
+ F.silu,
228
+ },
229
+ # F.mish
230
+ {
231
+ nn.Mish,
232
+ F.mish,
233
+ },
234
+ # F.tanh
235
+ {
236
+ nn.Tanh,
237
+ F.tanh,
238
+ torch.tanh,
239
+ 'tanh_',
240
+ 'tanh',
241
+ },
242
+ # F.hardsigmoid
243
+ {
244
+ 'hardsigmoid_',
245
+ 'hardsigmoid',
246
+ F.hardsigmoid,
247
+ nn.Hardsigmoid,
248
+ },
249
+ # F.hardtanh
250
+ {
251
+ nn.Hardtanh,
252
+ F.hardtanh,
253
+ F.hardtanh_,
254
+ },
255
+ # floordiv
256
+ {
257
+ operator.floordiv,
258
+ },
259
+ # unsqueeze
260
+ {
261
+ torch.unsqueeze,
262
+ },
263
+ # stack
264
+ {
265
+ torch.stack,
266
+ },
267
+ # squeeze
268
+ {
269
+ torch.squeeze,
270
+ },
271
+ # sort
272
+ {
273
+ torch.sort,
274
+ },
275
+ # repeat_interleave
276
+ {
277
+ torch.repeat_interleave,
278
+ },
279
+ # min
280
+ {
281
+ torch.min,
282
+ },
283
+ # mean
284
+ {
285
+ torch.mean,
286
+ },
287
+ # max
288
+ {
289
+ torch.max,
290
+ },
291
+ # transpose
292
+ {
293
+ torch.transpose,
294
+ },
295
+ # flatten
296
+ {
297
+ torch.flatten,
298
+ },
299
+ # clamp
300
+ {
301
+ torch.clamp,
302
+ },
303
+ # chunk
304
+ {
305
+ torch.chunk,
306
+ },
307
+ # interpolate
308
+ {
309
+ torch.nn.functional.interpolate,
310
+ },
311
+ # dropout
312
+ {
313
+ nn.Dropout,
314
+ },
315
+ # F.dropout
316
+ {
317
+ F.dropout,
318
+ },
319
+ # matmul
320
+ {
321
+ torch.matmul,
322
+ },
323
+ # Softmax
324
+ {
325
+ nn.Softmax,
326
+ },
327
+ # PReLU
328
+ {
329
+ nn.PReLU,
330
+ nnq.PReLU,
331
+ },
332
+ # F.prelu
333
+ {
334
+ F.prelu,
335
+ toq.prelu,
336
+ },
337
+ # pixel shuffle
338
+ {
339
+ nn.PixelShuffle,
340
+ },
341
+ {
342
+ F.pixel_shuffle,
343
+ },
344
+ # pixel unshuffle
345
+ {
346
+ nn.PixelUnshuffle,
347
+ },
348
+ {
349
+ F.pixel_unshuffle,
350
+ },
351
+ # narrow
352
+ {
353
+ torch.narrow,
354
+ },
355
+ ]
356
+
357
+ # for each floating point op, add versions of the op added by
358
+ # backend_config
359
+ backend_config = get_native_backend_config()
360
+
361
+ new_connections: List[Tuple[Callable, Callable]] = [
362
+ # technical debt edge case
363
+ (nn.Linear, nn.modules.linear.NonDynamicallyQuantizableLinear),
364
+ ]
365
+
366
+ for pattern, config in backend_config._pattern_complex_format_to_config.items():
367
+
368
+ # pattern format: (c, (b, a))
369
+ first_element = pattern
370
+ # look from the end, because pattern is in reverse order
371
+ while isinstance(first_element, (list, tuple)):
372
+ first_element = first_element[-1]
373
+
374
+ if config.fused_module is not None:
375
+ # case 1: pattern fuses a pattern of ops into an op
376
+ # example: nn.Conv1d, nn.ReLU fused into nni.ConvReLU1d
377
+ new_connections.append((first_element, config.fused_module))
378
+
379
+ if config.qat_module is not None:
380
+ # case 2: pattern swaps a module into a QAT module
381
+ # example: nni.ConvReLU1d swapped into nniqat.ConvReLU1d
382
+ new_connections.append((first_element, config.qat_module))
383
+
384
+ if config.reference_quantized_module is not None:
385
+ # case 3: reference version of floating point module, such as
386
+ # nn.Conv2d and nnqr.Conv2d
387
+ new_connections.append((first_element, config.reference_quantized_module))
388
+
389
+ #
390
+ # Add reference module swaps from default lowering path
391
+ #
392
+
393
+ for source_to_target in (
394
+ _lower_to_native_backend.STATIC_LOWER_MODULE_MAP,
395
+ _lower_to_native_backend.DYNAMIC_LOWER_MODULE_MAP,
396
+ _lower_to_native_backend.WEIGHT_ONLY_LOWER_MODULE_MAP,
397
+ _lower_to_native_backend.SPECIAL_PATTERN_LOWER_MODULE_MAP,
398
+ ):
399
+ for source, target in source_to_target.items(): # type: ignore[attr-defined]
400
+ new_connections.append((source, target))
401
+
402
+ for source_to_double_target in (
403
+ _lower_to_native_backend.STATIC_LOWER_FUSED_MODULE_MAP,
404
+ _lower_to_native_backend.STATIC_LOWER_FUSED_MODULE_TWO_INPUTS_MAP,
405
+ _lower_to_native_backend.DYNAMIC_LOWER_FUSED_MODULE_MAP,
406
+ ):
407
+ for source, (target1, target2) in source_to_double_target.items(): # type: ignore[attr-defined]
408
+ new_connections.append((source, target1))
409
+ new_connections.append((source, target2))
410
+
411
+ #
412
+ # Add function swaps from default lowering path
413
+ #
414
+
415
+ for source, (target1, target2) in \
416
+ _lower_to_native_backend.STATIC_LOWER_FUNCTIONAL_MAP.items():
417
+ new_connections.append((source, target1))
418
+ new_connections.append((source, target2))
419
+
420
+ for source_to_target in (
421
+ _lower_to_native_backend.QBIN_OP_MAPPING,
422
+ _lower_to_native_backend.QBIN_RELU_OP_MAPPING,
423
+ quantization_mappings.DEFAULT_FLOAT_TO_QUANTIZED_OPERATOR_MAPPINGS,
424
+ ):
425
+ for source, target in source_to_target.items():
426
+ new_connections.append((source, target))
427
+
428
+ #
429
+ # Add other swaps, ideally in the future this could be removed
430
+ # after the lowering code stops using these.
431
+ #
432
+ for source_to_target in (
433
+ quantization_mappings.DEFAULT_DYNAMIC_QUANT_MODULE_MAPPINGS,
434
+ ):
435
+ for source, target in source_to_target.items():
436
+ new_connections.append((source, target))
437
+
438
+
439
+ # add the new connections from backend_config
440
+ for item1, item2 in new_connections:
441
+ for set_of_related_ops in sets_of_related_ops:
442
+ if item1 in set_of_related_ops or item2 in set_of_related_ops:
443
+ set_of_related_ops.add(item1)
444
+ set_of_related_ops.add(item2)
445
+ break
446
+
447
+ base_name_to_sets_of_related_ops: Dict[str, Set[NSNodeTargetType]] = {}
448
+
449
+ counter = 0
450
+ for set_of_related_ops in sets_of_related_ops:
451
+ base_name = str(counter)
452
+ counter += 1
453
+ base_name_to_sets_of_related_ops[base_name] = set_of_related_ops
454
+
455
+ return base_name_to_sets_of_related_ops
456
+
457
+
458
+ def get_base_name_for_op(
459
+ base_name_to_sets_of_related_ops: Dict[str, Set[NSNodeTargetType]],
460
+ op: NSNodeTargetType,
461
+ ) -> Optional[str]:
462
+ for base_name, set_of_related_ops in base_name_to_sets_of_related_ops.items():
463
+ if op in set_of_related_ops:
464
+ return base_name
465
+ return None
466
+
467
+
468
+ def add_op_to_sets_of_related_ops(
469
+ base_name_to_sets_of_related_ops: Dict[str, Set[NSNodeTargetType]],
470
+ op: NSNodeTargetType,
471
+ related_op: Optional[NSNodeTargetType],
472
+ ) -> None:
473
+ if related_op is not None:
474
+ for set_of_related_ops in base_name_to_sets_of_related_ops.values():
475
+ if related_op in set_of_related_ops:
476
+ set_of_related_ops.add(op)
477
+ return
478
+ # if we got here, related_op was not found
479
+ raise AssertionError(f"{related_op} was not found")
480
+ else:
481
+ counter = 0
482
+ while str(counter) in base_name_to_sets_of_related_ops:
483
+ counter += 1
484
+ base_name_to_sets_of_related_ops[str(counter)] = {op}
485
+
486
+
487
+ # TODO(future PR): clean this up
488
+ def get_node_type_to_io_type_map() -> Dict[str, Set[NSNodeTargetType]]:
489
+ FUNS_IO_TYPE_FP32: Set[NSNodeTargetType] = {
490
+ F.linear,
491
+ F.conv1d,
492
+ F.conv2d,
493
+ F.conv3d,
494
+ torch.cat,
495
+ F.elu,
496
+ F.hardswish,
497
+ F.instance_norm,
498
+ F.layer_norm,
499
+ F.leaky_relu,
500
+ F.dropout,
501
+ F.silu,
502
+ F.mish,
503
+ operator.add,
504
+ torch.add,
505
+ operator.mul,
506
+ torch.mul,
507
+ torch.sum,
508
+ F.prelu,
509
+ }
510
+
511
+ FUNS_IO_TYPE_FP16: Set[NSNodeTargetType] = set()
512
+
513
+ FUNS_IO_TYPE_INT8: Set[NSNodeTargetType] = {
514
+ toq.linear,
515
+ toq.linear_relu,
516
+ toq.conv1d,
517
+ toq.conv1d_relu,
518
+ toq.conv2d,
519
+ toq.conv2d_relu,
520
+ toq.conv3d,
521
+ toq.conv3d_relu,
522
+ toq.cat,
523
+ toq.elu,
524
+ toq.hardswish,
525
+ toq.instance_norm,
526
+ toq.layer_norm,
527
+ toq.leaky_relu,
528
+ toq.dropout,
529
+ toq.prelu,
530
+ # TODO(future PR): implement shadowing for binary ops and
531
+ # uncomment below
532
+ # toq.add,
533
+ # toq.mul,
534
+ }
535
+
536
+ FUNS_IO_TYPE_FP32_OR_INT8: Set[NSNodeTargetType] = {
537
+ F.relu,
538
+ F.tanh,
539
+ torch.tanh,
540
+ F.sigmoid,
541
+ torch.sigmoid,
542
+ F.hardsigmoid,
543
+ operator.floordiv,
544
+ torch.adaptive_avg_pool1d,
545
+ F.adaptive_avg_pool2d,
546
+ F.adaptive_avg_pool3d,
547
+ F.dropout,
548
+ F.hardtanh,
549
+ F.hardtanh_,
550
+ F.interpolate,
551
+ F.max_pool1d,
552
+ F.max_pool2d,
553
+ F.max_pool3d,
554
+ F.relu6,
555
+ F.pixel_shuffle,
556
+ F.pixel_unshuffle,
557
+ torch.avg_pool1d,
558
+ torch._C._nn.avg_pool2d,
559
+ torch._C._nn.avg_pool3d,
560
+ torch.cat,
561
+ torch.chunk,
562
+ torch.clamp,
563
+ torch.flatten,
564
+ torch.transpose,
565
+ torch.max,
566
+ torch.mean,
567
+ torch.min,
568
+ torch.narrow,
569
+ torch.repeat_interleave,
570
+ torch.sort,
571
+ torch.squeeze,
572
+ torch.stack,
573
+ torch.unsqueeze,
574
+ operator.add,
575
+ }
576
+
577
+ MODS_IO_TYPE_FP32: Set[NSNodeTargetType] = {
578
+ nn.Linear,
579
+ nnqat.Linear,
580
+ nnqatd.Linear,
581
+ nnqd.Linear,
582
+ torch.nn.modules.linear.NonDynamicallyQuantizableLinear,
583
+ nn.Conv1d,
584
+ nn.Conv2d,
585
+ nn.Conv3d,
586
+ nnqat.Conv1d,
587
+ nnqat.Conv2d,
588
+ nnqat.Conv3d,
589
+ nnqat.Embedding,
590
+ nnqat.EmbeddingBag,
591
+ nn.LSTM,
592
+ # note: nnqd.Linear is an instance of nnq.Linear, so this
593
+ # check has to happen before the int8 module check
594
+ nnqd.LSTM,
595
+ nn.BatchNorm2d,
596
+ nn.BatchNorm3d,
597
+ nn.Dropout,
598
+ nn.ConvTranspose1d,
599
+ nn.ConvTranspose2d,
600
+ nn.ConvTranspose3d,
601
+ nn.ELU,
602
+ nn.GroupNorm,
603
+ nn.InstanceNorm1d,
604
+ nn.InstanceNorm2d,
605
+ nn.InstanceNorm3d,
606
+ nn.LayerNorm,
607
+ nn.Hardswish,
608
+ nn.LeakyReLU,
609
+ nn.ReLU6,
610
+ nn.SiLU,
611
+ nn.Mish,
612
+ nn.Softmax,
613
+ nn.PReLU,
614
+ nni.BNReLU2d,
615
+ nni.BNReLU3d,
616
+ nni.ConvReLU1d,
617
+ nni.ConvReLU2d,
618
+ nni.ConvReLU3d,
619
+ nni.LinearReLU,
620
+ nni.LinearBn1d,
621
+ nni.ConvBn1d,
622
+ nni.ConvBn2d,
623
+ nni.ConvBn3d,
624
+ nniqat.ConvBn1d,
625
+ nniqat.ConvBn2d,
626
+ nniqat.ConvBn3d,
627
+ nniqat.ConvBnReLU1d,
628
+ nniqat.ConvBnReLU2d,
629
+ nniqat.ConvBnReLU3d,
630
+ nniqat.ConvReLU1d,
631
+ nniqat.ConvReLU2d,
632
+ nniqat.ConvReLU3d,
633
+ nniqat.LinearReLU,
634
+ nniqat.LinearBn1d,
635
+ nniqd.LinearReLU,
636
+ nni.LinearLeakyReLU,
637
+ nni.LinearTanh,
638
+ nni.ConvAdd2d,
639
+ nni.ConvAddReLU2d,
640
+ }
641
+
642
+ MODS_IO_TYPE_INT8: Set[NSNodeTargetType] = {
643
+ nnq.Linear,
644
+ nnq.Conv1d,
645
+ nnq.Conv2d,
646
+ nnq.Conv3d,
647
+ nnq.BatchNorm2d,
648
+ nnq.BatchNorm3d,
649
+ nnq.Dropout,
650
+ nnq.ConvTranspose1d,
651
+ nnq.ConvTranspose2d,
652
+ nnq.ELU,
653
+ nnq.InstanceNorm1d,
654
+ nnq.InstanceNorm2d,
655
+ nnq.InstanceNorm3d,
656
+ nnq.LayerNorm,
657
+ nnq.Hardswish,
658
+ nnq.LeakyReLU,
659
+ nnq.Embedding,
660
+ nnq.EmbeddingBag,
661
+ nnq.Dropout,
662
+ nnq.Softmax,
663
+ nnq.PReLU,
664
+ nniq.BNReLU2d,
665
+ nniq.BNReLU3d,
666
+ nniq.ConvReLU1d,
667
+ nniq.ConvReLU2d,
668
+ nniq.ConvReLU3d,
669
+ nniq.LinearReLU,
670
+ nniq.LinearLeakyReLU,
671
+ nniq.LinearTanh,
672
+ nniq.ConvAdd2d,
673
+ nniq.ConvAddReLU2d,
674
+ }
675
+
676
+ MODS_IO_TYPE_FP32_OR_INT8: Set[NSNodeTargetType] = {
677
+ nn.ReLU,
678
+ nn.Tanh,
679
+ nn.Sigmoid,
680
+ nn.Hardsigmoid,
681
+ nn.AdaptiveAvgPool1d,
682
+ nn.AdaptiveAvgPool2d,
683
+ nn.AdaptiveAvgPool3d,
684
+ nn.AvgPool1d,
685
+ nn.AvgPool2d,
686
+ nn.AvgPool3d,
687
+ nn.Dropout,
688
+ nn.Hardtanh,
689
+ nn.Identity,
690
+ nn.MaxPool1d,
691
+ nn.MaxPool2d,
692
+ nn.MaxPool3d,
693
+ nn.PixelShuffle,
694
+ nn.PixelUnshuffle,
695
+ nn.ReLU6,
696
+ }
697
+
698
+ METHS_IO_TYPE_FP32_OR_INT8: Set[NSNodeTargetType] = {
699
+ 'sigmoid_',
700
+ 'sigmoid',
701
+ 'tanh_',
702
+ 'tanh',
703
+ 'hardsigmoid_',
704
+ 'hardsigmoid',
705
+ 'relu_',
706
+ 'relu',
707
+ }
708
+
709
+ return {
710
+ 'funs_io_type_fp32': FUNS_IO_TYPE_FP32,
711
+ 'funs_io_type_fp16': FUNS_IO_TYPE_FP16,
712
+ 'funs_io_type_int8': FUNS_IO_TYPE_INT8,
713
+ 'funs_io_type_fp32_or_int8': FUNS_IO_TYPE_FP32_OR_INT8,
714
+ 'mods_io_type_fp32': MODS_IO_TYPE_FP32,
715
+ 'mods_io_type_int8': MODS_IO_TYPE_INT8,
716
+ 'mods_io_type_fp32_or_int8': MODS_IO_TYPE_FP32_OR_INT8,
717
+ 'meths_io_type_fp32_or_int8': METHS_IO_TYPE_FP32_OR_INT8,
718
+ }
719
+
720
+
721
+ def get_unmatchable_types_map() -> Dict[str, Set[NSNodeTargetType]]:
722
+
723
+ FUNS_UNMATCHABLE: Set[NSNodeTargetType] = {
724
+ torch.quantize_per_tensor,
725
+ operator.getitem,
726
+ }
727
+
728
+ MODS_UNMATCHABLE: Set[NSNodeTargetType] = {
729
+ nn.Identity,
730
+ }
731
+
732
+ METHS_UNMATCHABLE: Set[NSNodeTargetType] = {
733
+ 'to',
734
+ 'dequantize',
735
+ 'reshape',
736
+ 'view',
737
+ 'unsqueeze_',
738
+ 'unsqueeze',
739
+ 'transpose',
740
+ 'squeeze_',
741
+ 'squeeze',
742
+ 'size',
743
+ 'shape',
744
+ 'resize_',
745
+ 'repeat_interleave',
746
+ 'repeat',
747
+ 'permute',
748
+ 'numel',
749
+ 'mean',
750
+ 'detach_',
751
+ 'detach',
752
+ 'contiguous',
753
+ 'clamp',
754
+ 'chunk',
755
+ }
756
+
757
+ return {
758
+ 'funs_unmatchable': FUNS_UNMATCHABLE,
759
+ 'mods_unmatchable': MODS_UNMATCHABLE,
760
+ 'meths_unmatchable': METHS_UNMATCHABLE,
761
+ }
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/n_shadows_utils.py ADDED
@@ -0,0 +1,1312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.fx
3
+ from torch.fx import (
4
+ Node,
5
+ GraphModule,
6
+ Graph,
7
+ )
8
+
9
+ from torch.ao.ns.fx.utils import (
10
+ # TODO(future PR): make this work correctly for methods
11
+ get_target_type_str,
12
+ get_normalized_nth_input,
13
+ )
14
+ from torch.ao.ns.fx.ns_types import (
15
+ NSSingleResultValuesType,
16
+ NSResultsType,
17
+ )
18
+ from torch.ao.ns.fx.graph_passes import _maybe_get_fqn
19
+ from torch.ao.quantization import QConfigMapping
20
+ from torch.ao.quantization.qconfig import QConfigAny
21
+ from torch.ao.quantization.utils import getattr_from_fqn
22
+ from torch.ao.quantization.fx.match_utils import _MatchResult
23
+ from torch.utils._pytree import tree_map
24
+
25
+ import collections
26
+ import copy
27
+ from typing import List, Dict, Set, Tuple, Callable, Any, Optional
28
+ import operator
29
+
30
+ SHADOW_NODE_NAME_PREFIX = 'shadow'
31
+ SHADOW_WRAPPER_NODE_NAME_PREFIX = 'shadow_wrapper'
32
+
33
+ # TODO(future PR): reuse existing mapping instead of creating a new one
34
+ BINARY_FUNCTIONS = {
35
+ torch.add,
36
+ torch.Tensor.add,
37
+ operator.add,
38
+ torch.mul,
39
+ torch.Tensor.mul,
40
+ operator.mul,
41
+ }
42
+
43
+ def _get_attr_name(subgraph_idx, subgraph_candidate_idx):
44
+ return f"{SHADOW_NODE_NAME_PREFIX}_{subgraph_idx}_{subgraph_candidate_idx}"
45
+
46
+ def _get_attr_wrapper_name(subgraph_idx, subgraph_candidate_idx):
47
+ return f"{SHADOW_WRAPPER_NODE_NAME_PREFIX}_{subgraph_idx}_{subgraph_candidate_idx}"
48
+
49
+
50
+ class OutputProp:
51
+ """
52
+ Output propagation (modeled from shape propagation).
53
+
54
+ Given a GraphModule and an example input, saves the output flowing
55
+ through each node on `node.traced_result`.
56
+
57
+ Code based on the example from
58
+ https://pytorch.org/docs/stable/fx.html#the-interpreter-pattern
59
+ """
60
+ def __init__(self, mod):
61
+ self.mod = mod
62
+ self.graph = mod.graph
63
+ self.modules = dict(self.mod.named_modules())
64
+
65
+ def propagate(self, *args):
66
+ args_iter = iter(args)
67
+ env : Dict[str, Node] = {}
68
+
69
+ def load_arg(a):
70
+ return torch.fx.graph.map_arg(a, lambda n: env[n.name])
71
+
72
+ def fetch_attr(target : str):
73
+ target_atoms = target.split('.')
74
+ attr_itr = self.mod
75
+ for i, atom in enumerate(target_atoms):
76
+ if not hasattr(attr_itr, atom):
77
+ raise RuntimeError(f"Node referenced nonexistent target {'.'.join(target_atoms[:i])}")
78
+ attr_itr = getattr(attr_itr, atom)
79
+ return attr_itr
80
+
81
+ for node in self.graph.nodes:
82
+ if node.op == 'placeholder':
83
+ result = next(args_iter)
84
+ elif node.op == 'get_attr':
85
+ result = fetch_attr(node.target)
86
+ elif node.op == 'call_function':
87
+ result = node.target(*load_arg(node.args), **load_arg(node.kwargs))
88
+ elif node.op == 'call_method':
89
+ self_obj, *args = load_arg(node.args)
90
+ kwargs = load_arg(node.kwargs)
91
+ result = getattr(self_obj, node.target)(*args, **kwargs)
92
+ elif node.op == 'call_module':
93
+ result = self.modules[node.target](*load_arg(node.args), **load_arg(node.kwargs))
94
+
95
+ if isinstance(result, torch.Tensor):
96
+ node.traced_result = result
97
+
98
+ env[node.name] = result
99
+
100
+ return None
101
+
102
+ def _get_dedup_subgraphs(
103
+ matches: Dict[str, _MatchResult]
104
+ ) -> Dict[str, List[Node]]:
105
+ # the original matches variable is unique by node, make it unique by subgraph
106
+ # instead
107
+ seen_nodes = set()
108
+ subgraphs_dedup = {}
109
+
110
+ # Dict items are not reversible until Python 3.8, so we hack it
111
+ # to be compatible with previous Python versions
112
+ # TODO(future PR): try reversed(list(matches.items()))
113
+ matches_items_reversed: List[Tuple[str, _MatchResult]] = []
114
+ for name, cur_match in matches.items():
115
+ matches_items_reversed.insert(0, (name, cur_match))
116
+
117
+ # Note: the order is important. `matches` currently provides the matches
118
+ # in reverse order. We would like to process the matches in non-reverse
119
+ # order, so that we can create an intuitive naming scheme, such as
120
+ # naming the first op's submodules `shadow_0_0` through `shadow_0_(n-1)`
121
+ for name, cur_match in matches_items_reversed: # type: ignore[call-overload]
122
+ was_seen = False
123
+ for node_or_tuple in cur_match[1]:
124
+
125
+ # Cur_match[1] has an unusual type. It says that it's a `List[Node]`,
126
+ # but it is really not. Furthermore, the contents of this field
127
+ # can change from match results of multiple nodes of the same pattern
128
+ #
129
+ # For example, for conv -> bn -> relu, we see
130
+ # match_results = {
131
+ # 'conv': (relu, [(bn, conv), relu], ...),
132
+ # 'bn': (relu, [(bn, conv), relu], ...),
133
+ # 'relu': (relu, [(bn, conv), relu], ...),
134
+ # }
135
+ #
136
+ # Ideally we should clean up the `find_matches` function to make
137
+ # this more intuitive. For the purposes of this prototype, we hack
138
+ # around it.
139
+
140
+ if isinstance(node_or_tuple, Node):
141
+ if node_or_tuple in seen_nodes:
142
+ was_seen = True
143
+ seen_nodes.add(node_or_tuple)
144
+
145
+ else:
146
+ assert isinstance(node_or_tuple, tuple)
147
+ for node in node_or_tuple:
148
+ assert isinstance(node, Node)
149
+ if node in seen_nodes:
150
+ was_seen = True
151
+ seen_nodes.add(node)
152
+
153
+ if was_seen:
154
+ continue
155
+
156
+ # Start with the unusual type, convert it to [op_0, ..., op_n]
157
+ list_of_nodes = []
158
+
159
+ if len(cur_match[1]) == 1:
160
+ list_of_nodes = cur_match[1]
161
+ else:
162
+ assert len(cur_match[1]) == 2
163
+ # either (a, b), or ((a, b), c) or (c, (a, b))
164
+ # cannot make any assumptions on order, not clear what the
165
+ # _find_matches function is doing to populate this
166
+ # TODO(future PR): make this code less confusing, see discussion
167
+ # in https://github.com/pytorch/pytorch/pull/80521/files#r975918836
168
+
169
+ def _order_nodes(node_a, node_b, node_c) -> List[Node]:
170
+ nodes = [node_a, node_b, node_c]
171
+ first_node = None
172
+ mid_node = None
173
+ last_node = None
174
+ for n in nodes:
175
+ prev_n = n.args[0]
176
+ next_n = next(iter(n.users))
177
+ if prev_n not in nodes:
178
+ first_node = n
179
+ elif next_n not in nodes:
180
+ last_node = n
181
+ else:
182
+ mid_node = n
183
+ assert first_node is not None and mid_node is not None and \
184
+ last_node is not None
185
+ assert mid_node.args[0] is first_node
186
+ assert last_node.args[0] is mid_node
187
+ return [last_node, mid_node, first_node]
188
+
189
+ if isinstance(cur_match[1][0], Node) and isinstance(cur_match[1][1], Node):
190
+ # (a, b)
191
+ list_of_nodes = cur_match[1]
192
+ elif isinstance(cur_match[1][0], tuple):
193
+ # ((a, b), c)
194
+ node_a, node_b = cur_match[1][0]
195
+ node_c = cur_match[1][1]
196
+ list_of_nodes = _order_nodes(node_a, node_b, node_c)
197
+ elif isinstance(cur_match[1][1], tuple):
198
+ # (a, (b, c))
199
+ node_a, node_b = cur_match[1][1]
200
+ node_c = cur_match[1][0]
201
+ list_of_nodes = _order_nodes(node_a, node_b, node_c)
202
+
203
+ # [node_n, ..., node_0], note that the order is reversed
204
+ # to make it chronological for simple subgraphs
205
+ list_of_nodes.reverse()
206
+ subgraphs_dedup[name] = list_of_nodes
207
+
208
+ return subgraphs_dedup
209
+
210
+ def _get_logger_for_subgraph(
211
+ model: GraphModule,
212
+ first_node: Node,
213
+ last_node: Node,
214
+ subgraph_idx: int,
215
+ subgraph_candidate_idx: int,
216
+ qconfig_str: str,
217
+ logger_cls: Callable,
218
+ fqn: Optional[str],
219
+ ) -> torch.nn.Module:
220
+ """
221
+ Given a model and a linear subgraph starting from `first_node` and
222
+ ending with `last_node`, creates a logger for the end of this
223
+ subgraph.
224
+ """
225
+ if fqn is None:
226
+ fqn = ''
227
+ logger_mod_orig = logger_cls(
228
+ first_node.name, # ref_node_name
229
+ last_node.name, # prev_node_name
230
+ f'subgraph_{subgraph_idx}_{subgraph_candidate_idx}', # model_name
231
+ 'model', # ref_name
232
+ get_target_type_str(last_node, model), # prev_node_target_type
233
+ get_target_type_str(first_node, model), # ref_node_target_type
234
+ NSSingleResultValuesType.NODE_OUTPUT.value, # results_type
235
+ 0, # index_within_arg
236
+ 0, # index_of_arg
237
+ fqn, # fqn
238
+ qconfig_str,
239
+ )
240
+ # Usually we expect the user to add loggers, then calibrate, then convert,
241
+ # and then populate loggers. This is why the loggers start disabled.
242
+ # TODO(future PR): reconsider the design to make this more intuitive.
243
+ logger_mod_orig.enabled = False
244
+ return logger_mod_orig
245
+
246
+ def create_submodule_from_subgraph(
247
+ model: torch.nn.Module,
248
+ first_node: Node,
249
+ last_node: Node,
250
+ ) -> GraphModule:
251
+ """
252
+ Input: a model, and a linear subgraph within the model from first_node to
253
+ last_node.
254
+
255
+ Output: a new submodule containing a copy of the subgraph, with the inputs
256
+ to the first node becoming the inputs to the submodule, and all other
257
+ nodes in the subgraph being copied.
258
+
259
+ Example inputs:
260
+
261
+ `model`: a module with graph
262
+
263
+ x0 -> op1 -> x1 -> op2 -> x2
264
+ |
265
+ arg1
266
+
267
+ `first_node`: op1
268
+ `last_node`: op2
269
+
270
+ Example output: a new module with graph
271
+
272
+ input1 -> op1_copy -> x1 -> op2_copy -> output1
273
+ |
274
+ arg1
275
+ """
276
+
277
+ #
278
+ # create a blank GraphModule with an empty graph
279
+ #
280
+
281
+ class M(torch.nn.Module):
282
+ def forward(self, x):
283
+ pass
284
+
285
+ m = M()
286
+ gm = torch.fx.symbolic_trace(m)
287
+ g = gm.graph
288
+ for node in reversed(gm.graph.nodes):
289
+ g.erase_node(node)
290
+
291
+ #
292
+ # modify the graph to have a copy of our subgraph
293
+ #
294
+
295
+ cur_node_orig = first_node
296
+ cur_args_orig = cur_node_orig.args
297
+ cur_kwargs_orig = cur_node_orig.kwargs
298
+
299
+ cur_name_idx = 0
300
+
301
+ iteration_limit = 100
302
+ cur_iteration = 0
303
+
304
+ while True:
305
+ if cur_node_orig is first_node:
306
+ # we are at the first node, we need to set up graph inputs
307
+ # TODO(future): some graphs could have placeholders which are unrelated
308
+ # to the first node, need to handle this
309
+ cur_args_copy = []
310
+ cur_kwargs_copy = {}
311
+ seen_names: Set[str] = set()
312
+ old_name_to_new_node: Dict[str, Node] = {}
313
+
314
+ def _add_placeholder(
315
+ g: Graph, node: Node, seen_names, old_name_to_new_node
316
+ ):
317
+ # note: for graphs starting with patterns such as `y = x + x`, we
318
+ # need to ensure we do not add multiple placeholders with the
319
+ # same name
320
+ counter = 0
321
+ while node.name + '_' + str(counter) in seen_names:
322
+ counter += 1
323
+ cur_name = node.name + '_' + str(counter)
324
+ seen_names.add(cur_name)
325
+ placeholder = g.placeholder(cur_name)
326
+ old_name_to_new_node[node.name] = placeholder
327
+ return placeholder
328
+
329
+ for arg in cur_node_orig.args:
330
+ if isinstance(arg, Node):
331
+ p = _add_placeholder(
332
+ g, arg, seen_names, old_name_to_new_node)
333
+ cur_args_copy.append(p)
334
+ elif isinstance(arg, (list, tuple)):
335
+ new_arg = []
336
+ for inner_arg in arg:
337
+ if isinstance(inner_arg, Node):
338
+ new_arg.append(_add_placeholder(
339
+ g, inner_arg, seen_names, old_name_to_new_node))
340
+ else:
341
+ new_arg.append(inner_arg)
342
+ cur_args_copy.append(new_arg)
343
+ else:
344
+ cur_args_copy.append(arg)
345
+
346
+ # TODO(future PR): handle non-normalized kwargs
347
+ for kwarg_name, kwarg in cur_node_orig.kwargs.items():
348
+ if isinstance(kwarg, Node):
349
+ cur_kwargs_copy[kwarg_name] = _add_placeholder(
350
+ g, kwarg, seen_names, old_name_to_new_node)
351
+ elif isinstance(kwarg, (list, tuple)):
352
+ new_kwarg = []
353
+ for inner_kwarg in kwarg:
354
+ p = _add_placeholder(
355
+ g, inner_kwarg, seen_names, old_name_to_new_node)
356
+ new_kwarg.append(p)
357
+ cur_kwargs_copy[kwarg_name] = new_kwarg
358
+ else:
359
+ cur_kwargs_copy[kwarg_name] = kwarg
360
+
361
+ cur_args_copy = tuple(cur_args_copy) # type: ignore[assignment]
362
+ else:
363
+ # we are not at first node, first arg is from the previous node,
364
+ # and all other args are copied
365
+
366
+ # the current implementation is simplistic and cannot handle
367
+ # ops with two or more arguments which need to be passed from
368
+ # the previous op, so we assert them out
369
+ assert cur_node_orig.target not in BINARY_FUNCTIONS
370
+
371
+ # at this point in the code, cur_node_copy is pointing to the copy
372
+ # of the previous node
373
+ # TODO(future PR): this is not handling complicated graphs correctly, need to
374
+ # look at actual relationships instead of assuming sequential graph
375
+ # TODO(future PR): this is ignoring kwargs, will need to support kwargs
376
+ # for any fusion pattern which has them for a node that is not the
377
+ # first node.
378
+ cur_args_copy = [cur_node_copy] # type: ignore[has-type]
379
+
380
+ if len(cur_node_orig.args) > 1:
381
+ for arg in cur_node_orig.args[1:]:
382
+ if isinstance(arg, torch.nn.Parameter):
383
+ new_arg = arg.clone().detach() # type: ignore[assignment]
384
+ mod_name = f"mod_{cur_name_idx}"
385
+ cur_name_idx += 1
386
+ setattr(gm, mod_name, new_arg)
387
+ new_arg_placeholder = gm.placeholder(mod_name)
388
+ cur_args_copy.append(new_arg_placeholder)
389
+ elif isinstance(arg, (float, int, torch.dtype)):
390
+ cur_args_copy.append(arg)
391
+ else:
392
+ raise AssertionError(f'arg of type {type(arg)} not handled yet')
393
+ cur_args_copy = tuple(cur_args_copy) # type: ignore[assignment]
394
+
395
+ # copy the node
396
+ if cur_node_orig.op == 'call_module':
397
+ orig_mod = getattr_from_fqn(model, cur_node_orig.target) # type: ignore[arg-type]
398
+ orig_mod_copy = copy.deepcopy(orig_mod)
399
+ mod_name = f"mod_{cur_name_idx}"
400
+ setattr(gm, mod_name, orig_mod_copy)
401
+ cur_name_idx += 1
402
+ cur_node_copy = g.call_module(mod_name, cur_args_copy, cur_kwargs_copy)
403
+
404
+ elif cur_node_orig.op == 'call_function':
405
+ cur_node_copy = g.call_function(
406
+ cur_node_orig.target, cur_args_copy, cur_kwargs_copy)
407
+
408
+ elif cur_node_orig.op == 'call_method':
409
+ cur_node_copy = g.call_method(
410
+ cur_node_orig.target, cur_args_copy, cur_kwargs_copy)
411
+
412
+ else:
413
+ raise AssertionError(f'{cur_node_orig.op} not supported yet')
414
+
415
+ if cur_node_orig is last_node:
416
+ break
417
+
418
+ # go to next node
419
+ assert len(cur_node_orig.users.keys()) == 1, \
420
+ f'{cur_node_orig} has more than 1 users, not supported yet'
421
+ cur_node_orig = next(iter(cur_node_orig.users.keys()))
422
+ cur_args_orig = cur_node_orig.args
423
+ cur_kwargs_orig = cur_node_orig.kwargs
424
+
425
+ cur_iteration += 1
426
+ if cur_iteration > iteration_limit:
427
+ raise AssertionError('iteration limit exceeded')
428
+
429
+ # set up outputs
430
+ g.output(cur_node_copy)
431
+
432
+ gm.recompile()
433
+ return gm
434
+
435
+ def create_one_transformed_and_logged_copy_of_subgraph(
436
+ mt: GraphModule,
437
+ subgraph_idx: int,
438
+ subgraph_candidate_idx: int,
439
+ first_node: Node,
440
+ last_node: Node,
441
+ fqn: Optional[str],
442
+ list_of_node_name_to_qconfig: List[Dict[str, QConfigAny]],
443
+ example_inputs: Any,
444
+ last_added_shadow_node_list: List[Optional[Node]],
445
+ custom_prepare_fn: Optional[Callable] = None,
446
+ custom_prepare_kwargs: Optional[Dict[str, Any]] = None,
447
+ ) -> None:
448
+ """
449
+ Given a subgraph in `mt` and a subgraph candidate idx, inserts the
450
+ subgraph candidate copy and instruments it with loggers.
451
+
452
+ If subgraph_candidate_idx is 0, this is the baseline fp32 subgraph and we just
453
+ add a logger to the end.
454
+
455
+ If subgraph_candidate_idx is not 0, we create a copy of the subgraph and
456
+ prepare it with `prepare_fx`.
457
+ """
458
+
459
+ # TODO(future PR): move logger classes to utils to remove circular dependency
460
+ from torch.ao.ns._numeric_suite_fx import OutputLogger, OutputComparisonLogger
461
+
462
+ if subgraph_candidate_idx == 0:
463
+ # idx = 0 is the floating point (original) version of the subgraph
464
+ # We keep the subgraph as is, and add a logger at the end
465
+
466
+ qconfig_str = ''
467
+ logger_mod_orig = _get_logger_for_subgraph(
468
+ mt, first_node, last_node, subgraph_idx, subgraph_candidate_idx,
469
+ qconfig_str, OutputLogger, fqn)
470
+
471
+ attr_name = _get_attr_name(subgraph_idx, subgraph_candidate_idx)
472
+ assert not hasattr(mt, attr_name)
473
+ setattr(mt, attr_name, logger_mod_orig)
474
+ with mt.graph.inserting_after(last_node):
475
+ new_node = mt.graph.call_module(attr_name, args=(last_node,), kwargs={})
476
+ last_added_shadow_node_list[0] = new_node
477
+
478
+ else:
479
+ # idx > 0 means we have a candidate qconfig to try, so we need
480
+ # to make a copy of the subgraph, feed it with the right inputs,
481
+ # and add a logger at the end
482
+
483
+ # get the qconfig
484
+ # subtract one because the first candidate is the floating point
485
+ # version of the subgraph
486
+ node_name_to_qconfig = \
487
+ list_of_node_name_to_qconfig[subgraph_candidate_idx - 1]
488
+ qconfig = node_name_to_qconfig[first_node.name]
489
+
490
+ # if no quantization is requested, skip
491
+ # TODO(future PR): deduplicate equivalent qconfigs that come from
492
+ # different qconfig mapping objects
493
+ if qconfig is None:
494
+ return
495
+
496
+ qconfig_mapping = QConfigMapping().set_global(qconfig)
497
+
498
+ # create a copy of the submodule, wrapped in a separate module
499
+ orig_mod_copy_wrapped = create_submodule_from_subgraph(
500
+ mt, first_node, last_node)
501
+
502
+ # add a call to prepare_fx on the wrapper module
503
+ if custom_prepare_fn is None:
504
+ orig_mod_copy_wrapped = torch.ao.quantization.quantize_fx.prepare_fx(
505
+ orig_mod_copy_wrapped, qconfig_mapping, example_inputs=example_inputs)
506
+ else:
507
+ if custom_prepare_kwargs is None:
508
+ custom_prepare_kwargs = {}
509
+ for kwarg_name in ["example_inputs", "prepare_custom_config", "qconfig_mapping"]:
510
+ assert kwarg_name not in custom_prepare_kwargs, f"cannot specify {kwarg_name} in custom_prepare_kwargs"
511
+ prepare_kwargs: Dict[str, Any] = {
512
+ "example_inputs": example_inputs,
513
+ "qconfig_mapping": qconfig_mapping
514
+ }
515
+ prepare_kwargs.update(custom_prepare_kwargs)
516
+ orig_mod_copy_wrapped = custom_prepare_fn(
517
+ orig_mod_copy_wrapped,
518
+ **prepare_kwargs)
519
+
520
+ # attach the wrapper to the model
521
+ attr_name = _get_attr_wrapper_name(subgraph_idx, subgraph_candidate_idx)
522
+ assert not hasattr(mt, attr_name)
523
+ setattr(mt, attr_name, orig_mod_copy_wrapped)
524
+
525
+ # add a call to the wrapper module from the parent graph
526
+ insert_after_node = last_added_shadow_node_list[0]
527
+ with mt.graph.inserting_after(insert_after_node):
528
+ # TODO(future PR): handle fusion patterns where non-first nodes
529
+ # need inputs
530
+
531
+ # pass in all node args and kwargs
532
+
533
+ new_args = []
534
+ for arg in first_node.args:
535
+ if isinstance(arg, Node):
536
+ new_args.append(arg)
537
+ elif isinstance(arg, (list, tuple)) and len(arg) and isinstance(arg[0], Node):
538
+ for inner_arg in arg:
539
+ if isinstance(inner_arg, Node):
540
+ new_args.append(inner_arg)
541
+
542
+ new_kwargs = {}
543
+ for name, old_kwarg in first_node.kwargs.items():
544
+ if isinstance(old_kwarg, Node):
545
+ new_kwargs[name] = old_kwarg
546
+ elif isinstance(old_kwarg, (list, tuple)) and len(old_kwarg):
547
+ for inner_old_kwarg in old_kwarg:
548
+ # TODO(future PR): clarify why we are adding kwargs to args
549
+ new_args.append(inner_old_kwarg)
550
+
551
+ new_args = tuple(new_args) # type: ignore[assignment]
552
+
553
+ new_node = mt.graph.call_module(
554
+ attr_name, args=new_args, kwargs=new_kwargs)
555
+
556
+ # add a logger to parent graph to observe the shadow wrapper
557
+ logger_mod_orig = _get_logger_for_subgraph(
558
+ mt, first_node, last_node, subgraph_idx, subgraph_candidate_idx,
559
+ str(qconfig), OutputComparisonLogger, fqn)
560
+
561
+ attr_name = _get_attr_name(subgraph_idx, subgraph_candidate_idx)
562
+ assert not hasattr(mt, attr_name)
563
+ setattr(mt, attr_name, logger_mod_orig)
564
+ with mt.graph.inserting_after(new_node):
565
+ logger = mt.graph.call_module(attr_name, args=(new_node, last_node), kwargs={})
566
+ last_added_shadow_node_list[0] = logger
567
+
568
+ mt.recompile()
569
+
570
+ def create_n_transformed_and_logged_copies_of_subgraph(
571
+ mt: GraphModule,
572
+ subgraph_idx: int,
573
+ match_name: str,
574
+ nodes_in_this_subgraph: List[Any],
575
+ qconfig_mappings: List[QConfigMapping],
576
+ list_of_node_name_to_qconfig: List[Dict[str, QConfigAny]],
577
+ custom_prepare_fn: Optional[Callable] = None,
578
+ custom_prepare_kwargs: Optional[Dict[str, Any]] = None,
579
+ ) -> None:
580
+ """
581
+ Given a model `mt` and a subgraph_idx, creates the needed copies
582
+ of the subgraph for all qconfigs, and instruments them with loggers.
583
+ """
584
+ # for now, assume that
585
+ # 1. the first node has one input
586
+ # 2. the last node has one output
587
+
588
+ # for now, ignore all subgraphs that contain non-nodes (tuples, etc)
589
+ # TODO(future PR): implement this
590
+ if any(
591
+ not isinstance(node, Node)
592
+ for node in nodes_in_this_subgraph
593
+ ):
594
+ return
595
+
596
+ first_node = nodes_in_this_subgraph[0]
597
+ last_node = nodes_in_this_subgraph[-1]
598
+ # We used output propagation to populate example values on each
599
+ # node. Use the example values from the previous node as the input
600
+ # to the current node.
601
+ prev_node = get_normalized_nth_input(first_node, mt, 0)
602
+ if isinstance(prev_node, list):
603
+ example_inputs = [x.traced_result for x in prev_node]
604
+ elif isinstance(prev_node, tuple):
605
+ example_inputs = (x.traced_result for x in prev_node) # type: ignore[assignment]
606
+ else:
607
+ # currently some customer models do not have a traced_result in
608
+ # every node, so we have to guard for this case since we cannot
609
+ # quantize without an example input
610
+ # TODO(future PR): add a test case for this once we have an easy
611
+ # repro, see https://github.com/pytorch/pytorch/pull/80521/files#r975940489
612
+ # for additional context
613
+ if hasattr(prev_node, 'traced_result'):
614
+ example_inputs = (prev_node.traced_result,) # type: ignore[attr-defined, assignment]
615
+ else:
616
+ print(
617
+ 'unable to get example input for node ' +
618
+ f'{first_node.format_node()}, skipping')
619
+ return
620
+
621
+ # If there are no quantization configs for this subgraph, skip adding
622
+ # loggers. This reduces memory usage for models where not all layers are
623
+ # quantized.
624
+ # TODO(future): consider making this configurable
625
+ found_at_least_one_qconfig = False
626
+ for subgraph_candidate_idx in range(len(qconfig_mappings) + 1):
627
+
628
+ if subgraph_candidate_idx == 0:
629
+ # fp32 baseline does not need a qconfig
630
+ continue
631
+
632
+ # a. we have N shadows, so len(qconfig_mappings) is N
633
+ # b. we will have the fp32 layer + N shadows, so overall number of
634
+ # (original_op) + (*shadows) will be N+1
635
+ # c. since `subgraph_candidate_idx` represents (b), we need
636
+ # to subtract 1 to query from (a)
637
+ node_name_to_qconfig = \
638
+ list_of_node_name_to_qconfig[subgraph_candidate_idx - 1]
639
+ qconfig = node_name_to_qconfig[first_node.name]
640
+ if qconfig is not None:
641
+ found_at_least_one_qconfig = True
642
+ break
643
+ if not found_at_least_one_qconfig:
644
+ print('unable to find at least one qconfig for node ' +
645
+ f'{first_node.format_node()}, skipping')
646
+ return
647
+
648
+ fqn = _maybe_get_fqn(first_node, mt)
649
+
650
+ # We want the results to contain the subgraphs in natural order,
651
+ # and the graph to also contain shadow wrappers and shadow loggers
652
+ # in natural order.
653
+ # If we just iterate in reverse, the graph will be in natural
654
+ # order but the eventual results will be in reverse order.
655
+ # So, we keep track of the last shadow logger we added and
656
+ # always insert after it.
657
+ last_added_shadow_node_list: List[Optional[Node]] = [None]
658
+ for subgraph_candidate_idx in range(len(qconfig_mappings) + 1):
659
+
660
+ create_one_transformed_and_logged_copy_of_subgraph(
661
+ mt, subgraph_idx, subgraph_candidate_idx, first_node,
662
+ last_node, fqn, list_of_node_name_to_qconfig,
663
+ example_inputs, last_added_shadow_node_list, custom_prepare_fn,
664
+ custom_prepare_kwargs)
665
+
666
+ def create_add_loggers_graph(
667
+ model: GraphModule,
668
+ subgraphs_dedup: Dict[str, List[Node]],
669
+ qconfig_mapping: QConfigMapping,
670
+ node_name_to_qconfig: Dict[str, QConfigAny],
671
+ ) -> None:
672
+ r"""
673
+ Given a model, a model graph partition (currently a set of matched
674
+ subgraphs) and instructions how to transform each subgraph
675
+ (currently quantizing it according to qconfig_mapping), modifies
676
+ the model graph to create an alternate path through the original graph,
677
+ with each of the subgraphs quantized. This is useful to compare
678
+ propagation error of a transformation such as quantization.
679
+
680
+ For example, given layer op0 and op1, there are four cases when handling op1:
681
+ 1. op0 and op1 quantized
682
+ 2. op0 and op1 unquantized
683
+ 3. op0 quantized, op1 unquantized
684
+ 4. op0 unquantized, op1 quantized
685
+
686
+ Example input, case 1:
687
+
688
+ .. code::
689
+
690
+ x0_0 -> op0_0 -> x1_0 -> log -----> op1_0 -> x2_0 -> log
691
+ \ \ \ \ # noqa: W605
692
+ ---> op0_1 -> x1_1 ----> clog op1_1 -> x2_1 ----> clog
693
+
694
+ Example output, case 1:
695
+
696
+ .. code::
697
+
698
+ x0_0 -> op0_0 -> x1_0 -> log -----> op1_0 -> x2_0 -> log
699
+ \ \ \ # noqa: W605
700
+ ---> op0_1 -> x1_1 ----> clog -> op1_1 -> x2_1 ----> clog
701
+
702
+ """
703
+ # TODO(future PR): move logger classes to utils to remove circular dependency
704
+ from torch.ao.ns._numeric_suite_fx import OutputLogger, OutputComparisonLogger
705
+
706
+ def _get_subgraph_containing_node(node, subgraphs_dedup):
707
+ for subgraph in subgraphs_dedup.values():
708
+ if node in subgraph:
709
+ return subgraph
710
+ return None
711
+
712
+ # First, we need to create shadow branches, going from
713
+ #
714
+ # x0 -> op0 -> x1 -> ...
715
+ #
716
+ #
717
+ # to
718
+ #
719
+ # x0 -> op0_0 -> x1_0 -> log -> ...
720
+ # \ \
721
+ # -> op0_1 -> x1_1 -> clog
722
+ #
723
+ # Later, the outputs of each shadow will be rerouted to calculate
724
+ # propagation error.
725
+
726
+ # Note: we cannot iterate over matched subgraphs because some nodes
727
+ # may not be matched. So, we iterate over nodes in the graph, and
728
+ # associate them to matched subgraphs if possible.
729
+
730
+ nodes_to_skip = set()
731
+ # for each subgraph, save a mapping from first node of subgraph
732
+ # to first and last node of the shadow of this subgraph
733
+ orig_first_node_to_shadow_in_node = {}
734
+ orig_first_node_to_shadow_out_node = {}
735
+ # need to record original list because we will mutate the graph as we go
736
+ orig_nodes = list(model.graph.nodes) # type: ignore[union-attr, arg-type]
737
+ cur_subgraph_idx = 0
738
+ for n in orig_nodes:
739
+ if n.op in ('placeholder', 'get_attr', 'output') or n in nodes_to_skip:
740
+ continue
741
+
742
+ maybe_subgraph = _get_subgraph_containing_node(n, subgraphs_dedup)
743
+ insert_submodule_copy = False
744
+ if maybe_subgraph is not None:
745
+ first_node, last_node = maybe_subgraph[0], maybe_subgraph[-1]
746
+ for node_to_skip in maybe_subgraph:
747
+ nodes_to_skip.add(node_to_skip)
748
+ qconfig = node_name_to_qconfig[first_node.name]
749
+ if qconfig is not None:
750
+ insert_submodule_copy = True
751
+ else:
752
+ first_node, last_node = n, n
753
+
754
+ if insert_submodule_copy:
755
+ match_name = first_node.name
756
+ create_n_transformed_and_logged_copies_of_subgraph(
757
+ model, cur_subgraph_idx, match_name, maybe_subgraph,
758
+ [qconfig_mapping], [node_name_to_qconfig],
759
+ None, None # type: ignore[arg-type]
760
+ )
761
+ # find the created shadow module and record it so we
762
+ # can find it easily in step 2
763
+ expected_shadow_target = f"shadow_wrapper_{cur_subgraph_idx}_1"
764
+ new_shadow_mod = None
765
+ for maybe_shadow_mod in model.graph.nodes:
766
+ if maybe_shadow_mod.op == 'call_module' and \
767
+ maybe_shadow_mod.target == expected_shadow_target:
768
+ new_shadow_mod = maybe_shadow_mod
769
+ break
770
+ assert new_shadow_mod is not None
771
+ orig_first_node_to_shadow_in_node[first_node] = new_shadow_mod
772
+ orig_first_node_to_shadow_out_node[first_node] = new_shadow_mod
773
+
774
+ else:
775
+ # create a copy of the subgraph by only copying FX nodes
776
+ # but not copying any parameters, to minimize memory usage
777
+ subgraph_to_use = maybe_subgraph if maybe_subgraph is not None \
778
+ else [first_node]
779
+
780
+ # add a regular logger after last_node
781
+ qconfig_str = ''
782
+ subgraph_candidate_idx = 0
783
+ fqn = _maybe_get_fqn(first_node, model)
784
+ logger_mod_orig = _get_logger_for_subgraph(
785
+ model, first_node, last_node, cur_subgraph_idx, subgraph_candidate_idx,
786
+ qconfig_str, OutputLogger, fqn)
787
+ attr_name = _get_attr_name(cur_subgraph_idx, subgraph_candidate_idx)
788
+ assert not hasattr(model, attr_name)
789
+ setattr(model, attr_name, logger_mod_orig)
790
+ insertion_point = last_node
791
+ with model.graph.inserting_after(insertion_point):
792
+ logger = model.graph.call_module(
793
+ attr_name, args=(last_node,), kwargs={})
794
+ insertion_point = logger
795
+
796
+ # create a copy of the subgraph
797
+ cur_node_orig = first_node
798
+ cur_node_copy = None
799
+ first_node_copy = None
800
+ while cur_node_orig in subgraph_to_use:
801
+ # TODO(future PR): make this support all possible args/kwargs
802
+ if cur_node_orig is first_node:
803
+ new_args = cur_node_orig.args
804
+ new_kwargs = cur_node_orig.kwargs
805
+ else:
806
+ first_arg_for_copy = cur_node_copy
807
+ new_args = tuple([first_arg_for_copy, *cur_node_orig.args[1:]]) # noqa: C409
808
+ new_kwargs = cur_node_orig.kwargs
809
+ # make a copy of cur_node_orig
810
+ with model.graph.inserting_after(insertion_point):
811
+ cur_node_copy = model.graph.create_node(
812
+ cur_node_orig.op,
813
+ cur_node_orig.target,
814
+ new_args,
815
+ new_kwargs,
816
+ # cur_node_orig.name, # TODO(future PR): set name explicitly
817
+ )
818
+ if first_node_copy is None:
819
+ first_node_copy = cur_node_copy
820
+ # since now only linear subgraphs are supported, all nodes
821
+ # except the last one must have only one user
822
+ if cur_node_orig != last_node:
823
+ assert len(cur_node_orig.users.keys()) == 1
824
+ cur_node_orig = next(iter(cur_node_orig.users.keys()))
825
+ assert not cur_node_orig.name.startswith(SHADOW_NODE_NAME_PREFIX)
826
+ insertion_point = cur_node_copy
827
+
828
+ # add a comparison logger after last_node's copy
829
+ subgraph_candidate_idx = 1
830
+ logger_mod_orig = _get_logger_for_subgraph(
831
+ model, first_node, last_node, cur_subgraph_idx, subgraph_candidate_idx,
832
+ qconfig_str, OutputComparisonLogger, fqn)
833
+ attr_name = _get_attr_name(cur_subgraph_idx, subgraph_candidate_idx)
834
+ assert not hasattr(model, attr_name)
835
+ setattr(model, attr_name, logger_mod_orig)
836
+ with model.graph.inserting_after(insertion_point):
837
+ logger = model.graph.call_module(
838
+ attr_name, args=(cur_node_copy, last_node), kwargs={})
839
+
840
+ # save the final node so we can use it in step 2
841
+ orig_first_node_to_shadow_in_node[first_node] = first_node_copy
842
+ orig_first_node_to_shadow_out_node[first_node] = cur_node_copy
843
+
844
+ cur_subgraph_idx += 1
845
+
846
+ model.recompile()
847
+
848
+ # Now, we go from
849
+ #
850
+ # x0 -> op0_0 -> x1_0 -> log -> x1 -> op1_0 -> ...
851
+ # \ \ \
852
+ # -> op0_1 -> x1_1 -> clog -> op1_1 -> ...
853
+ #
854
+ # to
855
+ #
856
+ # x0 -> op0_0 -> x1_0 -> log --> x1_0 -> op1_0 -> ...
857
+ # \ \
858
+ # -> op0_1 -> x1_1 -> clog -> x1_1 -> op1_1 -> ...
859
+ #
860
+ # sample values of key internal variables for the example above:
861
+ #
862
+ # orig_first_node_to_shadow_in_node = {op0_0: op0_1, op1_0: op1_1}
863
+ # orig_first_node_to_shadow_out_node = {op0_0: op0_1, op1_0: op1_1}
864
+ #
865
+ # note: for subgraphs with more than one node, in_node will be different
866
+ # compared to out_node
867
+
868
+
869
+ nodes_to_skip = set()
870
+ for n in orig_nodes:
871
+ if n.op in ('placeholder', 'get_attr', 'output') or n in nodes_to_skip:
872
+ continue
873
+
874
+ maybe_subgraph = _get_subgraph_containing_node(n, subgraphs_dedup)
875
+ if maybe_subgraph is not None:
876
+ first_node, last_node = maybe_subgraph[0], maybe_subgraph[-1]
877
+ for node_to_skip in maybe_subgraph:
878
+ nodes_to_skip.add(node_to_skip)
879
+ else:
880
+ first_node, last_node = n, n
881
+
882
+ def maybe_remap_node_to_shadow(node):
883
+ """
884
+ If unshadowed `node` has a shadow version, return that. If not,
885
+ return `node`.
886
+ """
887
+ if not isinstance(node, Node):
888
+ # handle scalars
889
+ return node
890
+
891
+ if node.op in ('placeholder', 'get_attr'):
892
+ return node
893
+
894
+ # Find the shadowed version of this arg from the previous
895
+ # subgraph. For this, we need to:
896
+ # 1. navigate to the first node of the previous subgraph
897
+ # 2. get the output of the shadow wrapper which has (1) as an input
898
+
899
+ # For now, assume the arg is in matched subgraphs. In the
900
+ # future we may have to handle the case where this is not true.
901
+ prev_subgraph = _get_subgraph_containing_node(
902
+ node, subgraphs_dedup)
903
+ if prev_subgraph is None:
904
+ prev_subgraph = [node]
905
+ prev_first_node = prev_subgraph[0]
906
+ prev_shadow_output = \
907
+ orig_first_node_to_shadow_out_node[prev_first_node]
908
+ return prev_shadow_output
909
+
910
+ cur_shadow_input = \
911
+ orig_first_node_to_shadow_in_node[first_node]
912
+ assert cur_shadow_input is not None
913
+ cur_shadow_input.args = tree_map(
914
+ maybe_remap_node_to_shadow, cur_shadow_input.args)
915
+ cur_shadow_input.kwargs = tree_map(
916
+ maybe_remap_node_to_shadow, cur_shadow_input.kwargs)
917
+
918
+ model.recompile()
919
+
920
+ def _get_weight_info_from_shadow_wrapper(shadow_wrapper: torch.nn.Module):
921
+ # input: shadow wrapper module
922
+ # output if shadow wrapper module has a weighted op:
923
+ # (quantize_fn, (quantize_fn_args))
924
+ # output if shadow wrapper module doesn't have a weighted op:
925
+ # None
926
+
927
+ # For now, assume that the weight is the second input
928
+ # to the shadow module. If that changes, we can fix it later.
929
+ placeholders_seen = 0
930
+ for shadow_n in shadow_wrapper.graph.nodes: # type: ignore[union-attr]
931
+ if shadow_n.op != 'placeholder':
932
+ continue
933
+
934
+ placeholders_seen += 1
935
+ if placeholders_seen != 2:
936
+ continue
937
+
938
+ # the subgraph looks like
939
+ #
940
+ # _input_scale_1 = self._input_scale_1
941
+ # _input_zero_point_1 = self._input_zero_point_1
942
+ # quantize_per_channel = torch.quantize_per_channel(
943
+ # w2_0, _input_scale_1, _input_zero_point_1,
944
+ # 0, torch.qint8)
945
+ #
946
+ # we have `w2_0`, and are navigating this subgraph
947
+ # to get `_input_scale_1` and `_input_zero_point_1`
948
+
949
+ assert len(shadow_n.users) == 1
950
+ quant_node = next(iter(shadow_n.users.keys()))
951
+ new_args: Any = None
952
+ if quant_node.target == torch.quantize_per_channel:
953
+ _weight, scale_node, zp_node, axis, dtype = quant_node.args
954
+ scale_val = getattr_from_fqn(
955
+ shadow_wrapper, scale_node.target)
956
+ zp_val = getattr_from_fqn(
957
+ shadow_wrapper, zp_node.target)
958
+ new_args = (scale_val, zp_val, axis, dtype)
959
+ else:
960
+ assert quant_node.target == torch.quantize_per_tensor
961
+ _weight, scale_node, zp_node, dtype = quant_node.args
962
+ scale_val = getattr_from_fqn(
963
+ shadow_wrapper, scale_node.target)
964
+ zp_val = getattr_from_fqn(
965
+ shadow_wrapper, zp_node.target)
966
+ new_args = (scale_val, zp_val, dtype)
967
+ return (quant_node.target, new_args)
968
+
969
+ return None
970
+
971
+
972
+ def extract_weight_comparison(m: GraphModule) -> NSResultsType:
973
+
974
+ # example graph:
975
+ #
976
+ # w1 = self.w1
977
+ # b1 = self.b1
978
+ # linear = torch._C._nn.linear(x, w1, b1)
979
+ # shadow_0_0 = self.shadow_0_0(linear)
980
+ # shadow_wrapper_0_1 = self.shadow_wrapper_0_1(x, w1, b1)
981
+ # shadow_0_1 = self.shadow_0_1(shadow_wrapper_0_1, linear)
982
+ #
983
+ # algorithm:
984
+ # 1. for each call_function node matching our allowlist:
985
+ # 2. if corresponding shadow wrapper exists, extract the weight pair
986
+ #
987
+ # Note: this is not super robust, but that's ok because this is
988
+ # just for legacy customers who depend on the previous two-model version
989
+ # of this API. TBD if we need to make this robust.
990
+ # Note: modules are not supported, since existing customers only
991
+ # use functions.
992
+
993
+ # TODO(future PR): move this to config
994
+ weighted_ops = {
995
+ torch.nn.functional.linear,
996
+ }
997
+
998
+ results: NSResultsType = {
999
+ 'model': {NSSingleResultValuesType.WEIGHT.value: {}}
1000
+ }
1001
+
1002
+ for n in m.graph.nodes: # type: ignore[union-attr]
1003
+ if not (n.op == 'call_function' and n.target in weighted_ops):
1004
+ continue
1005
+
1006
+ # Check if we have a corresponding shadow wrapper
1007
+ # TODO(future PR, if needed): support kwargs
1008
+ # TODO(future PR, if needed): support multiple shadow users
1009
+ first_arg = n.args[0]
1010
+ shadow_wrapper_node = None
1011
+ for user in first_arg.users:
1012
+ # TODO(before land): fix string match
1013
+ if user.op == 'call_module' and \
1014
+ user.target.startswith('shadow_wrapper'):
1015
+ shadow_wrapper_node = user
1016
+ break
1017
+
1018
+ if shadow_wrapper_node is None:
1019
+ continue
1020
+
1021
+ shadow_wrapper = getattr_from_fqn(
1022
+ m, shadow_wrapper_node.target) # type: ignore[arg-type]
1023
+ weight_info = _get_weight_info_from_shadow_wrapper(
1024
+ shadow_wrapper)
1025
+ if weight_info is None:
1026
+ continue
1027
+
1028
+ # get weight
1029
+ w_node = n.args[1]
1030
+ w_obj = getattr_from_fqn(m, w_node.target).detach()
1031
+
1032
+ # get a quantized version of weight
1033
+ quant_fn, quant_fn_args_except_first = weight_info
1034
+ new_args = (w_obj, *quant_fn_args_except_first)
1035
+ w_obj_q = quant_fn(*new_args)
1036
+
1037
+ # add a comparison
1038
+ ref_node_name = n.name
1039
+ prev_node_name = n.name
1040
+ ref_node_type = get_target_type_str(n, m)
1041
+ prev_node_type = ref_node_type
1042
+ fqn = None
1043
+ if hasattr(m, '_node_name_to_scope'):
1044
+ fqn = m._node_name_to_scope[n.name][0] # type: ignore[index]
1045
+ comparison = torch.ao.ns.fx.utils.compute_sqnr(w_obj, w_obj_q)
1046
+ result_fp32 = {
1047
+ 'res_type': NSSingleResultValuesType.WEIGHT.value,
1048
+ 'values': [w_obj],
1049
+ 'prev_node_name': prev_node_name,
1050
+ 'prev_node_target_type': prev_node_type,
1051
+ 'ref_node_name': ref_node_name,
1052
+ 'ref_node_target_type': ref_node_type,
1053
+ 'index_within_arg': 0,
1054
+ 'index_of_arg': 0,
1055
+ 'fqn': fqn,
1056
+ 'qconfig_str': '',
1057
+ 'comparisons': [comparison],
1058
+ 'comparison_fn_name': 'sqnr',
1059
+ }
1060
+ result_q = {
1061
+ 'res_type': NSSingleResultValuesType.WEIGHT.value,
1062
+ 'values': [w_obj_q],
1063
+ 'prev_node_name': prev_node_name,
1064
+ 'prev_node_target_type': prev_node_type,
1065
+ 'ref_node_name': ref_node_name,
1066
+ 'ref_node_target_type': ref_node_type,
1067
+ 'index_within_arg': 0,
1068
+ 'index_of_arg': 0,
1069
+ 'fqn': fqn,
1070
+ 'qconfig_str': '',
1071
+ 'comparisons': [comparison],
1072
+ 'comparison_fn_name': 'sqnr',
1073
+ }
1074
+
1075
+ # go from subgraph_n_1 to subgraph_n_0
1076
+ _1, _2, node_idx, _3 = shadow_wrapper_node.target.split('_')
1077
+ name_fp32 = f"subgraph_{node_idx}_0"
1078
+ name_q = f"subgraph_{node_idx}_1"
1079
+
1080
+ results['model'][NSSingleResultValuesType.WEIGHT.value][name_fp32] = \
1081
+ [result_fp32]
1082
+ results['model'][NSSingleResultValuesType.WEIGHT.value][name_q] = \
1083
+ [result_q]
1084
+
1085
+ return results
1086
+
1087
+ # TODO(future PR): redesign this to make it easier to consume outputs
1088
+ def group_results_by_subgraph(results: NSResultsType) -> Any:
1089
+ """
1090
+ Creates a comparison of results
1091
+
1092
+ Input:
1093
+
1094
+ {
1095
+ 'model': {
1096
+ 'node_output': {
1097
+ 'subgraph_0_0': [
1098
+ 'values': [torch.tensor(...), ...], ...
1099
+ 'ref_node_name': ...,
1100
+ 'ref_node_target_type': ...,
1101
+ 'qconfig_str': ...,
1102
+ 'comparisons': [], ...
1103
+ 'comparison_fn_name': '',
1104
+ 'fqn': '...',
1105
+ ],
1106
+ 'subgraph_0_1': [
1107
+ 'values': [torch.tensor(...), ...], ...
1108
+ 'ref_node_name': ...,
1109
+ 'ref_node_target_type': ...,
1110
+ 'qconfig_str': ...,
1111
+ 'comparisons': [torch.tensor(...), ...], ...
1112
+ 'comparison_fn_name': '...',
1113
+ 'fqn': '...',
1114
+ ],
1115
+ ...
1116
+ },
1117
+ },
1118
+ }
1119
+
1120
+ Output:
1121
+ {
1122
+ 'subgraph_0': {
1123
+ '0': {
1124
+ 'ref_node_name': '...',
1125
+ 'ref_node_target_type': ...,
1126
+ 'values': [torch.tensor(...), ...],
1127
+ 'qconfig_str': None,
1128
+ 'comparisons': [torch.tensor(...), ...], ...
1129
+ 'comparison_fn_name': '...',
1130
+ 'fqn': '...',
1131
+ },
1132
+ '1': {
1133
+ 'ref_node_name': '...',
1134
+ 'ref_node_target_type': ...,
1135
+ 'values': [torch.tensor(...), ...],
1136
+ 'qconfig_str': '...',
1137
+ 'comparisons': [torch.tensor(...), ...], ...
1138
+ 'comparison_fn_name': '...',
1139
+ 'fqn': '...',
1140
+ },
1141
+ },
1142
+ }
1143
+
1144
+ """
1145
+ subgraph_name_to_subgraph_results: Any = collections.defaultdict(dict)
1146
+
1147
+ # node_output or weight
1148
+ key_to_use = next(iter(results['model'].keys()))
1149
+
1150
+ for subgraph_name_with_idx, subgraph_candidate_results in \
1151
+ results['model'][key_to_use].items():
1152
+
1153
+ # convert from `subgraph_m_n` to `subgraph_m` and `n`
1154
+ subgraph_str, subgraph_idx, subgraph_candidate_idx = \
1155
+ subgraph_name_with_idx.split('_')
1156
+ subgraph_name = f'{subgraph_str}_{subgraph_idx}'
1157
+
1158
+ subgraph_results = {
1159
+ 'ref_node_name': subgraph_candidate_results[0]['ref_node_name'],
1160
+ 'ref_node_target_type': subgraph_candidate_results[0]['ref_node_target_type'],
1161
+ 'fqn': subgraph_candidate_results[0]['fqn'],
1162
+ 'values': subgraph_candidate_results[0]['values'],
1163
+ 'qconfig_str': subgraph_candidate_results[0]['qconfig_str'],
1164
+ 'comparisons': subgraph_candidate_results[0]['comparisons'],
1165
+ 'comparison_fn_name': subgraph_candidate_results[0]['comparison_fn_name'],
1166
+ }
1167
+
1168
+ subgraph_name_to_subgraph_results[subgraph_name][subgraph_candidate_idx] = \
1169
+ subgraph_results
1170
+
1171
+ return dict(subgraph_name_to_subgraph_results)
1172
+
1173
+ # TODO(future PR): redesign this to make it easier to consume outputs
1174
+ def create_results_comparison(
1175
+ results_grouped,
1176
+ ) -> Any:
1177
+ """
1178
+ Input:
1179
+
1180
+ {
1181
+ 'subgraph_0': {
1182
+ '0': {
1183
+ 'ref_node_name': '...',
1184
+ 'ref_node_target_type': ...,
1185
+ 'values': [torch.tensor(...), ...],
1186
+ 'qconfig_str': '',
1187
+ 'comparisons': [],
1188
+ 'comparison_fn_name': '',
1189
+ 'fqn': '...',
1190
+ },
1191
+ '1': {
1192
+ 'ref_node_name': '...',
1193
+ 'ref_node_target_type': ...,
1194
+ 'values': [torch.tensor(...), ...],
1195
+ 'qconfig_str': '...',
1196
+ 'comparisons': [torch.tensor(...), ...],
1197
+ 'comparison_fn_name': 'sqnr',
1198
+ 'fqn': '...',
1199
+ },
1200
+ },
1201
+ }
1202
+
1203
+ Output:
1204
+ {
1205
+ 'subgraph_0': {
1206
+ 'ref_node_name': '...',
1207
+ 'ref_node_target_type': '...',
1208
+ 'fqn': '...',
1209
+ 'candidates': {
1210
+ '1': {
1211
+ 'qconfig_str': ...,
1212
+ 'comparison_fn_name': 'sqnr',
1213
+ 'cmp_raw': [..., ...],
1214
+ 'cmp_mean': ...,
1215
+ },
1216
+ ...,
1217
+ },
1218
+ },
1219
+ }
1220
+ """
1221
+
1222
+ results_comparison = {}
1223
+
1224
+ for subgraph_name, subgraph_results in results_grouped.items():
1225
+
1226
+ candidates = {}
1227
+ for subgraph_inner_name, subgraph_inner_result in subgraph_results.items():
1228
+ # skip comparing baseline to baseline
1229
+ if subgraph_inner_name == '0':
1230
+ continue
1231
+
1232
+ # we expect the comparisons to be precalculated from
1233
+ # calibration, so we just fetch them here
1234
+ cmp_raw = subgraph_inner_result['comparisons']
1235
+ cmp_raw_tensor = torch.stack(cmp_raw)
1236
+
1237
+ candidates[subgraph_inner_name] = {
1238
+ 'qconfig_str': subgraph_inner_result['qconfig_str'],
1239
+ 'comparison_fn_name': subgraph_inner_result['comparison_fn_name'],
1240
+ 'cmp_raw': cmp_raw_tensor,
1241
+ 'cmp_mean': torch.mean(cmp_raw_tensor),
1242
+ }
1243
+
1244
+ results_comparison[subgraph_name] = {
1245
+ 'ref_node_name': subgraph_results['0']['ref_node_name'],
1246
+ 'ref_node_target_type': subgraph_results['0']['ref_node_target_type'],
1247
+ 'fqn': subgraph_results['0']['fqn'],
1248
+ 'candidates': candidates,
1249
+ }
1250
+
1251
+ return results_comparison
1252
+
1253
+ # TODO(future PR): redesign this to make it easier to consume outputs
1254
+ def print_n_shadows_summary(
1255
+ results_comparison,
1256
+ ) -> None:
1257
+ """
1258
+ Input:
1259
+
1260
+ {
1261
+ 'subgraph_0': {
1262
+ 'ref_node_name': 'linear1',
1263
+ 'ref_node_target_type': '...',
1264
+ 'fqn': '...',
1265
+ 'candidates': {
1266
+ '1': {
1267
+ 'qconfig_str': ...,
1268
+ 'comparison_fn_name': ...,
1269
+ 'cmp_raw': [45.0, 55.0],
1270
+ 'cmp_mean': 50.0,
1271
+ },
1272
+ ...,
1273
+ },
1274
+ },
1275
+ }
1276
+
1277
+ Prints:
1278
+
1279
+ node_name | node_type | fqn | 0 | 1 | ...
1280
+ linear1 | ... | ... | 45.0 | 50.0 | ...
1281
+ """
1282
+
1283
+ try:
1284
+ from tabulate import tabulate
1285
+ except ImportError:
1286
+ print("`print_tabular` relies on the library `tabulate`, "
1287
+ "which could not be found on this machine. Run `pip "
1288
+ "install tabulate` to install the library.")
1289
+ return
1290
+
1291
+ results = []
1292
+ for subgraph_data in results_comparison.values():
1293
+ mean_all_candidates = [
1294
+ candidate['cmp_mean']
1295
+ for candidate_name, candidate in subgraph_data['candidates'].items()
1296
+ ]
1297
+
1298
+ data_row = [
1299
+ subgraph_data['ref_node_name'],
1300
+ subgraph_data['ref_node_target_type'],
1301
+ subgraph_data['fqn'],
1302
+ *mean_all_candidates,
1303
+ ]
1304
+ results.append(data_row)
1305
+
1306
+ max_candidate_idx_len = -1
1307
+ for data_row in results:
1308
+ max_candidate_idx_len = max(max_candidate_idx_len, len(data_row[1]))
1309
+ candidate_idx_headers = [str(x) for x in range(max_candidate_idx_len)]
1310
+
1311
+ headers = ['node_name', 'node_type', 'fqn', *candidate_idx_headers]
1312
+ print(tabulate(results, headers=headers))
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/ns_types.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ from typing import NamedTuple
3
+
4
+ from torch.fx.graph import Node
5
+
6
+ from typing import Dict, Any, List, Union, Callable
7
+
8
+ class NSSingleResultValuesType(str, enum.Enum):
9
+ WEIGHT = 'weight'
10
+ NODE_OUTPUT = 'node_output'
11
+ NODE_INPUT = 'node_input'
12
+
13
+ class NSSubgraph(NamedTuple):
14
+ start_node: Node
15
+ end_node: Node
16
+ base_op_node: Node
17
+
18
+ # TODO(future PR): see if we can use typing_extensions's TypedDict instead
19
+ # to properly type the various keys
20
+ # {
21
+ # # one of NSSingleResultValuesType
22
+ # 'type': 'weight',
23
+ # # the values of type specified above
24
+ # 'values': [torch.tensor(...), ...],
25
+ # # name of the node directly before the logger
26
+ # 'prev_node_name': 'linear1',
27
+ # # type of the underlying function or module
28
+ # 'prev_node_target_type': torch.nn.functional.linear # or torch.nn.Linear, etc
29
+ # # name of the node responsible for adding this logger
30
+ # # Note: this may differ from prev_node_name if we are logging inputs
31
+ # 'ref_node_name': 'linear1',
32
+ # # index of this node within the arg of the input/output node
33
+ # # for example, in cat([x1, x2, x3], dim=0), x2 would have index_within_arg == 1
34
+ # 'index_within_arg': 0,
35
+ # # index of this node within the args of the input/output node
36
+ # # for example, in add(x1, x2), x2 would have index_of_arg == 1
37
+ # 'index_of_arg': 0,
38
+ # # precomputed comparisons of logger values to reference values
39
+ # 'comparisons': [torch.tensor(...), ...]
40
+ # # name of function used for precomputed comparisons
41
+ # 'comparison_fn_name': 'sqnr',
42
+ # # string representation of qconfig responsible for creating this logger
43
+ # 'qconfig_str': 'QConfig(...)',
44
+ # }
45
+ NSSingleResultType = Dict[str, Any]
46
+
47
+ # {
48
+ # 'layer_name_1': { # subgraph name
49
+ # 'node_output': { # results type (node_output, node_input, weight)
50
+ # 'model_name_a': # model name
51
+ # [NSSingleResultType, ...], # results, ordered by index_within_arg
52
+ # 'model_name_b':
53
+ # [NSSingleResultType, ...],
54
+ # },
55
+ # },
56
+ # }
57
+ #
58
+ NSResultsType = Dict[str, Dict[str, Dict[str, List[NSSingleResultType]]]]
59
+
60
+ # Defines the underlying target type of a node, for example:
61
+ # `F.conv1d` for a `call_function` conv node
62
+ # `nn.Conv1d` for a `call_module` node calling the forward of a `nn.Conv1d` module
63
+ # `'sigmoid'` for a `call_method` node calling `x.sigmoid()`
64
+ NSNodeTargetType = Union[Callable, str]
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/pattern_utils.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ toq = torch.ops.quantized
5
+
6
+ from torch.fx import GraphModule
7
+ from torch.fx.graph import Node
8
+
9
+ from torch.ao.quantization.backend_config import get_native_backend_config
10
+ from torch.ao.quantization.fx.quantize_handler import _get_pattern_to_quantize_handlers
11
+ from torch.ao.quantization.utils import getattr_from_fqn
12
+ from .ns_types import NSNodeTargetType
13
+ from torch.ao.quantization import (
14
+ ObserverBase,
15
+ FakeQuantizeBase,
16
+ )
17
+
18
+ from typing import Dict, Tuple, Set, Callable, Any, Union, List
19
+
20
+
21
+ def get_type_a_related_to_b(
22
+ base_name_to_sets_of_related_ops: Dict[str, Set[NSNodeTargetType]],
23
+ ) -> Set[Tuple[NSNodeTargetType, NSNodeTargetType]]:
24
+ # TODO(future PR): allow customizations
25
+ # TODO(future PR): reuse existing quantization mappings
26
+ # TODO(future PR): add the rest of modules and ops here
27
+ type_a_related_to_b: Set[Tuple[NSNodeTargetType, NSNodeTargetType]] = set()
28
+
29
+ for s in base_name_to_sets_of_related_ops.values():
30
+ s_list = list(s)
31
+ # add every bidirectional pair
32
+ for idx_0 in range(0, len(s_list)):
33
+ for idx_1 in range(idx_0, len(s_list)):
34
+ type_a_related_to_b.add((s_list[idx_0], s_list[idx_1]))
35
+ type_a_related_to_b.add((s_list[idx_1], s_list[idx_0]))
36
+
37
+ return type_a_related_to_b
38
+
39
+
40
+ NSFusionElType = Union[
41
+ Callable, # call_function or call_module type, example: F.linear or nn.Conv2d
42
+ str, # call_method name, example: "dequantize"
43
+ Tuple[str, Any], # call_method name and first argument, example: ("to", torch.float16)
44
+ ]
45
+ NSFusionType = Union[
46
+ Tuple[NSFusionElType, NSFusionElType],
47
+ Tuple[NSFusionElType, NSFusionElType, NSFusionElType, NSFusionElType],
48
+ ]
49
+
50
+ def get_reversed_fusions() -> List[Tuple[NSFusionType, int]]:
51
+ """
52
+ Set of potential fusions, in reverse order. The order is reversed
53
+ to match how fusion patterns are defined in quantization code.
54
+
55
+ Fusion format:
56
+ ((fusion_op_0, fusion_op_1), base_op_idx)
57
+
58
+ Where base_op_idx is the idx of the op we should use to match other related
59
+ ops. Note: base_op_idx is specified in non-reverse order, i.e. a base_op_idx
60
+ of 0 represents the first op in regular (non-reverse) order, 1 represents the
61
+ second op, etc.
62
+ """
63
+ results: List[Tuple[NSFusionType, int]] = []
64
+
65
+ # Possible syntaxes:
66
+ # * single op: torch.nn.Conv2d
67
+ # * multiple ops: (torch.nn.ReLU, torch.nn.Conv2d)
68
+ # For fusions, we only care about patterns composed of multiple ops.
69
+ # TODO(future PR): allow customizations from default patterns.
70
+ all_quant_patterns = _get_pattern_to_quantize_handlers(get_native_backend_config())
71
+
72
+ default_base_op_idx = 0
73
+ for quant_pattern in all_quant_patterns.keys():
74
+ # TODO: this is a temporary hack to flatten the patterns from quantization so
75
+ # that it works with the ns matcher function, maybe we should use `_is_match`
76
+ # in torch.ao.quantization.fx.match_utils to match the patterns
77
+ if isinstance(quant_pattern, tuple) and len(quant_pattern) == 2 and \
78
+ isinstance(quant_pattern[1], tuple) and len(quant_pattern[1]) == 2:
79
+ # flatten the pattern with form (nn.ReLU, (nn.BatchNorm2d, nn.Conv2d))
80
+ quant_pattern = (quant_pattern[0], quant_pattern[1][0], quant_pattern[1][1])
81
+
82
+ # Only patterns of multiple ops are fusions, ignore
83
+ # patterns which contain a single ops (they get matched
84
+ # without caring about fusions).
85
+ if isinstance(quant_pattern, tuple):
86
+ results.append((quant_pattern, default_base_op_idx)) # type: ignore[arg-type]
87
+
88
+ # For each pattern, add additional patterns with observers and
89
+ # fake quants at the end.
90
+ # TODO(future PR): if needed, implement matching for a node
91
+ # having multiple output observers.
92
+ for cls in (ObserverBase, FakeQuantizeBase):
93
+ if isinstance(quant_pattern, tuple):
94
+ new_pattern = (cls, *quant_pattern)
95
+ else:
96
+ new_pattern = (cls, quant_pattern)
97
+ results.append((new_pattern, default_base_op_idx)) # type: ignore[arg-type]
98
+
99
+
100
+ # After this point, results contains values such as
101
+ # [..., ((torch.nn.Relu, torch.nn.Conv2d), 0), ...]
102
+
103
+ # Patterns for matching fp16 emulation are not specified in the quantization
104
+ # fusion mappings. For now, define them here.
105
+ fp16_em_base_op_idx = 1
106
+ patterns_to_add = [
107
+ # linear-relu fp16 emulation:
108
+ # fp16_to_fp32 -> linear -> relu -> fp32_to_fp16
109
+ ((("to", torch.float16), F.relu, F.linear, "dequantize"), fp16_em_base_op_idx,),
110
+ # Conv-BN fusion (this happens outside of quantization patterns,
111
+ # which is why it is defined separately here).
112
+ ((nn.BatchNorm1d, nn.Conv1d), default_base_op_idx),
113
+ ((nn.BatchNorm2d, nn.Conv2d), default_base_op_idx),
114
+ ((nn.BatchNorm3d, nn.Conv3d), default_base_op_idx),
115
+ ((nn.ReLU, nn.BatchNorm1d, nn.Conv1d), default_base_op_idx),
116
+ ((nn.ReLU, nn.BatchNorm2d, nn.Conv2d), default_base_op_idx),
117
+ ((nn.ReLU, nn.BatchNorm3d, nn.Conv3d), default_base_op_idx),
118
+ ]
119
+ for p in patterns_to_add:
120
+ results.append(p) # type: ignore[arg-type]
121
+ results.append(((ObserverBase, *p[0]), p[1])) # type: ignore[arg-type]
122
+ results.append(((FakeQuantizeBase, *p[0]), p[1])) # type: ignore[arg-type]
123
+
124
+ return results
125
+
126
+
127
+ def end_node_matches_reversed_fusion(
128
+ end_node: Node,
129
+ reversed_fusion: NSFusionType,
130
+ gm: GraphModule,
131
+ seen_nodes: Set[Node],
132
+ ) -> bool:
133
+ """
134
+ Returns true if a pattern ending with `end_node` matches
135
+ the fusion pattern.
136
+ """
137
+ cur_node = end_node
138
+ for fusion_idx in range(len(reversed_fusion)):
139
+ # each node can only belong to one matched pattern
140
+ if cur_node in seen_nodes:
141
+ return False
142
+
143
+ cur_fusion_el = reversed_fusion[fusion_idx]
144
+
145
+ if cur_node.op == 'call_function':
146
+ fusion_el_is_fun = (not isinstance(cur_fusion_el, str)) and \
147
+ (not isinstance(cur_fusion_el, type))
148
+ if fusion_el_is_fun:
149
+ if cur_node.target != cur_fusion_el:
150
+ return False
151
+ if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
152
+ cur_node = cur_node.args[0]
153
+ else:
154
+ return False
155
+ else:
156
+ return False
157
+
158
+ elif cur_node.op == 'call_module':
159
+ fusion_el_is_mod = isinstance(cur_fusion_el, type)
160
+ if fusion_el_is_mod:
161
+ assert isinstance(cur_node.target, str)
162
+ target_mod = getattr_from_fqn(gm, cur_node.target)
163
+ if not isinstance(cur_fusion_el, type):
164
+ return False
165
+ if not isinstance(target_mod, cur_fusion_el):
166
+ return False
167
+ if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
168
+ cur_node = cur_node.args[0]
169
+ else:
170
+ return False
171
+ else:
172
+ return False
173
+
174
+ elif cur_node.op == 'call_method':
175
+ fusion_el_is_meth_with_second_arg = \
176
+ isinstance(cur_fusion_el, tuple) and len(cur_fusion_el) == 2
177
+ fusion_el_is_meth_without_args = isinstance(cur_fusion_el, str)
178
+ if fusion_el_is_meth_without_args or fusion_el_is_meth_with_second_arg:
179
+ if fusion_el_is_meth_without_args:
180
+ if cur_node.target != cur_fusion_el:
181
+ return False
182
+ else:
183
+ assert isinstance(cur_fusion_el, tuple)
184
+ if cur_node.target != cur_fusion_el[0]:
185
+ return False
186
+ elif len(cur_node.args) < 2:
187
+ return False
188
+ elif cur_node.args[1] != cur_fusion_el[1]:
189
+ return False
190
+
191
+ if len(cur_node.args) > 0 and isinstance(cur_node.args[0], Node):
192
+ cur_node = cur_node.args[0]
193
+ else:
194
+ return False
195
+ else:
196
+ return False
197
+ else:
198
+ return False
199
+
200
+ return True
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/qconfig_multi_mapping.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ from typing import Any, Callable, Dict, List, Union
5
+
6
+ import torch
7
+ from torch.ao.quantization import QConfigMapping
8
+ from torch.ao.quantization.qconfig_mapping import _QCONFIG_STYLE_ORDER
9
+ from torch.ao.quantization.qconfig import QConfigAny
10
+
11
+ __all__ = ["QConfigMultiMapping"]
12
+
13
+ _QCONFIG_STYLE_TO_METHOD: Dict[str, str] = {
14
+ "global_qconfig": "set_global",
15
+ "object_type_qconfigs": "set_object_type",
16
+ "module_name_regex_qconfigs": "set_module_name_regex",
17
+ "module_name_qconfigs": "set_module_name",
18
+ "module_name_object_type_order_qconfigs": "set_module_name_object_type_order",
19
+ }
20
+
21
+ def _remove_duplicates_and_none(qconfig_list: List[QConfigAny]) -> None:
22
+ to_remove = []
23
+ for index, cur_qconfig in enumerate(qconfig_list):
24
+ if cur_qconfig is None:
25
+ to_remove.append(index)
26
+ break
27
+ for checked_qconfig in qconfig_list[:index]:
28
+ if torch.ao.quantization.qconfig_equals(cur_qconfig, checked_qconfig):
29
+ to_remove.append(index)
30
+ break
31
+ for index in to_remove[::-1]:
32
+ qconfig_list.pop(index)
33
+
34
+ class QConfigMultiMapping:
35
+ """
36
+ This class, used with the prepare_n_shadows_model API, stores a list of :class:`torch.ao.quantization.QConfigMapping`s
37
+ so that multiple QConfigs can be specified for each QConfig matching style.
38
+
39
+ The user can specify QConfigs using the following methods (in increasing match priority):
40
+
41
+ ``set_global`` : sets the global (default) QConfigs
42
+
43
+ ``set_object_type`` : sets the QConfigs for a given module type, function, or method name
44
+
45
+ ``set_module_name_regex`` : sets the QConfigs for modules matching the given regex string
46
+
47
+ ``set_module_name`` : sets the QConfigs for modules matching the given module name
48
+
49
+ ``set_module_name_object_type_order`` : sets the QConfigs for modules matching a combination
50
+ of the given module name, object type, and the index at which the module appears
51
+
52
+ Note: Usage of set methods is the same as in QConfigMapping except with a passed in list of QConfigs rather than a
53
+ single QConfig.
54
+
55
+ Example usage::
56
+
57
+ qconfig_mapping = QConfigMultiMapping()
58
+ .set_global([qconfig1, qconfig2])
59
+ .set_object_type(torch.nn.Linear, [qconfig2, qconfig3])
60
+ .set_object_type(torch.nn.ReLU, [qconfig1])
61
+ .set_module_name_regex("foo.*bar.*conv[0-9]+", [qconfig2])
62
+ .set_module_name_regex("foo.*", [qconfig1, qconfig2, qconfig3])
63
+ .set_module_name("module1", [None])
64
+ .set_module_name("module2", [qconfig2])
65
+ .set_module_name_object_type_order("foo.bar", torch.nn.functional.linear, 0, [qconfig3])
66
+
67
+ """
68
+
69
+ def __init__(self):
70
+ # initialize this with 1 QConfigMapping to avoid corner cases
71
+ self.qconfig_mappings_list: List[QConfigMapping] = [QConfigMapping()]
72
+
73
+ def _handle_list_size_mismatch(
74
+ self, qconfig_list: List[QConfigAny], style: str
75
+ ) -> None:
76
+ # this method handles cases where the size of qconfig_list does not match
77
+ # the size of qconfig_mappings_list.
78
+ # Issue: Consider a user inserting global_qconfig A and B first, then inserting
79
+ # qconfig C as an object_type_qconfig for conv ops. If we internally store
80
+ # 1 QConfigMapping with A and C and another with just B, then the
81
+ # second QConfigMapping will match B to conv ops (which is not wanted), since B is global.
82
+
83
+ # we avoid this by maintaining the invariant that if any QConfigMapping
84
+ # has a qconfig style+key with a qconfig in it, all QConfigMappings must
85
+ # have either a qconfig or None for that same style+key. In the above
86
+ # example, a None qconfig would prevent the unwanted match in the
87
+ # second QConfigMapping
88
+
89
+ if len(qconfig_list) > len(self.qconfig_mappings_list):
90
+ # Case: we have more qconfigs (in qconfig_list) than QConfigMappings
91
+
92
+ # Add new QConfigMappings (initialized so we maintain the `invariant`)
93
+
94
+ new_qconfig_mapping = QConfigMapping()
95
+ # searches other QConfigMappings for qconfig style+keys
96
+ # that need to be inserted as `None` into the new QConfigMapping
97
+ for qconfig_mapping in self.qconfig_mappings_list:
98
+
99
+ # global_qconfig has None by default
100
+ for check_style in _QCONFIG_STYLE_ORDER[1:]:
101
+ qconfigs_dict = getattr(qconfig_mapping, check_style)
102
+ target_qconfigs_dict = getattr(new_qconfig_mapping, check_style)
103
+ for key in qconfigs_dict:
104
+ target_qconfigs_dict[key] = None
105
+ break
106
+
107
+ # insert copies of this new QConfigMapping until all entires
108
+ # in qconfig_list can fit among the QConfigMappings
109
+ while len(qconfig_list) > len(self.qconfig_mappings_list):
110
+ self.qconfig_mappings_list.append(copy.deepcopy(new_qconfig_mapping))
111
+ else:
112
+ # Case: we have fewer qconfigs in qconfig_list than QConfigMappings
113
+
114
+ # pad qconfig_list with `None` until length is same
115
+ while len(qconfig_list) < len(self.qconfig_mappings_list):
116
+ qconfig_list.append(None)
117
+
118
+ # this function applies the insertion method across each QConfigMapping
119
+ def _insert_qconfig_list(
120
+ self,
121
+ style: str,
122
+ args: List[Union[str, int, Callable]],
123
+ qconfig_list: List[QConfigAny],
124
+ ) -> None:
125
+
126
+ # we remove duplicates and None to make the ordering of qconfigs
127
+ # deterministic upon insertion.
128
+ _remove_duplicates_and_none(qconfig_list)
129
+
130
+ self._handle_list_size_mismatch(qconfig_list, style)
131
+ method_name = _QCONFIG_STYLE_TO_METHOD[style]
132
+ for qconfig_mapping, qconfig in zip(self.qconfig_mappings_list, qconfig_list):
133
+ # uses QConfigMapping set method to insert qconfig
134
+ set_method = getattr(qconfig_mapping, method_name)
135
+ set_method(*args, qconfig)
136
+
137
+ def set_global(self, global_qconfig_list: List[QConfigAny]) -> QConfigMultiMapping:
138
+ """
139
+ Set global QConfigs
140
+ see :func:`~torch.ao.quantization.QConfigMapping.set_global()` for more info
141
+ """
142
+ self._insert_qconfig_list("global_qconfig", [], global_qconfig_list)
143
+ return self
144
+
145
+ def set_object_type(
146
+ self, object_type: Union[Callable, str], qconfig_list: List[QConfigAny]
147
+ ) -> QConfigMultiMapping:
148
+ """
149
+ Set object type QConfigs
150
+ see :func:`~torch.ao.quantization.QConfigMapping.set_object_type()` for more info
151
+ """
152
+ self._insert_qconfig_list("object_type_qconfigs", [object_type], qconfig_list)
153
+ return self
154
+
155
+ def set_module_name_regex(
156
+ self, module_name_regex: str, qconfig_list: List[QConfigAny]
157
+ ) -> QConfigMultiMapping:
158
+ """
159
+ Set module_name_regex QConfigs
160
+ see :func:`~torch.ao.quantization.QConfigMapping.set_module_name_regex()` for more info
161
+ """
162
+ self._insert_qconfig_list(
163
+ "module_name_regex_qconfigs", [module_name_regex], qconfig_list
164
+ )
165
+ return self
166
+
167
+ def set_module_name(
168
+ self, module_name: str, qconfig_list: List[QConfigAny]
169
+ ) -> QConfigMultiMapping:
170
+ """
171
+ Set module_name QConfigs
172
+ see :func:`~torch.ao.quantization.QConfigMapping.set_module_name()` for more info
173
+ """
174
+ self._insert_qconfig_list("module_name_qconfigs", [module_name], qconfig_list)
175
+ return self
176
+
177
+ def set_module_name_object_type_order(
178
+ self,
179
+ module_name: str,
180
+ object_type: Callable,
181
+ index: int,
182
+ qconfig_list: List[QConfigAny],
183
+ ) -> QConfigMultiMapping:
184
+ """
185
+ Set module_name QConfigs
186
+ see :func:`~torch.ao.quantization.QConfigMapping.set_module_name_object_type_order()` for more info
187
+ """
188
+ self._insert_qconfig_list(
189
+ "module_name_object_type_order_qconfigs",
190
+ [module_name, object_type, index],
191
+ qconfig_list,
192
+ )
193
+ return self
194
+
195
+ def __repr__(self):
196
+ return (
197
+ self.__class__.__name__ +
198
+ " [" +
199
+ "".join(f"\n{qconfig_mapping.__repr__()}," for qconfig_mapping in self.qconfig_mappings_list) +
200
+ "\n]"
201
+ )
202
+
203
+ @classmethod
204
+ def from_list_qconfig_mapping(
205
+ cls, qconfig_mapping_list: List[QConfigMapping]
206
+ ) -> QConfigMultiMapping:
207
+ """
208
+ Creates a QConfigMultiMapping from a list of QConfigMappings
209
+ """
210
+ new_qconfig_multi_mapping = cls()
211
+
212
+ new_qconfig_multi_mapping.qconfig_mappings_list = copy.deepcopy(
213
+ qconfig_mapping_list
214
+ )
215
+
216
+ # we need to avoid the issue described in _handle_list_size_mismatch,
217
+ # so we reinsert all the qconfigs using the QConfigMultiMapping
218
+ # set methods
219
+
220
+ # go through all qconfig styles
221
+ # note: global can be ignored since it is None by default
222
+ for style in _QCONFIG_STYLE_ORDER[1:]:
223
+
224
+ # gather all key+qconfigs for current style
225
+ # into qconfig_dict_list
226
+ qconfig_dict_list: Dict[Any, List[QConfigAny]] = {}
227
+ for qconfig_mapping in qconfig_mapping_list:
228
+ qconfig_dict = getattr(qconfig_mapping, style)
229
+ for key, qconfig in qconfig_dict.items():
230
+ if key not in qconfig_dict_list:
231
+ qconfig_dict_list[key] = []
232
+ qconfig_dict_list[key].append(qconfig)
233
+
234
+ # reinsert all gathered key+qconfigs
235
+ set_method_name = _QCONFIG_STYLE_TO_METHOD[style]
236
+ set_method = getattr(new_qconfig_multi_mapping, set_method_name)
237
+ for key, qconfig_list in qconfig_dict_list.items():
238
+ if isinstance(key, tuple):
239
+ set_method(*key, qconfig_list)
240
+ else:
241
+ set_method(key, qconfig_list)
242
+
243
+ return new_qconfig_multi_mapping
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/utils.py ADDED
@@ -0,0 +1,533 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ import operator
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.ao.nn.intrinsic.quantized as nniq
7
+ import torch.ao.nn.quantized as nnq
8
+
9
+ toq = torch.ops.quantized
10
+ from typing import Tuple, Callable, Dict, Set, List, Optional, Union
11
+
12
+ from torch.fx import GraphModule
13
+ from torch.fx.graph import Node
14
+ from torch.ao.quantization import (
15
+ ObserverBase,
16
+ FakeQuantizeBase,
17
+ )
18
+ from torch.ao.quantization.utils import getattr_from_fqn
19
+ from torch.ao.quantization.observer import _is_activation_post_process
20
+
21
+ from .ns_types import NSNodeTargetType, NSResultsType
22
+
23
+ # TODO(future PR): consider deleting this enum and using the torch types
24
+ # directly. This might be tricky because it is not a one to one mapping.
25
+ class NodeInputOrOutputType(enum.Enum):
26
+ FP32 = enum.auto() # torch.float
27
+ INT8 = enum.auto() # torch.qint8 or torch.quint8
28
+ FP16 = enum.auto() # torch.float16
29
+ UNKNOWN = enum.auto() # we cannot determine input/output dtype
30
+ # TODO(future PR): while these functions can support multiple dtypes,
31
+ # for the purposes of numerical debugging we want to get the actual
32
+ # dtype used in the model. We will likely need some kind of dtype
33
+ # propagation to estimate this.
34
+ FP32_OR_INT8 = enum.auto() # either torch.float or torch.quint8 or torch.qint8
35
+ # TODO(future PRs): dynamic quant, fake quant, etc
36
+
37
+
38
+ def get_node_first_input_and_output_type(
39
+ node: Node,
40
+ gm: GraphModule,
41
+ logger_cls: Callable,
42
+ node_type_to_io_type_map: Dict[str, Set[NSNodeTargetType]],
43
+ ) -> Tuple[NodeInputOrOutputType, NodeInputOrOutputType]:
44
+
45
+ # TODO(future PR): clean this up
46
+ FUNS_IO_TYPE_FP32 = node_type_to_io_type_map["funs_io_type_fp32"]
47
+ FUNS_IO_TYPE_FP16 = node_type_to_io_type_map["funs_io_type_fp16"]
48
+ FUNS_IO_TYPE_INT8 = node_type_to_io_type_map["funs_io_type_int8"]
49
+ FUNS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["funs_io_type_fp32_or_int8"]
50
+ MODS_IO_TYPE_FP32 = node_type_to_io_type_map["mods_io_type_fp32"]
51
+ MODS_IO_TYPE_INT8 = node_type_to_io_type_map["mods_io_type_int8"]
52
+ MODS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["mods_io_type_fp32_or_int8"]
53
+ METHS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["meths_io_type_fp32_or_int8"]
54
+
55
+ if node.op == "call_function":
56
+ if node.target in FUNS_IO_TYPE_FP32:
57
+ return (NodeInputOrOutputType.FP32, NodeInputOrOutputType.FP32)
58
+ if node.target in FUNS_IO_TYPE_FP16:
59
+ return (NodeInputOrOutputType.FP16, NodeInputOrOutputType.FP16)
60
+ elif node.target in FUNS_IO_TYPE_INT8:
61
+ return (NodeInputOrOutputType.INT8, NodeInputOrOutputType.INT8)
62
+ elif node.target in FUNS_IO_TYPE_FP32_OR_INT8:
63
+ first_arg = get_normalized_nth_input(node, gm, 0)
64
+ assert isinstance(first_arg, Node)
65
+ (
66
+ _prev_node_input_type,
67
+ prev_node_output_type,
68
+ ) = get_node_first_input_and_output_type(
69
+ first_arg, gm, logger_cls, node_type_to_io_type_map
70
+ )
71
+ return (prev_node_output_type, prev_node_output_type)
72
+ else:
73
+ return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
74
+
75
+ elif node.op == "call_module":
76
+ assert node.op == "call_module"
77
+ assert isinstance(node.target, str)
78
+ mod = getattr_from_fqn(gm, node.target)
79
+ is_known_fp32_or_int8_input_module = any(
80
+ isinstance(mod, target_type) for target_type in MODS_IO_TYPE_FP32_OR_INT8 # type: ignore[arg-type]
81
+ )
82
+ if (
83
+ isinstance(mod, (logger_cls, ObserverBase, FakeQuantizeBase)) # type: ignore[arg-type]
84
+ or is_known_fp32_or_int8_input_module
85
+ ):
86
+ # A logger or observer's input and output type is the output
87
+ # type of the preceding node.
88
+ first_arg = get_normalized_nth_input(node, gm, 0)
89
+ assert isinstance(first_arg, Node)
90
+ (
91
+ _prev_node_input_type,
92
+ prev_node_output_type,
93
+ ) = get_node_first_input_and_output_type(
94
+ first_arg, gm, logger_cls, node_type_to_io_type_map
95
+ )
96
+ return (prev_node_output_type, prev_node_output_type)
97
+ is_known_fp32_input_module = any(
98
+ isinstance(mod, target_type) for target_type in MODS_IO_TYPE_FP32 # type: ignore[arg-type]
99
+ )
100
+ is_known_int8_input_module = any(
101
+ isinstance(mod, target_type) for target_type in MODS_IO_TYPE_INT8 # type: ignore[arg-type]
102
+ )
103
+ if is_known_fp32_input_module:
104
+ return (NodeInputOrOutputType.FP32, NodeInputOrOutputType.FP32)
105
+ elif is_known_int8_input_module:
106
+ return (NodeInputOrOutputType.INT8, NodeInputOrOutputType.INT8)
107
+ else:
108
+ return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
109
+
110
+ elif node.op == "call_method":
111
+ if node.target == "dequantize":
112
+ # Dequantize is a special node because it allows multiple input types.
113
+ # So, we look up the output type of the previous node and return that
114
+ # as the input type of this node instance.
115
+ prev_node = get_normalized_nth_input(node, gm, 0)
116
+ assert isinstance(prev_node, Node)
117
+ (
118
+ _prev_node_input_type,
119
+ prev_node_output_type,
120
+ ) = get_node_first_input_and_output_type(
121
+ prev_node, gm, logger_cls, node_type_to_io_type_map
122
+ )
123
+ return (prev_node_output_type, NodeInputOrOutputType.FP32)
124
+
125
+ elif node.target == "to":
126
+ # to is a special node because it allows multiple input types.
127
+ # So, we look up the output type of the previous node and return that
128
+ # as the input type of this node instance. We also look up the target
129
+ # of to and return the correct output type.
130
+ prev_node = get_normalized_nth_input(node, gm, 0)
131
+ assert isinstance(prev_node, Node)
132
+ (
133
+ _prev_node_input_type,
134
+ prev_node_output_type,
135
+ ) = get_node_first_input_and_output_type(
136
+ prev_node, gm, logger_cls, node_type_to_io_type_map
137
+ )
138
+
139
+ cur_node_dtype_target = get_normalized_nth_input(node, gm, 1)
140
+ assert (
141
+ cur_node_dtype_target is torch.float16
142
+ ), f"{cur_node_dtype_target} handling needs to be added"
143
+
144
+ return (prev_node_output_type, NodeInputOrOutputType.FP16)
145
+
146
+ elif node.target in METHS_IO_TYPE_FP32_OR_INT8:
147
+ first_arg = get_normalized_nth_input(node, gm, 0)
148
+ assert isinstance(first_arg, Node)
149
+ (
150
+ _prev_node_input_type,
151
+ prev_node_output_type,
152
+ ) = get_node_first_input_and_output_type(
153
+ first_arg, gm, logger_cls, node_type_to_io_type_map
154
+ )
155
+ return (prev_node_output_type, prev_node_output_type)
156
+
157
+ return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
158
+ else:
159
+ return (NodeInputOrOutputType.UNKNOWN, NodeInputOrOutputType.UNKNOWN)
160
+
161
+
162
+ def get_node_input_qparams(
163
+ node: Node,
164
+ gm: GraphModule,
165
+ node_type_to_io_type_map: Dict[str, Set[NSNodeTargetType]],
166
+ ) -> Optional[Tuple[Union[torch.Tensor, float], Union[torch.Tensor, int]]]:
167
+ """
168
+ Returns the qparams (scale, zero_point) of the first input to `node`,
169
+ if they can be inferred from the graph.
170
+ """
171
+ prev_node = get_normalized_nth_input(node, gm, 0)
172
+
173
+ if not isinstance(prev_node, Node):
174
+ return None
175
+
176
+ MODS_IO_TYPE_FP32_OR_INT8 = node_type_to_io_type_map["mods_io_type_fp32_or_int8"]
177
+
178
+ def _get_scale_zp_from_function_args(node, gm, scale_arg_idx, zp_arg_idx):
179
+ scale_node = get_normalized_nth_input(node, gm, scale_arg_idx)
180
+ zp_node = get_normalized_nth_input(node, gm, zp_arg_idx)
181
+ assert isinstance(scale_node, Node) and isinstance(scale_node.target, str)
182
+ assert isinstance(zp_node, Node) and isinstance(zp_node.target, str)
183
+ scale_obj = getattr_from_fqn(gm, scale_node.target)
184
+ zp_obj = getattr_from_fqn(gm, zp_node.target)
185
+ return (scale_obj, zp_obj)
186
+
187
+ if prev_node.op == "call_function":
188
+
189
+ # quantize - read the args directly
190
+ if prev_node.target == torch.quantize_per_tensor:
191
+ return _get_scale_zp_from_function_args(prev_node, gm, 1, 2)
192
+ elif prev_node.target in (toq.add, toq.add_relu, toq.mul, toq.mul_relu):
193
+ return _get_scale_zp_from_function_args(prev_node, gm, 2, 3)
194
+
195
+ return None
196
+ # TODO(future PR): handle more functionals
197
+ # TODO(future PR): handle functional ops which inherit qparams from input
198
+
199
+ elif prev_node.op == "call_module":
200
+
201
+ # get type of the module
202
+ assert isinstance(prev_node.target, str)
203
+ module_obj = getattr_from_fqn(gm, prev_node.target)
204
+ if isinstance(
205
+ module_obj,
206
+ (
207
+ nnq.Linear,
208
+ nnq.Conv1d,
209
+ nnq.Conv2d,
210
+ nniq.ConvReLU2d,
211
+ nnq.Conv3d,
212
+ nnq.BatchNorm2d,
213
+ nnq.BatchNorm3d,
214
+ nnq.ConvTranspose1d,
215
+ nnq.ConvTranspose2d,
216
+ nnq.ELU,
217
+ nnq.GroupNorm,
218
+ nnq.InstanceNorm1d,
219
+ nnq.InstanceNorm2d,
220
+ nnq.InstanceNorm3d,
221
+ nnq.LayerNorm,
222
+ nnq.Hardswish,
223
+ nnq.LeakyReLU,
224
+ nnq.ReLU6,
225
+ nniq.BNReLU2d,
226
+ nniq.BNReLU3d,
227
+ nniq.ConvReLU1d,
228
+ nniq.ConvReLU2d,
229
+ nniq.ConvReLU3d,
230
+ nniq.LinearReLU,
231
+ ),
232
+ ):
233
+ return (module_obj.scale, module_obj.zero_point) # type: ignore[return-value]
234
+
235
+ is_known_fp32_or_int8_input_module = any(
236
+ isinstance(module_obj, target_type) for target_type in MODS_IO_TYPE_FP32_OR_INT8 # type: ignore[arg-type]
237
+ )
238
+ if is_known_fp32_or_int8_input_module:
239
+ return get_node_input_qparams(prev_node, gm, node_type_to_io_type_map)
240
+
241
+ return None
242
+
243
+
244
+ def return_first_non_observer_node(
245
+ node: Node,
246
+ gm: GraphModule,
247
+ ) -> Node:
248
+ """
249
+ If node is not an observer, returns it. If node is an observer,
250
+ navigates up the graph and returns the first parent which is not an
251
+ observer. For example,
252
+
253
+ graph: (node_non_obs), node = node_non_obs : returns node_non_obs
254
+ graph: (node_non_obs -> obs0), node = obs0 : returns node_non_obs
255
+ graph: (node_non_obs -> obs0 -> fq0), node = fq0 : returns node_non_obs
256
+ """
257
+ if node.op == "call_module":
258
+ node_obj = getattr_from_fqn(gm, node.target) # type: ignore[arg-type]
259
+ if _is_activation_post_process(node_obj):
260
+ assert len(node.args) == 1
261
+ assert isinstance(node.args[0], Node)
262
+ node = node.args[0]
263
+ # code duplication intended, not worth refactoring
264
+ assert isinstance(node.target, str)
265
+ node_obj = getattr_from_fqn(gm, node.target)
266
+ if _is_activation_post_process(node_obj):
267
+ assert len(node.args) == 1
268
+ assert isinstance(node.args[0], Node)
269
+ node = node.args[0]
270
+ return node
271
+
272
+
273
+ def get_number_of_non_param_args(
274
+ node: Node,
275
+ gm: GraphModule,
276
+ ) -> int:
277
+ """
278
+ Assumes that all non-param args occur first. Returns the number of
279
+ non-param args expected for a node. For example, for
280
+
281
+ F.linear(x, weight, bias)
282
+
283
+ Returns 1, because x is a non-param arg and weight and bias are params.
284
+ For
285
+
286
+ lstm_mod(x, hid)
287
+
288
+ Returns 2, because both x and hid are non-param args.
289
+ """
290
+ if node.op == "call_module":
291
+ node_obj = getattr_from_fqn(gm, node.target) # type: ignore[arg-type]
292
+ if isinstance(node_obj, nn.LSTM):
293
+ return 2
294
+
295
+ # default is 1
296
+ return 1
297
+
298
+
299
+ def get_arg_indices_of_inputs_to_log(node: Node) -> List[int]:
300
+ """
301
+ Returns the indices of args of the node which we should attach
302
+ loggers to, if input logging is enabled.
303
+
304
+ For example,
305
+ * for (x + y), returns [0, 1]
306
+ * for (1 + y), returns [1]
307
+ * for (x + 1), returns [0]
308
+ * for (linear(x, w, b)) returns [0]
309
+ * by default, returns [0]
310
+ """
311
+ if len(node.args) == 0:
312
+ return []
313
+ if node.op == "call_function" and (
314
+ # TODO(future PR): use relationship map instead of hardcoding
315
+ node.target in (torch.add, torch.ops.quantized.add, operator.add)
316
+ or node.target in (torch.mul, torch.ops.quantized.mul, operator.mul)
317
+ ):
318
+ result = []
319
+ for i in range(2):
320
+ if type(node.args[i]) == Node:
321
+ result.append(i)
322
+ return result
323
+ return [0]
324
+
325
+
326
+ def get_target_type_str(node: Node, gm: GraphModule) -> str:
327
+ """
328
+ Returns a string representation of the type of the function or module
329
+ pointed to by this node, or '' for other node types.
330
+ """
331
+ target_type = ""
332
+ if node.op in ("call_function", "call_method"):
333
+ target_type = torch.typename(node.target)
334
+ elif node.op == "call_module":
335
+ assert isinstance(node.target, str)
336
+ target_mod = getattr_from_fqn(gm, node.target)
337
+ target_type = torch.typename(target_mod)
338
+ return target_type
339
+
340
+
341
+ def rekey_logger_info_on_node_name_of_model(
342
+ results: NSResultsType,
343
+ model_name: str,
344
+ ) -> NSResultsType:
345
+ """
346
+ Rekeys the layer name of a results dictionary to use node names
347
+ from `model_name`.
348
+
349
+ For example, transforms
350
+
351
+ {'base_op_1_0': {'node_output': {'model_a':
352
+ [{'ref_node_name': 'linear1', ...}]}}}
353
+
354
+ into
355
+
356
+ {'linear1': {'node_output': {'model_a':
357
+ [{'ref_node_name': 'linear1', ...}]}}}
358
+
359
+ Note: we cannot use these node names directly because they are not
360
+ guaranteed to be consistent across models. This is why we extract
361
+ the results first and rekey afterwards.
362
+ """
363
+ new_results = {}
364
+ for old_layer_name, result_type_to_results in results.items():
365
+ new_layer_name = None
366
+ for model_name_to_results in result_type_to_results.values():
367
+ for cur_model_name, list_of_results in model_name_to_results.items():
368
+ if cur_model_name == model_name:
369
+ assert len(list_of_results)
370
+ new_layer_name = list_of_results[0]["ref_node_name"]
371
+ else:
372
+ continue
373
+ if new_layer_name is not None:
374
+ new_results[new_layer_name] = result_type_to_results
375
+ else:
376
+ new_results[old_layer_name] = result_type_to_results
377
+ return new_results
378
+
379
+
380
+ def maybe_add_missing_fqns(results: NSResultsType) -> None:
381
+ """
382
+ If `fqn` entries are filled in for one of the models in `results`, copies
383
+ them over to any models which do not have them filled out.
384
+
385
+ A common use case benefitting from this is comparing a model prepared by
386
+ quantization to a quantized model. In this case, the model prepared by
387
+ quantization would have `fqn` entries, and the quantized model would not.
388
+ """
389
+
390
+ # Check in the first result to find any model with fqn entries defined.
391
+ model_name_with_fqns = None
392
+ for result_type_to_results in results.values():
393
+ for model_name_to_results in result_type_to_results.values():
394
+ for model_name, model_results in model_name_to_results.items():
395
+ if len(model_results) > 0:
396
+ if model_results[0]["fqn"] is not None:
397
+ model_name_with_fqns = model_name
398
+ break
399
+ break
400
+ break
401
+
402
+ if model_name_with_fqns:
403
+ for result_type_to_results in results.values():
404
+ for model_name_to_results in result_type_to_results.values():
405
+ ref_model_results = model_name_to_results[model_name_with_fqns]
406
+ for model_name, model_results in model_name_to_results.items():
407
+ if model_name == model_name_with_fqns:
408
+ continue
409
+ for i in range(len(model_results)):
410
+ fqn = ref_model_results[i]["fqn"]
411
+ model_results[i]["fqn"] = fqn
412
+
413
+
414
+ def maybe_dequantize_first_two_tensor_args_and_handle_tuples(f):
415
+ def inner(*args, **kwargs):
416
+ a0, a1, *a_other = args
417
+
418
+ if (isinstance(a0, tuple) and isinstance(a1, tuple)) or (
419
+ isinstance(a0, list) and isinstance(a1, list)
420
+ ):
421
+ results = []
422
+ for el0, el1 in zip(a0, a1):
423
+ new_args = (el0, el1, *a_other)
424
+ results.append(inner(*new_args, **kwargs))
425
+ return results
426
+
427
+ elif isinstance(a0, torch.Tensor) and isinstance(a1, torch.Tensor):
428
+ if a0.is_quantized:
429
+ a0 = a0.dequantize()
430
+ if a1.is_quantized:
431
+ a1 = a1.dequantize()
432
+
433
+ # for the purposes of this util, only handle floats
434
+ if a0.dtype != torch.float or a1.dtype != torch.float:
435
+ return None
436
+
437
+ new_args = (a0, a1, *a_other)
438
+ return f(*new_args, **kwargs)
439
+
440
+ return inner
441
+
442
+
443
+ @maybe_dequantize_first_two_tensor_args_and_handle_tuples
444
+ def compute_sqnr(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
445
+ """
446
+ Computes the SQNR between `x` and `y`.
447
+
448
+ Args:
449
+ x: Tensor or tuple of tensors
450
+ y: Tensor or tuple of tensors
451
+
452
+ Return:
453
+ float or tuple of floats
454
+ """
455
+ Ps = torch.norm(x)
456
+ Pn = torch.norm(x - y)
457
+ return 20 * torch.log10(Ps / Pn)
458
+
459
+
460
+ @maybe_dequantize_first_two_tensor_args_and_handle_tuples
461
+ def compute_normalized_l2_error(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
462
+ """
463
+ Computes the normalized L2 error between `x` and `y`.
464
+
465
+ Args:
466
+ x: Tensor or tuple of tensors
467
+ y: Tensor or tuple of tensors
468
+
469
+ Return:
470
+ float or tuple of floats
471
+ """
472
+ return torch.sqrt(((x - y) ** 2).sum() / (x ** 2).sum())
473
+
474
+
475
+ @maybe_dequantize_first_two_tensor_args_and_handle_tuples
476
+ def compute_cosine_similarity(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
477
+ """
478
+ Computes the cosine similarity between `x` and `y`.
479
+
480
+ Args:
481
+ x: Tensor or tuple of tensors
482
+ y: Tensor or tuple of tensors
483
+
484
+ Return:
485
+ float or tuple of floats
486
+ """
487
+ # For convolutions, the shape of the quantized weight has one additional
488
+ # dimension compared to the shape of the fp32 weight. Match the shapes
489
+ # to enable cosine similarity comparison.
490
+ x = x.reshape(1, -1)
491
+ y = y.reshape(1, -1)
492
+ return torch.nn.functional.cosine_similarity(x, y)
493
+
494
+ def op_type_supports_shadowing(node: Node) -> bool:
495
+ if node.op == 'call_function':
496
+ if node.target in (torch.add, torch.mul, operator.add, operator.mul, torch.cat, torch.stack):
497
+ # shadowing for ops with multiple tensor inputs is not implemented yet
498
+ return False
499
+ return True
500
+
501
+ def get_normalized_nth_input(node: Node, gm: GraphModule, idx: int) -> Node:
502
+ """
503
+ Given a node, gets the n'th input to that node, normalizing
504
+ args and kwargs to the best of its ability.
505
+ """
506
+ try:
507
+ norm_args_and_kwargs = node.normalized_arguments(
508
+ gm, normalize_to_only_use_kwargs=True)
509
+ if norm_args_and_kwargs is not None:
510
+ norm_args, norm_kwargs = norm_args_and_kwargs
511
+ assert len(norm_args) + len(norm_kwargs) > idx
512
+ if idx < len(norm_args):
513
+ return norm_args[idx]
514
+ else:
515
+ # note: in Python 3.7+ dicts are ordered
516
+ return list(norm_kwargs.values())[idx]
517
+ else:
518
+ assert len(node.args) + len(node.kwargs) > idx
519
+ if idx < len(node.args):
520
+ return node.args[idx] # type: ignore[return-value]
521
+ else:
522
+ kwargs_idx = idx + len(node.args)
523
+ return list(node.kwargs.values())[kwargs_idx] # type: ignore[return-value]
524
+ except RuntimeError:
525
+ # this RuntimeError happens when node argument normalization
526
+ # requires typehints to proceed, such as for torch.add where
527
+ # either the first, second or both arguments could be tensors
528
+ assert len(node.args) + len(node.kwargs) > idx
529
+ if idx < len(node.args):
530
+ return node.args[idx] # type: ignore[return-value]
531
+ else:
532
+ kwargs_idx = idx + len(node.args)
533
+ return list(node.kwargs.values())[kwargs_idx] # type: ignore[return-value]
videollama2/lib/python3.10/site-packages/torch/ao/ns/fx/weight_utils.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ import torch.ao.nn.quantized.dynamic as nnqd
5
+ import torch.ao.nn.quantized as nnq
6
+ import torch.ao.nn.intrinsic.qat as nniqat
7
+ import torch.ao.nn.qat as nnqat
8
+ import torch.ao.nn.intrinsic as nni
9
+ import torch.ao.nn.intrinsic.quantized as nniq
10
+ toq = torch.ops.quantized
11
+ from torch.fx import GraphModule
12
+ from torch.fx.graph import Node
13
+
14
+ from .utils import (
15
+ get_target_type_str,
16
+ getattr_from_fqn,
17
+ return_first_non_observer_node,
18
+ )
19
+
20
+ from .ns_types import (
21
+ NSSingleResultValuesType,
22
+ NSSingleResultType,
23
+ )
24
+
25
+ from typing import List, Optional, Dict, Callable
26
+
27
+ def mod_weight_detach(mod: nn.Module) -> torch.Tensor:
28
+ return mod.weight.detach() # type: ignore[operator]
29
+
30
+ def mod_0_weight_detach(mod: nn.Module) -> torch.Tensor:
31
+ return mod[0].weight.detach() # type: ignore[index]
32
+
33
+ def mod_weight_bias_0(mod: nn.Module) -> torch.Tensor:
34
+ return mod._weight_bias()[0] # type: ignore[operator]
35
+
36
+ def get_lstm_weight(mod: nn.Module) -> List[torch.Tensor]:
37
+ res = []
38
+ for idx, param_name in enumerate(mod._flat_weights_names): # type: ignore[arg-type]
39
+ if 'weight_ih_l' in param_name or 'weight_hh_l' in param_name:
40
+ param_value = mod._flat_weights[idx].detach() # type: ignore[index]
41
+ res.append(param_value)
42
+ return res
43
+
44
+ def get_qlstm_weight(mod: nn.Module) -> List[torch.Tensor]:
45
+ res = []
46
+ for weight_value in mod._all_weight_values: # type: ignore[union-attr]
47
+ res.append(weight_value.param.__getstate__()[0][4][0].__getstate__()[0][0])
48
+ res.append(weight_value.param.__getstate__()[0][4][1].__getstate__()[0][0])
49
+ return res
50
+
51
+ def get_conv_mod_weight(mod: nn.Module) -> torch.Tensor:
52
+ if (
53
+ isinstance(mod, (nn.Conv1d, nn.Conv2d, nn.Conv3d))
54
+ ):
55
+ return mod.weight.detach()
56
+ elif (
57
+ isinstance(mod, (nni.ConvReLU1d, nni.ConvReLU2d, nni.ConvReLU3d))
58
+ ):
59
+ return mod[0].weight.detach()
60
+ else:
61
+ return mod._weight_bias()[0] # type: ignore[operator]
62
+
63
+ def get_linear_mod_weight(mod: nn.Module) -> torch.Tensor:
64
+ if isinstance(mod, nn.Linear):
65
+ return mod.weight.detach()
66
+ elif isinstance(mod, nni.LinearReLU):
67
+ return mod[0].weight.detach()
68
+ else:
69
+ return mod._weight_bias()[0] # type: ignore[operator]
70
+
71
+ def get_lstm_mod_weights(mod: nn.Module) -> List[torch.Tensor]:
72
+ # TODO(future PR): make more generic, handle everything
73
+ if isinstance(mod, nn.LSTM):
74
+ res = []
75
+ for idx, param_name in enumerate(mod._flat_weights_names):
76
+ if 'weight_ih_l' in param_name or 'weight_hh_l' in param_name:
77
+ param_value = mod._flat_weights[idx].detach()
78
+ res.append(param_value)
79
+ return res
80
+ else:
81
+ assert isinstance(mod, nnqd.LSTM), f"type {type(mod)} not handled yet"
82
+ res = []
83
+ for weight_value in mod._all_weight_values:
84
+ res.append(weight_value.param.__getstate__()[0][4][0].__getstate__()[0][0])
85
+ res.append(weight_value.param.__getstate__()[0][4][1].__getstate__()[0][0])
86
+ return res
87
+
88
+ def get_conv_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
89
+ # traverse backwards from the weight arg, accounting for any observers
90
+ weight_arg_node = node.args[1]
91
+ assert isinstance(weight_arg_node, Node)
92
+ weight_node = return_first_non_observer_node(weight_arg_node, gm)
93
+ assert isinstance(weight_node, Node)
94
+ assert weight_node.op == 'get_attr'
95
+ weight = getattr_from_fqn(gm, weight_node.target) # type: ignore[arg-type]
96
+ return weight.detach()
97
+
98
+ def get_qconv_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
99
+ # qconv state is arg 1
100
+ qconv_state_node = node.args[1]
101
+ assert isinstance(qconv_state_node, Node)
102
+ assert qconv_state_node.op == 'get_attr'
103
+ qconv_state_obj = getattr_from_fqn(gm, qconv_state_node.target) # type: ignore[arg-type]
104
+ return qconv_state_obj.weight()
105
+
106
+ def get_linear_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
107
+ # traverse backwards from the weight arg, accounting for any observers
108
+ # supported patterns:
109
+ # weight -> obs -> linear
110
+ # weight -> to(torch.float16) -> dequantize -> linear
111
+ linear_second_arg = node.args[1]
112
+ assert isinstance(linear_second_arg, Node)
113
+
114
+ if linear_second_arg.op == 'call_module':
115
+ # weight -> obs -> linear
116
+ weight_arg_node = node.args[1]
117
+ assert isinstance(weight_arg_node, Node)
118
+ weight_node = weight_arg_node.args[0]
119
+ assert isinstance(weight_node, Node)
120
+ assert weight_node.op == 'get_attr'
121
+ weight = getattr_from_fqn(gm, weight_node.target) # type: ignore[arg-type]
122
+ return weight.detach()
123
+ elif linear_second_arg.op == 'call_method':
124
+ # weight -> to(torch.float16) -> dequantize -> linear
125
+ assert linear_second_arg.op == 'call_method'
126
+ dequant_node = node.args[1]
127
+ assert isinstance(dequant_node, Node)
128
+ to_fp16_node = dequant_node.args[0]
129
+ assert isinstance(to_fp16_node, Node)
130
+ # extract the dtype, so we can cast to it before returning
131
+ target_dtype = to_fp16_node.args[1]
132
+ weight_node = to_fp16_node.args[0]
133
+ assert isinstance(weight_node, Node)
134
+ assert weight_node.op == 'get_attr'
135
+ weight = getattr_from_fqn(gm, weight_node.target) # type: ignore[arg-type]
136
+ # return the weight with fp16 cast
137
+ return weight.detach().to(target_dtype)
138
+ else:
139
+ assert linear_second_arg.op == 'get_attr'
140
+ weight = getattr_from_fqn(gm, linear_second_arg.target) # type: ignore[arg-type]
141
+ return weight.detach()
142
+
143
+ def get_qlinear_fun_weight(node: Node, gm: GraphModule) -> torch.Tensor:
144
+ # packed weight is arg 1
145
+ packed_weight_node = node.args[1]
146
+ assert isinstance(packed_weight_node, Node)
147
+ assert packed_weight_node.op == 'get_attr'
148
+ packed_weight = getattr_from_fqn(gm, packed_weight_node.target) # type: ignore[arg-type]
149
+ # TODO(future PR): why does packed_weight.unpack() not work?
150
+ (weight, _bias), _name = packed_weight.__getstate__()
151
+ return weight
152
+
153
+ def get_op_to_type_to_weight_extraction_fn() -> Dict[str, Dict[Callable, Callable]]:
154
+
155
+ op_to_type_to_weight_extraction_fn: Dict[str, Dict[Callable, Callable]] = {
156
+ 'call_module': {
157
+ # Conv1d
158
+ nn.Conv1d: mod_weight_detach,
159
+ nni.ConvReLU1d: mod_0_weight_detach,
160
+ nnq.Conv1d: mod_weight_bias_0,
161
+ nnqat.Conv1d: mod_weight_detach,
162
+ nniqat.ConvBn1d: mod_weight_detach,
163
+ nniqat.ConvBnReLU1d: mod_weight_detach,
164
+ nniqat.ConvReLU1d: mod_weight_detach,
165
+ nniq.ConvReLU1d: mod_weight_bias_0,
166
+ # Conv2d
167
+ nn.Conv2d: mod_weight_detach,
168
+ nni.ConvReLU2d: mod_0_weight_detach,
169
+ nnq.Conv2d: mod_weight_bias_0,
170
+ nnqat.Conv2d: mod_weight_detach,
171
+ nniqat.ConvBn2d: mod_weight_detach,
172
+ nniqat.ConvBnReLU2d: mod_weight_detach,
173
+ nniqat.ConvReLU2d: mod_weight_detach,
174
+ nniq.ConvReLU2d: mod_weight_bias_0,
175
+ # Conv3d
176
+ nn.Conv3d: mod_weight_detach,
177
+ nni.ConvReLU3d: mod_0_weight_detach,
178
+ nnq.Conv3d: mod_weight_bias_0,
179
+ nnqat.Conv3d: mod_weight_detach,
180
+ nniqat.ConvBn3d: mod_weight_detach,
181
+ nniqat.ConvBnReLU3d: mod_weight_detach,
182
+ nniqat.ConvReLU3d: mod_weight_detach,
183
+ nniq.ConvReLU3d: mod_weight_bias_0,
184
+ # Linear
185
+ nn.Linear: mod_weight_detach,
186
+ nnq.Linear: mod_weight_bias_0,
187
+ nni.LinearReLU: mod_0_weight_detach,
188
+ nniq.LinearReLU: mod_weight_bias_0,
189
+ nnqat.Linear: mod_weight_detach,
190
+ nnqd.Linear: mod_weight_bias_0,
191
+ nniqat.LinearReLU: mod_weight_detach,
192
+ nniqat.LinearBn1d: mod_weight_detach,
193
+ nn.modules.linear.NonDynamicallyQuantizableLinear: mod_weight_detach,
194
+ # LSTM
195
+ nn.LSTM: get_lstm_weight,
196
+ nnqd.LSTM: get_qlstm_weight,
197
+ },
198
+ 'call_function': {
199
+ # Conv
200
+ F.conv1d: get_conv_fun_weight,
201
+ F.conv2d: get_conv_fun_weight,
202
+ F.conv3d: get_conv_fun_weight,
203
+ toq.conv1d: get_qconv_fun_weight,
204
+ toq.conv2d: get_qconv_fun_weight,
205
+ toq.conv3d: get_qconv_fun_weight,
206
+ toq.conv1d_relu: get_qconv_fun_weight,
207
+ toq.conv2d_relu: get_qconv_fun_weight,
208
+ toq.conv3d_relu: get_qconv_fun_weight,
209
+ # Linear
210
+ F.linear: get_linear_fun_weight,
211
+ toq.linear: get_qlinear_fun_weight,
212
+ toq.linear_relu: get_qlinear_fun_weight,
213
+ },
214
+ }
215
+
216
+ return op_to_type_to_weight_extraction_fn
217
+
218
+ def extract_weight_from_node(
219
+ node: Node,
220
+ gm: GraphModule,
221
+ op_to_type_to_weight_extraction_fn: Optional[Dict[str, Dict[Callable, Callable]]] = None,
222
+ ) -> Optional[NSSingleResultType]:
223
+ res_type = NSSingleResultValuesType.WEIGHT.value
224
+
225
+ # Not all graphmodules have _node_name_to_scope, so only fill it
226
+ # out if it exists.
227
+ fqn = None
228
+ if hasattr(gm, '_node_name_to_scope'):
229
+ fqn = gm._node_name_to_scope[node.name][0] # type: ignore[index]
230
+
231
+ if op_to_type_to_weight_extraction_fn is None:
232
+ op_to_type_to_weight_extraction_fn = get_op_to_type_to_weight_extraction_fn()
233
+
234
+ ref_node_type = get_target_type_str(node, gm)
235
+ # for extracting weights, these are always the same
236
+ prev_node_type = ref_node_type
237
+
238
+ if node.op == 'call_function':
239
+ function_mapping = op_to_type_to_weight_extraction_fn['call_function']
240
+ for target_fn_type, weight_extraction_fn in function_mapping.items():
241
+ if node.target == target_fn_type:
242
+ weight = weight_extraction_fn(node, gm)
243
+ return {
244
+ 'type': res_type,
245
+ 'values': [weight],
246
+ 'prev_node_name': node.name,
247
+ 'prev_node_target_type': prev_node_type,
248
+ 'ref_node_name': node.name,
249
+ 'ref_node_target_type': ref_node_type,
250
+ 'index_within_arg': 0,
251
+ 'index_of_arg': 0,
252
+ 'fqn': fqn,
253
+ }
254
+
255
+ elif node.op == 'call_module':
256
+ # for call_module, we need to look up the modules to do the type check
257
+ assert isinstance(node.target, str)
258
+ mod = getattr_from_fqn(gm, node.target)
259
+ module_mapping = op_to_type_to_weight_extraction_fn['call_module']
260
+ for target_mod_type, weight_extraction_fn in module_mapping.items():
261
+ if type(mod) == target_mod_type:
262
+ weight = weight_extraction_fn(mod)
263
+ return {
264
+ 'type': res_type,
265
+ 'values': [weight],
266
+ 'prev_node_name': node.name,
267
+ 'prev_node_target_type': prev_node_type,
268
+ 'ref_node_name': node.name,
269
+ 'ref_node_target_type': ref_node_type,
270
+ 'index_within_arg': 0,
271
+ 'index_of_arg': 0,
272
+ 'fqn': fqn,
273
+ }
274
+
275
+ return None
videollama2/lib/python3.10/site-packages/torch/include/dnnl_threadpool.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright 2020 Intel Corporation
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *******************************************************************************/
16
+
17
+ #ifndef DNNL_THREADPOOL_H
18
+ #define DNNL_THREADPOOL_H
19
+
20
+ #include "oneapi/dnnl/dnnl_threadpool.h"
21
+
22
+ #endif /* DNNL_THREADPOOL_H */
videollama2/lib/python3.10/site-packages/torch/include/dnnl_types.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright 2020 Intel Corporation
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *******************************************************************************/
16
+
17
+ #ifndef DNNL_TYPES_H
18
+ #define DNNL_TYPES_H
19
+
20
+ #include "oneapi/dnnl/dnnl_types.h"
21
+
22
+ #endif /* DNNL_TYPES_H */
videollama2/lib/python3.10/site-packages/torch/include/dnnl_version.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright 2020 Intel Corporation
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ *******************************************************************************/
16
+
17
+ #ifndef DNNL_VERSION_H
18
+ #define DNNL_VERSION_H
19
+
20
+ #include "oneapi/dnnl/dnnl_version.h"
21
+
22
+ #endif /* DNNL_VERSION_H */
videollama2/lib/python3.10/site-packages/torch/include/fp16.h ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #ifndef FP16_H
3
+ #define FP16_H
4
+
5
+ #include <fp16/fp16.h>
6
+
7
+ #if defined(PSIMD_H)
8
+ #include <fp16/psimd.h>
9
+ #endif
10
+
11
+ #endif /* FP16_H */
videollama2/lib/python3.10/site-packages/torch/include/libshm.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ #include <ATen/MapAllocator.h>
4
+
5
+ #ifdef __cplusplus
6
+
7
+ void libshm_init(const char* manager_exec_path);
8
+
9
+ // Superclass to run a constructor before at::RefcountedMapAllocator
10
+ class THManagedMapAllocatorInit {
11
+ protected:
12
+ THManagedMapAllocatorInit(const char* manager_handle, const char* filename);
13
+ std::string manager_handle_;
14
+ };
15
+
16
+ // Like a at::RefcountedMapAllocator, but it also makes use of an external
17
+ // shared memory manager process to ensure that shared memory regions actually
18
+ // get freed in the end (even if processes lose the memory).
19
+ class THManagedMapAllocator : private THManagedMapAllocatorInit,
20
+ public at::RefcountedMapAllocator {
21
+ public:
22
+ THManagedMapAllocator(
23
+ const char* manager_handle,
24
+ const char* filename,
25
+ int flags,
26
+ size_t size);
27
+
28
+ void close() override;
29
+
30
+ ~THManagedMapAllocator() override {
31
+ close();
32
+ }
33
+
34
+ static at::DataPtr makeDataPtr(
35
+ const char* manager_handle,
36
+ const char* filename,
37
+ int flags,
38
+ size_t size);
39
+ static THManagedMapAllocator* fromDataPtr(const at::DataPtr&);
40
+
41
+ const char* manager_handle() const {
42
+ return manager_handle_.c_str();
43
+ }
44
+ };
45
+
46
+ #endif
videollama2/lib/python3.10/site-packages/torch/include/psimd.h ADDED
@@ -0,0 +1,1384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ #ifndef PSIMD_H
3
+ #define PSIMD_H
4
+
5
+ #if defined(__CUDA_ARCH__)
6
+ /* CUDA compiler */
7
+ #define PSIMD_INTRINSIC __forceinline__ __device__
8
+ #elif defined(__OPENCL_VERSION__)
9
+ /* OpenCL compiler */
10
+ #define PSIMD_INTRINSIC inline static
11
+ #elif defined(__INTEL_COMPILER)
12
+ /* Intel compiler, even on Windows */
13
+ #define PSIMD_INTRINSIC inline static __attribute__((__always_inline__))
14
+ #elif defined(__GNUC__)
15
+ /* GCC-compatible compiler (gcc/clang/icc) */
16
+ #define PSIMD_INTRINSIC inline static __attribute__((__always_inline__))
17
+ #elif defined(_MSC_VER)
18
+ /* MSVC-compatible compiler (cl/icl/clang-cl) */
19
+ #define PSIMD_INTRINSIC __forceinline static
20
+ #elif defined(__cplusplus)
21
+ /* Generic C++ compiler */
22
+ #define PSIMD_INTRINSIC inline static
23
+ #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
24
+ /* Generic C99 compiler */
25
+ #define PSIMD_INTRINSIC inline static
26
+ #else
27
+ /* Generic C compiler */
28
+ #define PSIMD_INTRINSIC static
29
+ #endif
30
+
31
+ #if defined(__GNUC__) || defined(__clang__)
32
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
33
+ #include <arm_neon.h>
34
+ #endif
35
+
36
+ #if defined(__SSE2__)
37
+ #include <emmintrin.h>
38
+ #endif
39
+
40
+ #if defined(__SSE3__)
41
+ #include <pmmintrin.h>
42
+ #endif
43
+
44
+ #if defined(__SSSE3__)
45
+ #include <tmmintrin.h>
46
+ #endif
47
+
48
+ #if defined(__SSE4_1__)
49
+ #include <smmintrin.h>
50
+ #endif
51
+
52
+ #if defined(__SSE4_2__)
53
+ #include <nmmintrin.h>
54
+ #endif
55
+
56
+ #if defined(__AVX__)
57
+ #include <immintrin.h>
58
+ #endif
59
+ #elif defined(_MSC_VER)
60
+ #include <intrin.h>
61
+ #endif
62
+
63
+ #if defined(__cplusplus)
64
+ #define PSIMD_CXX_SYNTAX
65
+ #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
66
+ #define PSIMD_C11_SYNTAX
67
+ #elif defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
68
+ #define PSIMD_C99_SYNTAX
69
+ #else
70
+ #define PSIMD_C89_SYNTAX
71
+ #endif
72
+
73
+ #if defined(__cplusplus) && (__cplusplus >= 201103L)
74
+ #include <cstddef>
75
+ #include <cstdint>
76
+ #elif !defined(__OPENCL_VERSION__)
77
+ #include <stddef.h>
78
+ #include <stdint.h>
79
+ #endif
80
+
81
+ #if defined(__GNUC__) || defined(__clang__)
82
+ #define PSIMD_HAVE_F64 0
83
+ #define PSIMD_HAVE_F32 1
84
+ #define PSIMD_HAVE_U8 1
85
+ #define PSIMD_HAVE_S8 1
86
+ #define PSIMD_HAVE_U16 1
87
+ #define PSIMD_HAVE_S16 1
88
+ #define PSIMD_HAVE_U32 1
89
+ #define PSIMD_HAVE_S32 1
90
+ #define PSIMD_HAVE_U64 0
91
+ #define PSIMD_HAVE_S64 0
92
+
93
+ typedef int8_t psimd_s8 __attribute__((vector_size(16), aligned(1)));
94
+ typedef uint8_t psimd_u8 __attribute__((vector_size(16), aligned(1)));
95
+ typedef int16_t psimd_s16 __attribute__((vector_size(16), aligned(2)));
96
+ typedef uint16_t psimd_u16 __attribute__((vector_size(16), aligned(2)));
97
+ typedef int32_t psimd_s32 __attribute__((vector_size(16), aligned(4)));
98
+ typedef uint32_t psimd_u32 __attribute__((vector_size(16), aligned(4)));
99
+ typedef float psimd_f32 __attribute__((vector_size(16), aligned(4)));
100
+
101
+ typedef struct {
102
+ psimd_s8 lo;
103
+ psimd_s8 hi;
104
+ } psimd_s8x2;
105
+
106
+ typedef struct {
107
+ psimd_u8 lo;
108
+ psimd_u8 hi;
109
+ } psimd_u8x2;
110
+
111
+ typedef struct {
112
+ psimd_s16 lo;
113
+ psimd_s16 hi;
114
+ } psimd_s16x2;
115
+
116
+ typedef struct {
117
+ psimd_u16 lo;
118
+ psimd_u16 hi;
119
+ } psimd_u16x2;
120
+
121
+ typedef struct {
122
+ psimd_s32 lo;
123
+ psimd_s32 hi;
124
+ } psimd_s32x2;
125
+
126
+ typedef struct {
127
+ psimd_u32 lo;
128
+ psimd_u32 hi;
129
+ } psimd_u32x2;
130
+
131
+ typedef struct {
132
+ psimd_f32 lo;
133
+ psimd_f32 hi;
134
+ } psimd_f32x2;
135
+
136
+ /* Bit casts */
137
+ PSIMD_INTRINSIC psimd_u32x2 psimd_cast_s32x2_u32x2(psimd_s32x2 v) {
138
+ return (psimd_u32x2) { .lo = (psimd_u32) v.lo, .hi = (psimd_u32) v.hi };
139
+ }
140
+
141
+ PSIMD_INTRINSIC psimd_f32x2 psimd_cast_s32x2_f32x2(psimd_s32x2 v) {
142
+ return (psimd_f32x2) { .lo = (psimd_f32) v.lo, .hi = (psimd_f32) v.hi };
143
+ }
144
+
145
+ PSIMD_INTRINSIC psimd_s32x2 psimd_cast_u32x2_s32x2(psimd_u32x2 v) {
146
+ return (psimd_s32x2) { .lo = (psimd_s32) v.lo, .hi = (psimd_s32) v.hi };
147
+ }
148
+
149
+ PSIMD_INTRINSIC psimd_f32x2 psimd_cast_u32x2_f32x2(psimd_u32x2 v) {
150
+ return (psimd_f32x2) { .lo = (psimd_f32) v.lo, .hi = (psimd_f32) v.hi };
151
+ }
152
+
153
+ PSIMD_INTRINSIC psimd_s32x2 psimd_cast_f32x2_s32x2(psimd_f32x2 v) {
154
+ return (psimd_s32x2) { .lo = (psimd_s32) v.lo, .hi = (psimd_s32) v.hi };
155
+ }
156
+
157
+ PSIMD_INTRINSIC psimd_u32x2 psimd_cast_f32x2_u32x2(psimd_f32x2 v) {
158
+ return (psimd_u32x2) { .lo = (psimd_u32) v.lo, .hi = (psimd_u32) v.hi };
159
+ }
160
+
161
+ /* Swap */
162
+ PSIMD_INTRINSIC void psimd_swap_s8(psimd_s8 a[1], psimd_s8 b[1]) {
163
+ const psimd_s8 new_a = *b;
164
+ const psimd_s8 new_b = *a;
165
+ *a = new_a;
166
+ *b = new_b;
167
+ }
168
+
169
+ PSIMD_INTRINSIC void psimd_swap_u8(psimd_u8 a[1], psimd_u8 b[1]) {
170
+ const psimd_u8 new_a = *b;
171
+ const psimd_u8 new_b = *a;
172
+ *a = new_a;
173
+ *b = new_b;
174
+ }
175
+
176
+ PSIMD_INTRINSIC void psimd_swap_s16(psimd_s16 a[1], psimd_s16 b[1]) {
177
+ const psimd_s16 new_a = *b;
178
+ const psimd_s16 new_b = *a;
179
+ *a = new_a;
180
+ *b = new_b;
181
+ }
182
+
183
+ PSIMD_INTRINSIC void psimd_swap_u16(psimd_u16 a[1], psimd_u16 b[1]) {
184
+ const psimd_u16 new_a = *b;
185
+ const psimd_u16 new_b = *a;
186
+ *a = new_a;
187
+ *b = new_b;
188
+ }
189
+
190
+ PSIMD_INTRINSIC void psimd_swap_s32(psimd_s32 a[1], psimd_s32 b[1]) {
191
+ const psimd_s32 new_a = *b;
192
+ const psimd_s32 new_b = *a;
193
+ *a = new_a;
194
+ *b = new_b;
195
+ }
196
+
197
+ PSIMD_INTRINSIC void psimd_swap_u32(psimd_u32 a[1], psimd_u32 b[1]) {
198
+ const psimd_u32 new_a = *b;
199
+ const psimd_u32 new_b = *a;
200
+ *a = new_a;
201
+ *b = new_b;
202
+ }
203
+
204
+ PSIMD_INTRINSIC void psimd_swap_f32(psimd_f32 a[1], psimd_f32 b[1]) {
205
+ const psimd_f32 new_a = *b;
206
+ const psimd_f32 new_b = *a;
207
+ *a = new_a;
208
+ *b = new_b;
209
+ }
210
+
211
+ /* Zero-initialization */
212
+ PSIMD_INTRINSIC psimd_s8 psimd_zero_s8(void) {
213
+ return (psimd_s8) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
214
+ }
215
+
216
+ PSIMD_INTRINSIC psimd_u8 psimd_zero_u8(void) {
217
+ return (psimd_u8) { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
218
+ }
219
+
220
+ PSIMD_INTRINSIC psimd_s16 psimd_zero_s16(void) {
221
+ return (psimd_s16) { 0, 0, 0, 0, 0, 0, 0, 0 };
222
+ }
223
+
224
+ PSIMD_INTRINSIC psimd_u16 psimd_zero_u16(void) {
225
+ return (psimd_u16) { 0, 0, 0, 0, 0, 0, 0, 0 };
226
+ }
227
+
228
+ PSIMD_INTRINSIC psimd_s32 psimd_zero_s32(void) {
229
+ return (psimd_s32) { 0, 0, 0, 0 };
230
+ }
231
+
232
+ PSIMD_INTRINSIC psimd_u32 psimd_zero_u32(void) {
233
+ return (psimd_u32) { 0, 0, 0, 0 };
234
+ }
235
+
236
+ PSIMD_INTRINSIC psimd_f32 psimd_zero_f32(void) {
237
+ return (psimd_f32) { 0.0f, 0.0f, 0.0f, 0.0f };
238
+ }
239
+
240
+ /* Initialization to the same constant */
241
+ PSIMD_INTRINSIC psimd_s8 psimd_splat_s8(int8_t c) {
242
+ return (psimd_s8) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c };
243
+ }
244
+
245
+ PSIMD_INTRINSIC psimd_u8 psimd_splat_u8(uint8_t c) {
246
+ return (psimd_u8) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c };
247
+ }
248
+
249
+ PSIMD_INTRINSIC psimd_s16 psimd_splat_s16(int16_t c) {
250
+ return (psimd_s16) { c, c, c, c, c, c, c, c };
251
+ }
252
+
253
+ PSIMD_INTRINSIC psimd_u16 psimd_splat_u16(uint16_t c) {
254
+ return (psimd_u16) { c, c, c, c, c, c, c, c };
255
+ }
256
+
257
+ PSIMD_INTRINSIC psimd_s32 psimd_splat_s32(int32_t c) {
258
+ return (psimd_s32) { c, c, c, c };
259
+ }
260
+
261
+ PSIMD_INTRINSIC psimd_u32 psimd_splat_u32(uint32_t c) {
262
+ return (psimd_u32) { c, c, c, c };
263
+ }
264
+
265
+ PSIMD_INTRINSIC psimd_f32 psimd_splat_f32(float c) {
266
+ return (psimd_f32) { c, c, c, c };
267
+ }
268
+
269
+ /* Load vector */
270
+ PSIMD_INTRINSIC psimd_s8 psimd_load_s8(const void* address) {
271
+ return *((const psimd_s8*) address);
272
+ }
273
+
274
+ PSIMD_INTRINSIC psimd_u8 psimd_load_u8(const void* address) {
275
+ return *((const psimd_u8*) address);
276
+ }
277
+
278
+ PSIMD_INTRINSIC psimd_s16 psimd_load_s16(const void* address) {
279
+ return *((const psimd_s16*) address);
280
+ }
281
+
282
+ PSIMD_INTRINSIC psimd_u16 psimd_load_u16(const void* address) {
283
+ return *((const psimd_u16*) address);
284
+ }
285
+
286
+ PSIMD_INTRINSIC psimd_s32 psimd_load_s32(const void* address) {
287
+ return *((const psimd_s32*) address);
288
+ }
289
+
290
+ PSIMD_INTRINSIC psimd_u32 psimd_load_u32(const void* address) {
291
+ return *((const psimd_u32*) address);
292
+ }
293
+
294
+ PSIMD_INTRINSIC psimd_f32 psimd_load_f32(const void* address) {
295
+ return *((const psimd_f32*) address);
296
+ }
297
+
298
+ PSIMD_INTRINSIC psimd_s8 psimd_load_splat_s8(const void* address) {
299
+ return psimd_splat_s8(*((const int8_t*) address));
300
+ }
301
+
302
+ PSIMD_INTRINSIC psimd_u8 psimd_load_splat_u8(const void* address) {
303
+ return psimd_splat_u8(*((const uint8_t*) address));
304
+ }
305
+
306
+ PSIMD_INTRINSIC psimd_s16 psimd_load_splat_s16(const void* address) {
307
+ return psimd_splat_s16(*((const int16_t*) address));
308
+ }
309
+
310
+ PSIMD_INTRINSIC psimd_u16 psimd_load_splat_u16(const void* address) {
311
+ return psimd_splat_u16(*((const uint16_t*) address));
312
+ }
313
+
314
+ PSIMD_INTRINSIC psimd_s32 psimd_load_splat_s32(const void* address) {
315
+ return psimd_splat_s32(*((const int32_t*) address));
316
+ }
317
+
318
+ PSIMD_INTRINSIC psimd_u32 psimd_load_splat_u32(const void* address) {
319
+ return psimd_splat_u32(*((const uint32_t*) address));
320
+ }
321
+
322
+ PSIMD_INTRINSIC psimd_f32 psimd_load_splat_f32(const void* address) {
323
+ return psimd_splat_f32(*((const float*) address));
324
+ }
325
+
326
+ PSIMD_INTRINSIC psimd_s32 psimd_load1_s32(const void* address) {
327
+ return (psimd_s32) { *((const int32_t*) address), 0, 0, 0 };
328
+ }
329
+
330
+ PSIMD_INTRINSIC psimd_u32 psimd_load1_u32(const void* address) {
331
+ return (psimd_u32) { *((const uint32_t*) address), 0, 0, 0 };
332
+ }
333
+
334
+ PSIMD_INTRINSIC psimd_f32 psimd_load1_f32(const void* address) {
335
+ return (psimd_f32) { *((const float*) address), 0.0f, 0.0f, 0.0f };
336
+ }
337
+
338
+ PSIMD_INTRINSIC psimd_s32 psimd_load2_s32(const void* address) {
339
+ const int32_t* address_s32 = (const int32_t*) address;
340
+ return (psimd_s32) { address_s32[0], address_s32[1], 0, 0 };
341
+ }
342
+
343
+ PSIMD_INTRINSIC psimd_u32 psimd_load2_u32(const void* address) {
344
+ const uint32_t* address_u32 = (const uint32_t*) address;
345
+ return (psimd_u32) { address_u32[0], address_u32[1], 0, 0 };
346
+ }
347
+
348
+ PSIMD_INTRINSIC psimd_f32 psimd_load2_f32(const void* address) {
349
+ const float* address_f32 = (const float*) address;
350
+ return (psimd_f32) { address_f32[0], address_f32[1], 0.0f, 0.0f };
351
+ }
352
+
353
+ PSIMD_INTRINSIC psimd_s32 psimd_load3_s32(const void* address) {
354
+ const int32_t* address_s32 = (const int32_t*) address;
355
+ return (psimd_s32) { address_s32[0], address_s32[1], address_s32[2], 0 };
356
+ }
357
+
358
+ PSIMD_INTRINSIC psimd_u32 psimd_load3_u32(const void* address) {
359
+ const uint32_t* address_u32 = (const uint32_t*) address;
360
+ return (psimd_u32) { address_u32[0], address_u32[1], address_u32[2], 0 };
361
+ }
362
+
363
+ PSIMD_INTRINSIC psimd_f32 psimd_load3_f32(const void* address) {
364
+ const float* address_f32 = (const float*) address;
365
+ return (psimd_f32) { address_f32[0], address_f32[1], address_f32[2], 0.0f };
366
+ }
367
+
368
+ PSIMD_INTRINSIC psimd_s32 psimd_load4_s32(const void* address) {
369
+ return psimd_load_s32(address);
370
+ }
371
+
372
+ PSIMD_INTRINSIC psimd_u32 psimd_load4_u32(const void* address) {
373
+ return psimd_load_u32(address);
374
+ }
375
+
376
+ PSIMD_INTRINSIC psimd_f32 psimd_load4_f32(const void* address) {
377
+ return psimd_load_f32(address);
378
+ }
379
+
380
+ PSIMD_INTRINSIC psimd_f32 psimd_load_stride2_f32(const void* address) {
381
+ const psimd_f32 v0x1x = psimd_load_f32(address);
382
+ const psimd_f32 vx2x3 = psimd_load_f32((const float*) address + 3);
383
+ #if defined(__clang__)
384
+ return __builtin_shufflevector(v0x1x, vx2x3, 0, 2, 5, 7);
385
+ #else
386
+ return __builtin_shuffle(v0x1x, vx2x3, (psimd_s32) { 0, 2, 5, 7 });
387
+ #endif
388
+ }
389
+
390
+ PSIMD_INTRINSIC psimd_f32 psimd_load1_stride2_f32(const void* address) {
391
+ return psimd_load_f32(address);
392
+ }
393
+
394
+ PSIMD_INTRINSIC psimd_f32 psimd_load2_stride2_f32(const void* address) {
395
+ const float* address_f32 = (const float*) address;
396
+ return (psimd_f32) { address_f32[0], address_f32[2], 0.0f, 0.0f };
397
+ }
398
+
399
+ PSIMD_INTRINSIC psimd_f32 psimd_load3_stride2_f32(const void* address) {
400
+ const psimd_f32 v0x1x = psimd_load_f32(address);
401
+ const psimd_f32 v2zzz = psimd_load1_f32((const float*) address + 2);
402
+ #if defined(__clang__)
403
+ return __builtin_shufflevector(v0x1x, v2zzz, 0, 2, 4, 6);
404
+ #else
405
+ return __builtin_shuffle(v0x1x, v2zzz, (psimd_s32) { 0, 2, 4, 6 });
406
+ #endif
407
+ }
408
+
409
+ PSIMD_INTRINSIC psimd_f32 psimd_load4_stride2_f32(const void* address) {
410
+ return psimd_load_stride2_f32(address);
411
+ }
412
+
413
+ PSIMD_INTRINSIC psimd_f32 psimd_load_stride_f32(const void* address, size_t stride) {
414
+ const float* address0_f32 = (const float*) address;
415
+ const float* address1_f32 = address0_f32 + stride;
416
+ const float* address2_f32 = address1_f32 + stride;
417
+ const float* address3_f32 = address2_f32 + stride;
418
+ return (psimd_f32) { *address0_f32, *address1_f32, *address2_f32, *address3_f32 };
419
+ }
420
+
421
+ PSIMD_INTRINSIC psimd_f32 psimd_load1_stride_f32(const void* address, size_t stride) {
422
+ return psimd_load1_f32(address);
423
+ }
424
+
425
+ PSIMD_INTRINSIC psimd_f32 psimd_load2_stride_f32(const void* address, size_t stride) {
426
+ const float* address_f32 = (const float*) address;
427
+ return (psimd_f32) { address_f32[0], address_f32[stride], 0.0f, 0.0f };
428
+ }
429
+
430
+ PSIMD_INTRINSIC psimd_f32 psimd_load3_stride_f32(const void* address, size_t stride) {
431
+ const float* address0_f32 = (const float*) address;
432
+ const float* address1_f32 = address0_f32 + stride;
433
+ const float* address2_f32 = address1_f32 + stride;
434
+ return (psimd_f32) { *address0_f32, *address1_f32, *address2_f32, 0.0f };
435
+ }
436
+
437
+ PSIMD_INTRINSIC psimd_f32 psimd_load4_stride_f32(const void* address, size_t stride) {
438
+ return psimd_load_stride_f32(address, stride);
439
+ }
440
+
441
+ /* Store vector */
442
+ PSIMD_INTRINSIC void psimd_store_s8(void* address, psimd_s8 value) {
443
+ *((psimd_s8*) address) = value;
444
+ }
445
+
446
+ PSIMD_INTRINSIC void psimd_store_u8(void* address, psimd_u8 value) {
447
+ *((psimd_u8*) address) = value;
448
+ }
449
+
450
+ PSIMD_INTRINSIC void psimd_store_s16(void* address, psimd_s16 value) {
451
+ *((psimd_s16*) address) = value;
452
+ }
453
+
454
+ PSIMD_INTRINSIC void psimd_store_u16(void* address, psimd_u16 value) {
455
+ *((psimd_u16*) address) = value;
456
+ }
457
+
458
+ PSIMD_INTRINSIC void psimd_store_s32(void* address, psimd_s32 value) {
459
+ *((psimd_s32*) address) = value;
460
+ }
461
+
462
+ PSIMD_INTRINSIC void psimd_store_u32(void* address, psimd_u32 value) {
463
+ *((psimd_u32*) address) = value;
464
+ }
465
+
466
+ PSIMD_INTRINSIC void psimd_store_f32(void* address, psimd_f32 value) {
467
+ *((psimd_f32*) address) = value;
468
+ }
469
+
470
+ PSIMD_INTRINSIC void psimd_store1_s32(void* address, psimd_s32 value) {
471
+ *((int32_t*) address) = value[0];
472
+ }
473
+
474
+ PSIMD_INTRINSIC void psimd_store1_u32(void* address, psimd_u32 value) {
475
+ *((uint32_t*) address) = value[0];
476
+ }
477
+
478
+ PSIMD_INTRINSIC void psimd_store1_f32(void* address, psimd_f32 value) {
479
+ *((float*) address) = value[0];
480
+ }
481
+
482
+ PSIMD_INTRINSIC void psimd_store2_s32(void* address, psimd_s32 value) {
483
+ int32_t* address_s32 = (int32_t*) address;
484
+ address_s32[0] = value[0];
485
+ address_s32[1] = value[1];
486
+ }
487
+
488
+ PSIMD_INTRINSIC void psimd_store2_u32(void* address, psimd_u32 value) {
489
+ uint32_t* address_u32 = (uint32_t*) address;
490
+ address_u32[0] = value[0];
491
+ address_u32[1] = value[1];
492
+ }
493
+
494
+ PSIMD_INTRINSIC void psimd_store2_f32(void* address, psimd_f32 value) {
495
+ float* address_f32 = (float*) address;
496
+ address_f32[0] = value[0];
497
+ address_f32[1] = value[1];
498
+ }
499
+
500
+ PSIMD_INTRINSIC void psimd_store3_s32(void* address, psimd_s32 value) {
501
+ int32_t* address_s32 = (int32_t*) address;
502
+ address_s32[0] = value[0];
503
+ address_s32[1] = value[1];
504
+ address_s32[2] = value[2];
505
+ }
506
+
507
+ PSIMD_INTRINSIC void psimd_store3_u32(void* address, psimd_u32 value) {
508
+ uint32_t* address_u32 = (uint32_t*) address;
509
+ address_u32[0] = value[0];
510
+ address_u32[1] = value[1];
511
+ address_u32[2] = value[2];
512
+ }
513
+
514
+ PSIMD_INTRINSIC void psimd_store3_f32(void* address, psimd_f32 value) {
515
+ float* address_f32 = (float*) address;
516
+ address_f32[0] = value[0];
517
+ address_f32[1] = value[1];
518
+ address_f32[2] = value[2];
519
+ }
520
+
521
+ PSIMD_INTRINSIC void psimd_store4_s32(void* address, psimd_s32 value) {
522
+ psimd_store_s32(address, value);
523
+ }
524
+
525
+ PSIMD_INTRINSIC void psimd_store4_u32(void* address, psimd_u32 value) {
526
+ psimd_store_u32(address, value);
527
+ }
528
+
529
+ PSIMD_INTRINSIC void psimd_store4_f32(void* address, psimd_f32 value) {
530
+ psimd_store_f32(address, value);
531
+ }
532
+
533
+ PSIMD_INTRINSIC void psimd_store_stride_f32(void* address, size_t stride, psimd_f32 value) {
534
+ float* address0_f32 = (float*) address;
535
+ float* address1_f32 = address0_f32 + stride;
536
+ float* address2_f32 = address1_f32 + stride;
537
+ float* address3_f32 = address2_f32 + stride;
538
+ *address0_f32 = value[0];
539
+ *address1_f32 = value[1];
540
+ *address2_f32 = value[2];
541
+ *address3_f32 = value[3];
542
+ }
543
+
544
+ PSIMD_INTRINSIC void psimd_store1_stride_f32(void* address, size_t stride, psimd_f32 value) {
545
+ psimd_store1_f32(address, value);
546
+ }
547
+
548
+ PSIMD_INTRINSIC void psimd_store2_stride_f32(void* address, size_t stride, psimd_f32 value) {
549
+ float* address_f32 = (float*) address;
550
+ address_f32[0] = value[0];
551
+ address_f32[stride] = value[1];
552
+ }
553
+
554
+ PSIMD_INTRINSIC void psimd_store3_stride_f32(void* address, size_t stride, psimd_f32 value) {
555
+ float* address0_f32 = (float*) address;
556
+ float* address1_f32 = address0_f32 + stride;
557
+ float* address2_f32 = address1_f32 + stride;
558
+ *address0_f32 = value[0];
559
+ *address1_f32 = value[1];
560
+ *address2_f32 = value[2];
561
+ }
562
+
563
+ /* Vector addition */
564
+ PSIMD_INTRINSIC psimd_s8 psimd_add_s8(psimd_s8 a, psimd_s8 b) {
565
+ return a + b;
566
+ }
567
+
568
+ PSIMD_INTRINSIC psimd_u8 psimd_add_u8(psimd_u8 a, psimd_u8 b) {
569
+ return a + b;
570
+ }
571
+
572
+ PSIMD_INTRINSIC psimd_s16 psimd_add_s16(psimd_s16 a, psimd_s16 b) {
573
+ return a + b;
574
+ }
575
+
576
+ PSIMD_INTRINSIC psimd_u16 psimd_add_u16(psimd_u16 a, psimd_u16 b) {
577
+ return a + b;
578
+ }
579
+
580
+ PSIMD_INTRINSIC psimd_s32 psimd_add_s32(psimd_s32 a, psimd_s32 b) {
581
+ return a + b;
582
+ }
583
+
584
+ PSIMD_INTRINSIC psimd_u32 psimd_add_u32(psimd_u32 a, psimd_u32 b) {
585
+ return a + b;
586
+ }
587
+
588
+ PSIMD_INTRINSIC psimd_f32 psimd_add_f32(psimd_f32 a, psimd_f32 b) {
589
+ #if defined(__ARM_ARCH_7A__) && defined(__ARM_NEON__) && !defined(__FAST_MATH__)
590
+ return (psimd_f32) vaddq_f32((float32x4_t) a, (float32x4_t) b);
591
+ #else
592
+ return a + b;
593
+ #endif
594
+ }
595
+
596
+ /* Vector subtraction */
597
+ PSIMD_INTRINSIC psimd_s8 psimd_sub_s8(psimd_s8 a, psimd_s8 b) {
598
+ return a - b;
599
+ }
600
+
601
+ PSIMD_INTRINSIC psimd_u8 psimd_sub_u8(psimd_u8 a, psimd_u8 b) {
602
+ return a - b;
603
+ }
604
+
605
+ PSIMD_INTRINSIC psimd_s16 psimd_sub_s16(psimd_s16 a, psimd_s16 b) {
606
+ return a - b;
607
+ }
608
+
609
+ PSIMD_INTRINSIC psimd_u16 psimd_sub_u16(psimd_u16 a, psimd_u16 b) {
610
+ return a - b;
611
+ }
612
+
613
+ PSIMD_INTRINSIC psimd_s32 psimd_sub_s32(psimd_s32 a, psimd_s32 b) {
614
+ return a - b;
615
+ }
616
+
617
+ PSIMD_INTRINSIC psimd_u32 psimd_sub_u32(psimd_u32 a, psimd_u32 b) {
618
+ return a - b;
619
+ }
620
+
621
+ PSIMD_INTRINSIC psimd_f32 psimd_sub_f32(psimd_f32 a, psimd_f32 b) {
622
+ #if defined(__ARM_ARCH_7A__) && defined(__ARM_NEON__) && !defined(__FAST_MATH__)
623
+ return (psimd_f32) vsubq_f32((float32x4_t) a, (float32x4_t) b);
624
+ #else
625
+ return a - b;
626
+ #endif
627
+ }
628
+
629
+ /* Vector multiplication */
630
+ PSIMD_INTRINSIC psimd_s8 psimd_mul_s8(psimd_s8 a, psimd_s8 b) {
631
+ return a * b;
632
+ }
633
+
634
+ PSIMD_INTRINSIC psimd_u8 psimd_mul_u8(psimd_u8 a, psimd_u8 b) {
635
+ return a * b;
636
+ }
637
+
638
+ PSIMD_INTRINSIC psimd_s16 psimd_mul_s16(psimd_s16 a, psimd_s16 b) {
639
+ return a * b;
640
+ }
641
+
642
+ PSIMD_INTRINSIC psimd_u16 psimd_mul_u16(psimd_u16 a, psimd_u16 b) {
643
+ return a * b;
644
+ }
645
+
646
+ PSIMD_INTRINSIC psimd_s32 psimd_mul_s32(psimd_s32 a, psimd_s32 b) {
647
+ return a * b;
648
+ }
649
+
650
+ PSIMD_INTRINSIC psimd_u32 psimd_mul_u32(psimd_u32 a, psimd_u32 b) {
651
+ return a * b;
652
+ }
653
+
654
+ PSIMD_INTRINSIC psimd_f32 psimd_mul_f32(psimd_f32 a, psimd_f32 b) {
655
+ #if defined(__ARM_ARCH_7A__) && defined(__ARM_NEON__) && !defined(__FAST_MATH__)
656
+ return (psimd_f32) vmulq_f32((float32x4_t) a, (float32x4_t) b);
657
+ #else
658
+ return a * b;
659
+ #endif
660
+ }
661
+
662
+ /* Quasi-Fused Multiply-Add */
663
+ PSIMD_INTRINSIC psimd_f32 psimd_qfma_f32(psimd_f32 a, psimd_f32 b, psimd_f32 c) {
664
+ #if defined(__aarch64__) || defined(__ARM_NEON__) && defined(__ARM_FEATURE_FMA)
665
+ return (psimd_f32) vfmaq_f32((float32x4_t) a, (float32x4_t) b, (float32x4_t) c);
666
+ #elif (defined(__x86_64__) || defined(__i386__) || defined(__i686__)) && defined(__FMA__)
667
+ return (psimd_f32) _mm_fmadd_ps((__m128) b, (__m128) c, (__m128) a);
668
+ #elif (defined(__x86_64__) || defined(__i386__) || defined(__i686__)) && defined(__FMA4__)
669
+ return (psimd_f32) _mm_macc_ps((__m128) b, (__m128) c, (__m128) a);
670
+ #elif defined(__wasm__) && defined(__wasm_simd128__) && defined(__clang__) && PSIMD_ENABLE_WASM_QFMA
671
+ return (psimd_f32) __builtin_wasm_qfma_f32x4(a, b, c);
672
+ #else
673
+ return a + b * c;
674
+ #endif
675
+ }
676
+
677
+ PSIMD_INTRINSIC psimd_f32 psimd_div_f32(psimd_f32 a, psimd_f32 b) {
678
+ return a / b;
679
+ }
680
+
681
+ /* Vector and */
682
+ PSIMD_INTRINSIC psimd_f32 psimd_andmask_f32(psimd_s32 mask, psimd_f32 v) {
683
+ return (psimd_f32) (mask & (psimd_s32) v);
684
+ }
685
+
686
+ /* Vector and-not */
687
+ PSIMD_INTRINSIC psimd_f32 psimd_andnotmask_f32(psimd_s32 mask, psimd_f32 v) {
688
+ return (psimd_f32) (~mask & (psimd_s32) v);
689
+ }
690
+
691
+ /* Vector blend */
692
+ PSIMD_INTRINSIC psimd_s8 psimd_blend_s8(psimd_s8 mask, psimd_s8 a, psimd_s8 b) {
693
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
694
+ return (psimd_s8) vbslq_s8((uint8x16_t) mask, (int8x16_t) a, (int8x16_t) b);
695
+ #elif defined(__wasm__) && defined(__wasm_simd128__) && defined(__clang__)
696
+ return (psimd_s8) __builtin_wasm_bitselect(a, b, mask);
697
+ #else
698
+ return (mask & a) | (~mask & b);
699
+ #endif
700
+ }
701
+
702
+ PSIMD_INTRINSIC psimd_u8 psimd_blend_u8(psimd_s8 mask, psimd_u8 a, psimd_u8 b) {
703
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
704
+ return (psimd_u8) vbslq_u8((uint8x16_t) mask, (uint8x16_t) a, (uint8x16_t) b);
705
+ #elif defined(__wasm__) && defined(__wasm_simd128__) && defined(__clang__)
706
+ return (psimd_u8) __builtin_wasm_bitselect(a, b, mask);
707
+ #else
708
+ return (psimd_u8) ((mask & (psimd_s8) a) | (~mask & (psimd_s8) b));
709
+ #endif
710
+ }
711
+
712
+ PSIMD_INTRINSIC psimd_s16 psimd_blend_s16(psimd_s16 mask, psimd_s16 a, psimd_s16 b) {
713
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
714
+ return (psimd_s16) vbslq_s16((uint16x8_t) mask, (int16x8_t) a, (int16x8_t) b);
715
+ #elif defined(__wasm__) && defined(__wasm_simd128__) && defined(__clang__)
716
+ return (psimd_s16) __builtin_wasm_bitselect(a, b, mask);
717
+ #else
718
+ return (mask & a) | (~mask & b);
719
+ #endif
720
+ }
721
+
722
+ PSIMD_INTRINSIC psimd_u16 psimd_blend_u16(psimd_s16 mask, psimd_u16 a, psimd_u16 b) {
723
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
724
+ return (psimd_u16) vbslq_u16((uint16x8_t) mask, (uint16x8_t) a, (uint16x8_t) b);
725
+ #elif defined(__wasm__) && defined(__wasm_simd128__) && defined(__clang__)
726
+ return (psimd_u16) __builtin_wasm_bitselect(a, b, mask);
727
+ #else
728
+ return (psimd_u16) ((mask & (psimd_s16) a) | (~mask & (psimd_s16) b));
729
+ #endif
730
+ }
731
+
732
+ PSIMD_INTRINSIC psimd_s32 psimd_blend_s32(psimd_s32 mask, psimd_s32 a, psimd_s32 b) {
733
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
734
+ return (psimd_s32) vbslq_s32((uint32x4_t) mask, (int32x4_t) a, (int32x4_t) b);
735
+ #elif defined(__wasm__) && defined(__wasm_simd128__) && defined(__clang__)
736
+ return (psimd_s32) __builtin_wasm_bitselect(a, b, mask);
737
+ #else
738
+ return (mask & a) | (~mask & b);
739
+ #endif
740
+ }
741
+
742
+ PSIMD_INTRINSIC psimd_u32 psimd_blend_u32(psimd_s32 mask, psimd_u32 a, psimd_u32 b) {
743
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
744
+ return (psimd_u32) vbslq_u32((uint32x4_t) mask, (uint32x4_t) a, (uint32x4_t) b);
745
+ #elif defined(__wasm__) && defined(__wasm_simd128__) && defined(__clang__)
746
+ return (psimd_u32) __builtin_wasm_bitselect(a, b, mask);
747
+ #else
748
+ return (psimd_u32) ((mask & (psimd_s32) a) | (~mask & (psimd_s32) b));
749
+ #endif
750
+ }
751
+
752
+ PSIMD_INTRINSIC psimd_f32 psimd_blend_f32(psimd_s32 mask, psimd_f32 a, psimd_f32 b) {
753
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
754
+ return (psimd_f32) vbslq_f32((uint32x4_t) mask, (float32x4_t) a, (float32x4_t) b);
755
+ #elif defined(__wasm__) && defined(__wasm_simd128__) && defined(__clang__)
756
+ return (psimd_f32) __builtin_wasm_bitselect(a, b, mask);
757
+ #else
758
+ return (psimd_f32) ((mask & (psimd_s32) a) | (~mask & (psimd_s32) b));
759
+ #endif
760
+ }
761
+
762
+ /* Vector blend on sign */
763
+ PSIMD_INTRINSIC psimd_s8 psimd_signblend_s8(psimd_s8 x, psimd_s8 a, psimd_s8 b) {
764
+ return psimd_blend_s8(x >> psimd_splat_s8(7), a, b);
765
+ }
766
+
767
+ PSIMD_INTRINSIC psimd_u8 psimd_signblend_u8(psimd_s8 x, psimd_u8 a, psimd_u8 b) {
768
+ return psimd_blend_u8((x >> psimd_splat_s8(7)), a, b);
769
+ }
770
+
771
+ PSIMD_INTRINSIC psimd_s16 psimd_signblend_s16(psimd_s16 x, psimd_s16 a, psimd_s16 b) {
772
+ return psimd_blend_s16(x >> psimd_splat_s16(15), a, b);
773
+ }
774
+
775
+ PSIMD_INTRINSIC psimd_u16 psimd_signblend_u16(psimd_s16 x, psimd_u16 a, psimd_u16 b) {
776
+ return psimd_blend_u16((x >> psimd_splat_s16(15)), a, b);
777
+ }
778
+
779
+ PSIMD_INTRINSIC psimd_s32 psimd_signblend_s32(psimd_s32 x, psimd_s32 a, psimd_s32 b) {
780
+ return psimd_blend_s32(x >> psimd_splat_s32(31), a, b);
781
+ }
782
+
783
+ PSIMD_INTRINSIC psimd_u32 psimd_signblend_u32(psimd_s32 x, psimd_u32 a, psimd_u32 b) {
784
+ return psimd_blend_u32((x >> psimd_splat_s32(31)), a, b);
785
+ }
786
+
787
+ PSIMD_INTRINSIC psimd_f32 psimd_signblend_f32(psimd_f32 x, psimd_f32 a, psimd_f32 b) {
788
+ const psimd_s32 mask = (psimd_s32) x >> psimd_splat_s32(31);
789
+ return psimd_blend_f32(mask, a, b);
790
+ }
791
+
792
+ /* Vector absolute value */
793
+ PSIMD_INTRINSIC psimd_f32 psimd_abs_f32(psimd_f32 v) {
794
+ const psimd_s32 mask = (psimd_s32) psimd_splat_f32(-0.0f);
795
+ return (psimd_f32) ((psimd_s32) v & ~mask);
796
+ }
797
+
798
+ /* Vector negation */
799
+ PSIMD_INTRINSIC psimd_f32 psimd_neg_f32(psimd_f32 v) {
800
+ const psimd_s32 mask = (psimd_s32) psimd_splat_f32(-0.0f);
801
+ return (psimd_f32) ((psimd_s32) v ^ mask);
802
+ }
803
+
804
+ /* Vector maximum */
805
+ PSIMD_INTRINSIC psimd_s8 psimd_max_s8(psimd_s8 a, psimd_s8 b) {
806
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
807
+ return (psimd_s8) vmaxq_s8((int8x16_t) a, (int8x16_t) b);
808
+ #else
809
+ return psimd_blend_s8(a > b, a, b);
810
+ #endif
811
+ }
812
+
813
+ PSIMD_INTRINSIC psimd_u8 psimd_max_u8(psimd_u8 a, psimd_u8 b) {
814
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
815
+ return (psimd_u8) vmaxq_u8((uint8x16_t) a, (uint8x16_t) b);
816
+ #else
817
+ return psimd_blend_u8(a > b, a, b);
818
+ #endif
819
+ }
820
+
821
+ PSIMD_INTRINSIC psimd_s16 psimd_max_s16(psimd_s16 a, psimd_s16 b) {
822
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
823
+ return (psimd_s16) vmaxq_s16((int16x8_t) a, (int16x8_t) b);
824
+ #else
825
+ return psimd_blend_s16(a > b, a, b);
826
+ #endif
827
+ }
828
+
829
+ PSIMD_INTRINSIC psimd_u16 psimd_max_u16(psimd_u16 a, psimd_u16 b) {
830
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
831
+ return (psimd_u16) vmaxq_u16((uint16x8_t) a, (uint16x8_t) b);
832
+ #else
833
+ return psimd_blend_u16(a > b, a, b);
834
+ #endif
835
+ }
836
+
837
+ PSIMD_INTRINSIC psimd_s32 psimd_max_s32(psimd_s32 a, psimd_s32 b) {
838
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
839
+ return (psimd_s32) vmaxq_s32((int32x4_t) a, (int32x4_t) b);
840
+ #else
841
+ return psimd_blend_s32(a > b, a, b);
842
+ #endif
843
+ }
844
+
845
+ PSIMD_INTRINSIC psimd_u32 psimd_max_u32(psimd_u32 a, psimd_u32 b) {
846
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
847
+ return (psimd_u32) vmaxq_u32((uint32x4_t) a, (uint32x4_t) b);
848
+ #else
849
+ return psimd_blend_u32(a > b, a, b);
850
+ #endif
851
+ }
852
+
853
+ PSIMD_INTRINSIC psimd_f32 psimd_max_f32(psimd_f32 a, psimd_f32 b) {
854
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
855
+ return (psimd_f32) vmaxq_f32((float32x4_t) a, (float32x4_t) b);
856
+ #elif defined(__wasm__) && defined(__wasm_simd128__) && defined(__clang__)
857
+ return __builtin_wasm_max_f32x4(a, b);
858
+ #else
859
+ return psimd_blend_f32(a > b, a, b);
860
+ #endif
861
+ }
862
+
863
+ /* Vector minimum */
864
+ PSIMD_INTRINSIC psimd_s8 psimd_min_s8(psimd_s8 a, psimd_s8 b) {
865
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
866
+ return (psimd_s8) vminq_s8((int8x16_t) a, (int8x16_t) b);
867
+ #else
868
+ return psimd_blend_s8(a < b, a, b);
869
+ #endif
870
+ }
871
+
872
+ PSIMD_INTRINSIC psimd_u8 psimd_min_u8(psimd_u8 a, psimd_u8 b) {
873
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
874
+ return (psimd_u8) vminq_u8((uint8x16_t) a, (uint8x16_t) b);
875
+ #else
876
+ return psimd_blend_u8(a < b, a, b);
877
+ #endif
878
+ }
879
+
880
+ PSIMD_INTRINSIC psimd_s16 psimd_min_s16(psimd_s16 a, psimd_s16 b) {
881
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
882
+ return (psimd_s16) vminq_s16((int16x8_t) a, (int16x8_t) b);
883
+ #else
884
+ return psimd_blend_s16(a < b, a, b);
885
+ #endif
886
+ }
887
+
888
+ PSIMD_INTRINSIC psimd_u16 psimd_min_u16(psimd_u16 a, psimd_u16 b) {
889
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
890
+ return (psimd_u16) vminq_u16((uint16x8_t) a, (uint16x8_t) b);
891
+ #else
892
+ return psimd_blend_u16(a < b, a, b);
893
+ #endif
894
+ }
895
+
896
+ PSIMD_INTRINSIC psimd_s32 psimd_min_s32(psimd_s32 a, psimd_s32 b) {
897
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
898
+ return (psimd_s32) vminq_s32((int32x4_t) a, (int32x4_t) b);
899
+ #else
900
+ return psimd_blend_s32(a < b, a, b);
901
+ #endif
902
+ }
903
+
904
+ PSIMD_INTRINSIC psimd_u32 psimd_min_u32(psimd_u32 a, psimd_u32 b) {
905
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
906
+ return (psimd_u32) vminq_u32((uint32x4_t) a, (uint32x4_t) b);
907
+ #else
908
+ return psimd_blend_u32(a < b, a, b);
909
+ #endif
910
+ }
911
+
912
+ PSIMD_INTRINSIC psimd_f32 psimd_min_f32(psimd_f32 a, psimd_f32 b) {
913
+ #if defined(__ARM_NEON__) || defined(__ARM_NEON)
914
+ return (psimd_f32) vminq_f32((float32x4_t) a, (float32x4_t) b);
915
+ #elif defined(__wasm__) && defined(__wasm_simd128__) && defined(__clang__)
916
+ return __builtin_wasm_min_f32x4(a, b);
917
+ #else
918
+ return psimd_blend_f32(a < b, a, b);
919
+ #endif
920
+ }
921
+
922
+ PSIMD_INTRINSIC psimd_f32 psimd_cvt_s32_f32(psimd_s32 v) {
923
+ #if defined(__clang__)
924
+ return __builtin_convertvector(v, psimd_f32);
925
+ #elif defined(__ARM_NEON__) || defined(__ARM_NEON)
926
+ return (psimd_f32) vcvtq_f32_s32((int32x4_t) v);
927
+ #elif defined(__SSE2__)
928
+ return (psimd_f32) _mm_cvtepi32_ps((__m128i) v);
929
+ #else
930
+ return (psimd_f32) { (float) v[0], (float) v[1], (float) v[2], (float) v[3] };
931
+ #endif
932
+ }
933
+
934
+ /* Broadcast vector element */
935
+ #if defined(__clang__)
936
+ PSIMD_INTRINSIC psimd_f32 psimd_splat0_f32(psimd_f32 v) {
937
+ return __builtin_shufflevector(v, v, 0, 0, 0, 0);
938
+ }
939
+
940
+ PSIMD_INTRINSIC psimd_f32 psimd_splat1_f32(psimd_f32 v) {
941
+ return __builtin_shufflevector(v, v, 1, 1, 1, 1);
942
+ }
943
+
944
+ PSIMD_INTRINSIC psimd_f32 psimd_splat2_f32(psimd_f32 v) {
945
+ return __builtin_shufflevector(v, v, 2, 2, 2, 2);
946
+ }
947
+
948
+ PSIMD_INTRINSIC psimd_f32 psimd_splat3_f32(psimd_f32 v) {
949
+ return __builtin_shufflevector(v, v, 3, 3, 3, 3);
950
+ }
951
+ #else
952
+ PSIMD_INTRINSIC psimd_f32 psimd_splat0_f32(psimd_f32 v) {
953
+ return __builtin_shuffle(v, (psimd_s32) { 0, 0, 0, 0 });
954
+ }
955
+
956
+ PSIMD_INTRINSIC psimd_f32 psimd_splat1_f32(psimd_f32 v) {
957
+ return __builtin_shuffle(v, (psimd_s32) { 1, 1, 1, 1 });
958
+ }
959
+
960
+ PSIMD_INTRINSIC psimd_f32 psimd_splat2_f32(psimd_f32 v) {
961
+ return __builtin_shuffle(v, (psimd_s32) { 2, 2, 2, 2 });
962
+ }
963
+
964
+ PSIMD_INTRINSIC psimd_f32 psimd_splat3_f32(psimd_f32 v) {
965
+ return __builtin_shuffle(v, (psimd_s32) { 3, 3, 3, 3 });
966
+ }
967
+ #endif
968
+
969
+ /* Reversal of vector elements */
970
+ #if defined(__clang__)
971
+ PSIMD_INTRINSIC psimd_s8 psimd_reverse_s8(psimd_s8 v) {
972
+ return __builtin_shufflevector(v, v, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
973
+ }
974
+
975
+ PSIMD_INTRINSIC psimd_u8 psimd_reverse_u8(psimd_u8 v) {
976
+ return __builtin_shufflevector(v, v, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0);
977
+ }
978
+
979
+ PSIMD_INTRINSIC psimd_s16 psimd_reverse_s16(psimd_s16 v) {
980
+ return __builtin_shufflevector(v, v, 7, 6, 5, 4, 3, 2, 1, 0);
981
+ }
982
+
983
+ PSIMD_INTRINSIC psimd_u16 psimd_reverse_u16(psimd_u16 v) {
984
+ return __builtin_shufflevector(v, v, 7, 6, 5, 4, 3, 2, 1, 0);
985
+ }
986
+
987
+ PSIMD_INTRINSIC psimd_s32 psimd_reverse_s32(psimd_s32 v) {
988
+ return __builtin_shufflevector(v, v, 3, 2, 1, 0);
989
+ }
990
+
991
+ PSIMD_INTRINSIC psimd_u32 psimd_reverse_u32(psimd_u32 v) {
992
+ return __builtin_shufflevector(v, v, 3, 2, 1, 0);
993
+ }
994
+
995
+ PSIMD_INTRINSIC psimd_f32 psimd_reverse_f32(psimd_f32 v) {
996
+ return __builtin_shufflevector(v, v, 3, 2, 1, 0);
997
+ }
998
+ #else
999
+ PSIMD_INTRINSIC psimd_s8 psimd_reverse_s8(psimd_s8 v) {
1000
+ return __builtin_shuffle(v, (psimd_s8) { 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });
1001
+ }
1002
+
1003
+ PSIMD_INTRINSIC psimd_u8 psimd_reverse_u8(psimd_u8 v) {
1004
+ return __builtin_shuffle(v, (psimd_s8) { 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 });
1005
+ }
1006
+
1007
+ PSIMD_INTRINSIC psimd_s16 psimd_reverse_s16(psimd_s16 v) {
1008
+ return __builtin_shuffle(v, (psimd_s16) { 7, 6, 5, 4, 3, 2, 1, 0 });
1009
+ }
1010
+
1011
+ PSIMD_INTRINSIC psimd_u16 psimd_reverse_u16(psimd_u16 v) {
1012
+ return __builtin_shuffle(v, (psimd_s16) { 7, 6, 5, 4, 3, 2, 1, 0 });
1013
+ }
1014
+
1015
+ PSIMD_INTRINSIC psimd_s32 psimd_reverse_s32(psimd_s32 v) {
1016
+ return __builtin_shuffle(v, (psimd_s32) { 3, 2, 1, 0 });
1017
+ }
1018
+
1019
+ PSIMD_INTRINSIC psimd_u32 psimd_reverse_u32(psimd_u32 v) {
1020
+ return __builtin_shuffle(v, (psimd_s32) { 3, 2, 1, 0 });
1021
+ }
1022
+
1023
+ PSIMD_INTRINSIC psimd_f32 psimd_reverse_f32(psimd_f32 v) {
1024
+ return __builtin_shuffle(v, (psimd_s32) { 3, 2, 1, 0 });
1025
+ }
1026
+ #endif
1027
+
1028
+ /* Interleaving of vector elements */
1029
+ #if defined(__clang__)
1030
+ PSIMD_INTRINSIC psimd_s16 psimd_interleave_lo_s16(psimd_s16 a, psimd_s16 b) {
1031
+ return __builtin_shufflevector(a, b, 0, 8+0, 1, 8+1, 2, 8+2, 3, 8+3);
1032
+ }
1033
+
1034
+ PSIMD_INTRINSIC psimd_s16 psimd_interleave_hi_s16(psimd_s16 a, psimd_s16 b) {
1035
+ return __builtin_shufflevector(a, b, 4, 8+4, 5, 8+5, 6, 8+6, 7, 8+7);
1036
+ }
1037
+
1038
+ PSIMD_INTRINSIC psimd_u16 psimd_interleave_lo_u16(psimd_u16 a, psimd_u16 b) {
1039
+ return __builtin_shufflevector(a, b, 0, 8+0, 1, 8+1, 2, 8+2, 3, 8+3);
1040
+ }
1041
+
1042
+ PSIMD_INTRINSIC psimd_u16 psimd_interleave_hi_u16(psimd_u16 a, psimd_u16 b) {
1043
+ return __builtin_shufflevector(a, b, 4, 8+4, 5, 8+5, 6, 8+6, 7, 8+7);
1044
+ }
1045
+
1046
+ PSIMD_INTRINSIC psimd_s32 psimd_interleave_lo_s32(psimd_s32 a, psimd_s32 b) {
1047
+ return __builtin_shufflevector(a, b, 0, 4+0, 1, 4+1);
1048
+ }
1049
+
1050
+ PSIMD_INTRINSIC psimd_s32 psimd_interleave_hi_s32(psimd_s32 a, psimd_s32 b) {
1051
+ return __builtin_shufflevector(a, b, 2, 4+2, 3, 4+3);
1052
+ }
1053
+
1054
+ PSIMD_INTRINSIC psimd_u32 psimd_interleave_lo_u32(psimd_u32 a, psimd_u32 b) {
1055
+ return __builtin_shufflevector(a, b, 0, 4+0, 1, 4+1);
1056
+ }
1057
+
1058
+ PSIMD_INTRINSIC psimd_u32 psimd_interleave_hi_u32(psimd_u32 a, psimd_u32 b) {
1059
+ return __builtin_shufflevector(a, b, 2, 4+2, 3, 4+3);
1060
+ }
1061
+
1062
+ PSIMD_INTRINSIC psimd_f32 psimd_interleave_lo_f32(psimd_f32 a, psimd_f32 b) {
1063
+ return __builtin_shufflevector(a, b, 0, 4+0, 1, 4+1);
1064
+ }
1065
+
1066
+ PSIMD_INTRINSIC psimd_f32 psimd_interleave_hi_f32(psimd_f32 a, psimd_f32 b) {
1067
+ return __builtin_shufflevector(a, b, 2, 4+2, 3, 4+3);
1068
+ }
1069
+ #else
1070
+ PSIMD_INTRINSIC psimd_s16 psimd_interleave_lo_s16(psimd_s16 a, psimd_s16 b) {
1071
+ return __builtin_shuffle(a, b, (psimd_s16) { 0, 8+0, 1, 8+1, 2, 8+2, 3, 8+3 });
1072
+ }
1073
+
1074
+ PSIMD_INTRINSIC psimd_s16 psimd_interleave_hi_s16(psimd_s16 a, psimd_s16 b) {
1075
+ return __builtin_shuffle(a, b, (psimd_s16) { 4, 8+4, 5, 8+5, 6, 8+6, 7, 8+7 });
1076
+ }
1077
+
1078
+ PSIMD_INTRINSIC psimd_u16 psimd_interleave_lo_u16(psimd_u16 a, psimd_u16 b) {
1079
+ return __builtin_shuffle(a, b, (psimd_s16) { 0, 8+0, 1, 8+1, 2, 8+2, 3, 8+3 });
1080
+ }
1081
+
1082
+ PSIMD_INTRINSIC psimd_u16 psimd_interleave_hi_u16(psimd_u16 a, psimd_u16 b) {
1083
+ return __builtin_shuffle(a, b, (psimd_s16) { 4, 8+4, 5, 8+5, 6, 8+6, 7, 8+7 });
1084
+ }
1085
+
1086
+ PSIMD_INTRINSIC psimd_s32 psimd_interleave_lo_s32(psimd_s32 a, psimd_s32 b) {
1087
+ return __builtin_shuffle(a, b, (psimd_s32) { 0, 4+0, 1, 4+1 });
1088
+ }
1089
+
1090
+ PSIMD_INTRINSIC psimd_s32 psimd_interleave_hi_s32(psimd_s32 a, psimd_s32 b) {
1091
+ return __builtin_shuffle(a, b, (psimd_s32) { 2, 4+2, 3, 4+3 });
1092
+ }
1093
+
1094
+ PSIMD_INTRINSIC psimd_u32 psimd_interleave_lo_u32(psimd_u32 a, psimd_u32 b) {
1095
+ return __builtin_shuffle(a, b, (psimd_s32) { 0, 4+0, 1, 4+1 });
1096
+ }
1097
+
1098
+ PSIMD_INTRINSIC psimd_u32 psimd_interleave_hi_u32(psimd_u32 a, psimd_u32 b) {
1099
+ return __builtin_shuffle(a, b, (psimd_s32) { 2, 4+2, 3, 4+3 });
1100
+ }
1101
+
1102
+ PSIMD_INTRINSIC psimd_f32 psimd_interleave_lo_f32(psimd_f32 a, psimd_f32 b) {
1103
+ return __builtin_shuffle(a, b, (psimd_s32) { 0, 4+0, 1, 4+1 });
1104
+ }
1105
+
1106
+ PSIMD_INTRINSIC psimd_f32 psimd_interleave_hi_f32(psimd_f32 a, psimd_f32 b) {
1107
+ return __builtin_shuffle(a, b, (psimd_s32) { 2, 4+2, 3, 4+3 });
1108
+ }
1109
+ #endif
1110
+
1111
+ /* Concatenation of low/high vector elements */
1112
+ #if defined(__clang__)
1113
+ PSIMD_INTRINSIC psimd_s16 psimd_concat_lo_s16(psimd_s16 a, psimd_s16 b) {
1114
+ return __builtin_shufflevector(a, b, 0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3);
1115
+ }
1116
+
1117
+ PSIMD_INTRINSIC psimd_s16 psimd_concat_hi_s16(psimd_s16 a, psimd_s16 b) {
1118
+ return __builtin_shufflevector(a, b, 4, 5, 6, 7, 8+4, 8+5, 8+6, 8+7);
1119
+ }
1120
+
1121
+ PSIMD_INTRINSIC psimd_u16 psimd_concat_lo_u16(psimd_u16 a, psimd_u16 b) {
1122
+ return __builtin_shufflevector(a, b, 0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3);
1123
+ }
1124
+
1125
+ PSIMD_INTRINSIC psimd_u16 psimd_concat_hi_u16(psimd_u16 a, psimd_u16 b) {
1126
+ return __builtin_shufflevector(a, b, 4, 5, 6, 7, 8+4, 8+5, 8+6, 8+7);
1127
+ }
1128
+
1129
+ PSIMD_INTRINSIC psimd_s32 psimd_concat_lo_s32(psimd_s32 a, psimd_s32 b) {
1130
+ return __builtin_shufflevector(a, b, 0, 1, 4+0, 4+1);
1131
+ }
1132
+
1133
+ PSIMD_INTRINSIC psimd_s32 psimd_concat_hi_s32(psimd_s32 a, psimd_s32 b) {
1134
+ return __builtin_shufflevector(a, b, 2, 3, 4+2, 4+3);
1135
+ }
1136
+
1137
+ PSIMD_INTRINSIC psimd_u32 psimd_concat_lo_u32(psimd_u32 a, psimd_u32 b) {
1138
+ return __builtin_shufflevector(a, b, 0, 1, 4+0, 4+1);
1139
+ }
1140
+
1141
+ PSIMD_INTRINSIC psimd_u32 psimd_concat_hi_u32(psimd_u32 a, psimd_u32 b) {
1142
+ return __builtin_shufflevector(a, b, 2, 3, 4+2, 4+3);
1143
+ }
1144
+
1145
+ PSIMD_INTRINSIC psimd_f32 psimd_concat_lo_f32(psimd_f32 a, psimd_f32 b) {
1146
+ return __builtin_shufflevector(a, b, 0, 1, 4+0, 4+1);
1147
+ }
1148
+
1149
+ PSIMD_INTRINSIC psimd_f32 psimd_concat_hi_f32(psimd_f32 a, psimd_f32 b) {
1150
+ return __builtin_shufflevector(a, b, 2, 3, 4+2, 4+3);
1151
+ }
1152
+ #else
1153
+ PSIMD_INTRINSIC psimd_s16 psimd_concat_lo_s16(psimd_s16 a, psimd_s16 b) {
1154
+ return __builtin_shuffle(a, b, (psimd_s16) { 0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3 });
1155
+ }
1156
+
1157
+ PSIMD_INTRINSIC psimd_s16 psimd_concat_hi_s16(psimd_s16 a, psimd_s16 b) {
1158
+ return __builtin_shuffle(a, b, (psimd_s16) { 4, 5, 6, 7, 8+4, 8+5, 8+6, 8+7 });
1159
+ }
1160
+
1161
+ PSIMD_INTRINSIC psimd_u16 psimd_concat_lo_u16(psimd_u16 a, psimd_u16 b) {
1162
+ return __builtin_shuffle(a, b, (psimd_s16) { 0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3 });
1163
+ }
1164
+
1165
+ PSIMD_INTRINSIC psimd_u16 psimd_concat_hi_u16(psimd_u16 a, psimd_u16 b) {
1166
+ return __builtin_shuffle(a, b, (psimd_s16) { 4, 5, 6, 7, 8+4, 8+5, 8+6, 8+7 });
1167
+ }
1168
+
1169
+ PSIMD_INTRINSIC psimd_s32 psimd_concat_lo_s32(psimd_s32 a, psimd_s32 b) {
1170
+ return __builtin_shuffle(a, b, (psimd_s32) { 0, 1, 4+0, 4+1 });
1171
+ }
1172
+
1173
+ PSIMD_INTRINSIC psimd_s32 psimd_concat_hi_s32(psimd_s32 a, psimd_s32 b) {
1174
+ return __builtin_shuffle(a, b, (psimd_s32) { 2, 3, 4+2, 4+3 });
1175
+ }
1176
+
1177
+ PSIMD_INTRINSIC psimd_u32 psimd_concat_lo_u32(psimd_u32 a, psimd_u32 b) {
1178
+ return __builtin_shuffle(a, b, (psimd_s32) { 0, 1, 4+0, 4+1 });
1179
+ }
1180
+
1181
+ PSIMD_INTRINSIC psimd_u32 psimd_concat_hi_u32(psimd_u32 a, psimd_u32 b) {
1182
+ return __builtin_shuffle(a, b, (psimd_s32) { 2, 3, 4+2, 4+3 });
1183
+ }
1184
+
1185
+ PSIMD_INTRINSIC psimd_f32 psimd_concat_lo_f32(psimd_f32 a, psimd_f32 b) {
1186
+ return __builtin_shuffle(a, b, (psimd_s32) { 0, 1, 4+0, 4+1 });
1187
+ }
1188
+
1189
+ PSIMD_INTRINSIC psimd_f32 psimd_concat_hi_f32(psimd_f32 a, psimd_f32 b) {
1190
+ return __builtin_shuffle(a, b, (psimd_s32) { 2, 3, 4+2, 4+3 });
1191
+ }
1192
+ #endif
1193
+
1194
+ /* Concatenation of even/odd vector elements */
1195
+ #if defined(__clang__)
1196
+ PSIMD_INTRINSIC psimd_s8 psimd_concat_even_s8(psimd_s8 a, psimd_s8 b) {
1197
+ return __builtin_shufflevector(a, b,
1198
+ 0, 2, 4, 6, 8, 10, 12, 14, 16+0, 16+2, 16+4, 16+6, 16+8, 16+10, 16+12, 16+14);
1199
+ }
1200
+
1201
+ PSIMD_INTRINSIC psimd_s8 psimd_concat_odd_s8(psimd_s8 a, psimd_s8 b) {
1202
+ return __builtin_shufflevector(a, b,
1203
+ 1, 3, 5, 7, 9, 11, 13, 15, 16+1, 16+3, 16+5, 16+7, 16+9, 16+11, 16+13, 16+15);
1204
+ }
1205
+
1206
+ PSIMD_INTRINSIC psimd_u8 psimd_concat_even_u8(psimd_u8 a, psimd_u8 b) {
1207
+ return __builtin_shufflevector(a, b,
1208
+ 0, 2, 4, 6, 8, 10, 12, 14, 16+0, 16+2, 16+4, 16+6, 16+8, 16+10, 16+12, 16+14);
1209
+ }
1210
+
1211
+ PSIMD_INTRINSIC psimd_u8 psimd_concat_odd_u8(psimd_u8 a, psimd_u8 b) {
1212
+ return __builtin_shufflevector(a, b,
1213
+ 1, 3, 5, 7, 9, 11, 13, 15, 16+1, 16+3, 16+5, 16+7, 16+9, 16+11, 16+13, 16+15);
1214
+ }
1215
+
1216
+ PSIMD_INTRINSIC psimd_s16 psimd_concat_even_s16(psimd_s16 a, psimd_s16 b) {
1217
+ return __builtin_shufflevector(a, b, 0, 2, 4, 6, 8+0, 8+2, 8+4, 8+6);
1218
+ }
1219
+
1220
+ PSIMD_INTRINSIC psimd_s16 psimd_concat_odd_s16(psimd_s16 a, psimd_s16 b) {
1221
+ return __builtin_shufflevector(a, b, 1, 3, 5, 7, 8+1, 8+3, 8+5, 8+7);
1222
+ }
1223
+
1224
+ PSIMD_INTRINSIC psimd_u16 psimd_concat_even_u16(psimd_u16 a, psimd_u16 b) {
1225
+ return __builtin_shufflevector(a, b, 0, 2, 4, 6, 8+0, 8+2, 8+4, 8+6);
1226
+ }
1227
+
1228
+ PSIMD_INTRINSIC psimd_u16 psimd_concat_odd_u16(psimd_u16 a, psimd_u16 b) {
1229
+ return __builtin_shufflevector(a, b, 1, 3, 5, 7, 8+1, 8+3, 8+5, 8+7);
1230
+ }
1231
+
1232
+ PSIMD_INTRINSIC psimd_s32 psimd_concat_even_s32(psimd_s32 a, psimd_s32 b) {
1233
+ return __builtin_shufflevector(a, b, 0, 2, 4+0, 4+2);
1234
+ }
1235
+
1236
+ PSIMD_INTRINSIC psimd_s32 psimd_concat_odd_s32(psimd_s32 a, psimd_s32 b) {
1237
+ return __builtin_shufflevector(a, b, 1, 3, 4+1, 4+3);
1238
+ }
1239
+
1240
+ PSIMD_INTRINSIC psimd_u32 psimd_concat_even_u32(psimd_u32 a, psimd_u32 b) {
1241
+ return __builtin_shufflevector(a, b, 0, 2, 4+0, 4+2);
1242
+ }
1243
+
1244
+ PSIMD_INTRINSIC psimd_u32 psimd_concat_odd_u32(psimd_u32 a, psimd_u32 b) {
1245
+ return __builtin_shufflevector(a, b, 1, 3, 4+1, 4+3);
1246
+ }
1247
+
1248
+ PSIMD_INTRINSIC psimd_f32 psimd_concat_even_f32(psimd_f32 a, psimd_f32 b) {
1249
+ return __builtin_shufflevector(a, b, 0, 2, 4+0, 4+2);
1250
+ }
1251
+
1252
+ PSIMD_INTRINSIC psimd_f32 psimd_concat_odd_f32(psimd_f32 a, psimd_f32 b) {
1253
+ return __builtin_shufflevector(a, b, 1, 3, 4+1, 4+3);
1254
+ }
1255
+ #else
1256
+ PSIMD_INTRINSIC psimd_s8 psimd_concat_even_s8(psimd_s8 a, psimd_s8 b) {
1257
+ return __builtin_shuffle(a, b,
1258
+ (psimd_s8) { 0, 2, 4, 6, 8, 10, 12, 14, 16+0, 16+2, 16+4, 16+6, 16+8, 16+10, 16+12, 16+14 });
1259
+ }
1260
+
1261
+ PSIMD_INTRINSIC psimd_s8 psimd_concat_odd_s8(psimd_s8 a, psimd_s8 b) {
1262
+ return __builtin_shuffle(a, b,
1263
+ (psimd_s8) { 1, 3, 5, 7, 9, 11, 13, 15, 16+1, 16+3, 16+5, 16+7, 16+9, 16+11, 16+13, 16+15 });
1264
+ }
1265
+
1266
+ PSIMD_INTRINSIC psimd_u8 psimd_concat_even_u8(psimd_u8 a, psimd_u8 b) {
1267
+ return __builtin_shuffle(a, b,
1268
+ (psimd_s8) { 0, 2, 4, 6, 8, 10, 12, 14, 16+0, 16+2, 16+4, 16+6, 16+8, 16+10, 16+12, 16+14 });
1269
+ }
1270
+
1271
+ PSIMD_INTRINSIC psimd_u8 psimd_concat_odd_u8(psimd_u8 a, psimd_u8 b) {
1272
+ return __builtin_shuffle(a, b,
1273
+ (psimd_s8) { 1, 3, 5, 7, 9, 11, 13, 15, 16+1, 16+3, 16+5, 16+7, 16+9, 16+11, 16+13, 16+15 });
1274
+ }
1275
+
1276
+ PSIMD_INTRINSIC psimd_s16 psimd_concat_even_s16(psimd_s16 a, psimd_s16 b) {
1277
+ return __builtin_shuffle(a, b, (psimd_s16) { 0, 2, 4, 6, 8+0, 8+2, 8+4, 8+6 });
1278
+ }
1279
+
1280
+ PSIMD_INTRINSIC psimd_s16 psimd_concat_odd_s16(psimd_s16 a, psimd_s16 b) {
1281
+ return __builtin_shuffle(a, b, (psimd_s16) { 1, 3, 5, 7, 8+1, 8+3, 8+5, 8+7 });
1282
+ }
1283
+
1284
+ PSIMD_INTRINSIC psimd_u16 psimd_concat_even_u16(psimd_u16 a, psimd_u16 b) {
1285
+ return __builtin_shuffle(a, b, (psimd_s16) { 0, 2, 4, 6, 8+0, 8+2, 8+4, 8+6 });
1286
+ }
1287
+
1288
+ PSIMD_INTRINSIC psimd_u16 psimd_concat_odd_u16(psimd_u16 a, psimd_u16 b) {
1289
+ return __builtin_shuffle(a, b, (psimd_s16) { 1, 3, 5, 7, 8+1, 8+3, 8+5, 8+7 });
1290
+ }
1291
+
1292
+ PSIMD_INTRINSIC psimd_s32 psimd_concat_even_s32(psimd_s32 a, psimd_s32 b) {
1293
+ return __builtin_shuffle(a, b, (psimd_s32) { 0, 2, 4+0, 4+2 });
1294
+ }
1295
+
1296
+ PSIMD_INTRINSIC psimd_s32 psimd_concat_odd_s32(psimd_s32 a, psimd_s32 b) {
1297
+ return __builtin_shuffle(a, b, (psimd_s32) { 1, 3, 4+1, 4+3 });
1298
+ }
1299
+
1300
+ PSIMD_INTRINSIC psimd_u32 psimd_concat_even_u32(psimd_u32 a, psimd_u32 b) {
1301
+ return __builtin_shuffle(a, b, (psimd_s32) { 0, 2, 4+0, 4+2 });
1302
+ }
1303
+
1304
+ PSIMD_INTRINSIC psimd_u32 psimd_concat_odd_u32(psimd_u32 a, psimd_u32 b) {
1305
+ return __builtin_shuffle(a, b, (psimd_s32) { 1, 3, 4+1, 4+3 });
1306
+ }
1307
+
1308
+ PSIMD_INTRINSIC psimd_f32 psimd_concat_even_f32(psimd_f32 a, psimd_f32 b) {
1309
+ return __builtin_shuffle(a, b, (psimd_s32) { 0, 2, 4+0, 4+2 });
1310
+ }
1311
+
1312
+ PSIMD_INTRINSIC psimd_f32 psimd_concat_odd_f32(psimd_f32 a, psimd_f32 b) {
1313
+ return __builtin_shuffle(a, b, (psimd_s32) { 1, 3, 4+1, 4+3 });
1314
+ }
1315
+ #endif
1316
+
1317
+ /* Vector reduce */
1318
+ #if defined(__clang__)
1319
+ PSIMD_INTRINSIC psimd_f32 psimd_allreduce_sum_f32(psimd_f32 v) {
1320
+ const psimd_f32 temp = v + __builtin_shufflevector(v, v, 2, 3, 0, 1);
1321
+ return temp + __builtin_shufflevector(temp, temp, 1, 0, 3, 2);
1322
+ }
1323
+
1324
+ PSIMD_INTRINSIC psimd_f32 psimd_allreduce_max_f32(psimd_f32 v) {
1325
+ const psimd_f32 temp = psimd_max_f32(v, __builtin_shufflevector(v, v, 2, 3, 0, 1));
1326
+ return psimd_max_f32(temp, __builtin_shufflevector(temp, temp, 1, 0, 3, 2));
1327
+ }
1328
+
1329
+ PSIMD_INTRINSIC psimd_f32 psimd_allreduce_min_f32(psimd_f32 v) {
1330
+ const psimd_f32 temp = psimd_min_f32(v, __builtin_shufflevector(v, v, 2, 3, 0, 1));
1331
+ return psimd_min_f32(temp, __builtin_shufflevector(temp, temp, 1, 0, 3, 2));
1332
+ }
1333
+
1334
+ PSIMD_INTRINSIC float psimd_reduce_sum_f32(psimd_f32 v) {
1335
+ const psimd_f32 temp = v + __builtin_shufflevector(v, v, 2, 3, -1, -1);
1336
+ const psimd_f32 result = temp + __builtin_shufflevector(temp, temp, 1, -1, -1, -1);
1337
+ return result[0];
1338
+ }
1339
+
1340
+ PSIMD_INTRINSIC float psimd_reduce_max_f32(psimd_f32 v) {
1341
+ const psimd_f32 temp = psimd_max_f32(v, __builtin_shufflevector(v, v, 2, 3, -1, -1));
1342
+ const psimd_f32 result = psimd_max_f32(temp, __builtin_shufflevector(temp, temp, 1, -1, -1, -1));
1343
+ return result[0];
1344
+ }
1345
+
1346
+ PSIMD_INTRINSIC float psimd_reduce_min_f32(psimd_f32 v) {
1347
+ const psimd_f32 temp = psimd_min_f32(v, __builtin_shufflevector(v, v, 2, 3, -1, -1));
1348
+ const psimd_f32 result = psimd_min_f32(temp, __builtin_shufflevector(temp, temp, 1, -1, -1, -1));
1349
+ return result[0];
1350
+ }
1351
+ #else
1352
+ PSIMD_INTRINSIC psimd_f32 psimd_allreduce_sum_f32(psimd_f32 v) {
1353
+ const psimd_f32 temp = v + __builtin_shuffle(v, (psimd_s32) { 2, 3, 0, 1 });
1354
+ return temp + __builtin_shuffle(temp, (psimd_s32) { 1, 0, 3, 2 });
1355
+ }
1356
+
1357
+ PSIMD_INTRINSIC psimd_f32 psimd_allreduce_max_f32(psimd_f32 v) {
1358
+ const psimd_f32 temp = psimd_max_f32(v, __builtin_shuffle(v, (psimd_s32) { 2, 3, 0, 1 }));
1359
+ return psimd_max_f32(temp, __builtin_shuffle(temp, (psimd_s32) { 1, 0, 3, 2 }));
1360
+ }
1361
+
1362
+ PSIMD_INTRINSIC psimd_f32 psimd_allreduce_min_f32(psimd_f32 v) {
1363
+ const psimd_f32 temp = psimd_min_f32(v, __builtin_shuffle(v, (psimd_s32) { 2, 3, 0, 1 }));
1364
+ return psimd_min_f32(temp, __builtin_shuffle(temp, (psimd_s32) { 1, 0, 3, 2 }));
1365
+ }
1366
+
1367
+ PSIMD_INTRINSIC float psimd_reduce_sum_f32(psimd_f32 v) {
1368
+ const psimd_f32 result = psimd_allreduce_sum_f32(v);
1369
+ return result[0];
1370
+ }
1371
+
1372
+ PSIMD_INTRINSIC float psimd_reduce_max_f32(psimd_f32 v) {
1373
+ const psimd_f32 result = psimd_allreduce_max_f32(v);
1374
+ return result[0];
1375
+ }
1376
+
1377
+ PSIMD_INTRINSIC float psimd_reduce_min_f32(psimd_f32 v) {
1378
+ const psimd_f32 result = psimd_allreduce_min_f32(v);
1379
+ return result[0];
1380
+ }
1381
+ #endif
1382
+ #endif
1383
+
1384
+ #endif /* PSIMD_H */
videollama2/lib/python3.10/site-packages/torch/include/qnnpack.h ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ * Copyright (c) Facebook, Inc. and its affiliates.
3
+ * All rights reserved.
4
+ *
5
+ * This source code is licensed under the BSD-style license found in the
6
+ * LICENSE file in the root directory of this source tree.
7
+ */
8
+
9
+ #pragma once
10
+
11
+ #include <stdbool.h>
12
+ #include <stddef.h>
13
+ #include <stdint.h>
14
+
15
+ #include <pthreadpool.h>
16
+
17
+ #ifdef __cplusplus
18
+ extern "C" {
19
+ #endif
20
+
21
+ /**
22
+ * @brief Status code for any QNNPACK function call.
23
+ */
24
+ enum qnnp_status {
25
+ /** The call succeeded, and all output arguments now contain valid data. */
26
+ qnnp_status_success = 0,
27
+ qnnp_status_uninitialized = 1,
28
+ qnnp_status_invalid_parameter = 2,
29
+ qnnp_status_unsupported_parameter = 3,
30
+ qnnp_status_unsupported_hardware = 4,
31
+ qnnp_status_out_of_memory = 5,
32
+ };
33
+
34
+ enum qnnp_status qnnp_initialize(void);
35
+
36
+ enum qnnp_status qnnp_deinitialize(void);
37
+
38
+ typedef struct qnnp_operator* qnnp_operator_t;
39
+
40
+ enum qnnp_status qnnp_create_convolution2d_nhwc_q8(
41
+ uint32_t input_padding_top,
42
+ uint32_t input_padding_right,
43
+ uint32_t input_padding_bottom,
44
+ uint32_t input_padding_left,
45
+ uint32_t kernel_height,
46
+ uint32_t kernel_width,
47
+ uint32_t subsampling_height,
48
+ uint32_t subsampling_width,
49
+ uint32_t dilation_height,
50
+ uint32_t dilation_width,
51
+ uint32_t groups,
52
+ size_t group_input_channels,
53
+ size_t group_output_channels,
54
+ uint8_t input_zero_point,
55
+ float input_scale,
56
+ uint8_t kernel_zero_point,
57
+ float kernel_scale,
58
+ const uint8_t* kernel,
59
+ const int32_t* bias,
60
+ uint8_t output_zero_point,
61
+ float output_scale,
62
+ uint8_t output_min,
63
+ uint8_t output_max,
64
+ uint32_t flags,
65
+ qnnp_operator_t* convolution);
66
+
67
+ enum qnnp_status qnnp_setup_convolution2d_nhwc_q8(
68
+ qnnp_operator_t convolution,
69
+ size_t batch_size,
70
+ size_t input_height,
71
+ size_t input_width,
72
+ const uint8_t* input,
73
+ size_t input_stride,
74
+ uint8_t* output,
75
+ size_t output_stride,
76
+ pthreadpool_t threadpool);
77
+
78
+ enum qnnp_status qnnp_create_deconvolution2d_nhwc_q8(
79
+ uint32_t input_padding_top,
80
+ uint32_t input_padding_right,
81
+ uint32_t input_padding_bottom,
82
+ uint32_t input_padding_left,
83
+ uint32_t adjustment_height,
84
+ uint32_t adjustment_width,
85
+ uint32_t kernel_height,
86
+ uint32_t kernel_width,
87
+ uint32_t stride_height,
88
+ uint32_t stride_width,
89
+ uint32_t dilation_height,
90
+ uint32_t dilation_width,
91
+ uint32_t groups,
92
+ size_t group_input_channels,
93
+ size_t group_output_channels,
94
+ uint8_t input_zero_point,
95
+ float input_scale,
96
+ uint8_t kernel_zero_point,
97
+ float kernel_scale,
98
+ const uint8_t* kernel,
99
+ const int32_t* bias,
100
+ uint8_t output_zero_point,
101
+ float output_scale,
102
+ uint8_t output_min,
103
+ uint8_t output_max,
104
+ uint32_t flags,
105
+ qnnp_operator_t* deconvolution);
106
+
107
+ enum qnnp_status qnnp_setup_deconvolution2d_nhwc_q8(
108
+ qnnp_operator_t deconvolution,
109
+ size_t batch_size,
110
+ size_t input_height,
111
+ size_t input_width,
112
+ const uint8_t* input,
113
+ size_t input_stride,
114
+ uint8_t* output,
115
+ size_t output_stride,
116
+ pthreadpool_t threadpool);
117
+
118
+ enum qnnp_status qnnp_create_fully_connected_nc_q8(
119
+ size_t input_channels,
120
+ size_t output_channels,
121
+ uint8_t input_zero_point,
122
+ float input_scale,
123
+ uint8_t kernel_zero_point,
124
+ float kernel_scale,
125
+ const uint8_t* kernel,
126
+ const int32_t* bias,
127
+ uint8_t output_zero_point,
128
+ float output_scale,
129
+ uint8_t output_min,
130
+ uint8_t output_max,
131
+ uint32_t flags,
132
+ qnnp_operator_t* fully_connected);
133
+
134
+ enum qnnp_status qnnp_setup_fully_connected_nc_q8(
135
+ qnnp_operator_t fully_connected,
136
+ size_t batch_size,
137
+ const uint8_t* input,
138
+ size_t input_stride,
139
+ uint8_t* output,
140
+ size_t output_stride);
141
+
142
+ enum qnnp_status qnnp_create_global_average_pooling_nwc_q8(
143
+ size_t channels,
144
+ uint8_t input_zero_point,
145
+ float input_scale,
146
+ uint8_t output_zero_point,
147
+ float output_scale,
148
+ uint8_t output_min,
149
+ uint8_t output_max,
150
+ uint32_t flags,
151
+ qnnp_operator_t* global_average_pooling);
152
+
153
+ enum qnnp_status qnnp_setup_global_average_pooling_nwc_q8(
154
+ qnnp_operator_t global_average_pooling,
155
+ size_t batch_size,
156
+ size_t width,
157
+ const uint8_t* input,
158
+ size_t input_stride,
159
+ uint8_t* output,
160
+ size_t output_stride);
161
+
162
+ enum qnnp_status qnnp_create_average_pooling2d_nhwc_q8(
163
+ uint32_t input_padding_top,
164
+ uint32_t input_padding_right,
165
+ uint32_t input_padding_bottom,
166
+ uint32_t input_padding_left,
167
+ uint32_t pooling_height,
168
+ uint32_t pooling_width,
169
+ uint32_t stride_height,
170
+ uint32_t stride_width,
171
+ size_t channels,
172
+ uint8_t input_zero_point,
173
+ float input_scale,
174
+ uint8_t output_zero_point,
175
+ float output_scale,
176
+ uint8_t output_min,
177
+ uint8_t output_max,
178
+ uint32_t flags,
179
+ qnnp_operator_t* average_pooling);
180
+
181
+ enum qnnp_status qnnp_setup_average_pooling2d_nhwc_q8(
182
+ qnnp_operator_t average_pooling,
183
+ size_t batch_size,
184
+ size_t input_height,
185
+ size_t input_width,
186
+ const uint8_t* input,
187
+ size_t input_stride,
188
+ uint8_t* output,
189
+ size_t output_stride,
190
+ pthreadpool_t threadpool);
191
+
192
+ enum qnnp_status qnnp_create_max_pooling2d_nhwc_u8(
193
+ uint32_t input_padding_top,
194
+ uint32_t input_padding_right,
195
+ uint32_t input_padding_bottom,
196
+ uint32_t input_padding_left,
197
+ uint32_t pooling_height,
198
+ uint32_t pooling_width,
199
+ uint32_t stride_height,
200
+ uint32_t stride_width,
201
+ uint32_t dilation_height,
202
+ uint32_t dilation_width,
203
+ size_t channels,
204
+ uint8_t output_min,
205
+ uint8_t output_max,
206
+ uint32_t flags,
207
+ qnnp_operator_t* max_pooling);
208
+
209
+ enum qnnp_status qnnp_setup_max_pooling2d_nhwc_u8(
210
+ qnnp_operator_t max_pooling,
211
+ size_t batch_size,
212
+ size_t input_height,
213
+ size_t input_width,
214
+ const uint8_t* input,
215
+ size_t input_stride,
216
+ uint8_t* output,
217
+ size_t output_stride,
218
+ pthreadpool_t threadpool);
219
+
220
+ enum qnnp_status qnnp_create_channel_shuffle_nc_x8(
221
+ size_t groups,
222
+ size_t group_channels,
223
+ uint32_t flags,
224
+ qnnp_operator_t* channel_shuffle);
225
+
226
+ enum qnnp_status qnnp_setup_channel_shuffle_nc_x8(
227
+ qnnp_operator_t channel_shuffle,
228
+ size_t batch_size,
229
+ const uint8_t* input,
230
+ size_t input_stride,
231
+ uint8_t* output,
232
+ size_t output_stride);
233
+
234
+ enum qnnp_status qnnp_create_add_nc_q8(
235
+ size_t channels,
236
+ uint8_t a_zero_point,
237
+ float a_scale,
238
+ uint8_t b_zero_point,
239
+ float b_scale,
240
+ uint8_t sum_zero_point,
241
+ float sum_scale,
242
+ uint8_t sum_min,
243
+ uint8_t sum_max,
244
+ uint32_t flags,
245
+ qnnp_operator_t* add);
246
+
247
+ enum qnnp_status qnnp_setup_add_nc_q8(
248
+ qnnp_operator_t add,
249
+ size_t batch_size,
250
+ const uint8_t* a,
251
+ size_t a_stride,
252
+ const uint8_t* b,
253
+ size_t b_stride,
254
+ uint8_t* sum,
255
+ size_t sum_stride);
256
+
257
+ enum qnnp_status qnnp_create_clamp_nc_u8(
258
+ size_t channels,
259
+ uint8_t output_min,
260
+ uint8_t output_max,
261
+ uint32_t flags,
262
+ qnnp_operator_t* clamp);
263
+
264
+ enum qnnp_status qnnp_setup_clamp_nc_u8(
265
+ qnnp_operator_t clamp,
266
+ size_t batch_size,
267
+ const uint8_t* input,
268
+ size_t input_stride,
269
+ uint8_t* output,
270
+ size_t output_stride);
271
+
272
+ enum qnnp_status qnnp_create_sigmoid_nc_q8(
273
+ size_t channels,
274
+ uint8_t input_zero_point,
275
+ float input_scale,
276
+ uint8_t output_zero_point,
277
+ float output_scale,
278
+ uint8_t output_min,
279
+ uint8_t output_max,
280
+ uint32_t flags,
281
+ qnnp_operator_t* sigmoid);
282
+
283
+ enum qnnp_status qnnp_setup_sigmoid_nc_q8(
284
+ qnnp_operator_t sigmoid,
285
+ size_t batch_size,
286
+ const uint8_t* input,
287
+ size_t input_stride,
288
+ uint8_t* output,
289
+ size_t output_stride);
290
+
291
+ enum qnnp_status qnnp_create_leaky_relu_nc_q8(
292
+ size_t channels,
293
+ float negative_slope,
294
+ uint8_t input_zero_point,
295
+ float input_scale,
296
+ uint8_t output_zero_point,
297
+ float output_scale,
298
+ uint8_t output_min,
299
+ uint8_t output_max,
300
+ uint32_t flags,
301
+ qnnp_operator_t* leaky_relu);
302
+
303
+ enum qnnp_status qnnp_setup_leaky_relu_nc_q8(
304
+ qnnp_operator_t leaky_relu,
305
+ size_t batch_size,
306
+ const uint8_t* input,
307
+ size_t input_stride,
308
+ uint8_t* output,
309
+ size_t output_stride);
310
+
311
+ enum qnnp_status qnnp_create_softargmax_nc_q8(
312
+ size_t channels,
313
+ float input_scale,
314
+ uint8_t output_zero_point,
315
+ float output_scale,
316
+ uint32_t flags,
317
+ qnnp_operator_t* softargmax);
318
+
319
+ enum qnnp_status qnnp_setup_softargmax_nc_q8(
320
+ qnnp_operator_t softargmax,
321
+ size_t batch_size,
322
+ const uint8_t* input,
323
+ size_t input_stride,
324
+ uint8_t* output,
325
+ size_t output_stride);
326
+
327
+ enum qnnp_status qnnp_run_operator(
328
+ qnnp_operator_t op,
329
+ pthreadpool_t threadpool);
330
+
331
+ enum qnnp_status qnnp_delete_operator(
332
+ qnnp_operator_t op);
333
+
334
+ #ifdef __cplusplus
335
+ } /* extern "C" */
336
+ #endif
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/api.h ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ // Coarse public API while the library is in development
19
+
20
+ #pragma once
21
+
22
+ #include "arrow/array.h" // IWYU pragma: export
23
+ #include "arrow/array/array_run_end.h" // IWYU pragma: export
24
+ #include "arrow/array/concatenate.h" // IWYU pragma: export
25
+ #include "arrow/buffer.h" // IWYU pragma: export
26
+ #include "arrow/builder.h" // IWYU pragma: export
27
+ #include "arrow/chunked_array.h" // IWYU pragma: export
28
+ #include "arrow/compare.h" // IWYU pragma: export
29
+ #include "arrow/config.h" // IWYU pragma: export
30
+ #include "arrow/datum.h" // IWYU pragma: export
31
+ #include "arrow/extension_type.h" // IWYU pragma: export
32
+ #include "arrow/memory_pool.h" // IWYU pragma: export
33
+ #include "arrow/pretty_print.h" // IWYU pragma: export
34
+ #include "arrow/record_batch.h" // IWYU pragma: export
35
+ #include "arrow/result.h" // IWYU pragma: export
36
+ #include "arrow/status.h" // IWYU pragma: export
37
+ #include "arrow/table.h" // IWYU pragma: export
38
+ #include "arrow/table_builder.h" // IWYU pragma: export
39
+ #include "arrow/tensor.h" // IWYU pragma: export
40
+ #include "arrow/type.h" // IWYU pragma: export
41
+ #include "arrow/util/key_value_metadata.h" // IWYU pragma: export
42
+ #include "arrow/visit_array_inline.h" // IWYU pragma: export
43
+ #include "arrow/visit_scalar_inline.h" // IWYU pragma: export
44
+ #include "arrow/visitor.h" // IWYU pragma: export
45
+
46
+ /// \brief Top-level namespace for Apache Arrow C++ API
47
+ namespace arrow {}
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/builder.h ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <memory>
21
+
22
+ #include "arrow/array/builder_adaptive.h" // IWYU pragma: keep
23
+ #include "arrow/array/builder_base.h" // IWYU pragma: keep
24
+ #include "arrow/array/builder_binary.h" // IWYU pragma: keep
25
+ #include "arrow/array/builder_decimal.h" // IWYU pragma: keep
26
+ #include "arrow/array/builder_dict.h" // IWYU pragma: keep
27
+ #include "arrow/array/builder_nested.h" // IWYU pragma: keep
28
+ #include "arrow/array/builder_primitive.h" // IWYU pragma: keep
29
+ #include "arrow/array/builder_run_end.h" // IWYU pragma: keep
30
+ #include "arrow/array/builder_time.h" // IWYU pragma: keep
31
+ #include "arrow/array/builder_union.h" // IWYU pragma: keep
32
+ #include "arrow/status.h"
33
+ #include "arrow/util/visibility.h"
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/chunked_array.h ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <memory>
22
+ #include <string>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ #include "arrow/chunk_resolver.h"
27
+ #include "arrow/compare.h"
28
+ #include "arrow/device_allocation_type_set.h"
29
+ #include "arrow/result.h"
30
+ #include "arrow/status.h"
31
+ #include "arrow/type_fwd.h"
32
+ #include "arrow/util/macros.h"
33
+ #include "arrow/util/visibility.h"
34
+
35
+ namespace arrow {
36
+
37
+ class Array;
38
+ class DataType;
39
+ class MemoryPool;
40
+ namespace stl {
41
+ template <typename T, typename V>
42
+ class ChunkedArrayIterator;
43
+ } // namespace stl
44
+
45
+ /// \class ChunkedArray
46
+ /// \brief A data structure managing a list of primitive Arrow arrays logically
47
+ /// as one large array
48
+ ///
49
+ /// Data chunking is treated throughout this project largely as an
50
+ /// implementation detail for performance and memory use optimization.
51
+ /// ChunkedArray allows Array objects to be collected and interpreted
52
+ /// as a single logical array without requiring an expensive concatenation
53
+ /// step.
54
+ ///
55
+ /// In some cases, data produced by a function may exceed the capacity of an
56
+ /// Array (like BinaryArray or StringArray) and so returning multiple Arrays is
57
+ /// the only possibility. In these cases, we recommend returning a ChunkedArray
58
+ /// instead of vector of Arrays or some alternative.
59
+ ///
60
+ /// When data is processed in parallel, it may not be practical or possible to
61
+ /// create large contiguous memory allocations and write output into them. With
62
+ /// some data types, like binary and string types, it is not possible at all to
63
+ /// produce non-chunked array outputs without requiring a concatenation step at
64
+ /// the end of processing.
65
+ ///
66
+ /// Application developers may tune chunk sizes based on analysis of
67
+ /// performance profiles but many developer-users will not need to be
68
+ /// especially concerned with the chunking details.
69
+ ///
70
+ /// Preserving the chunk layout/sizes in processing steps is generally not
71
+ /// considered to be a contract in APIs. A function may decide to alter the
72
+ /// chunking of its result. Similarly, APIs accepting multiple ChunkedArray
73
+ /// inputs should not expect the chunk layout to be the same in each input.
74
+ class ARROW_EXPORT ChunkedArray {
75
+ public:
76
+ ChunkedArray(ChunkedArray&&) = default;
77
+ ChunkedArray& operator=(ChunkedArray&&) = default;
78
+
79
+ /// \brief Construct a chunked array from a single Array
80
+ explicit ChunkedArray(std::shared_ptr<Array> chunk)
81
+ : ChunkedArray(ArrayVector{std::move(chunk)}) {}
82
+
83
+ /// \brief Construct a chunked array from a vector of arrays and an optional data type
84
+ ///
85
+ /// The vector elements must have the same data type.
86
+ /// If the data type is passed explicitly, the vector may be empty.
87
+ /// If the data type is omitted, the vector must be non-empty.
88
+ explicit ChunkedArray(ArrayVector chunks, std::shared_ptr<DataType> type = NULLPTR);
89
+
90
+ // \brief Constructor with basic input validation.
91
+ static Result<std::shared_ptr<ChunkedArray>> Make(
92
+ ArrayVector chunks, std::shared_ptr<DataType> type = NULLPTR);
93
+
94
+ /// \brief Create an empty ChunkedArray of a given type
95
+ ///
96
+ /// The output ChunkedArray will have one chunk with an empty
97
+ /// array of the given type.
98
+ ///
99
+ /// \param[in] type the data type of the empty ChunkedArray
100
+ /// \param[in] pool the memory pool to allocate memory from
101
+ /// \return the resulting ChunkedArray
102
+ static Result<std::shared_ptr<ChunkedArray>> MakeEmpty(
103
+ std::shared_ptr<DataType> type, MemoryPool* pool = default_memory_pool());
104
+
105
+ /// \return the total length of the chunked array; computed on construction
106
+ int64_t length() const { return length_; }
107
+
108
+ /// \return the total number of nulls among all chunks
109
+ int64_t null_count() const { return null_count_; }
110
+
111
+ /// \return the total number of chunks in the chunked array
112
+ int num_chunks() const { return static_cast<int>(chunks_.size()); }
113
+
114
+ /// \return chunk a particular chunk from the chunked array
115
+ const std::shared_ptr<Array>& chunk(int i) const { return chunks_[i]; }
116
+
117
+ /// \return an ArrayVector of chunks
118
+ const ArrayVector& chunks() const { return chunks_; }
119
+
120
+ /// \return The set of device allocation types used by the chunks in this
121
+ /// chunked array.
122
+ DeviceAllocationTypeSet device_types() const;
123
+
124
+ /// \return true if all chunks are allocated on CPU-accessible memory.
125
+ bool is_cpu() const { return device_types().is_cpu_only(); }
126
+
127
+ /// \brief Construct a zero-copy slice of the chunked array with the
128
+ /// indicated offset and length
129
+ ///
130
+ /// \param[in] offset the position of the first element in the constructed
131
+ /// slice
132
+ /// \param[in] length the length of the slice. If there are not enough
133
+ /// elements in the chunked array, the length will be adjusted accordingly
134
+ ///
135
+ /// \return a new object wrapped in std::shared_ptr<ChunkedArray>
136
+ std::shared_ptr<ChunkedArray> Slice(int64_t offset, int64_t length) const;
137
+
138
+ /// \brief Slice from offset until end of the chunked array
139
+ std::shared_ptr<ChunkedArray> Slice(int64_t offset) const;
140
+
141
+ /// \brief Flatten this chunked array as a vector of chunked arrays, one
142
+ /// for each struct field
143
+ ///
144
+ /// \param[in] pool The pool for buffer allocations, if any
145
+ Result<std::vector<std::shared_ptr<ChunkedArray>>> Flatten(
146
+ MemoryPool* pool = default_memory_pool()) const;
147
+
148
+ /// Construct a zero-copy view of this chunked array with the given
149
+ /// type. Calls Array::View on each constituent chunk. Always succeeds if
150
+ /// there are zero chunks
151
+ Result<std::shared_ptr<ChunkedArray>> View(const std::shared_ptr<DataType>& type) const;
152
+
153
+ /// \brief Return the type of the chunked array
154
+ const std::shared_ptr<DataType>& type() const { return type_; }
155
+
156
+ /// \brief Return a Scalar containing the value of this array at index
157
+ Result<std::shared_ptr<Scalar>> GetScalar(int64_t index) const;
158
+
159
+ /// \brief Determine if two chunked arrays are equal.
160
+ ///
161
+ /// Two chunked arrays can be equal only if they have equal datatypes.
162
+ /// However, they may be equal even if they have different chunkings.
163
+ bool Equals(const ChunkedArray& other,
164
+ const EqualOptions& opts = EqualOptions::Defaults()) const;
165
+ /// \brief Determine if two chunked arrays are equal.
166
+ bool Equals(const std::shared_ptr<ChunkedArray>& other,
167
+ const EqualOptions& opts = EqualOptions::Defaults()) const;
168
+ /// \brief Determine if two chunked arrays approximately equal
169
+ bool ApproxEquals(const ChunkedArray& other,
170
+ const EqualOptions& = EqualOptions::Defaults()) const;
171
+
172
+ /// \return PrettyPrint representation suitable for debugging
173
+ std::string ToString() const;
174
+
175
+ /// \brief Perform cheap validation checks to determine obvious inconsistencies
176
+ /// within the chunk array's internal data.
177
+ ///
178
+ /// This is O(k*m) where k is the number of array descendents,
179
+ /// and m is the number of chunks.
180
+ ///
181
+ /// \return Status
182
+ Status Validate() const;
183
+
184
+ /// \brief Perform extensive validation checks to determine inconsistencies
185
+ /// within the chunk array's internal data.
186
+ ///
187
+ /// This is O(k*n) where k is the number of array descendents,
188
+ /// and n is the length in elements.
189
+ ///
190
+ /// \return Status
191
+ Status ValidateFull() const;
192
+
193
+ protected:
194
+ ArrayVector chunks_;
195
+ std::shared_ptr<DataType> type_;
196
+ int64_t length_;
197
+ int64_t null_count_;
198
+
199
+ private:
200
+ template <typename T, typename V>
201
+ friend class ::arrow::stl::ChunkedArrayIterator;
202
+ ChunkResolver chunk_resolver_;
203
+ ARROW_DISALLOW_COPY_AND_ASSIGN(ChunkedArray);
204
+ };
205
+
206
+ namespace internal {
207
+
208
+ /// \brief EXPERIMENTAL: Utility for incremental iteration over contiguous
209
+ /// pieces of potentially differently-chunked ChunkedArray objects
210
+ class ARROW_EXPORT MultipleChunkIterator {
211
+ public:
212
+ MultipleChunkIterator(const ChunkedArray& left, const ChunkedArray& right)
213
+ : left_(left),
214
+ right_(right),
215
+ pos_(0),
216
+ length_(left.length()),
217
+ chunk_idx_left_(0),
218
+ chunk_idx_right_(0),
219
+ chunk_pos_left_(0),
220
+ chunk_pos_right_(0) {}
221
+
222
+ bool Next(std::shared_ptr<Array>* next_left, std::shared_ptr<Array>* next_right);
223
+
224
+ int64_t position() const { return pos_; }
225
+
226
+ private:
227
+ const ChunkedArray& left_;
228
+ const ChunkedArray& right_;
229
+
230
+ // The amount of the entire ChunkedArray consumed
231
+ int64_t pos_;
232
+
233
+ // Length of the chunked array(s)
234
+ int64_t length_;
235
+
236
+ // Current left chunk
237
+ int chunk_idx_left_;
238
+
239
+ // Current right chunk
240
+ int chunk_idx_right_;
241
+
242
+ // Offset into the current left chunk
243
+ int64_t chunk_pos_left_;
244
+
245
+ // Offset into the current right chunk
246
+ int64_t chunk_pos_right_;
247
+ };
248
+
249
+ /// \brief Evaluate binary function on two ChunkedArray objects having possibly
250
+ /// different chunk layouts. The passed binary function / functor should have
251
+ /// the following signature.
252
+ ///
253
+ /// Status(const Array&, const Array&, int64_t)
254
+ ///
255
+ /// The third argument is the absolute position relative to the start of each
256
+ /// ChunkedArray. The function is executed against each contiguous pair of
257
+ /// array segments, slicing if necessary.
258
+ ///
259
+ /// For example, if two arrays have chunk sizes
260
+ ///
261
+ /// left: [10, 10, 20]
262
+ /// right: [15, 10, 15]
263
+ ///
264
+ /// Then the following invocations take place (pseudocode)
265
+ ///
266
+ /// func(left.chunk[0][0:10], right.chunk[0][0:10], 0)
267
+ /// func(left.chunk[1][0:5], right.chunk[0][10:15], 10)
268
+ /// func(left.chunk[1][5:10], right.chunk[1][0:5], 15)
269
+ /// func(left.chunk[2][0:5], right.chunk[1][5:10], 20)
270
+ /// func(left.chunk[2][5:20], right.chunk[2][:], 25)
271
+ template <typename Action>
272
+ Status ApplyBinaryChunked(const ChunkedArray& left, const ChunkedArray& right,
273
+ Action&& action) {
274
+ MultipleChunkIterator iterator(left, right);
275
+ std::shared_ptr<Array> left_piece, right_piece;
276
+ while (iterator.Next(&left_piece, &right_piece)) {
277
+ ARROW_RETURN_NOT_OK(action(*left_piece, *right_piece, iterator.position()));
278
+ }
279
+ return Status::OK();
280
+ }
281
+
282
+ } // namespace internal
283
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/device_allocation_type_set.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <bitset>
21
+ #include <string>
22
+
23
+ #include "arrow/type_fwd.h"
24
+ #include "arrow/util/visibility.h"
25
+
26
+ namespace arrow {
27
+
28
+ ARROW_EXPORT
29
+ const char* DeviceAllocationTypeToCStr(DeviceAllocationType type);
30
+
31
+ class ARROW_EXPORT DeviceAllocationTypeSet {
32
+ private:
33
+ std::bitset<kDeviceAllocationTypeMax + 1> device_type_bitset_;
34
+
35
+ public:
36
+ /// \brief Construct an empty set of device types.
37
+ DeviceAllocationTypeSet() = default;
38
+
39
+ /// \brief Construct a set of device types with a single device type.
40
+ DeviceAllocationTypeSet( // NOLINT implicit construction
41
+ DeviceAllocationType accepted_device_type) {
42
+ add(accepted_device_type);
43
+ }
44
+
45
+ /// \brief Construct a set of device types containing only "kCPU".
46
+ static DeviceAllocationTypeSet CpuOnly() {
47
+ return DeviceAllocationTypeSet{DeviceAllocationType::kCPU};
48
+ }
49
+
50
+ /// \brief Construct a set of device types containing all device types.
51
+ static DeviceAllocationTypeSet All() {
52
+ DeviceAllocationTypeSet all;
53
+ all.device_type_bitset_.set();
54
+ // Don't set the invalid enum values.
55
+ all.device_type_bitset_.reset(0);
56
+ all.device_type_bitset_.reset(5);
57
+ all.device_type_bitset_.reset(6);
58
+ return all;
59
+ }
60
+
61
+ /// \brief Add a device type to the set of device types.
62
+ void add(DeviceAllocationType device_type) {
63
+ device_type_bitset_.set(static_cast<int>(device_type));
64
+ }
65
+
66
+ /// \brief Remove a device type from the set of device types.
67
+ void remove(DeviceAllocationType device_type) {
68
+ device_type_bitset_.reset(static_cast<int>(device_type));
69
+ }
70
+
71
+ /// \brief Return true iff the set only contains the CPU device type.
72
+ bool is_cpu_only() const {
73
+ return device_type_bitset_ == CpuOnly().device_type_bitset_;
74
+ }
75
+
76
+ /// \brief Return true if the set of accepted device types includes the
77
+ /// device type.
78
+ bool contains(DeviceAllocationType device_type) const {
79
+ return device_type_bitset_.test(static_cast<int>(device_type));
80
+ }
81
+
82
+ /// \brief Add all device types from another set to this set.
83
+ void Add(DeviceAllocationTypeSet other) {
84
+ device_type_bitset_ |= other.device_type_bitset_;
85
+ }
86
+
87
+ /// \brief Return true if the set of accepted device types includes all the
88
+ /// device types in the other set.
89
+ bool Contains(DeviceAllocationTypeSet other) const {
90
+ // other \subseteq this <==> (other \intersect this == other)
91
+ return (other.device_type_bitset_ & device_type_bitset_) == other.device_type_bitset_;
92
+ }
93
+
94
+ std::string ToString() const;
95
+ };
96
+
97
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/extension_type.h ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ /// User-defined extension types.
19
+ /// \since 0.13.0
20
+
21
+ #pragma once
22
+
23
+ #include <memory>
24
+ #include <string>
25
+
26
+ #include "arrow/array/array_base.h"
27
+ #include "arrow/array/data.h"
28
+ #include "arrow/result.h"
29
+ #include "arrow/status.h"
30
+ #include "arrow/type.h"
31
+ #include "arrow/type_fwd.h"
32
+ #include "arrow/util/checked_cast.h"
33
+ #include "arrow/util/macros.h"
34
+ #include "arrow/util/visibility.h"
35
+
36
+ namespace arrow {
37
+
38
+ /// \brief The base class for custom / user-defined types.
39
+ class ARROW_EXPORT ExtensionType : public DataType {
40
+ public:
41
+ static constexpr Type::type type_id = Type::EXTENSION;
42
+
43
+ static constexpr const char* type_name() { return "extension"; }
44
+
45
+ /// \brief The type of array used to represent this extension type's data
46
+ const std::shared_ptr<DataType>& storage_type() const { return storage_type_; }
47
+
48
+ /// \brief Return the type category of the storage type
49
+ Type::type storage_id() const override { return storage_type_->id(); }
50
+
51
+ DataTypeLayout layout() const override;
52
+
53
+ std::string ToString(bool show_metadata = false) const override;
54
+
55
+ std::string name() const override { return "extension"; }
56
+
57
+ int32_t byte_width() const override { return storage_type_->byte_width(); }
58
+ int bit_width() const override { return storage_type_->bit_width(); }
59
+
60
+ /// \brief Unique name of extension type used to identify type for
61
+ /// serialization
62
+ /// \return the string name of the extension
63
+ virtual std::string extension_name() const = 0;
64
+
65
+ /// \brief Determine if two instances of the same extension types are
66
+ /// equal. Invoked from ExtensionType::Equals
67
+ /// \param[in] other the type to compare this type with
68
+ /// \return bool true if type instances are equal
69
+ virtual bool ExtensionEquals(const ExtensionType& other) const = 0;
70
+
71
+ /// \brief Wrap built-in Array type in a user-defined ExtensionArray instance
72
+ /// \param[in] data the physical storage for the extension type
73
+ virtual std::shared_ptr<Array> MakeArray(std::shared_ptr<ArrayData> data) const = 0;
74
+
75
+ /// \brief Create an instance of the ExtensionType given the actual storage
76
+ /// type and the serialized representation
77
+ /// \param[in] storage_type the physical storage type of the extension
78
+ /// \param[in] serialized_data the serialized representation produced by
79
+ /// Serialize
80
+ virtual Result<std::shared_ptr<DataType>> Deserialize(
81
+ std::shared_ptr<DataType> storage_type,
82
+ const std::string& serialized_data) const = 0;
83
+
84
+ /// \brief Create a serialized representation of the extension type's
85
+ /// metadata. The storage type will be handled automatically in IPC code
86
+ /// paths
87
+ /// \return the serialized representation
88
+ virtual std::string Serialize() const = 0;
89
+
90
+ /// \brief Wrap the given storage array as an extension array
91
+ static std::shared_ptr<Array> WrapArray(const std::shared_ptr<DataType>& ext_type,
92
+ const std::shared_ptr<Array>& storage);
93
+
94
+ /// \brief Wrap the given chunked storage array as a chunked extension array
95
+ static std::shared_ptr<ChunkedArray> WrapArray(
96
+ const std::shared_ptr<DataType>& ext_type,
97
+ const std::shared_ptr<ChunkedArray>& storage);
98
+
99
+ protected:
100
+ explicit ExtensionType(std::shared_ptr<DataType> storage_type)
101
+ : DataType(Type::EXTENSION), storage_type_(storage_type) {}
102
+
103
+ std::shared_ptr<DataType> storage_type_;
104
+ };
105
+
106
+ /// \brief Base array class for user-defined extension types
107
+ class ARROW_EXPORT ExtensionArray : public Array {
108
+ public:
109
+ using TypeClass = ExtensionType;
110
+ /// \brief Construct an ExtensionArray from an ArrayData.
111
+ ///
112
+ /// The ArrayData must have the right ExtensionType.
113
+ explicit ExtensionArray(const std::shared_ptr<ArrayData>& data);
114
+
115
+ /// \brief Construct an ExtensionArray from a type and the underlying storage.
116
+ ExtensionArray(const std::shared_ptr<DataType>& type,
117
+ const std::shared_ptr<Array>& storage);
118
+
119
+ const ExtensionType* extension_type() const {
120
+ return internal::checked_cast<const ExtensionType*>(data_->type.get());
121
+ }
122
+
123
+ /// \brief The physical storage for the extension array
124
+ const std::shared_ptr<Array>& storage() const { return storage_; }
125
+
126
+ protected:
127
+ void SetData(const std::shared_ptr<ArrayData>& data);
128
+ std::shared_ptr<Array> storage_;
129
+ };
130
+
131
+ class ARROW_EXPORT ExtensionTypeRegistry {
132
+ public:
133
+ /// \brief Provide access to the global registry to allow code to control for
134
+ /// race conditions in registry teardown when some types need to be
135
+ /// unregistered and destroyed first
136
+ static std::shared_ptr<ExtensionTypeRegistry> GetGlobalRegistry();
137
+
138
+ virtual ~ExtensionTypeRegistry() = default;
139
+
140
+ virtual Status RegisterType(std::shared_ptr<ExtensionType> type) = 0;
141
+ virtual Status UnregisterType(const std::string& type_name) = 0;
142
+ virtual std::shared_ptr<ExtensionType> GetType(const std::string& type_name) = 0;
143
+ };
144
+
145
+ /// \brief Register an extension type globally. The name returned by the type's
146
+ /// extension_name() method should be unique. This method is thread-safe
147
+ /// \param[in] type an instance of the extension type
148
+ /// \return Status
149
+ ARROW_EXPORT
150
+ Status RegisterExtensionType(std::shared_ptr<ExtensionType> type);
151
+
152
+ /// \brief Delete an extension type from the global registry. This method is
153
+ /// thread-safe
154
+ /// \param[in] type_name the unique name of a registered extension type
155
+ /// \return Status error if the type name is unknown
156
+ ARROW_EXPORT
157
+ Status UnregisterExtensionType(const std::string& type_name);
158
+
159
+ /// \brief Retrieve an extension type from the global registry. Returns nullptr
160
+ /// if not found. This method is thread-safe
161
+ /// \return the globally-registered extension type
162
+ ARROW_EXPORT
163
+ std::shared_ptr<ExtensionType> GetExtensionType(const std::string& type_name);
164
+
165
+ ARROW_EXPORT extern const char kExtensionTypeKeyName[];
166
+ ARROW_EXPORT extern const char kExtensionMetadataKeyName[];
167
+
168
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/memory_pool.h ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <atomic>
21
+ #include <cstdint>
22
+ #include <functional>
23
+ #include <memory>
24
+ #include <string>
25
+
26
+ #include "arrow/result.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/type_fwd.h"
29
+ #include "arrow/util/visibility.h"
30
+
31
+ namespace arrow {
32
+
33
+ namespace internal {
34
+
35
+ ///////////////////////////////////////////////////////////////////////
36
+ // Helper tracking memory statistics
37
+
38
+ /// \brief Memory pool statistics
39
+ ///
40
+ /// 64-byte aligned so that all atomic values are on the same cache line.
41
+ class alignas(64) MemoryPoolStats {
42
+ private:
43
+ // All atomics are updated according to Acquire-Release ordering.
44
+ // https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
45
+ //
46
+ // max_memory_, total_allocated_bytes_, and num_allocs_ only go up (they are
47
+ // monotonically increasing) which can allow some optimizations.
48
+ std::atomic<int64_t> max_memory_{0};
49
+ std::atomic<int64_t> bytes_allocated_{0};
50
+ std::atomic<int64_t> total_allocated_bytes_{0};
51
+ std::atomic<int64_t> num_allocs_{0};
52
+
53
+ public:
54
+ int64_t max_memory() const { return max_memory_.load(std::memory_order_acquire); }
55
+
56
+ int64_t bytes_allocated() const {
57
+ return bytes_allocated_.load(std::memory_order_acquire);
58
+ }
59
+
60
+ int64_t total_bytes_allocated() const {
61
+ return total_allocated_bytes_.load(std::memory_order_acquire);
62
+ }
63
+
64
+ int64_t num_allocations() const { return num_allocs_.load(std::memory_order_acquire); }
65
+
66
+ inline void DidAllocateBytes(int64_t size) {
67
+ // Issue the load before everything else. max_memory_ is monotonically increasing,
68
+ // so we can use a relaxed load before the read-modify-write.
69
+ auto max_memory = max_memory_.load(std::memory_order_relaxed);
70
+ const auto old_bytes_allocated =
71
+ bytes_allocated_.fetch_add(size, std::memory_order_acq_rel);
72
+ // Issue store operations on values that we don't depend on to proceed
73
+ // with execution. When done, max_memory and old_bytes_allocated have
74
+ // a higher chance of being available on CPU registers. This also has the
75
+ // nice side-effect of putting 3 atomic stores close to each other in the
76
+ // instruction stream.
77
+ total_allocated_bytes_.fetch_add(size, std::memory_order_acq_rel);
78
+ num_allocs_.fetch_add(1, std::memory_order_acq_rel);
79
+
80
+ // If other threads are updating max_memory_ concurrently we leave the loop without
81
+ // updating knowing that it already reached a value even higher than ours.
82
+ const auto allocated = old_bytes_allocated + size;
83
+ while (max_memory < allocated && !max_memory_.compare_exchange_weak(
84
+ /*expected=*/max_memory, /*desired=*/allocated,
85
+ std::memory_order_acq_rel)) {
86
+ }
87
+ }
88
+
89
+ inline void DidReallocateBytes(int64_t old_size, int64_t new_size) {
90
+ if (new_size > old_size) {
91
+ DidAllocateBytes(new_size - old_size);
92
+ } else {
93
+ DidFreeBytes(old_size - new_size);
94
+ }
95
+ }
96
+
97
+ inline void DidFreeBytes(int64_t size) {
98
+ bytes_allocated_.fetch_sub(size, std::memory_order_acq_rel);
99
+ }
100
+ };
101
+
102
+ } // namespace internal
103
+
104
+ /// Base class for memory allocation on the CPU.
105
+ ///
106
+ /// Besides tracking the number of allocated bytes, the allocator also should
107
+ /// take care of the required 64-byte alignment.
108
+ class ARROW_EXPORT MemoryPool {
109
+ public:
110
+ virtual ~MemoryPool() = default;
111
+
112
+ /// \brief EXPERIMENTAL. Create a new instance of the default MemoryPool
113
+ static std::unique_ptr<MemoryPool> CreateDefault();
114
+
115
+ /// Allocate a new memory region of at least size bytes.
116
+ ///
117
+ /// The allocated region shall be 64-byte aligned.
118
+ Status Allocate(int64_t size, uint8_t** out) {
119
+ return Allocate(size, kDefaultBufferAlignment, out);
120
+ }
121
+
122
+ /// Allocate a new memory region of at least size bytes aligned to alignment.
123
+ virtual Status Allocate(int64_t size, int64_t alignment, uint8_t** out) = 0;
124
+
125
+ /// Resize an already allocated memory section.
126
+ ///
127
+ /// As by default most default allocators on a platform don't support aligned
128
+ /// reallocation, this function can involve a copy of the underlying data.
129
+ virtual Status Reallocate(int64_t old_size, int64_t new_size, int64_t alignment,
130
+ uint8_t** ptr) = 0;
131
+ Status Reallocate(int64_t old_size, int64_t new_size, uint8_t** ptr) {
132
+ return Reallocate(old_size, new_size, kDefaultBufferAlignment, ptr);
133
+ }
134
+
135
+ /// Free an allocated region.
136
+ ///
137
+ /// @param buffer Pointer to the start of the allocated memory region
138
+ /// @param size Allocated size located at buffer. An allocator implementation
139
+ /// may use this for tracking the amount of allocated bytes as well as for
140
+ /// faster deallocation if supported by its backend.
141
+ /// @param alignment The alignment of the allocation. Defaults to 64 bytes.
142
+ virtual void Free(uint8_t* buffer, int64_t size, int64_t alignment) = 0;
143
+ void Free(uint8_t* buffer, int64_t size) {
144
+ Free(buffer, size, kDefaultBufferAlignment);
145
+ }
146
+
147
+ /// Return unused memory to the OS
148
+ ///
149
+ /// Only applies to allocators that hold onto unused memory. This will be
150
+ /// best effort, a memory pool may not implement this feature or may be
151
+ /// unable to fulfill the request due to fragmentation.
152
+ virtual void ReleaseUnused() {}
153
+
154
+ /// The number of bytes that were allocated and not yet free'd through
155
+ /// this allocator.
156
+ virtual int64_t bytes_allocated() const = 0;
157
+
158
+ /// Return peak memory allocation in this memory pool
159
+ ///
160
+ /// \return Maximum bytes allocated. If not known (or not implemented),
161
+ /// returns -1
162
+ virtual int64_t max_memory() const;
163
+
164
+ /// The number of bytes that were allocated.
165
+ virtual int64_t total_bytes_allocated() const = 0;
166
+
167
+ /// The number of allocations or reallocations that were requested.
168
+ virtual int64_t num_allocations() const = 0;
169
+
170
+ /// The name of the backend used by this MemoryPool (e.g. "system" or "jemalloc").
171
+ virtual std::string backend_name() const = 0;
172
+
173
+ protected:
174
+ MemoryPool() = default;
175
+ };
176
+
177
+ class ARROW_EXPORT LoggingMemoryPool : public MemoryPool {
178
+ public:
179
+ explicit LoggingMemoryPool(MemoryPool* pool);
180
+ ~LoggingMemoryPool() override = default;
181
+
182
+ using MemoryPool::Allocate;
183
+ using MemoryPool::Free;
184
+ using MemoryPool::Reallocate;
185
+
186
+ Status Allocate(int64_t size, int64_t alignment, uint8_t** out) override;
187
+ Status Reallocate(int64_t old_size, int64_t new_size, int64_t alignment,
188
+ uint8_t** ptr) override;
189
+ void Free(uint8_t* buffer, int64_t size, int64_t alignment) override;
190
+
191
+ int64_t bytes_allocated() const override;
192
+
193
+ int64_t max_memory() const override;
194
+
195
+ int64_t total_bytes_allocated() const override;
196
+
197
+ int64_t num_allocations() const override;
198
+
199
+ std::string backend_name() const override;
200
+
201
+ private:
202
+ MemoryPool* pool_;
203
+ };
204
+
205
+ /// Derived class for memory allocation.
206
+ ///
207
+ /// Tracks the number of bytes and maximum memory allocated through its direct
208
+ /// calls. Actual allocation is delegated to MemoryPool class.
209
+ class ARROW_EXPORT ProxyMemoryPool : public MemoryPool {
210
+ public:
211
+ explicit ProxyMemoryPool(MemoryPool* pool);
212
+ ~ProxyMemoryPool() override;
213
+
214
+ using MemoryPool::Allocate;
215
+ using MemoryPool::Free;
216
+ using MemoryPool::Reallocate;
217
+
218
+ Status Allocate(int64_t size, int64_t alignment, uint8_t** out) override;
219
+ Status Reallocate(int64_t old_size, int64_t new_size, int64_t alignment,
220
+ uint8_t** ptr) override;
221
+ void Free(uint8_t* buffer, int64_t size, int64_t alignment) override;
222
+
223
+ int64_t bytes_allocated() const override;
224
+
225
+ int64_t max_memory() const override;
226
+
227
+ int64_t total_bytes_allocated() const override;
228
+
229
+ int64_t num_allocations() const override;
230
+
231
+ std::string backend_name() const override;
232
+
233
+ private:
234
+ class ProxyMemoryPoolImpl;
235
+ std::unique_ptr<ProxyMemoryPoolImpl> impl_;
236
+ };
237
+
238
+ /// \brief Return a process-wide memory pool based on the system allocator.
239
+ ARROW_EXPORT MemoryPool* system_memory_pool();
240
+
241
+ /// \brief Return a process-wide memory pool based on jemalloc.
242
+ ///
243
+ /// May return NotImplemented if jemalloc is not available.
244
+ ARROW_EXPORT Status jemalloc_memory_pool(MemoryPool** out);
245
+
246
+ /// \brief Set jemalloc memory page purging behavior for future-created arenas
247
+ /// to the indicated number of milliseconds. See dirty_decay_ms and
248
+ /// muzzy_decay_ms options in jemalloc for a description of what these do. The
249
+ /// default is configured to 1000 (1 second) which releases memory more
250
+ /// aggressively to the operating system than the jemalloc default of 10
251
+ /// seconds. If you set the value to 0, dirty / muzzy pages will be released
252
+ /// immediately rather than with a time decay, but this may reduce application
253
+ /// performance.
254
+ ARROW_EXPORT
255
+ Status jemalloc_set_decay_ms(int ms);
256
+
257
+ /// \brief Get basic statistics from jemalloc's mallctl.
258
+ /// See the MALLCTL NAMESPACE section in jemalloc project documentation for
259
+ /// available stats.
260
+ ARROW_EXPORT
261
+ Result<int64_t> jemalloc_get_stat(const char* name);
262
+
263
+ /// \brief Reset the counter for peak bytes allocated in the calling thread to zero.
264
+ /// This affects subsequent calls to thread.peak.read, but not the values returned by
265
+ /// thread.allocated or thread.deallocated.
266
+ ARROW_EXPORT
267
+ Status jemalloc_peak_reset();
268
+
269
+ /// \brief Print summary statistics in human-readable form to stderr.
270
+ /// See malloc_stats_print documentation in jemalloc project documentation for
271
+ /// available opt flags.
272
+ ARROW_EXPORT
273
+ Status jemalloc_stats_print(const char* opts = "");
274
+
275
+ /// \brief Print summary statistics in human-readable form using a callback
276
+ /// See malloc_stats_print documentation in jemalloc project documentation for
277
+ /// available opt flags.
278
+ ARROW_EXPORT
279
+ Status jemalloc_stats_print(std::function<void(const char*)> write_cb,
280
+ const char* opts = "");
281
+
282
+ /// \brief Get summary statistics in human-readable form.
283
+ /// See malloc_stats_print documentation in jemalloc project documentation for
284
+ /// available opt flags.
285
+ ARROW_EXPORT
286
+ Result<std::string> jemalloc_stats_string(const char* opts = "");
287
+
288
+ /// \brief Return a process-wide memory pool based on mimalloc.
289
+ ///
290
+ /// May return NotImplemented if mimalloc is not available.
291
+ ARROW_EXPORT Status mimalloc_memory_pool(MemoryPool** out);
292
+
293
+ /// \brief Return the names of the backends supported by this Arrow build.
294
+ ARROW_EXPORT std::vector<std::string> SupportedMemoryBackendNames();
295
+
296
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/stl_iterator.h ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cassert>
21
+ #include <cstddef>
22
+ #include <iterator>
23
+ #include <optional>
24
+ #include <utility>
25
+
26
+ #include "arrow/chunked_array.h"
27
+ #include "arrow/type.h"
28
+ #include "arrow/type_fwd.h"
29
+ #include "arrow/type_traits.h"
30
+ #include "arrow/util/macros.h"
31
+
32
+ namespace arrow {
33
+ namespace stl {
34
+
35
+ namespace detail {
36
+
37
+ template <typename ArrayType>
38
+ struct DefaultValueAccessor {
39
+ using ValueType = decltype(std::declval<ArrayType>().GetView(0));
40
+
41
+ ValueType operator()(const ArrayType& array, int64_t index) {
42
+ return array.GetView(index);
43
+ }
44
+ };
45
+
46
+ } // namespace detail
47
+
48
+ template <typename ArrayType,
49
+ typename ValueAccessor = detail::DefaultValueAccessor<ArrayType>>
50
+ class ArrayIterator {
51
+ public:
52
+ using value_type = std::optional<typename ValueAccessor::ValueType>;
53
+ using difference_type = int64_t;
54
+ using pointer = value_type*;
55
+ using reference = value_type&;
56
+ using iterator_category = std::random_access_iterator_tag;
57
+
58
+ // Some algorithms need to default-construct an iterator
59
+ ArrayIterator() : array_(NULLPTR), index_(0) {}
60
+
61
+ explicit ArrayIterator(const ArrayType& array, int64_t index = 0)
62
+ : array_(&array), index_(index) {}
63
+
64
+ // Value access
65
+ value_type operator*() const {
66
+ assert(array_);
67
+ return array_->IsNull(index_) ? value_type{} : array_->GetView(index_);
68
+ }
69
+
70
+ value_type operator[](difference_type n) const {
71
+ assert(array_);
72
+ return array_->IsNull(index_ + n) ? value_type{} : array_->GetView(index_ + n);
73
+ }
74
+
75
+ int64_t index() const { return index_; }
76
+
77
+ // Forward / backward
78
+ ArrayIterator& operator++() {
79
+ ++index_;
80
+ return *this;
81
+ }
82
+ ArrayIterator& operator--() {
83
+ --index_;
84
+ return *this;
85
+ }
86
+ ArrayIterator operator++(int) {
87
+ ArrayIterator tmp(*this);
88
+ ++index_;
89
+ return tmp;
90
+ }
91
+ ArrayIterator operator--(int) {
92
+ ArrayIterator tmp(*this);
93
+ --index_;
94
+ return tmp;
95
+ }
96
+
97
+ // Arithmetic
98
+ difference_type operator-(const ArrayIterator& other) const {
99
+ return index_ - other.index_;
100
+ }
101
+ ArrayIterator operator+(difference_type n) const {
102
+ return ArrayIterator(*array_, index_ + n);
103
+ }
104
+ ArrayIterator operator-(difference_type n) const {
105
+ return ArrayIterator(*array_, index_ - n);
106
+ }
107
+ friend inline ArrayIterator operator+(difference_type diff,
108
+ const ArrayIterator& other) {
109
+ return ArrayIterator(*other.array_, diff + other.index_);
110
+ }
111
+ friend inline ArrayIterator operator-(difference_type diff,
112
+ const ArrayIterator& other) {
113
+ return ArrayIterator(*other.array_, diff - other.index_);
114
+ }
115
+ ArrayIterator& operator+=(difference_type n) {
116
+ index_ += n;
117
+ return *this;
118
+ }
119
+ ArrayIterator& operator-=(difference_type n) {
120
+ index_ -= n;
121
+ return *this;
122
+ }
123
+
124
+ // Comparisons
125
+ bool operator==(const ArrayIterator& other) const { return index_ == other.index_; }
126
+ bool operator!=(const ArrayIterator& other) const { return index_ != other.index_; }
127
+ bool operator<(const ArrayIterator& other) const { return index_ < other.index_; }
128
+ bool operator>(const ArrayIterator& other) const { return index_ > other.index_; }
129
+ bool operator<=(const ArrayIterator& other) const { return index_ <= other.index_; }
130
+ bool operator>=(const ArrayIterator& other) const { return index_ >= other.index_; }
131
+
132
+ private:
133
+ const ArrayType* array_;
134
+ int64_t index_;
135
+ };
136
+
137
+ template <typename ArrayType,
138
+ typename ValueAccessor = detail::DefaultValueAccessor<ArrayType>>
139
+ class ChunkedArrayIterator {
140
+ public:
141
+ using value_type = std::optional<typename ValueAccessor::ValueType>;
142
+ using difference_type = int64_t;
143
+ using pointer = value_type*;
144
+ using reference = value_type&;
145
+ using iterator_category = std::random_access_iterator_tag;
146
+
147
+ // Some algorithms need to default-construct an iterator
148
+ ChunkedArrayIterator() noexcept : chunked_array_(NULLPTR), index_(0) {}
149
+
150
+ explicit ChunkedArrayIterator(const ChunkedArray& chunked_array,
151
+ int64_t index = 0) noexcept
152
+ : chunked_array_(&chunked_array), index_(index) {}
153
+
154
+ // Value access
155
+ value_type operator*() const {
156
+ auto chunk_location = GetChunkLocation(index_);
157
+ ArrayIterator<ArrayType> target_iterator{
158
+ arrow::internal::checked_cast<const ArrayType&>(
159
+ *chunked_array_->chunk(static_cast<int>(chunk_location.chunk_index)))};
160
+ return target_iterator[chunk_location.index_in_chunk];
161
+ }
162
+
163
+ value_type operator[](difference_type n) const { return *(*this + n); }
164
+
165
+ int64_t index() const { return index_; }
166
+
167
+ // Forward / backward
168
+ ChunkedArrayIterator& operator++() {
169
+ (*this) += 1;
170
+ return *this;
171
+ }
172
+ ChunkedArrayIterator& operator--() {
173
+ (*this) -= 1;
174
+ return *this;
175
+ }
176
+
177
+ ChunkedArrayIterator operator++(int) {
178
+ ChunkedArrayIterator tmp(*this);
179
+ ++*this;
180
+ return tmp;
181
+ }
182
+ ChunkedArrayIterator operator--(int) {
183
+ ChunkedArrayIterator tmp(*this);
184
+ --*this;
185
+ return tmp;
186
+ }
187
+
188
+ // Arithmetic
189
+ difference_type operator-(const ChunkedArrayIterator& other) const {
190
+ return index_ - other.index_;
191
+ }
192
+ ChunkedArrayIterator operator+(difference_type n) const {
193
+ assert(chunked_array_);
194
+ return ChunkedArrayIterator(*chunked_array_, index_ + n);
195
+ }
196
+ ChunkedArrayIterator operator-(difference_type n) const {
197
+ assert(chunked_array_);
198
+ return ChunkedArrayIterator(*chunked_array_, index_ - n);
199
+ }
200
+ friend inline ChunkedArrayIterator operator+(difference_type diff,
201
+ const ChunkedArrayIterator& other) {
202
+ assert(other.chunked_array_);
203
+ return ChunkedArrayIterator(*other.chunked_array_, diff + other.index_);
204
+ }
205
+ friend inline ChunkedArrayIterator operator-(difference_type diff,
206
+ const ChunkedArrayIterator& other) {
207
+ assert(other.chunked_array_);
208
+ return ChunkedArrayIterator(*other.chunked_array_, diff - other.index_);
209
+ }
210
+ ChunkedArrayIterator& operator+=(difference_type n) {
211
+ index_ += n;
212
+ return *this;
213
+ }
214
+ ChunkedArrayIterator& operator-=(difference_type n) {
215
+ (*this) += -n;
216
+ return *this;
217
+ }
218
+
219
+ // Comparisons
220
+ bool operator==(const ChunkedArrayIterator& other) const {
221
+ return index_ == other.index_;
222
+ }
223
+ bool operator!=(const ChunkedArrayIterator& other) const {
224
+ return index_ != other.index_;
225
+ }
226
+ bool operator<(const ChunkedArrayIterator& other) const {
227
+ return index_ < other.index_;
228
+ }
229
+ bool operator>(const ChunkedArrayIterator& other) const {
230
+ return index_ > other.index_;
231
+ }
232
+ bool operator<=(const ChunkedArrayIterator& other) const {
233
+ return index_ <= other.index_;
234
+ }
235
+ bool operator>=(const ChunkedArrayIterator& other) const {
236
+ return index_ >= other.index_;
237
+ }
238
+
239
+ private:
240
+ arrow::ChunkLocation GetChunkLocation(int64_t index) const {
241
+ assert(chunked_array_);
242
+ return chunked_array_->chunk_resolver_.Resolve(index);
243
+ }
244
+
245
+ const ChunkedArray* chunked_array_;
246
+ int64_t index_;
247
+ };
248
+
249
+ /// Return an iterator to the beginning of the chunked array
250
+ template <typename Type, typename ArrayType = typename TypeTraits<Type>::ArrayType>
251
+ ChunkedArrayIterator<ArrayType> Begin(const ChunkedArray& chunked_array) {
252
+ return ChunkedArrayIterator<ArrayType>(chunked_array);
253
+ }
254
+
255
+ /// Return an iterator to the end of the chunked array
256
+ template <typename Type, typename ArrayType = typename TypeTraits<Type>::ArrayType>
257
+ ChunkedArrayIterator<ArrayType> End(const ChunkedArray& chunked_array) {
258
+ return ChunkedArrayIterator<ArrayType>(chunked_array, chunked_array.length());
259
+ }
260
+
261
+ template <typename ArrayType>
262
+ struct ChunkedArrayRange {
263
+ const ChunkedArray* chunked_array;
264
+
265
+ ChunkedArrayIterator<ArrayType> begin() {
266
+ return stl::ChunkedArrayIterator<ArrayType>(*chunked_array);
267
+ }
268
+ ChunkedArrayIterator<ArrayType> end() {
269
+ return stl::ChunkedArrayIterator<ArrayType>(*chunked_array, chunked_array->length());
270
+ }
271
+ };
272
+
273
+ /// Return an iterable range over the chunked array
274
+ template <typename Type, typename ArrayType = typename TypeTraits<Type>::ArrayType>
275
+ ChunkedArrayRange<ArrayType> Iterate(const ChunkedArray& chunked_array) {
276
+ return stl::ChunkedArrayRange<ArrayType>{&chunked_array};
277
+ }
278
+
279
+ } // namespace stl
280
+ } // namespace arrow
281
+
282
+ namespace std {
283
+
284
+ template <typename ArrayType>
285
+ struct iterator_traits<::arrow::stl::ArrayIterator<ArrayType>> {
286
+ using IteratorType = ::arrow::stl::ArrayIterator<ArrayType>;
287
+ using difference_type = typename IteratorType::difference_type;
288
+ using value_type = typename IteratorType::value_type;
289
+ using pointer = typename IteratorType::pointer;
290
+ using reference = typename IteratorType::reference;
291
+ using iterator_category = typename IteratorType::iterator_category;
292
+ };
293
+
294
+ template <typename ArrayType>
295
+ struct iterator_traits<::arrow::stl::ChunkedArrayIterator<ArrayType>> {
296
+ using IteratorType = ::arrow::stl::ChunkedArrayIterator<ArrayType>;
297
+ using difference_type = typename IteratorType::difference_type;
298
+ using value_type = typename IteratorType::value_type;
299
+ using pointer = typename IteratorType::pointer;
300
+ using reference = typename IteratorType::reference;
301
+ using iterator_category = typename IteratorType::iterator_category;
302
+ };
303
+
304
+ } // namespace std
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/type.h ADDED
@@ -0,0 +1,2629 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <atomic>
21
+ #include <climits>
22
+ #include <cstdint>
23
+ #include <iosfwd>
24
+ #include <limits>
25
+ #include <memory>
26
+ #include <optional>
27
+ #include <string>
28
+ #include <utility>
29
+ #include <variant>
30
+ #include <vector>
31
+
32
+ #include "arrow/result.h"
33
+ #include "arrow/type_fwd.h" // IWYU pragma: export
34
+ #include "arrow/util/checked_cast.h"
35
+ #include "arrow/util/endian.h"
36
+ #include "arrow/util/macros.h"
37
+ #include "arrow/util/visibility.h"
38
+ #include "arrow/visitor.h" // IWYU pragma: keep
39
+
40
+ namespace arrow {
41
+ namespace detail {
42
+
43
+ /// \defgroup numeric-datatypes Datatypes for numeric data
44
+ /// @{
45
+ /// @}
46
+
47
+ /// \defgroup binary-datatypes Datatypes for binary/string data
48
+ /// @{
49
+ /// @}
50
+
51
+ /// \defgroup temporal-datatypes Datatypes for temporal data
52
+ /// @{
53
+ /// @}
54
+
55
+ /// \defgroup nested-datatypes Datatypes for nested data
56
+ /// @{
57
+ /// @}
58
+
59
+ class ARROW_EXPORT Fingerprintable {
60
+ public:
61
+ virtual ~Fingerprintable();
62
+
63
+ const std::string& fingerprint() const {
64
+ auto p = fingerprint_.load();
65
+ if (ARROW_PREDICT_TRUE(p != NULLPTR)) {
66
+ return *p;
67
+ }
68
+ return LoadFingerprintSlow();
69
+ }
70
+
71
+ const std::string& metadata_fingerprint() const {
72
+ auto p = metadata_fingerprint_.load();
73
+ if (ARROW_PREDICT_TRUE(p != NULLPTR)) {
74
+ return *p;
75
+ }
76
+ return LoadMetadataFingerprintSlow();
77
+ }
78
+
79
+ protected:
80
+ const std::string& LoadFingerprintSlow() const;
81
+ const std::string& LoadMetadataFingerprintSlow() const;
82
+
83
+ virtual std::string ComputeFingerprint() const = 0;
84
+ virtual std::string ComputeMetadataFingerprint() const = 0;
85
+
86
+ mutable std::atomic<std::string*> fingerprint_{NULLPTR};
87
+ mutable std::atomic<std::string*> metadata_fingerprint_{NULLPTR};
88
+ };
89
+
90
+ } // namespace detail
91
+
92
+ /// EXPERIMENTAL: Layout specification for a data type
93
+ struct ARROW_EXPORT DataTypeLayout {
94
+ enum BufferKind { FIXED_WIDTH, VARIABLE_WIDTH, BITMAP, ALWAYS_NULL };
95
+
96
+ /// Layout specification for a single data type buffer
97
+ struct BufferSpec {
98
+ BufferKind kind;
99
+ int64_t byte_width; // For FIXED_WIDTH
100
+
101
+ bool operator==(const BufferSpec& other) const {
102
+ return kind == other.kind &&
103
+ (kind != FIXED_WIDTH || byte_width == other.byte_width);
104
+ }
105
+ bool operator!=(const BufferSpec& other) const { return !(*this == other); }
106
+ };
107
+
108
+ static BufferSpec FixedWidth(int64_t w) { return BufferSpec{FIXED_WIDTH, w}; }
109
+ static BufferSpec VariableWidth() { return BufferSpec{VARIABLE_WIDTH, -1}; }
110
+ static BufferSpec Bitmap() { return BufferSpec{BITMAP, -1}; }
111
+ static BufferSpec AlwaysNull() { return BufferSpec{ALWAYS_NULL, -1}; }
112
+
113
+ /// A vector of buffer layout specifications, one for each expected buffer
114
+ std::vector<BufferSpec> buffers;
115
+ /// Whether this type expects an associated dictionary array.
116
+ bool has_dictionary = false;
117
+ /// If this is provided, the number of buffers expected is only lower-bounded by
118
+ /// buffers.size(). Buffers beyond this lower bound are expected to conform to
119
+ /// variadic_spec.
120
+ std::optional<BufferSpec> variadic_spec;
121
+
122
+ explicit DataTypeLayout(std::vector<BufferSpec> buffers,
123
+ std::optional<BufferSpec> variadic_spec = {})
124
+ : buffers(std::move(buffers)), variadic_spec(variadic_spec) {}
125
+ };
126
+
127
+ /// \brief Base class for all data types
128
+ ///
129
+ /// Data types in this library are all *logical*. They can be expressed as
130
+ /// either a primitive physical type (bytes or bits of some fixed size), a
131
+ /// nested type consisting of other data types, or another data type (e.g. a
132
+ /// timestamp encoded as an int64).
133
+ ///
134
+ /// Simple datatypes may be entirely described by their Type::type id, but
135
+ /// complex datatypes are usually parametric.
136
+ class ARROW_EXPORT DataType : public std::enable_shared_from_this<DataType>,
137
+ public detail::Fingerprintable,
138
+ public util::EqualityComparable<DataType> {
139
+ public:
140
+ explicit DataType(Type::type id) : detail::Fingerprintable(), id_(id) {}
141
+ ~DataType() override;
142
+
143
+ /// \brief Return whether the types are equal
144
+ ///
145
+ /// Types that are logically convertible from one to another (e.g. List<UInt8>
146
+ /// and Binary) are NOT equal.
147
+ bool Equals(const DataType& other, bool check_metadata = false) const;
148
+
149
+ /// \brief Return whether the types are equal
150
+ bool Equals(const std::shared_ptr<DataType>& other, bool check_metadata = false) const;
151
+
152
+ /// \brief Return the child field at index i.
153
+ const std::shared_ptr<Field>& field(int i) const { return children_[i]; }
154
+
155
+ /// \brief Return the children fields associated with this type.
156
+ const FieldVector& fields() const { return children_; }
157
+
158
+ /// \brief Return the number of children fields associated with this type.
159
+ int num_fields() const { return static_cast<int>(children_.size()); }
160
+
161
+ /// \brief Apply the TypeVisitor::Visit() method specialized to the data type
162
+ Status Accept(TypeVisitor* visitor) const;
163
+
164
+ /// \brief A string representation of the type, including any children
165
+ virtual std::string ToString(bool show_metadata = false) const = 0;
166
+
167
+ /// \brief Return hash value (excluding metadata in child fields)
168
+ size_t Hash() const;
169
+
170
+ /// \brief A string name of the type, omitting any child fields
171
+ ///
172
+ /// \since 0.7.0
173
+ virtual std::string name() const = 0;
174
+
175
+ /// \brief Return the data type layout. Children are not included.
176
+ ///
177
+ /// \note Experimental API
178
+ virtual DataTypeLayout layout() const = 0;
179
+
180
+ /// \brief Return the type category
181
+ Type::type id() const { return id_; }
182
+
183
+ /// \brief Return the type category of the storage type
184
+ virtual Type::type storage_id() const { return id_; }
185
+
186
+ /// \brief Returns the type's fixed byte width, if any. Returns -1
187
+ /// for non-fixed-width types, and should only be used for
188
+ /// subclasses of FixedWidthType
189
+ virtual int32_t byte_width() const {
190
+ int32_t num_bits = this->bit_width();
191
+ return num_bits > 0 ? num_bits / 8 : -1;
192
+ }
193
+
194
+ /// \brief Returns the type's fixed bit width, if any. Returns -1
195
+ /// for non-fixed-width types, and should only be used for
196
+ /// subclasses of FixedWidthType
197
+ virtual int bit_width() const { return -1; }
198
+
199
+ // \brief EXPERIMENTAL: Enable retrieving shared_ptr<DataType> from a const
200
+ // context.
201
+ std::shared_ptr<DataType> GetSharedPtr() const {
202
+ return const_cast<DataType*>(this)->shared_from_this();
203
+ }
204
+
205
+ protected:
206
+ // Dummy version that returns a null string (indicating not implemented).
207
+ // Subclasses should override for fast equality checks.
208
+ std::string ComputeFingerprint() const override;
209
+
210
+ // Generic versions that works for all regular types, nested or not.
211
+ std::string ComputeMetadataFingerprint() const override;
212
+
213
+ Type::type id_;
214
+ FieldVector children_;
215
+
216
+ private:
217
+ ARROW_DISALLOW_COPY_AND_ASSIGN(DataType);
218
+ };
219
+
220
+ /// \brief EXPERIMENTAL: Container for a type pointer which can hold a
221
+ /// dynamically created shared_ptr<DataType> if it needs to.
222
+ struct ARROW_EXPORT TypeHolder {
223
+ const DataType* type = NULLPTR;
224
+ std::shared_ptr<DataType> owned_type;
225
+
226
+ TypeHolder() = default;
227
+ TypeHolder(const TypeHolder& other) = default;
228
+ TypeHolder& operator=(const TypeHolder& other) = default;
229
+ TypeHolder(TypeHolder&& other) = default;
230
+ TypeHolder& operator=(TypeHolder&& other) = default;
231
+
232
+ TypeHolder(std::shared_ptr<DataType> owned_type) // NOLINT implicit construction
233
+ : type(owned_type.get()), owned_type(std::move(owned_type)) {}
234
+
235
+ TypeHolder(const DataType* type) // NOLINT implicit construction
236
+ : type(type) {}
237
+
238
+ Type::type id() const { return this->type->id(); }
239
+
240
+ std::shared_ptr<DataType> GetSharedPtr() const {
241
+ return this->type != NULLPTR ? this->type->GetSharedPtr() : NULLPTR;
242
+ }
243
+
244
+ const DataType& operator*() const { return *this->type; }
245
+
246
+ operator bool() const { return this->type != NULLPTR; }
247
+
248
+ bool operator==(const TypeHolder& other) const {
249
+ if (type == other.type) return true;
250
+ if (type == NULLPTR || other.type == NULLPTR) return false;
251
+ return type->Equals(*other.type);
252
+ }
253
+
254
+ bool operator==(decltype(NULLPTR)) const { return this->type == NULLPTR; }
255
+
256
+ bool operator==(const DataType& other) const {
257
+ if (this->type == NULLPTR) return false;
258
+ return other.Equals(*this->type);
259
+ }
260
+
261
+ bool operator!=(const DataType& other) const { return !(*this == other); }
262
+
263
+ bool operator==(const std::shared_ptr<DataType>& other) const {
264
+ return *this == *other;
265
+ }
266
+
267
+ bool operator!=(const TypeHolder& other) const { return !(*this == other); }
268
+
269
+ std::string ToString(bool show_metadata = false) const {
270
+ return this->type ? this->type->ToString(show_metadata) : "<NULLPTR>";
271
+ }
272
+
273
+ static std::string ToString(const std::vector<TypeHolder>&, bool show_metadata = false);
274
+
275
+ static std::vector<TypeHolder> FromTypes(
276
+ const std::vector<std::shared_ptr<DataType>>& types);
277
+ };
278
+
279
+ ARROW_EXPORT
280
+ std::ostream& operator<<(std::ostream& os, const DataType& type);
281
+
282
+ ARROW_EXPORT
283
+ std::ostream& operator<<(std::ostream& os, const TypeHolder& type);
284
+
285
+ /// \brief Return the compatible physical data type
286
+ ///
287
+ /// Some types may have distinct logical meanings but the exact same physical
288
+ /// representation. For example, TimestampType has Int64Type as a physical
289
+ /// type (defined as TimestampType::PhysicalType).
290
+ ///
291
+ /// The return value is as follows:
292
+ /// - if a `PhysicalType` alias exists in the concrete type class, return
293
+ /// an instance of `PhysicalType`.
294
+ /// - otherwise, return the input type itself.
295
+ std::shared_ptr<DataType> GetPhysicalType(const std::shared_ptr<DataType>& type);
296
+
297
+ /// \brief Base class for all fixed-width data types
298
+ class ARROW_EXPORT FixedWidthType : public DataType {
299
+ public:
300
+ using DataType::DataType;
301
+ // This is only for preventing defining this class in each
302
+ // translation unit to avoid one-definition-rule violation.
303
+ ~FixedWidthType() override;
304
+ };
305
+
306
+ /// \brief Base class for all data types representing primitive values
307
+ class ARROW_EXPORT PrimitiveCType : public FixedWidthType {
308
+ public:
309
+ using FixedWidthType::FixedWidthType;
310
+ // This is only for preventing defining this class in each
311
+ // translation unit to avoid one-definition-rule violation.
312
+ ~PrimitiveCType() override;
313
+ };
314
+
315
+ /// \brief Base class for all numeric data types
316
+ class ARROW_EXPORT NumberType : public PrimitiveCType {
317
+ public:
318
+ using PrimitiveCType::PrimitiveCType;
319
+ // This is only for preventing defining this class in each
320
+ // translation unit to avoid one-definition-rule violation.
321
+ ~NumberType() override;
322
+ };
323
+
324
+ /// \brief Base class for all integral data types
325
+ class ARROW_EXPORT IntegerType : public NumberType {
326
+ public:
327
+ using NumberType::NumberType;
328
+ // This is only for preventing defining this class in each
329
+ // translation unit to avoid one-definition-rule violation.
330
+ ~IntegerType() override;
331
+ virtual bool is_signed() const = 0;
332
+ };
333
+
334
+ /// \brief Base class for all floating-point data types
335
+ class ARROW_EXPORT FloatingPointType : public NumberType {
336
+ public:
337
+ using NumberType::NumberType;
338
+ // This is only for preventing defining this class in each
339
+ // translation unit to avoid one-definition-rule violation.
340
+ ~FloatingPointType() override;
341
+ enum Precision { HALF, SINGLE, DOUBLE };
342
+ virtual Precision precision() const = 0;
343
+ };
344
+
345
+ /// \brief Base class for all parametric data types
346
+ class ParametricType {};
347
+
348
+ class ARROW_EXPORT NestedType : public DataType, public ParametricType {
349
+ public:
350
+ using DataType::DataType;
351
+ // This is only for preventing defining this class in each
352
+ // translation unit to avoid one-definition-rule violation.
353
+ ~NestedType() override;
354
+ };
355
+
356
+ /// \brief The combination of a field name and data type, with optional metadata
357
+ ///
358
+ /// Fields are used to describe the individual constituents of a
359
+ /// nested DataType or a Schema.
360
+ ///
361
+ /// A field's metadata is represented by a KeyValueMetadata instance,
362
+ /// which holds arbitrary key-value pairs.
363
+ class ARROW_EXPORT Field : public detail::Fingerprintable,
364
+ public util::EqualityComparable<Field> {
365
+ public:
366
+ Field(std::string name, std::shared_ptr<DataType> type, bool nullable = true,
367
+ std::shared_ptr<const KeyValueMetadata> metadata = NULLPTR)
368
+ : detail::Fingerprintable(),
369
+ name_(std::move(name)),
370
+ type_(std::move(type)),
371
+ nullable_(nullable),
372
+ metadata_(std::move(metadata)) {}
373
+
374
+ ~Field() override;
375
+
376
+ /// \brief Return the field's attached metadata
377
+ std::shared_ptr<const KeyValueMetadata> metadata() const { return metadata_; }
378
+
379
+ /// \brief Return whether the field has non-empty metadata
380
+ bool HasMetadata() const;
381
+
382
+ /// \brief Return a copy of this field with the given metadata attached to it
383
+ std::shared_ptr<Field> WithMetadata(
384
+ const std::shared_ptr<const KeyValueMetadata>& metadata) const;
385
+
386
+ /// \brief EXPERIMENTAL: Return a copy of this field with the given metadata
387
+ /// merged with existing metadata (any colliding keys will be overridden by
388
+ /// the passed metadata)
389
+ std::shared_ptr<Field> WithMergedMetadata(
390
+ const std::shared_ptr<const KeyValueMetadata>& metadata) const;
391
+
392
+ /// \brief Return a copy of this field without any metadata attached to it
393
+ std::shared_ptr<Field> RemoveMetadata() const;
394
+
395
+ /// \brief Return a copy of this field with the replaced type.
396
+ std::shared_ptr<Field> WithType(const std::shared_ptr<DataType>& type) const;
397
+
398
+ /// \brief Return a copy of this field with the replaced name.
399
+ std::shared_ptr<Field> WithName(const std::string& name) const;
400
+
401
+ /// \brief Return a copy of this field with the replaced nullability.
402
+ std::shared_ptr<Field> WithNullable(bool nullable) const;
403
+
404
+ /// \brief Options that control the behavior of `MergeWith`.
405
+ /// Options are to be added to allow type conversions, including integer
406
+ /// widening, promotion from integer to float, or conversion to or from boolean.
407
+ struct ARROW_EXPORT MergeOptions : public util::ToStringOstreamable<MergeOptions> {
408
+ /// If true, a Field of NullType can be unified with a Field of another type.
409
+ /// The unified field will be of the other type and become nullable.
410
+ /// Nullability will be promoted to the looser option (nullable if one is not
411
+ /// nullable).
412
+ bool promote_nullability = true;
413
+
414
+ /// Allow a decimal to be unified with another decimal of the same
415
+ /// width, adjusting scale and precision as appropriate. May fail
416
+ /// if the adjustment is not possible.
417
+ bool promote_decimal = false;
418
+
419
+ /// Allow a decimal to be promoted to a float. The float type will
420
+ /// not itself be promoted (e.g. Decimal128 + Float32 = Float32).
421
+ bool promote_decimal_to_float = false;
422
+
423
+ /// Allow an integer to be promoted to a decimal.
424
+ ///
425
+ /// May fail if the decimal has insufficient precision to
426
+ /// accommodate the integer (see promote_numeric_width).
427
+ bool promote_integer_to_decimal = false;
428
+
429
+ /// Allow an integer of a given bit width to be promoted to a
430
+ /// float; the result will be a float of an equal or greater bit
431
+ /// width to both of the inputs. Examples:
432
+ /// - int8 + float32 = float32
433
+ /// - int32 + float32 = float64
434
+ /// - int32 + float64 = float64
435
+ /// Because an int32 cannot always be represented exactly in the
436
+ /// 24 bits of a float32 mantissa.
437
+ bool promote_integer_to_float = false;
438
+
439
+ /// Allow an unsigned integer of a given bit width to be promoted
440
+ /// to a signed integer that fits into the signed type:
441
+ /// uint + int16 = int16
442
+ /// When widening is needed, set promote_numeric_width to true:
443
+ /// uint16 + int16 = int32
444
+ bool promote_integer_sign = false;
445
+
446
+ /// Allow an integer, float, or decimal of a given bit width to be
447
+ /// promoted to an equivalent type of a greater bit width.
448
+ bool promote_numeric_width = false;
449
+
450
+ /// Allow strings to be promoted to binary types. Promotion of fixed size
451
+ /// binary types to variable sized formats, and binary to large binary,
452
+ /// and string to large string.
453
+ bool promote_binary = false;
454
+
455
+ /// Second to millisecond, Time32 to Time64, Time32(SECOND) to Time32(MILLI), etc
456
+ bool promote_temporal_unit = false;
457
+
458
+ /// Allow promotion from a list to a large-list and from a fixed-size list to a
459
+ /// variable sized list
460
+ bool promote_list = false;
461
+
462
+ /// Unify dictionary index types and dictionary value types.
463
+ bool promote_dictionary = false;
464
+
465
+ /// Allow merging ordered and non-ordered dictionaries.
466
+ /// The result will be ordered if and only if both inputs
467
+ /// are ordered.
468
+ bool promote_dictionary_ordered = false;
469
+
470
+ /// Get default options. Only NullType will be merged with other types.
471
+ static MergeOptions Defaults() { return MergeOptions(); }
472
+ /// Get permissive options. All options are enabled, except
473
+ /// promote_dictionary_ordered.
474
+ static MergeOptions Permissive();
475
+ /// Get a human-readable representation of the options.
476
+ std::string ToString() const;
477
+ };
478
+
479
+ /// \brief Merge the current field with a field of the same name.
480
+ ///
481
+ /// The two fields must be compatible, i.e:
482
+ /// - have the same name
483
+ /// - have the same type, or of compatible types according to `options`.
484
+ ///
485
+ /// The metadata of the current field is preserved; the metadata of the other
486
+ /// field is discarded.
487
+ Result<std::shared_ptr<Field>> MergeWith(
488
+ const Field& other, MergeOptions options = MergeOptions::Defaults()) const;
489
+ Result<std::shared_ptr<Field>> MergeWith(
490
+ const std::shared_ptr<Field>& other,
491
+ MergeOptions options = MergeOptions::Defaults()) const;
492
+
493
+ FieldVector Flatten() const;
494
+
495
+ /// \brief Indicate if fields are equals.
496
+ ///
497
+ /// \param[in] other field to check equality with.
498
+ /// \param[in] check_metadata controls if it should check for metadata
499
+ /// equality.
500
+ ///
501
+ /// \return true if fields are equal, false otherwise.
502
+ bool Equals(const Field& other, bool check_metadata = false) const;
503
+ bool Equals(const std::shared_ptr<Field>& other, bool check_metadata = false) const;
504
+
505
+ /// \brief Indicate if fields are compatibles.
506
+ ///
507
+ /// See the criteria of MergeWith.
508
+ ///
509
+ /// \return true if fields are compatible, false otherwise.
510
+ bool IsCompatibleWith(const Field& other) const;
511
+ bool IsCompatibleWith(const std::shared_ptr<Field>& other) const;
512
+
513
+ /// \brief Return a string representation ot the field
514
+ /// \param[in] show_metadata when true, if KeyValueMetadata is non-empty,
515
+ /// print keys and values in the output
516
+ std::string ToString(bool show_metadata = false) const;
517
+
518
+ /// \brief Return the field name
519
+ const std::string& name() const { return name_; }
520
+ /// \brief Return the field data type
521
+ const std::shared_ptr<DataType>& type() const { return type_; }
522
+ /// \brief Return whether the field is nullable
523
+ bool nullable() const { return nullable_; }
524
+
525
+ std::shared_ptr<Field> Copy() const;
526
+
527
+ private:
528
+ std::string ComputeFingerprint() const override;
529
+ std::string ComputeMetadataFingerprint() const override;
530
+
531
+ // Field name
532
+ std::string name_;
533
+
534
+ // The field's data type
535
+ std::shared_ptr<DataType> type_;
536
+
537
+ // Fields can be nullable
538
+ bool nullable_;
539
+
540
+ // The field's metadata, if any
541
+ std::shared_ptr<const KeyValueMetadata> metadata_;
542
+
543
+ ARROW_DISALLOW_COPY_AND_ASSIGN(Field);
544
+ };
545
+
546
+ ARROW_EXPORT void PrintTo(const Field& field, std::ostream* os);
547
+
548
+ namespace detail {
549
+
550
+ template <typename DERIVED, typename BASE, Type::type TYPE_ID, typename C_TYPE>
551
+ class ARROW_EXPORT CTypeImpl : public BASE {
552
+ public:
553
+ static constexpr Type::type type_id = TYPE_ID;
554
+ using c_type = C_TYPE;
555
+ using PhysicalType = DERIVED;
556
+
557
+ CTypeImpl() : BASE(TYPE_ID) {}
558
+
559
+ int bit_width() const override { return static_cast<int>(sizeof(C_TYPE) * CHAR_BIT); }
560
+
561
+ DataTypeLayout layout() const override {
562
+ return DataTypeLayout(
563
+ {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(C_TYPE))});
564
+ }
565
+
566
+ std::string name() const override { return DERIVED::type_name(); }
567
+
568
+ std::string ToString(bool show_metadata = false) const override { return this->name(); }
569
+ };
570
+
571
+ template <typename DERIVED, typename BASE, Type::type TYPE_ID, typename C_TYPE>
572
+ constexpr Type::type CTypeImpl<DERIVED, BASE, TYPE_ID, C_TYPE>::type_id;
573
+
574
+ template <typename DERIVED, Type::type TYPE_ID, typename C_TYPE>
575
+ class IntegerTypeImpl : public detail::CTypeImpl<DERIVED, IntegerType, TYPE_ID, C_TYPE> {
576
+ bool is_signed() const override { return std::is_signed<C_TYPE>::value; }
577
+ };
578
+
579
+ } // namespace detail
580
+
581
+ /// Concrete type class for always-null data
582
+ class ARROW_EXPORT NullType : public DataType {
583
+ public:
584
+ static constexpr Type::type type_id = Type::NA;
585
+
586
+ static constexpr const char* type_name() { return "null"; }
587
+
588
+ NullType() : DataType(Type::NA) {}
589
+
590
+ std::string ToString(bool show_metadata = false) const override;
591
+
592
+ DataTypeLayout layout() const override {
593
+ return DataTypeLayout({DataTypeLayout::AlwaysNull()});
594
+ }
595
+
596
+ std::string name() const override { return "null"; }
597
+
598
+ protected:
599
+ std::string ComputeFingerprint() const override;
600
+ };
601
+
602
+ /// Concrete type class for boolean data
603
+ class ARROW_EXPORT BooleanType
604
+ : public detail::CTypeImpl<BooleanType, PrimitiveCType, Type::BOOL, bool> {
605
+ public:
606
+ static constexpr const char* type_name() { return "bool"; }
607
+
608
+ // BooleanType within arrow use a single bit instead of the C 8-bits layout.
609
+ int bit_width() const final { return 1; }
610
+
611
+ DataTypeLayout layout() const override {
612
+ return DataTypeLayout({DataTypeLayout::Bitmap(), DataTypeLayout::Bitmap()});
613
+ }
614
+
615
+ protected:
616
+ std::string ComputeFingerprint() const override;
617
+ };
618
+
619
+ /// \addtogroup numeric-datatypes
620
+ ///
621
+ /// @{
622
+
623
+ /// Concrete type class for unsigned 8-bit integer data
624
+ class ARROW_EXPORT UInt8Type
625
+ : public detail::IntegerTypeImpl<UInt8Type, Type::UINT8, uint8_t> {
626
+ public:
627
+ static constexpr const char* type_name() { return "uint8"; }
628
+
629
+ protected:
630
+ std::string ComputeFingerprint() const override;
631
+ };
632
+
633
+ /// Concrete type class for signed 8-bit integer data
634
+ class ARROW_EXPORT Int8Type
635
+ : public detail::IntegerTypeImpl<Int8Type, Type::INT8, int8_t> {
636
+ public:
637
+ static constexpr const char* type_name() { return "int8"; }
638
+
639
+ protected:
640
+ std::string ComputeFingerprint() const override;
641
+ };
642
+
643
+ /// Concrete type class for unsigned 16-bit integer data
644
+ class ARROW_EXPORT UInt16Type
645
+ : public detail::IntegerTypeImpl<UInt16Type, Type::UINT16, uint16_t> {
646
+ public:
647
+ static constexpr const char* type_name() { return "uint16"; }
648
+
649
+ protected:
650
+ std::string ComputeFingerprint() const override;
651
+ };
652
+
653
+ /// Concrete type class for signed 16-bit integer data
654
+ class ARROW_EXPORT Int16Type
655
+ : public detail::IntegerTypeImpl<Int16Type, Type::INT16, int16_t> {
656
+ public:
657
+ static constexpr const char* type_name() { return "int16"; }
658
+
659
+ protected:
660
+ std::string ComputeFingerprint() const override;
661
+ };
662
+
663
+ /// Concrete type class for unsigned 32-bit integer data
664
+ class ARROW_EXPORT UInt32Type
665
+ : public detail::IntegerTypeImpl<UInt32Type, Type::UINT32, uint32_t> {
666
+ public:
667
+ static constexpr const char* type_name() { return "uint32"; }
668
+
669
+ protected:
670
+ std::string ComputeFingerprint() const override;
671
+ };
672
+
673
+ /// Concrete type class for signed 32-bit integer data
674
+ class ARROW_EXPORT Int32Type
675
+ : public detail::IntegerTypeImpl<Int32Type, Type::INT32, int32_t> {
676
+ public:
677
+ static constexpr const char* type_name() { return "int32"; }
678
+
679
+ protected:
680
+ std::string ComputeFingerprint() const override;
681
+ };
682
+
683
+ /// Concrete type class for unsigned 64-bit integer data
684
+ class ARROW_EXPORT UInt64Type
685
+ : public detail::IntegerTypeImpl<UInt64Type, Type::UINT64, uint64_t> {
686
+ public:
687
+ static constexpr const char* type_name() { return "uint64"; }
688
+
689
+ protected:
690
+ std::string ComputeFingerprint() const override;
691
+ };
692
+
693
+ /// Concrete type class for signed 64-bit integer data
694
+ class ARROW_EXPORT Int64Type
695
+ : public detail::IntegerTypeImpl<Int64Type, Type::INT64, int64_t> {
696
+ public:
697
+ static constexpr const char* type_name() { return "int64"; }
698
+
699
+ protected:
700
+ std::string ComputeFingerprint() const override;
701
+ };
702
+
703
+ /// Concrete type class for 16-bit floating-point data
704
+ class ARROW_EXPORT HalfFloatType
705
+ : public detail::CTypeImpl<HalfFloatType, FloatingPointType, Type::HALF_FLOAT,
706
+ uint16_t> {
707
+ public:
708
+ Precision precision() const override;
709
+ static constexpr const char* type_name() { return "halffloat"; }
710
+
711
+ protected:
712
+ std::string ComputeFingerprint() const override;
713
+ };
714
+
715
+ /// Concrete type class for 32-bit floating-point data (C "float")
716
+ class ARROW_EXPORT FloatType
717
+ : public detail::CTypeImpl<FloatType, FloatingPointType, Type::FLOAT, float> {
718
+ public:
719
+ Precision precision() const override;
720
+ static constexpr const char* type_name() { return "float"; }
721
+
722
+ protected:
723
+ std::string ComputeFingerprint() const override;
724
+ };
725
+
726
+ /// Concrete type class for 64-bit floating-point data (C "double")
727
+ class ARROW_EXPORT DoubleType
728
+ : public detail::CTypeImpl<DoubleType, FloatingPointType, Type::DOUBLE, double> {
729
+ public:
730
+ Precision precision() const override;
731
+ static constexpr const char* type_name() { return "double"; }
732
+
733
+ protected:
734
+ std::string ComputeFingerprint() const override;
735
+ };
736
+
737
+ /// @}
738
+
739
+ /// \brief Base class for all variable-size binary data types
740
+ class ARROW_EXPORT BaseBinaryType : public DataType {
741
+ public:
742
+ using DataType::DataType;
743
+ // This is only for preventing defining this class in each
744
+ // translation unit to avoid one-definition-rule violation.
745
+ ~BaseBinaryType() override;
746
+ };
747
+
748
+ constexpr int64_t kBinaryMemoryLimit = std::numeric_limits<int32_t>::max() - 1;
749
+
750
+ /// \addtogroup binary-datatypes
751
+ ///
752
+ /// @{
753
+
754
+ /// \brief Concrete type class for variable-size binary data
755
+ class ARROW_EXPORT BinaryType : public BaseBinaryType {
756
+ public:
757
+ static constexpr Type::type type_id = Type::BINARY;
758
+ static constexpr bool is_utf8 = false;
759
+ using offset_type = int32_t;
760
+ using PhysicalType = BinaryType;
761
+
762
+ static constexpr const char* type_name() { return "binary"; }
763
+
764
+ BinaryType() : BinaryType(Type::BINARY) {}
765
+
766
+ DataTypeLayout layout() const override {
767
+ return DataTypeLayout({DataTypeLayout::Bitmap(),
768
+ DataTypeLayout::FixedWidth(sizeof(offset_type)),
769
+ DataTypeLayout::VariableWidth()});
770
+ }
771
+
772
+ std::string ToString(bool show_metadata = false) const override;
773
+ std::string name() const override { return "binary"; }
774
+
775
+ protected:
776
+ std::string ComputeFingerprint() const override;
777
+
778
+ // Allow subclasses like StringType to change the logical type.
779
+ explicit BinaryType(Type::type logical_type) : BaseBinaryType(logical_type) {}
780
+ };
781
+
782
+ /// \brief Concrete type class for variable-size binary view data
783
+ class ARROW_EXPORT BinaryViewType : public DataType {
784
+ public:
785
+ static constexpr Type::type type_id = Type::BINARY_VIEW;
786
+ static constexpr bool is_utf8 = false;
787
+ using PhysicalType = BinaryViewType;
788
+
789
+ static constexpr int kSize = 16;
790
+ static constexpr int kInlineSize = 12;
791
+ static constexpr int kPrefixSize = 4;
792
+
793
+ /// Variable length string or binary with inline optimization for small values (12 bytes
794
+ /// or fewer). This is similar to std::string_view except limited in size to INT32_MAX
795
+ /// and at least the first four bytes of the string are copied inline (accessible
796
+ /// without pointer dereference). This inline prefix allows failing comparisons early.
797
+ /// Furthermore when dealing with short strings the CPU cache working set is reduced
798
+ /// since many can be inline.
799
+ ///
800
+ /// This union supports two states:
801
+ ///
802
+ /// - Entirely inlined string data
803
+ /// |----|--------------|
804
+ /// ^ ^
805
+ /// | |
806
+ /// size in-line string data, zero padded
807
+ ///
808
+ /// - Reference into a buffer
809
+ /// |----|----|----|----|
810
+ /// ^ ^ ^ ^
811
+ /// | | | |
812
+ /// size | | `------.
813
+ /// prefix | |
814
+ /// buffer index |
815
+ /// offset in buffer
816
+ ///
817
+ /// Adapted from TU Munich's UmbraDB [1], Velox, DuckDB.
818
+ ///
819
+ /// [1]: https://db.in.tum.de/~freitag/papers/p29-neumann-cidr20.pdf
820
+ ///
821
+ /// Alignment to 64 bits enables an aligned load of the size and prefix into
822
+ /// a single 64 bit integer, which is useful to the comparison fast path.
823
+ union alignas(int64_t) c_type {
824
+ struct {
825
+ int32_t size;
826
+ std::array<uint8_t, kInlineSize> data;
827
+ } inlined;
828
+
829
+ struct {
830
+ int32_t size;
831
+ std::array<uint8_t, kPrefixSize> prefix;
832
+ int32_t buffer_index;
833
+ int32_t offset;
834
+ } ref;
835
+
836
+ /// The number of bytes viewed.
837
+ int32_t size() const {
838
+ // Size is in the common initial subsequence of each member of the union,
839
+ // so accessing `inlined.size` is legal even if another member is active.
840
+ return inlined.size;
841
+ }
842
+
843
+ /// True if the view's data is entirely stored inline.
844
+ bool is_inline() const { return size() <= kInlineSize; }
845
+
846
+ /// Return a pointer to the inline data of a view.
847
+ ///
848
+ /// For inline views, this points to the entire data of the view.
849
+ /// For other views, this points to the 4 byte prefix.
850
+ const uint8_t* inline_data() const& {
851
+ // Since `ref.prefix` has the same address as `inlined.data`,
852
+ // the branch will be trivially optimized out.
853
+ return is_inline() ? inlined.data.data() : ref.prefix.data();
854
+ }
855
+ const uint8_t* inline_data() && = delete;
856
+ };
857
+ static_assert(sizeof(c_type) == kSize);
858
+ static_assert(std::is_trivial_v<c_type>);
859
+
860
+ static constexpr const char* type_name() { return "binary_view"; }
861
+
862
+ BinaryViewType() : BinaryViewType(Type::BINARY_VIEW) {}
863
+
864
+ DataTypeLayout layout() const override {
865
+ return DataTypeLayout({DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(kSize)},
866
+ DataTypeLayout::VariableWidth());
867
+ }
868
+
869
+ std::string ToString(bool show_metadata = false) const override;
870
+ std::string name() const override { return "binary_view"; }
871
+
872
+ protected:
873
+ std::string ComputeFingerprint() const override;
874
+
875
+ // Allow subclasses like StringType to change the logical type.
876
+ explicit BinaryViewType(Type::type logical_type) : DataType(logical_type) {}
877
+ };
878
+
879
+ /// \brief Concrete type class for large variable-size binary data
880
+ class ARROW_EXPORT LargeBinaryType : public BaseBinaryType {
881
+ public:
882
+ static constexpr Type::type type_id = Type::LARGE_BINARY;
883
+ static constexpr bool is_utf8 = false;
884
+ using offset_type = int64_t;
885
+ using PhysicalType = LargeBinaryType;
886
+
887
+ static constexpr const char* type_name() { return "large_binary"; }
888
+
889
+ LargeBinaryType() : LargeBinaryType(Type::LARGE_BINARY) {}
890
+
891
+ DataTypeLayout layout() const override {
892
+ return DataTypeLayout({DataTypeLayout::Bitmap(),
893
+ DataTypeLayout::FixedWidth(sizeof(offset_type)),
894
+ DataTypeLayout::VariableWidth()});
895
+ }
896
+
897
+ std::string ToString(bool show_metadata = false) const override;
898
+ std::string name() const override { return "large_binary"; }
899
+
900
+ protected:
901
+ std::string ComputeFingerprint() const override;
902
+
903
+ // Allow subclasses like LargeStringType to change the logical type.
904
+ explicit LargeBinaryType(Type::type logical_type) : BaseBinaryType(logical_type) {}
905
+ };
906
+
907
+ /// \brief Concrete type class for variable-size string data, utf8-encoded
908
+ class ARROW_EXPORT StringType : public BinaryType {
909
+ public:
910
+ static constexpr Type::type type_id = Type::STRING;
911
+ static constexpr bool is_utf8 = true;
912
+ using PhysicalType = BinaryType;
913
+
914
+ static constexpr const char* type_name() { return "utf8"; }
915
+
916
+ StringType() : BinaryType(Type::STRING) {}
917
+
918
+ std::string ToString(bool show_metadata = false) const override;
919
+ std::string name() const override { return "utf8"; }
920
+
921
+ protected:
922
+ std::string ComputeFingerprint() const override;
923
+ };
924
+
925
+ /// \brief Concrete type class for variable-size string data, utf8-encoded
926
+ class ARROW_EXPORT StringViewType : public BinaryViewType {
927
+ public:
928
+ static constexpr Type::type type_id = Type::STRING_VIEW;
929
+ static constexpr bool is_utf8 = true;
930
+ using PhysicalType = BinaryViewType;
931
+
932
+ static constexpr const char* type_name() { return "utf8_view"; }
933
+
934
+ StringViewType() : BinaryViewType(Type::STRING_VIEW) {}
935
+
936
+ std::string ToString(bool show_metadata = false) const override;
937
+ std::string name() const override { return "utf8_view"; }
938
+
939
+ protected:
940
+ std::string ComputeFingerprint() const override;
941
+ };
942
+
943
+ /// \brief Concrete type class for large variable-size string data, utf8-encoded
944
+ class ARROW_EXPORT LargeStringType : public LargeBinaryType {
945
+ public:
946
+ static constexpr Type::type type_id = Type::LARGE_STRING;
947
+ static constexpr bool is_utf8 = true;
948
+ using PhysicalType = LargeBinaryType;
949
+
950
+ static constexpr const char* type_name() { return "large_utf8"; }
951
+
952
+ LargeStringType() : LargeBinaryType(Type::LARGE_STRING) {}
953
+
954
+ std::string ToString(bool show_metadata = false) const override;
955
+ std::string name() const override { return "large_utf8"; }
956
+
957
+ protected:
958
+ std::string ComputeFingerprint() const override;
959
+ };
960
+
961
+ /// \brief Concrete type class for fixed-size binary data
962
+ class ARROW_EXPORT FixedSizeBinaryType : public FixedWidthType, public ParametricType {
963
+ public:
964
+ static constexpr Type::type type_id = Type::FIXED_SIZE_BINARY;
965
+ static constexpr bool is_utf8 = false;
966
+
967
+ static constexpr const char* type_name() { return "fixed_size_binary"; }
968
+
969
+ explicit FixedSizeBinaryType(int32_t byte_width)
970
+ : FixedWidthType(Type::FIXED_SIZE_BINARY), byte_width_(byte_width) {}
971
+ explicit FixedSizeBinaryType(int32_t byte_width, Type::type override_type_id)
972
+ : FixedWidthType(override_type_id), byte_width_(byte_width) {}
973
+
974
+ std::string ToString(bool show_metadata = false) const override;
975
+ std::string name() const override { return "fixed_size_binary"; }
976
+
977
+ DataTypeLayout layout() const override {
978
+ return DataTypeLayout(
979
+ {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(byte_width())});
980
+ }
981
+
982
+ int byte_width() const override { return byte_width_; }
983
+
984
+ int bit_width() const override;
985
+
986
+ // Validating constructor
987
+ static Result<std::shared_ptr<DataType>> Make(int32_t byte_width);
988
+
989
+ protected:
990
+ std::string ComputeFingerprint() const override;
991
+
992
+ int32_t byte_width_;
993
+ };
994
+
995
+ /// @}
996
+
997
+ /// \addtogroup numeric-datatypes
998
+ ///
999
+ /// @{
1000
+
1001
+ /// \brief Base type class for (fixed-size) decimal data
1002
+ class ARROW_EXPORT DecimalType : public FixedSizeBinaryType {
1003
+ public:
1004
+ explicit DecimalType(Type::type type_id, int32_t byte_width, int32_t precision,
1005
+ int32_t scale)
1006
+ : FixedSizeBinaryType(byte_width, type_id), precision_(precision), scale_(scale) {}
1007
+
1008
+ /// Constructs concrete decimal types
1009
+ static Result<std::shared_ptr<DataType>> Make(Type::type type_id, int32_t precision,
1010
+ int32_t scale);
1011
+
1012
+ int32_t precision() const { return precision_; }
1013
+ int32_t scale() const { return scale_; }
1014
+
1015
+ /// \brief Returns the number of bytes needed for precision.
1016
+ ///
1017
+ /// precision must be >= 1
1018
+ static int32_t DecimalSize(int32_t precision);
1019
+
1020
+ protected:
1021
+ std::string ComputeFingerprint() const override;
1022
+
1023
+ int32_t precision_;
1024
+ int32_t scale_;
1025
+ };
1026
+
1027
+ /// \brief Concrete type class for 32-bit decimal data
1028
+ ///
1029
+ /// Arrow decimals are fixed-point decimal numbers encoded as a scaled
1030
+ /// integer. The precision is the number of significant digits that the
1031
+ /// decimal type can represent; the scale is the number of digits after
1032
+ /// the decimal point (note the scale can be negative).
1033
+ ///
1034
+ /// As an example, `Decimal32Type(7, 3)` can exactly represent the numbers
1035
+ /// 1234.567 and -1234.567 (encoded internally as the 32-bit integers
1036
+ /// 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567.
1037
+ ///
1038
+ /// Decimal32Type has a maximum precision of 9 significant digits
1039
+ /// (also available as Decimal32Type::kMaxPrecision).
1040
+ /// If higher precision is needed, consider using Decimal64Type,
1041
+ /// Decimal128Type or Decimal256Type.
1042
+ class ARROW_EXPORT Decimal32Type : public DecimalType {
1043
+ public:
1044
+ static constexpr Type::type type_id = Type::DECIMAL32;
1045
+
1046
+ static constexpr const char* type_name() { return "decimal32"; }
1047
+
1048
+ /// Decimal32Type constructor that aborts on invalid input.
1049
+ explicit Decimal32Type(int32_t precision, int32_t scale);
1050
+
1051
+ /// Decimal32Type constructor that returns an error on invalid input
1052
+ static Result<std::shared_ptr<DataType>> Make(int32_t precision, int32_t scale);
1053
+
1054
+ std::string ToString(bool show_metadata = false) const override;
1055
+ std::string name() const override { return "decimal32"; }
1056
+
1057
+ static constexpr int32_t kMinPrecision = 1;
1058
+ static constexpr int32_t kMaxPrecision = 9;
1059
+ static constexpr int32_t kByteWidth = 4;
1060
+ };
1061
+
1062
+ /// \brief Concrete type class for 64-bit decimal data
1063
+ ///
1064
+ /// Arrow decimals are fixed-point decimal numbers encoded as a scaled
1065
+ /// integer. The precision is the number of significant digits that the
1066
+ /// decimal type can represent; the scale is the number of digits after
1067
+ /// the decimal point (note the scale can be negative).
1068
+ ///
1069
+ /// As an example, `Decimal64Type(7, 3)` can exactly represent the numbers
1070
+ /// 1234.567 and -1234.567 (encoded internally as the 64-bit integers
1071
+ /// 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567.
1072
+ ///
1073
+ /// Decimal64Type has a maximum precision of 18 significant digits
1074
+ /// (also available as Decimal64Type::kMaxPrecision).
1075
+ /// If higher precision is needed, consider using Decimal128Type or
1076
+ /// Decimal256Type.
1077
+ class ARROW_EXPORT Decimal64Type : public DecimalType {
1078
+ public:
1079
+ static constexpr Type::type type_id = Type::DECIMAL64;
1080
+
1081
+ static constexpr const char* type_name() { return "decimal64"; }
1082
+
1083
+ /// Decimal32Type constructor that aborts on invalid input.
1084
+ explicit Decimal64Type(int32_t precision, int32_t scale);
1085
+
1086
+ /// Decimal32Type constructor that returns an error on invalid input
1087
+ static Result<std::shared_ptr<DataType>> Make(int32_t precision, int32_t scale);
1088
+
1089
+ std::string ToString(bool show_metadata = false) const override;
1090
+ std::string name() const override { return "decimal64"; }
1091
+
1092
+ static constexpr int32_t kMinPrecision = 1;
1093
+ static constexpr int32_t kMaxPrecision = 18;
1094
+ static constexpr int32_t kByteWidth = 8;
1095
+ };
1096
+
1097
+ /// \brief Concrete type class for 128-bit decimal data
1098
+ ///
1099
+ /// Arrow decimals are fixed-point decimal numbers encoded as a scaled
1100
+ /// integer. The precision is the number of significant digits that the
1101
+ /// decimal type can represent; the scale is the number of digits after
1102
+ /// the decimal point (note the scale can be negative).
1103
+ ///
1104
+ /// As an example, `Decimal128Type(7, 3)` can exactly represent the numbers
1105
+ /// 1234.567 and -1234.567 (encoded internally as the 128-bit integers
1106
+ /// 1234567 and -1234567, respectively), but neither 12345.67 nor 123.4567.
1107
+ ///
1108
+ /// Decimal128Type has a maximum precision of 38 significant digits
1109
+ /// (also available as Decimal128Type::kMaxPrecision).
1110
+ /// If higher precision is needed, consider using Decimal256Type.
1111
+ class ARROW_EXPORT Decimal128Type : public DecimalType {
1112
+ public:
1113
+ static constexpr Type::type type_id = Type::DECIMAL128;
1114
+
1115
+ static constexpr const char* type_name() { return "decimal128"; }
1116
+
1117
+ /// Decimal128Type constructor that aborts on invalid input.
1118
+ explicit Decimal128Type(int32_t precision, int32_t scale);
1119
+
1120
+ /// Decimal128Type constructor that returns an error on invalid input.
1121
+ static Result<std::shared_ptr<DataType>> Make(int32_t precision, int32_t scale);
1122
+
1123
+ std::string ToString(bool show_metadata = false) const override;
1124
+ std::string name() const override { return "decimal128"; }
1125
+
1126
+ static constexpr int32_t kMinPrecision = 1;
1127
+ static constexpr int32_t kMaxPrecision = 38;
1128
+ static constexpr int32_t kByteWidth = 16;
1129
+ };
1130
+
1131
+ /// \brief Concrete type class for 256-bit decimal data
1132
+ ///
1133
+ /// Arrow decimals are fixed-point decimal numbers encoded as a scaled
1134
+ /// integer. The precision is the number of significant digits that the
1135
+ /// decimal type can represent; the scale is the number of digits after
1136
+ /// the decimal point (note the scale can be negative).
1137
+ ///
1138
+ /// Decimal256Type has a maximum precision of 76 significant digits.
1139
+ /// (also available as Decimal256Type::kMaxPrecision).
1140
+ ///
1141
+ /// For most use cases, the maximum precision offered by Decimal128Type
1142
+ /// is sufficient, and it will result in a more compact and more efficient
1143
+ /// encoding.
1144
+ class ARROW_EXPORT Decimal256Type : public DecimalType {
1145
+ public:
1146
+ static constexpr Type::type type_id = Type::DECIMAL256;
1147
+
1148
+ static constexpr const char* type_name() { return "decimal256"; }
1149
+
1150
+ /// Decimal256Type constructor that aborts on invalid input.
1151
+ explicit Decimal256Type(int32_t precision, int32_t scale);
1152
+
1153
+ /// Decimal256Type constructor that returns an error on invalid input.
1154
+ static Result<std::shared_ptr<DataType>> Make(int32_t precision, int32_t scale);
1155
+
1156
+ std::string ToString(bool show_metadata = false) const override;
1157
+ std::string name() const override { return "decimal256"; }
1158
+
1159
+ static constexpr int32_t kMinPrecision = 1;
1160
+ static constexpr int32_t kMaxPrecision = 76;
1161
+ static constexpr int32_t kByteWidth = 32;
1162
+ };
1163
+
1164
+ /// @}
1165
+
1166
+ /// \addtogroup nested-datatypes
1167
+ ///
1168
+ /// @{
1169
+
1170
+ /// \brief Base class for all variable-size list data types
1171
+ class ARROW_EXPORT BaseListType : public NestedType {
1172
+ public:
1173
+ using NestedType::NestedType;
1174
+ // This is only for preventing defining this class in each
1175
+ // translation unit to avoid one-definition-rule violation.
1176
+ ~BaseListType() override;
1177
+ const std::shared_ptr<Field>& value_field() const { return children_[0]; }
1178
+
1179
+ const std::shared_ptr<DataType>& value_type() const { return children_[0]->type(); }
1180
+ };
1181
+
1182
+ /// \brief Concrete type class for list data
1183
+ ///
1184
+ /// List data is nested data where each value is a variable number of
1185
+ /// child items. Lists can be recursively nested, for example
1186
+ /// list(list(int32)).
1187
+ class ARROW_EXPORT ListType : public BaseListType {
1188
+ public:
1189
+ static constexpr Type::type type_id = Type::LIST;
1190
+ using offset_type = int32_t;
1191
+
1192
+ static constexpr const char* type_name() { return "list"; }
1193
+
1194
+ // List can contain any other logical value type
1195
+ explicit ListType(std::shared_ptr<DataType> value_type)
1196
+ : ListType(std::make_shared<Field>("item", std::move(value_type))) {}
1197
+
1198
+ explicit ListType(std::shared_ptr<Field> value_field) : BaseListType(type_id) {
1199
+ children_ = {std::move(value_field)};
1200
+ }
1201
+
1202
+ DataTypeLayout layout() const override {
1203
+ return DataTypeLayout(
1204
+ {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(offset_type))});
1205
+ }
1206
+
1207
+ std::string ToString(bool show_metadata = false) const override;
1208
+
1209
+ std::string name() const override { return "list"; }
1210
+
1211
+ protected:
1212
+ std::string ComputeFingerprint() const override;
1213
+ };
1214
+
1215
+ /// \brief Concrete type class for large list data
1216
+ ///
1217
+ /// LargeListType is like ListType but with 64-bit rather than 32-bit offsets.
1218
+ class ARROW_EXPORT LargeListType : public BaseListType {
1219
+ public:
1220
+ static constexpr Type::type type_id = Type::LARGE_LIST;
1221
+ using offset_type = int64_t;
1222
+
1223
+ static constexpr const char* type_name() { return "large_list"; }
1224
+
1225
+ // List can contain any other logical value type
1226
+ explicit LargeListType(std::shared_ptr<DataType> value_type)
1227
+ : LargeListType(std::make_shared<Field>("item", std::move(value_type))) {}
1228
+
1229
+ explicit LargeListType(std::shared_ptr<Field> value_field) : BaseListType(type_id) {
1230
+ children_ = {std::move(value_field)};
1231
+ }
1232
+
1233
+ DataTypeLayout layout() const override {
1234
+ return DataTypeLayout(
1235
+ {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(sizeof(offset_type))});
1236
+ }
1237
+
1238
+ std::string ToString(bool show_metadata = false) const override;
1239
+
1240
+ std::string name() const override { return "large_list"; }
1241
+
1242
+ protected:
1243
+ std::string ComputeFingerprint() const override;
1244
+ };
1245
+
1246
+ /// \brief Type class for array of list views
1247
+ class ARROW_EXPORT ListViewType : public BaseListType {
1248
+ public:
1249
+ static constexpr Type::type type_id = Type::LIST_VIEW;
1250
+ using offset_type = int32_t;
1251
+
1252
+ static constexpr const char* type_name() { return "list_view"; }
1253
+
1254
+ // ListView can contain any other logical value type
1255
+ explicit ListViewType(const std::shared_ptr<DataType>& value_type)
1256
+ : ListViewType(std::make_shared<Field>("item", value_type)) {}
1257
+
1258
+ explicit ListViewType(const std::shared_ptr<Field>& value_field)
1259
+ : BaseListType(type_id) {
1260
+ children_ = {value_field};
1261
+ }
1262
+
1263
+ DataTypeLayout layout() const override {
1264
+ return DataTypeLayout({DataTypeLayout::Bitmap(),
1265
+ DataTypeLayout::FixedWidth(sizeof(offset_type)),
1266
+ DataTypeLayout::FixedWidth(sizeof(offset_type))});
1267
+ }
1268
+
1269
+ std::string ToString(bool show_metadata = false) const override;
1270
+
1271
+ std::string name() const override { return "list_view"; }
1272
+
1273
+ protected:
1274
+ std::string ComputeFingerprint() const override;
1275
+ };
1276
+
1277
+ /// \brief Concrete type class for large list-view data
1278
+ ///
1279
+ /// LargeListViewType is like ListViewType but with 64-bit rather than 32-bit offsets and
1280
+ /// sizes.
1281
+ class ARROW_EXPORT LargeListViewType : public BaseListType {
1282
+ public:
1283
+ static constexpr Type::type type_id = Type::LARGE_LIST_VIEW;
1284
+ using offset_type = int64_t;
1285
+
1286
+ static constexpr const char* type_name() { return "large_list_view"; }
1287
+
1288
+ // LargeListView can contain any other logical value type
1289
+ explicit LargeListViewType(const std::shared_ptr<DataType>& value_type)
1290
+ : LargeListViewType(std::make_shared<Field>("item", value_type)) {}
1291
+
1292
+ explicit LargeListViewType(const std::shared_ptr<Field>& value_field)
1293
+ : BaseListType(type_id) {
1294
+ children_ = {value_field};
1295
+ }
1296
+
1297
+ DataTypeLayout layout() const override {
1298
+ return DataTypeLayout({DataTypeLayout::Bitmap(),
1299
+ DataTypeLayout::FixedWidth(sizeof(offset_type)),
1300
+ DataTypeLayout::FixedWidth(sizeof(offset_type))});
1301
+ }
1302
+
1303
+ std::string ToString(bool show_metadata = false) const override;
1304
+
1305
+ std::string name() const override { return "large_list_view"; }
1306
+
1307
+ protected:
1308
+ std::string ComputeFingerprint() const override;
1309
+ };
1310
+
1311
+ /// \brief Concrete type class for map data
1312
+ ///
1313
+ /// Map data is nested data where each value is a variable number of
1314
+ /// key-item pairs. Its physical representation is the same as
1315
+ /// a list of `{key, item}` structs.
1316
+ ///
1317
+ /// Maps can be recursively nested, for example map(utf8, map(utf8, int32)).
1318
+ class ARROW_EXPORT MapType : public ListType {
1319
+ public:
1320
+ static constexpr Type::type type_id = Type::MAP;
1321
+
1322
+ static constexpr const char* type_name() { return "map"; }
1323
+
1324
+ MapType(std::shared_ptr<DataType> key_type, std::shared_ptr<DataType> item_type,
1325
+ bool keys_sorted = false);
1326
+
1327
+ MapType(std::shared_ptr<DataType> key_type, std::shared_ptr<Field> item_field,
1328
+ bool keys_sorted = false);
1329
+
1330
+ MapType(std::shared_ptr<Field> key_field, std::shared_ptr<Field> item_field,
1331
+ bool keys_sorted = false);
1332
+
1333
+ explicit MapType(std::shared_ptr<Field> value_field, bool keys_sorted = false);
1334
+
1335
+ // Validating constructor
1336
+ static Result<std::shared_ptr<DataType>> Make(std::shared_ptr<Field> value_field,
1337
+ bool keys_sorted = false);
1338
+
1339
+ std::shared_ptr<Field> key_field() const { return value_type()->field(0); }
1340
+ std::shared_ptr<DataType> key_type() const { return key_field()->type(); }
1341
+
1342
+ std::shared_ptr<Field> item_field() const { return value_type()->field(1); }
1343
+ std::shared_ptr<DataType> item_type() const { return item_field()->type(); }
1344
+
1345
+ std::string ToString(bool show_metadata = false) const override;
1346
+
1347
+ std::string name() const override { return "map"; }
1348
+
1349
+ bool keys_sorted() const { return keys_sorted_; }
1350
+
1351
+ private:
1352
+ std::string ComputeFingerprint() const override;
1353
+
1354
+ bool keys_sorted_;
1355
+ };
1356
+
1357
+ /// \brief Concrete type class for fixed size list data
1358
+ class ARROW_EXPORT FixedSizeListType : public BaseListType {
1359
+ public:
1360
+ static constexpr Type::type type_id = Type::FIXED_SIZE_LIST;
1361
+ // While the individual item size is 32-bit, the overall data size
1362
+ // (item size * list length) may not fit in a 32-bit int.
1363
+ using offset_type = int64_t;
1364
+
1365
+ static constexpr const char* type_name() { return "fixed_size_list"; }
1366
+
1367
+ // List can contain any other logical value type
1368
+ FixedSizeListType(std::shared_ptr<DataType> value_type, int32_t list_size)
1369
+ : FixedSizeListType(std::make_shared<Field>("item", std::move(value_type)),
1370
+ list_size) {}
1371
+
1372
+ FixedSizeListType(std::shared_ptr<Field> value_field, int32_t list_size)
1373
+ : BaseListType(type_id), list_size_(list_size) {
1374
+ children_ = {std::move(value_field)};
1375
+ }
1376
+
1377
+ DataTypeLayout layout() const override {
1378
+ return DataTypeLayout({DataTypeLayout::Bitmap()});
1379
+ }
1380
+
1381
+ std::string ToString(bool show_metadata = false) const override;
1382
+
1383
+ std::string name() const override { return "fixed_size_list"; }
1384
+
1385
+ int32_t list_size() const { return list_size_; }
1386
+
1387
+ protected:
1388
+ std::string ComputeFingerprint() const override;
1389
+
1390
+ int32_t list_size_;
1391
+ };
1392
+
1393
+ /// \brief Concrete type class for struct data
1394
+ class ARROW_EXPORT StructType : public NestedType {
1395
+ public:
1396
+ static constexpr Type::type type_id = Type::STRUCT;
1397
+
1398
+ static constexpr const char* type_name() { return "struct"; }
1399
+
1400
+ explicit StructType(const FieldVector& fields);
1401
+
1402
+ ~StructType() override;
1403
+
1404
+ DataTypeLayout layout() const override {
1405
+ return DataTypeLayout({DataTypeLayout::Bitmap()});
1406
+ }
1407
+
1408
+ std::string ToString(bool show_metadata = false) const override;
1409
+ std::string name() const override { return "struct"; }
1410
+
1411
+ /// Returns null if name not found
1412
+ std::shared_ptr<Field> GetFieldByName(const std::string& name) const;
1413
+
1414
+ /// Return all fields having this name
1415
+ FieldVector GetAllFieldsByName(const std::string& name) const;
1416
+
1417
+ /// Returns -1 if name not found or if there are multiple fields having the
1418
+ /// same name
1419
+ int GetFieldIndex(const std::string& name) const;
1420
+
1421
+ /// \brief Return the indices of all fields having this name in sorted order
1422
+ std::vector<int> GetAllFieldIndices(const std::string& name) const;
1423
+
1424
+ /// \brief Create a new StructType with field added at given index
1425
+ Result<std::shared_ptr<StructType>> AddField(int i,
1426
+ const std::shared_ptr<Field>& field) const;
1427
+ /// \brief Create a new StructType by removing the field at given index
1428
+ Result<std::shared_ptr<StructType>> RemoveField(int i) const;
1429
+ /// \brief Create a new StructType by changing the field at given index
1430
+ Result<std::shared_ptr<StructType>> SetField(int i,
1431
+ const std::shared_ptr<Field>& field) const;
1432
+
1433
+ private:
1434
+ std::string ComputeFingerprint() const override;
1435
+
1436
+ class Impl;
1437
+ std::unique_ptr<Impl> impl_;
1438
+ };
1439
+
1440
+ /// \brief Base type class for union data
1441
+ class ARROW_EXPORT UnionType : public NestedType {
1442
+ public:
1443
+ static constexpr int8_t kMaxTypeCode = 127;
1444
+ static constexpr int kInvalidChildId = -1;
1445
+
1446
+ static Result<std::shared_ptr<DataType>> Make(
1447
+ const FieldVector& fields, const std::vector<int8_t>& type_codes,
1448
+ UnionMode::type mode = UnionMode::SPARSE) {
1449
+ if (mode == UnionMode::SPARSE) {
1450
+ return sparse_union(fields, type_codes);
1451
+ } else {
1452
+ return dense_union(fields, type_codes);
1453
+ }
1454
+ }
1455
+
1456
+ DataTypeLayout layout() const override;
1457
+
1458
+ std::string ToString(bool show_metadata = false) const override;
1459
+
1460
+ /// The array of logical type ids.
1461
+ ///
1462
+ /// For example, the first type in the union might be denoted by the id 5
1463
+ /// (instead of 0).
1464
+ const std::vector<int8_t>& type_codes() const { return type_codes_; }
1465
+
1466
+ /// An array mapping logical type ids to physical child ids.
1467
+ const std::vector<int>& child_ids() const { return child_ids_; }
1468
+
1469
+ uint8_t max_type_code() const;
1470
+
1471
+ UnionMode::type mode() const;
1472
+
1473
+ protected:
1474
+ UnionType(FieldVector fields, std::vector<int8_t> type_codes, Type::type id);
1475
+
1476
+ static Status ValidateParameters(const FieldVector& fields,
1477
+ const std::vector<int8_t>& type_codes,
1478
+ UnionMode::type mode);
1479
+
1480
+ private:
1481
+ std::string ComputeFingerprint() const override;
1482
+
1483
+ std::vector<int8_t> type_codes_;
1484
+ std::vector<int> child_ids_;
1485
+ };
1486
+
1487
+ /// \brief Concrete type class for sparse union data
1488
+ ///
1489
+ /// A sparse union is a nested type where each logical value is taken from
1490
+ /// a single child. A buffer of 8-bit type ids indicates which child
1491
+ /// a given logical value is to be taken from.
1492
+ ///
1493
+ /// In a sparse union, each child array should have the same length as the
1494
+ /// union array, regardless of the actual number of union values that
1495
+ /// refer to it.
1496
+ ///
1497
+ /// Note that, unlike most other types, unions don't have a top-level validity bitmap.
1498
+ class ARROW_EXPORT SparseUnionType : public UnionType {
1499
+ public:
1500
+ static constexpr Type::type type_id = Type::SPARSE_UNION;
1501
+
1502
+ static constexpr const char* type_name() { return "sparse_union"; }
1503
+
1504
+ SparseUnionType(FieldVector fields, std::vector<int8_t> type_codes);
1505
+
1506
+ // A constructor variant that validates input parameters
1507
+ static Result<std::shared_ptr<DataType>> Make(FieldVector fields,
1508
+ std::vector<int8_t> type_codes);
1509
+
1510
+ std::string name() const override { return "sparse_union"; }
1511
+ };
1512
+
1513
+ /// \brief Concrete type class for dense union data
1514
+ ///
1515
+ /// A dense union is a nested type where each logical value is taken from
1516
+ /// a single child, at a specific offset. A buffer of 8-bit type ids
1517
+ /// indicates which child a given logical value is to be taken from,
1518
+ /// and a buffer of 32-bit offsets indicates at which physical position
1519
+ /// in the given child array the logical value is to be taken from.
1520
+ ///
1521
+ /// Unlike a sparse union, a dense union allows encoding only the child array
1522
+ /// values which are actually referred to by the union array. This is
1523
+ /// counterbalanced by the additional footprint of the offsets buffer, and
1524
+ /// the additional indirection cost when looking up values.
1525
+ ///
1526
+ /// Note that, unlike most other types, unions don't have a top-level validity bitmap.
1527
+ class ARROW_EXPORT DenseUnionType : public UnionType {
1528
+ public:
1529
+ static constexpr Type::type type_id = Type::DENSE_UNION;
1530
+
1531
+ static constexpr const char* type_name() { return "dense_union"; }
1532
+
1533
+ DenseUnionType(FieldVector fields, std::vector<int8_t> type_codes);
1534
+
1535
+ // A constructor variant that validates input parameters
1536
+ static Result<std::shared_ptr<DataType>> Make(FieldVector fields,
1537
+ std::vector<int8_t> type_codes);
1538
+
1539
+ std::string name() const override { return "dense_union"; }
1540
+ };
1541
+
1542
+ /// \brief Type class for run-end encoded data
1543
+ class ARROW_EXPORT RunEndEncodedType : public NestedType {
1544
+ public:
1545
+ static constexpr Type::type type_id = Type::RUN_END_ENCODED;
1546
+
1547
+ static constexpr const char* type_name() { return "run_end_encoded"; }
1548
+
1549
+ explicit RunEndEncodedType(std::shared_ptr<DataType> run_end_type,
1550
+ std::shared_ptr<DataType> value_type);
1551
+ ~RunEndEncodedType() override;
1552
+
1553
+ DataTypeLayout layout() const override {
1554
+ // A lot of existing code expects at least one buffer
1555
+ return DataTypeLayout({DataTypeLayout::AlwaysNull()});
1556
+ }
1557
+
1558
+ const std::shared_ptr<DataType>& run_end_type() const { return fields()[0]->type(); }
1559
+ const std::shared_ptr<DataType>& value_type() const { return fields()[1]->type(); }
1560
+
1561
+ std::string ToString(bool show_metadata = false) const override;
1562
+
1563
+ std::string name() const override { return "run_end_encoded"; }
1564
+
1565
+ static bool RunEndTypeValid(const DataType& run_end_type);
1566
+
1567
+ private:
1568
+ std::string ComputeFingerprint() const override;
1569
+ };
1570
+
1571
+ /// @}
1572
+
1573
+ // ----------------------------------------------------------------------
1574
+ // Date and time types
1575
+
1576
+ /// \addtogroup temporal-datatypes
1577
+ ///
1578
+ /// @{
1579
+
1580
+ /// \brief Base type for all date and time types
1581
+ class ARROW_EXPORT TemporalType : public FixedWidthType {
1582
+ public:
1583
+ using FixedWidthType::FixedWidthType;
1584
+ // This is only for preventing defining this class in each
1585
+ // translation unit to avoid one-definition-rule violation.
1586
+ ~TemporalType() override;
1587
+
1588
+ DataTypeLayout layout() const override {
1589
+ return DataTypeLayout(
1590
+ {DataTypeLayout::Bitmap(), DataTypeLayout::FixedWidth(bit_width() / 8)});
1591
+ }
1592
+ };
1593
+
1594
+ /// \brief Base type class for date data
1595
+ class ARROW_EXPORT DateType : public TemporalType {
1596
+ public:
1597
+ virtual DateUnit unit() const = 0;
1598
+
1599
+ protected:
1600
+ explicit DateType(Type::type type_id);
1601
+ };
1602
+
1603
+ /// Concrete type class for 32-bit date data (as number of days since UNIX epoch)
1604
+ class ARROW_EXPORT Date32Type : public DateType {
1605
+ public:
1606
+ static constexpr Type::type type_id = Type::DATE32;
1607
+ static constexpr DateUnit UNIT = DateUnit::DAY;
1608
+ using c_type = int32_t;
1609
+ using PhysicalType = Int32Type;
1610
+
1611
+ static constexpr const char* type_name() { return "date32"; }
1612
+
1613
+ Date32Type();
1614
+
1615
+ int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
1616
+
1617
+ std::string ToString(bool show_metadata = false) const override;
1618
+
1619
+ std::string name() const override { return "date32"; }
1620
+ DateUnit unit() const override { return UNIT; }
1621
+
1622
+ protected:
1623
+ std::string ComputeFingerprint() const override;
1624
+ };
1625
+
1626
+ /// Concrete type class for 64-bit date data (as number of milliseconds since UNIX epoch)
1627
+ class ARROW_EXPORT Date64Type : public DateType {
1628
+ public:
1629
+ static constexpr Type::type type_id = Type::DATE64;
1630
+ static constexpr DateUnit UNIT = DateUnit::MILLI;
1631
+ using c_type = int64_t;
1632
+ using PhysicalType = Int64Type;
1633
+
1634
+ static constexpr const char* type_name() { return "date64"; }
1635
+
1636
+ Date64Type();
1637
+
1638
+ int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
1639
+
1640
+ std::string ToString(bool show_metadata = false) const override;
1641
+
1642
+ std::string name() const override { return "date64"; }
1643
+ DateUnit unit() const override { return UNIT; }
1644
+
1645
+ protected:
1646
+ std::string ComputeFingerprint() const override;
1647
+ };
1648
+
1649
+ ARROW_EXPORT
1650
+ std::ostream& operator<<(std::ostream& os, TimeUnit::type unit);
1651
+
1652
+ /// Base type class for time data
1653
+ class ARROW_EXPORT TimeType : public TemporalType, public ParametricType {
1654
+ public:
1655
+ TimeUnit::type unit() const { return unit_; }
1656
+
1657
+ protected:
1658
+ TimeType(Type::type type_id, TimeUnit::type unit);
1659
+ std::string ComputeFingerprint() const override;
1660
+
1661
+ TimeUnit::type unit_;
1662
+ };
1663
+
1664
+ /// Concrete type class for 32-bit time data (as number of seconds or milliseconds
1665
+ /// since midnight)
1666
+ class ARROW_EXPORT Time32Type : public TimeType {
1667
+ public:
1668
+ static constexpr Type::type type_id = Type::TIME32;
1669
+ using c_type = int32_t;
1670
+ using PhysicalType = Int32Type;
1671
+
1672
+ static constexpr const char* type_name() { return "time32"; }
1673
+
1674
+ int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
1675
+
1676
+ explicit Time32Type(TimeUnit::type unit = TimeUnit::MILLI);
1677
+
1678
+ std::string ToString(bool show_metadata = false) const override;
1679
+
1680
+ std::string name() const override { return "time32"; }
1681
+ };
1682
+
1683
+ /// Concrete type class for 64-bit time data (as number of microseconds or nanoseconds
1684
+ /// since midnight)
1685
+ class ARROW_EXPORT Time64Type : public TimeType {
1686
+ public:
1687
+ static constexpr Type::type type_id = Type::TIME64;
1688
+ using c_type = int64_t;
1689
+ using PhysicalType = Int64Type;
1690
+
1691
+ static constexpr const char* type_name() { return "time64"; }
1692
+
1693
+ int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
1694
+
1695
+ explicit Time64Type(TimeUnit::type unit = TimeUnit::NANO);
1696
+
1697
+ std::string ToString(bool show_metadata = false) const override;
1698
+
1699
+ std::string name() const override { return "time64"; }
1700
+ };
1701
+
1702
+ /// \brief Concrete type class for datetime data (as number of seconds, milliseconds,
1703
+ /// microseconds or nanoseconds since UNIX epoch)
1704
+ ///
1705
+ /// If supplied, the timezone string should take either the form (i) "Area/Location",
1706
+ /// with values drawn from the names in the IANA Time Zone Database (such as
1707
+ /// "Europe/Zurich"); or (ii) "(+|-)HH:MM" indicating an absolute offset from GMT
1708
+ /// (such as "-08:00"). To indicate a native UTC timestamp, one of the strings "UTC",
1709
+ /// "Etc/UTC" or "+00:00" should be used.
1710
+ ///
1711
+ /// If any non-empty string is supplied as the timezone for a TimestampType, then the
1712
+ /// Arrow field containing that timestamp type (and by extension the column associated
1713
+ /// with such a field) is considered "timezone-aware". The integer arrays that comprise
1714
+ /// a timezone-aware column must contain UTC normalized datetime values, regardless of
1715
+ /// the contents of their timezone string. More precisely, (i) the producer of a
1716
+ /// timezone-aware column must populate its constituent arrays with valid UTC values
1717
+ /// (performing offset conversions from non-UTC values if necessary); and (ii) the
1718
+ /// consumer of a timezone-aware column may assume that the column's values are directly
1719
+ /// comparable (that is, with no offset adjustment required) to the values of any other
1720
+ /// timezone-aware column or to any other valid UTC datetime value (provided all values
1721
+ /// are expressed in the same units).
1722
+ ///
1723
+ /// If a TimestampType is constructed without a timezone (or, equivalently, if the
1724
+ /// timezone supplied is an empty string) then the resulting Arrow field (column) is
1725
+ /// considered "timezone-naive". The producer of a timezone-naive column may populate
1726
+ /// its constituent integer arrays with datetime values from any timezone; the consumer
1727
+ /// of a timezone-naive column should make no assumptions about the interoperability or
1728
+ /// comparability of the values of such a column with those of any other timestamp
1729
+ /// column or datetime value.
1730
+ ///
1731
+ /// If a timezone-aware field contains a recognized timezone, its values may be
1732
+ /// localized to that locale upon display; the values of timezone-naive fields must
1733
+ /// always be displayed "as is", with no localization performed on them.
1734
+ class ARROW_EXPORT TimestampType : public TemporalType, public ParametricType {
1735
+ public:
1736
+ using Unit = TimeUnit;
1737
+
1738
+ static constexpr Type::type type_id = Type::TIMESTAMP;
1739
+ using c_type = int64_t;
1740
+ using PhysicalType = Int64Type;
1741
+
1742
+ static constexpr const char* type_name() { return "timestamp"; }
1743
+
1744
+ int bit_width() const override { return static_cast<int>(sizeof(int64_t) * CHAR_BIT); }
1745
+
1746
+ explicit TimestampType(TimeUnit::type unit = TimeUnit::MILLI)
1747
+ : TemporalType(Type::TIMESTAMP), unit_(unit) {}
1748
+
1749
+ explicit TimestampType(TimeUnit::type unit, const std::string& timezone)
1750
+ : TemporalType(Type::TIMESTAMP), unit_(unit), timezone_(timezone) {}
1751
+
1752
+ std::string ToString(bool show_metadata = false) const override;
1753
+ std::string name() const override { return "timestamp"; }
1754
+
1755
+ TimeUnit::type unit() const { return unit_; }
1756
+ const std::string& timezone() const { return timezone_; }
1757
+
1758
+ protected:
1759
+ std::string ComputeFingerprint() const override;
1760
+
1761
+ private:
1762
+ TimeUnit::type unit_;
1763
+ std::string timezone_;
1764
+ };
1765
+
1766
+ // Base class for the different kinds of calendar intervals.
1767
+ class ARROW_EXPORT IntervalType : public TemporalType, public ParametricType {
1768
+ public:
1769
+ enum type { MONTHS, DAY_TIME, MONTH_DAY_NANO };
1770
+
1771
+ virtual type interval_type() const = 0;
1772
+
1773
+ protected:
1774
+ explicit IntervalType(Type::type subtype) : TemporalType(subtype) {}
1775
+ std::string ComputeFingerprint() const override;
1776
+ };
1777
+
1778
+ /// \brief Represents a number of months.
1779
+ ///
1780
+ /// Type representing a number of months. Corresponds to YearMonth type
1781
+ /// in Schema.fbs (years are defined as 12 months).
1782
+ class ARROW_EXPORT MonthIntervalType : public IntervalType {
1783
+ public:
1784
+ static constexpr Type::type type_id = Type::INTERVAL_MONTHS;
1785
+ using c_type = int32_t;
1786
+ using PhysicalType = Int32Type;
1787
+
1788
+ static constexpr const char* type_name() { return "month_interval"; }
1789
+
1790
+ IntervalType::type interval_type() const override { return IntervalType::MONTHS; }
1791
+
1792
+ int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
1793
+
1794
+ MonthIntervalType() : IntervalType(type_id) {}
1795
+
1796
+ std::string ToString(bool ARROW_ARG_UNUSED(show_metadata) = false) const override {
1797
+ return name();
1798
+ }
1799
+ std::string name() const override { return "month_interval"; }
1800
+ };
1801
+
1802
+ /// \brief Represents a number of days and milliseconds (fraction of day).
1803
+ class ARROW_EXPORT DayTimeIntervalType : public IntervalType {
1804
+ public:
1805
+ struct DayMilliseconds {
1806
+ int32_t days = 0;
1807
+ int32_t milliseconds = 0;
1808
+ constexpr DayMilliseconds() = default;
1809
+ constexpr DayMilliseconds(int32_t days, int32_t milliseconds)
1810
+ : days(days), milliseconds(milliseconds) {}
1811
+ bool operator==(DayMilliseconds other) const {
1812
+ return this->days == other.days && this->milliseconds == other.milliseconds;
1813
+ }
1814
+ bool operator!=(DayMilliseconds other) const { return !(*this == other); }
1815
+ bool operator<(DayMilliseconds other) const {
1816
+ return this->days < other.days || this->milliseconds < other.milliseconds;
1817
+ }
1818
+ };
1819
+ using c_type = DayMilliseconds;
1820
+ using PhysicalType = DayTimeIntervalType;
1821
+
1822
+ static_assert(sizeof(DayMilliseconds) == 8,
1823
+ "DayMilliseconds struct assumed to be of size 8 bytes");
1824
+ static constexpr Type::type type_id = Type::INTERVAL_DAY_TIME;
1825
+
1826
+ static constexpr const char* type_name() { return "day_time_interval"; }
1827
+
1828
+ IntervalType::type interval_type() const override { return IntervalType::DAY_TIME; }
1829
+
1830
+ DayTimeIntervalType() : IntervalType(type_id) {}
1831
+
1832
+ int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
1833
+
1834
+ std::string ToString(bool ARROW_ARG_UNUSED(show_metadata) = false) const override {
1835
+ return name();
1836
+ }
1837
+ std::string name() const override { return "day_time_interval"; }
1838
+ };
1839
+
1840
+ ARROW_EXPORT
1841
+ std::ostream& operator<<(std::ostream& os, DayTimeIntervalType::DayMilliseconds interval);
1842
+
1843
+ /// \brief Represents a number of months, days and nanoseconds between
1844
+ /// two dates.
1845
+ ///
1846
+ /// All fields are independent from one another.
1847
+ class ARROW_EXPORT MonthDayNanoIntervalType : public IntervalType {
1848
+ public:
1849
+ struct MonthDayNanos {
1850
+ int32_t months;
1851
+ int32_t days;
1852
+ int64_t nanoseconds;
1853
+ bool operator==(MonthDayNanos other) const {
1854
+ return this->months == other.months && this->days == other.days &&
1855
+ this->nanoseconds == other.nanoseconds;
1856
+ }
1857
+ bool operator!=(MonthDayNanos other) const { return !(*this == other); }
1858
+ };
1859
+ using c_type = MonthDayNanos;
1860
+ using PhysicalType = MonthDayNanoIntervalType;
1861
+
1862
+ static_assert(sizeof(MonthDayNanos) == 16,
1863
+ "MonthDayNanos struct assumed to be of size 16 bytes");
1864
+ static constexpr Type::type type_id = Type::INTERVAL_MONTH_DAY_NANO;
1865
+
1866
+ static constexpr const char* type_name() { return "month_day_nano_interval"; }
1867
+
1868
+ IntervalType::type interval_type() const override {
1869
+ return IntervalType::MONTH_DAY_NANO;
1870
+ }
1871
+
1872
+ MonthDayNanoIntervalType() : IntervalType(type_id) {}
1873
+
1874
+ int bit_width() const override { return static_cast<int>(sizeof(c_type) * CHAR_BIT); }
1875
+
1876
+ std::string ToString(bool ARROW_ARG_UNUSED(show_metadata) = false) const override {
1877
+ return name();
1878
+ }
1879
+ std::string name() const override { return "month_day_nano_interval"; }
1880
+ };
1881
+
1882
+ ARROW_EXPORT
1883
+ std::ostream& operator<<(std::ostream& os,
1884
+ MonthDayNanoIntervalType::MonthDayNanos interval);
1885
+
1886
+ /// \brief Represents an elapsed time without any relation to a calendar artifact.
1887
+ class ARROW_EXPORT DurationType : public TemporalType, public ParametricType {
1888
+ public:
1889
+ using Unit = TimeUnit;
1890
+
1891
+ static constexpr Type::type type_id = Type::DURATION;
1892
+ using c_type = int64_t;
1893
+ using PhysicalType = Int64Type;
1894
+
1895
+ static constexpr const char* type_name() { return "duration"; }
1896
+
1897
+ int bit_width() const override { return static_cast<int>(sizeof(int64_t) * CHAR_BIT); }
1898
+
1899
+ explicit DurationType(TimeUnit::type unit = TimeUnit::MILLI)
1900
+ : TemporalType(Type::DURATION), unit_(unit) {}
1901
+
1902
+ std::string ToString(bool show_metadata = false) const override;
1903
+ std::string name() const override { return "duration"; }
1904
+
1905
+ TimeUnit::type unit() const { return unit_; }
1906
+
1907
+ protected:
1908
+ std::string ComputeFingerprint() const override;
1909
+
1910
+ private:
1911
+ TimeUnit::type unit_;
1912
+ };
1913
+
1914
+ /// @}
1915
+
1916
+ // ----------------------------------------------------------------------
1917
+ // Dictionary type (for representing categorical or dictionary-encoded
1918
+ // in memory)
1919
+
1920
+ /// \brief Dictionary-encoded value type with data-dependent
1921
+ /// dictionary. Indices are represented by any integer types.
1922
+ class ARROW_EXPORT DictionaryType : public FixedWidthType {
1923
+ public:
1924
+ static constexpr Type::type type_id = Type::DICTIONARY;
1925
+
1926
+ static constexpr const char* type_name() { return "dictionary"; }
1927
+
1928
+ DictionaryType(const std::shared_ptr<DataType>& index_type,
1929
+ const std::shared_ptr<DataType>& value_type, bool ordered = false);
1930
+
1931
+ // A constructor variant that validates its input parameters
1932
+ static Result<std::shared_ptr<DataType>> Make(
1933
+ const std::shared_ptr<DataType>& index_type,
1934
+ const std::shared_ptr<DataType>& value_type, bool ordered = false);
1935
+
1936
+ std::string ToString(bool show_metadata = false) const override;
1937
+ std::string name() const override { return "dictionary"; }
1938
+
1939
+ int bit_width() const override;
1940
+
1941
+ DataTypeLayout layout() const override;
1942
+
1943
+ const std::shared_ptr<DataType>& index_type() const { return index_type_; }
1944
+ const std::shared_ptr<DataType>& value_type() const { return value_type_; }
1945
+
1946
+ bool ordered() const { return ordered_; }
1947
+
1948
+ protected:
1949
+ static Status ValidateParameters(const DataType& index_type,
1950
+ const DataType& value_type);
1951
+
1952
+ std::string ComputeFingerprint() const override;
1953
+
1954
+ // Must be an integer type (not currently checked)
1955
+ std::shared_ptr<DataType> index_type_;
1956
+ std::shared_ptr<DataType> value_type_;
1957
+ bool ordered_;
1958
+ };
1959
+
1960
+ // ----------------------------------------------------------------------
1961
+ // FieldRef
1962
+
1963
+ /// \class FieldPath
1964
+ ///
1965
+ /// Represents a path to a nested field using indices of child fields.
1966
+ /// For example, given indices {5, 9, 3} the field would be retrieved with
1967
+ /// schema->field(5)->type()->field(9)->type()->field(3)
1968
+ ///
1969
+ /// Attempting to retrieve a child field using a FieldPath which is not valid for
1970
+ /// a given schema will raise an error. Invalid FieldPaths include:
1971
+ /// - an index is out of range
1972
+ /// - the path is empty (note: a default constructed FieldPath will be empty)
1973
+ ///
1974
+ /// FieldPaths provide a number of accessors for drilling down to potentially nested
1975
+ /// children. They are overloaded for convenience to support Schema (returns a field),
1976
+ /// DataType (returns a child field), Field (returns a child field of this field's type)
1977
+ /// Array (returns a child array), RecordBatch (returns a column).
1978
+ class ARROW_EXPORT FieldPath {
1979
+ public:
1980
+ FieldPath() = default;
1981
+
1982
+ FieldPath(std::vector<int> indices) // NOLINT runtime/explicit
1983
+ : indices_(std::move(indices)) {}
1984
+
1985
+ FieldPath(std::initializer_list<int> indices) // NOLINT runtime/explicit
1986
+ : indices_(std::move(indices)) {}
1987
+
1988
+ std::string ToString() const;
1989
+
1990
+ size_t hash() const;
1991
+ struct Hash {
1992
+ size_t operator()(const FieldPath& path) const { return path.hash(); }
1993
+ };
1994
+
1995
+ bool empty() const { return indices_.empty(); }
1996
+ bool operator==(const FieldPath& other) const { return indices() == other.indices(); }
1997
+ bool operator!=(const FieldPath& other) const { return indices() != other.indices(); }
1998
+
1999
+ const std::vector<int>& indices() const { return indices_; }
2000
+ int operator[](size_t i) const { return indices_[i]; }
2001
+ std::vector<int>::const_iterator begin() const { return indices_.begin(); }
2002
+ std::vector<int>::const_iterator end() const { return indices_.end(); }
2003
+
2004
+ /// \brief Retrieve the referenced child Field from a Schema, Field, or DataType
2005
+ Result<std::shared_ptr<Field>> Get(const Schema& schema) const;
2006
+ Result<std::shared_ptr<Field>> Get(const Field& field) const;
2007
+ Result<std::shared_ptr<Field>> Get(const DataType& type) const;
2008
+ Result<std::shared_ptr<Field>> Get(const FieldVector& fields) const;
2009
+
2010
+ static Result<std::shared_ptr<Schema>> GetAll(const Schema& schema,
2011
+ const std::vector<FieldPath>& paths);
2012
+
2013
+ /// \brief Retrieve the referenced column from a RecordBatch or Table
2014
+ Result<std::shared_ptr<Array>> Get(const RecordBatch& batch) const;
2015
+ Result<std::shared_ptr<ChunkedArray>> Get(const Table& table) const;
2016
+
2017
+ /// \brief Retrieve the referenced child from an Array or ArrayData
2018
+ Result<std::shared_ptr<Array>> Get(const Array& array) const;
2019
+ Result<std::shared_ptr<ArrayData>> Get(const ArrayData& data) const;
2020
+
2021
+ /// \brief Retrieve the referenced child from a ChunkedArray
2022
+ Result<std::shared_ptr<ChunkedArray>> Get(const ChunkedArray& chunked_array) const;
2023
+
2024
+ /// \brief Retrieve the referenced child/column from an Array, ArrayData, ChunkedArray,
2025
+ /// RecordBatch, or Table
2026
+ ///
2027
+ /// Unlike `FieldPath::Get`, these variants are not zero-copy and the retrieved child's
2028
+ /// null bitmap is ANDed with its ancestors'
2029
+ Result<std::shared_ptr<Array>> GetFlattened(const Array& array,
2030
+ MemoryPool* pool = NULLPTR) const;
2031
+ Result<std::shared_ptr<ArrayData>> GetFlattened(const ArrayData& data,
2032
+ MemoryPool* pool = NULLPTR) const;
2033
+ Result<std::shared_ptr<ChunkedArray>> GetFlattened(const ChunkedArray& chunked_array,
2034
+ MemoryPool* pool = NULLPTR) const;
2035
+ Result<std::shared_ptr<Array>> GetFlattened(const RecordBatch& batch,
2036
+ MemoryPool* pool = NULLPTR) const;
2037
+ Result<std::shared_ptr<ChunkedArray>> GetFlattened(const Table& table,
2038
+ MemoryPool* pool = NULLPTR) const;
2039
+
2040
+ private:
2041
+ std::vector<int> indices_;
2042
+ };
2043
+
2044
+ /// \class FieldRef
2045
+ /// \brief Descriptor of a (potentially nested) field within a schema.
2046
+ ///
2047
+ /// Unlike FieldPath (which exclusively uses indices of child fields), FieldRef may
2048
+ /// reference a field by name. It is intended to replace parameters like `int field_index`
2049
+ /// and `const std::string& field_name`; it can be implicitly constructed from either a
2050
+ /// field index or a name.
2051
+ ///
2052
+ /// Nested fields can be referenced as well. Given
2053
+ /// schema({field("a", struct_({field("n", null())})), field("b", int32())})
2054
+ ///
2055
+ /// the following all indicate the nested field named "n":
2056
+ /// FieldRef ref1(0, 0);
2057
+ /// FieldRef ref2("a", 0);
2058
+ /// FieldRef ref3("a", "n");
2059
+ /// FieldRef ref4(0, "n");
2060
+ /// ARROW_ASSIGN_OR_RAISE(FieldRef ref5,
2061
+ /// FieldRef::FromDotPath(".a[0]"));
2062
+ ///
2063
+ /// FieldPaths matching a FieldRef are retrieved using the member function FindAll.
2064
+ /// Multiple matches are possible because field names may be duplicated within a schema.
2065
+ /// For example:
2066
+ /// Schema a_is_ambiguous({field("a", int32()), field("a", float32())});
2067
+ /// auto matches = FieldRef("a").FindAll(a_is_ambiguous);
2068
+ /// assert(matches.size() == 2);
2069
+ /// assert(matches[0].Get(a_is_ambiguous)->Equals(a_is_ambiguous.field(0)));
2070
+ /// assert(matches[1].Get(a_is_ambiguous)->Equals(a_is_ambiguous.field(1)));
2071
+ ///
2072
+ /// Convenience accessors are available which raise a helpful error if the field is not
2073
+ /// found or ambiguous, and for immediately calling FieldPath::Get to retrieve any
2074
+ /// matching children:
2075
+ /// auto maybe_match = FieldRef("struct", "field_i32").FindOneOrNone(schema);
2076
+ /// auto maybe_column = FieldRef("struct", "field_i32").GetOne(some_table);
2077
+ class ARROW_EXPORT FieldRef : public util::EqualityComparable<FieldRef> {
2078
+ public:
2079
+ FieldRef() = default;
2080
+
2081
+ /// Construct a FieldRef using a string of indices. The reference will be retrieved as:
2082
+ /// schema.fields[self.indices[0]].type.fields[self.indices[1]] ...
2083
+ ///
2084
+ /// Empty indices are not valid.
2085
+ FieldRef(FieldPath indices); // NOLINT runtime/explicit
2086
+
2087
+ /// Construct a by-name FieldRef. Multiple fields may match a by-name FieldRef:
2088
+ /// [f for f in schema.fields where f.name == self.name]
2089
+ FieldRef(std::string name) : impl_(std::move(name)) {} // NOLINT runtime/explicit
2090
+ FieldRef(const char* name) : impl_(std::string(name)) {} // NOLINT runtime/explicit
2091
+
2092
+ /// Equivalent to a single index string of indices.
2093
+ FieldRef(int index) : impl_(FieldPath({index})) {} // NOLINT runtime/explicit
2094
+
2095
+ /// Construct a nested FieldRef.
2096
+ explicit FieldRef(std::vector<FieldRef> refs) { Flatten(std::move(refs)); }
2097
+
2098
+ /// Convenience constructor for nested FieldRefs: each argument will be used to
2099
+ /// construct a FieldRef
2100
+ template <typename A0, typename A1, typename... A>
2101
+ FieldRef(A0&& a0, A1&& a1, A&&... a) {
2102
+ Flatten({// cpplint thinks the following are constructor decls
2103
+ FieldRef(std::forward<A0>(a0)), // NOLINT runtime/explicit
2104
+ FieldRef(std::forward<A1>(a1)), // NOLINT runtime/explicit
2105
+ FieldRef(std::forward<A>(a))...}); // NOLINT runtime/explicit
2106
+ }
2107
+
2108
+ /// Parse a dot path into a FieldRef.
2109
+ ///
2110
+ /// dot_path = '.' name
2111
+ /// | '[' digit+ ']'
2112
+ /// | dot_path+
2113
+ ///
2114
+ /// Examples:
2115
+ /// ".alpha" => FieldRef("alpha")
2116
+ /// "[2]" => FieldRef(2)
2117
+ /// ".beta[3]" => FieldRef("beta", 3)
2118
+ /// "[5].gamma.delta[7]" => FieldRef(5, "gamma", "delta", 7)
2119
+ /// ".hello world" => FieldRef("hello world")
2120
+ /// R"(.\[y\]\\tho\.\)" => FieldRef(R"([y]\tho.\)")
2121
+ ///
2122
+ /// Note: When parsing a name, a '\' preceding any other character will be dropped from
2123
+ /// the resulting name. Therefore if a name must contain the characters '.', '\', or '['
2124
+ /// those must be escaped with a preceding '\'.
2125
+ static Result<FieldRef> FromDotPath(const std::string& dot_path);
2126
+ std::string ToDotPath() const;
2127
+
2128
+ bool Equals(const FieldRef& other) const { return impl_ == other.impl_; }
2129
+
2130
+ std::string ToString() const;
2131
+
2132
+ size_t hash() const;
2133
+ struct Hash {
2134
+ size_t operator()(const FieldRef& ref) const { return ref.hash(); }
2135
+ };
2136
+
2137
+ explicit operator bool() const { return Equals(FieldPath{}); }
2138
+ bool operator!() const { return !Equals(FieldPath{}); }
2139
+
2140
+ bool IsFieldPath() const { return std::holds_alternative<FieldPath>(impl_); }
2141
+ bool IsName() const { return std::holds_alternative<std::string>(impl_); }
2142
+ bool IsNested() const {
2143
+ if (IsName()) return false;
2144
+ if (IsFieldPath()) return std::get<FieldPath>(impl_).indices().size() > 1;
2145
+ return true;
2146
+ }
2147
+
2148
+ /// \brief Return true if this ref is a name or a nested sequence of only names
2149
+ ///
2150
+ /// Useful for determining if iteration is possible without recursion or inner loops
2151
+ bool IsNameSequence() const {
2152
+ if (IsName()) return true;
2153
+ if (const auto* nested = nested_refs()) {
2154
+ for (const auto& ref : *nested) {
2155
+ if (!ref.IsName()) return false;
2156
+ }
2157
+ return !nested->empty();
2158
+ }
2159
+ return false;
2160
+ }
2161
+
2162
+ const FieldPath* field_path() const {
2163
+ return IsFieldPath() ? &std::get<FieldPath>(impl_) : NULLPTR;
2164
+ }
2165
+ const std::string* name() const {
2166
+ return IsName() ? &std::get<std::string>(impl_) : NULLPTR;
2167
+ }
2168
+ const std::vector<FieldRef>* nested_refs() const {
2169
+ return std::holds_alternative<std::vector<FieldRef>>(impl_)
2170
+ ? &std::get<std::vector<FieldRef>>(impl_)
2171
+ : NULLPTR;
2172
+ }
2173
+
2174
+ /// \brief Retrieve FieldPath of every child field which matches this FieldRef.
2175
+ std::vector<FieldPath> FindAll(const Schema& schema) const;
2176
+ std::vector<FieldPath> FindAll(const Field& field) const;
2177
+ std::vector<FieldPath> FindAll(const DataType& type) const;
2178
+ std::vector<FieldPath> FindAll(const FieldVector& fields) const;
2179
+
2180
+ /// \brief Convenience function which applies FindAll to arg's type or schema.
2181
+ std::vector<FieldPath> FindAll(const ArrayData& array) const;
2182
+ std::vector<FieldPath> FindAll(const Array& array) const;
2183
+ std::vector<FieldPath> FindAll(const ChunkedArray& chunked_array) const;
2184
+ std::vector<FieldPath> FindAll(const RecordBatch& batch) const;
2185
+ std::vector<FieldPath> FindAll(const Table& table) const;
2186
+
2187
+ /// \brief Convenience function: raise an error if matches is empty.
2188
+ template <typename T>
2189
+ Status CheckNonEmpty(const std::vector<FieldPath>& matches, const T& root) const {
2190
+ if (matches.empty()) {
2191
+ return Status::Invalid("No match for ", ToString(), " in ", root.ToString());
2192
+ }
2193
+ return Status::OK();
2194
+ }
2195
+
2196
+ /// \brief Convenience function: raise an error if matches contains multiple FieldPaths.
2197
+ template <typename T>
2198
+ Status CheckNonMultiple(const std::vector<FieldPath>& matches, const T& root) const {
2199
+ if (matches.size() > 1) {
2200
+ return Status::Invalid("Multiple matches for ", ToString(), " in ",
2201
+ root.ToString());
2202
+ }
2203
+ return Status::OK();
2204
+ }
2205
+
2206
+ /// \brief Retrieve FieldPath of a single child field which matches this
2207
+ /// FieldRef. Emit an error if none or multiple match.
2208
+ template <typename T>
2209
+ Result<FieldPath> FindOne(const T& root) const {
2210
+ auto matches = FindAll(root);
2211
+ ARROW_RETURN_NOT_OK(CheckNonEmpty(matches, root));
2212
+ ARROW_RETURN_NOT_OK(CheckNonMultiple(matches, root));
2213
+ return std::move(matches[0]);
2214
+ }
2215
+
2216
+ /// \brief Retrieve FieldPath of a single child field which matches this
2217
+ /// FieldRef. Emit an error if multiple match. An empty (invalid) FieldPath
2218
+ /// will be returned if none match.
2219
+ template <typename T>
2220
+ Result<FieldPath> FindOneOrNone(const T& root) const {
2221
+ auto matches = FindAll(root);
2222
+ ARROW_RETURN_NOT_OK(CheckNonMultiple(matches, root));
2223
+ if (matches.empty()) {
2224
+ return FieldPath();
2225
+ }
2226
+ return std::move(matches[0]);
2227
+ }
2228
+
2229
+ template <typename T>
2230
+ using GetType = decltype(std::declval<FieldPath>().Get(std::declval<T>()).ValueOrDie());
2231
+
2232
+ /// \brief Get all children matching this FieldRef.
2233
+ template <typename T>
2234
+ std::vector<GetType<T>> GetAll(const T& root) const {
2235
+ std::vector<GetType<T>> out;
2236
+ for (const auto& match : FindAll(root)) {
2237
+ out.push_back(match.Get(root).ValueOrDie());
2238
+ }
2239
+ return out;
2240
+ }
2241
+ /// \brief Get all children matching this FieldRef.
2242
+ ///
2243
+ /// Unlike `FieldRef::GetAll`, this variant is not zero-copy and the retrieved
2244
+ /// children's null bitmaps are ANDed with their ancestors'
2245
+ template <typename T>
2246
+ Result<std::vector<GetType<T>>> GetAllFlattened(const T& root,
2247
+ MemoryPool* pool = NULLPTR) const {
2248
+ std::vector<GetType<T>> out;
2249
+ for (const auto& match : FindAll(root)) {
2250
+ ARROW_ASSIGN_OR_RAISE(auto child, match.GetFlattened(root, pool));
2251
+ out.push_back(std::move(child));
2252
+ }
2253
+ return out;
2254
+ }
2255
+
2256
+ /// \brief Get the single child matching this FieldRef.
2257
+ /// Emit an error if none or multiple match.
2258
+ template <typename T>
2259
+ Result<GetType<T>> GetOne(const T& root) const {
2260
+ ARROW_ASSIGN_OR_RAISE(auto match, FindOne(root));
2261
+ return match.Get(root).ValueOrDie();
2262
+ }
2263
+ /// \brief Get the single child matching this FieldRef.
2264
+ ///
2265
+ /// Unlike `FieldRef::GetOne`, this variant is not zero-copy and the retrieved
2266
+ /// child's null bitmap is ANDed with its ancestors'
2267
+ template <typename T>
2268
+ Result<GetType<T>> GetOneFlattened(const T& root, MemoryPool* pool = NULLPTR) const {
2269
+ ARROW_ASSIGN_OR_RAISE(auto match, FindOne(root));
2270
+ return match.GetFlattened(root, pool);
2271
+ }
2272
+
2273
+ /// \brief Get the single child matching this FieldRef.
2274
+ /// Return nullptr if none match, emit an error if multiple match.
2275
+ template <typename T>
2276
+ Result<GetType<T>> GetOneOrNone(const T& root) const {
2277
+ ARROW_ASSIGN_OR_RAISE(auto match, FindOneOrNone(root));
2278
+ if (match.empty()) {
2279
+ return static_cast<GetType<T>>(NULLPTR);
2280
+ }
2281
+ return match.Get(root).ValueOrDie();
2282
+ }
2283
+ /// \brief Get the single child matching this FieldRef.
2284
+ ///
2285
+ /// Return nullptr if none match, emit an error if multiple match.
2286
+ /// Unlike `FieldRef::GetOneOrNone`, this variant is not zero-copy and the
2287
+ /// retrieved child's null bitmap is ANDed with its ancestors'
2288
+ template <typename T>
2289
+ Result<GetType<T>> GetOneOrNoneFlattened(const T& root,
2290
+ MemoryPool* pool = NULLPTR) const {
2291
+ ARROW_ASSIGN_OR_RAISE(auto match, FindOneOrNone(root));
2292
+ if (match.empty()) {
2293
+ return static_cast<GetType<T>>(NULLPTR);
2294
+ }
2295
+ return match.GetFlattened(root, pool);
2296
+ }
2297
+
2298
+ private:
2299
+ void Flatten(std::vector<FieldRef> children);
2300
+
2301
+ std::variant<FieldPath, std::string, std::vector<FieldRef>> impl_;
2302
+ };
2303
+
2304
+ ARROW_EXPORT void PrintTo(const FieldRef& ref, std::ostream* os);
2305
+
2306
+ ARROW_EXPORT
2307
+ std::ostream& operator<<(std::ostream& os, const FieldRef&);
2308
+
2309
+ // ----------------------------------------------------------------------
2310
+ // Schema
2311
+
2312
+ enum class Endianness {
2313
+ Little = 0,
2314
+ Big = 1,
2315
+ #if ARROW_LITTLE_ENDIAN
2316
+ Native = Little
2317
+ #else
2318
+ Native = Big
2319
+ #endif
2320
+ };
2321
+
2322
+ /// \class Schema
2323
+ /// \brief Sequence of arrow::Field objects describing the columns of a record
2324
+ /// batch or table data structure
2325
+ class ARROW_EXPORT Schema : public detail::Fingerprintable,
2326
+ public util::EqualityComparable<Schema>,
2327
+ public util::ToStringOstreamable<Schema> {
2328
+ public:
2329
+ explicit Schema(FieldVector fields, Endianness endianness,
2330
+ std::shared_ptr<const KeyValueMetadata> metadata = NULLPTR);
2331
+
2332
+ explicit Schema(FieldVector fields,
2333
+ std::shared_ptr<const KeyValueMetadata> metadata = NULLPTR);
2334
+
2335
+ Schema(const Schema&);
2336
+
2337
+ ~Schema() override;
2338
+
2339
+ /// Returns true if all of the schema fields are equal
2340
+ bool Equals(const Schema& other, bool check_metadata = false) const;
2341
+ bool Equals(const std::shared_ptr<Schema>& other, bool check_metadata = false) const;
2342
+
2343
+ /// \brief Set endianness in the schema
2344
+ ///
2345
+ /// \return new Schema
2346
+ std::shared_ptr<Schema> WithEndianness(Endianness endianness) const;
2347
+
2348
+ /// \brief Return endianness in the schema
2349
+ Endianness endianness() const;
2350
+
2351
+ /// \brief Indicate if endianness is equal to platform-native endianness
2352
+ bool is_native_endian() const;
2353
+
2354
+ /// \brief Return the number of fields (columns) in the schema
2355
+ int num_fields() const;
2356
+
2357
+ /// Return the ith schema element. Does not boundscheck
2358
+ const std::shared_ptr<Field>& field(int i) const;
2359
+
2360
+ const FieldVector& fields() const;
2361
+
2362
+ std::vector<std::string> field_names() const;
2363
+
2364
+ /// Returns null if name not found
2365
+ std::shared_ptr<Field> GetFieldByName(const std::string& name) const;
2366
+
2367
+ /// \brief Return the indices of all fields having this name in sorted order
2368
+ FieldVector GetAllFieldsByName(const std::string& name) const;
2369
+
2370
+ /// Returns -1 if name not found
2371
+ int GetFieldIndex(const std::string& name) const;
2372
+
2373
+ /// Return the indices of all fields having this name
2374
+ std::vector<int> GetAllFieldIndices(const std::string& name) const;
2375
+
2376
+ /// Indicate if field named `name` can be found unambiguously in the schema.
2377
+ Status CanReferenceFieldByName(const std::string& name) const;
2378
+
2379
+ /// Indicate if fields named `names` can be found unambiguously in the schema.
2380
+ Status CanReferenceFieldsByNames(const std::vector<std::string>& names) const;
2381
+
2382
+ /// \brief The custom key-value metadata, if any
2383
+ ///
2384
+ /// \return metadata may be null
2385
+ const std::shared_ptr<const KeyValueMetadata>& metadata() const;
2386
+
2387
+ /// \brief Render a string representation of the schema suitable for debugging
2388
+ /// \param[in] show_metadata when true, if KeyValueMetadata is non-empty,
2389
+ /// print keys and values in the output
2390
+ std::string ToString(bool show_metadata = false) const;
2391
+
2392
+ Result<std::shared_ptr<Schema>> AddField(int i,
2393
+ const std::shared_ptr<Field>& field) const;
2394
+ Result<std::shared_ptr<Schema>> RemoveField(int i) const;
2395
+ Result<std::shared_ptr<Schema>> SetField(int i,
2396
+ const std::shared_ptr<Field>& field) const;
2397
+
2398
+ /// \brief Replace field names with new names
2399
+ ///
2400
+ /// \param[in] names new names
2401
+ /// \return new Schema
2402
+ Result<std::shared_ptr<Schema>> WithNames(const std::vector<std::string>& names) const;
2403
+
2404
+ /// \brief Replace key-value metadata with new metadata
2405
+ ///
2406
+ /// \param[in] metadata new KeyValueMetadata
2407
+ /// \return new Schema
2408
+ std::shared_ptr<Schema> WithMetadata(
2409
+ const std::shared_ptr<const KeyValueMetadata>& metadata) const;
2410
+
2411
+ /// \brief Return copy of Schema without the KeyValueMetadata
2412
+ std::shared_ptr<Schema> RemoveMetadata() const;
2413
+
2414
+ /// \brief Indicate that the Schema has non-empty KevValueMetadata
2415
+ bool HasMetadata() const;
2416
+
2417
+ /// \brief Indicate that the Schema has distinct field names.
2418
+ bool HasDistinctFieldNames() const;
2419
+
2420
+ protected:
2421
+ std::string ComputeFingerprint() const override;
2422
+ std::string ComputeMetadataFingerprint() const override;
2423
+
2424
+ private:
2425
+ class Impl;
2426
+ std::unique_ptr<Impl> impl_;
2427
+ };
2428
+
2429
+ ARROW_EXPORT void PrintTo(const Schema& s, std::ostream* os);
2430
+
2431
+ ARROW_EXPORT
2432
+ std::string EndiannessToString(Endianness endianness);
2433
+
2434
+ // ----------------------------------------------------------------------
2435
+
2436
+ /// \brief Convenience class to incrementally construct/merge schemas.
2437
+ ///
2438
+ /// This class amortizes the cost of validating field name conflicts by
2439
+ /// maintaining the mapping. The caller also controls the conflict resolution
2440
+ /// scheme.
2441
+ class ARROW_EXPORT SchemaBuilder {
2442
+ public:
2443
+ // Indicate how field conflict(s) should be resolved when building a schema. A
2444
+ // conflict arise when a field is added to the builder and one or more field(s)
2445
+ // with the same name already exists.
2446
+ enum ConflictPolicy {
2447
+ // Ignore the conflict and append the field. This is the default behavior of the
2448
+ // Schema constructor and the `arrow::schema` factory function.
2449
+ CONFLICT_APPEND = 0,
2450
+ // Keep the existing field and ignore the newer one.
2451
+ CONFLICT_IGNORE,
2452
+ // Replace the existing field with the newer one.
2453
+ CONFLICT_REPLACE,
2454
+ // Merge the fields. The merging behavior can be controlled by `Field::MergeOptions`
2455
+ // specified at construction time. Also see documentation of `Field::MergeWith`.
2456
+ CONFLICT_MERGE,
2457
+ // Refuse the new field and error out.
2458
+ CONFLICT_ERROR
2459
+ };
2460
+
2461
+ /// \brief Construct an empty SchemaBuilder
2462
+ /// `field_merge_options` is only effective when `conflict_policy` == `CONFLICT_MERGE`.
2463
+ SchemaBuilder(
2464
+ ConflictPolicy conflict_policy = CONFLICT_APPEND,
2465
+ Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults());
2466
+ /// \brief Construct a SchemaBuilder from a list of fields
2467
+ /// `field_merge_options` is only effective when `conflict_policy` == `CONFLICT_MERGE`.
2468
+ SchemaBuilder(
2469
+ FieldVector fields, ConflictPolicy conflict_policy = CONFLICT_APPEND,
2470
+ Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults());
2471
+ /// \brief Construct a SchemaBuilder from a schema, preserving the metadata
2472
+ /// `field_merge_options` is only effective when `conflict_policy` == `CONFLICT_MERGE`.
2473
+ SchemaBuilder(
2474
+ const std::shared_ptr<Schema>& schema,
2475
+ ConflictPolicy conflict_policy = CONFLICT_APPEND,
2476
+ Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults());
2477
+
2478
+ /// \brief Return the conflict resolution method.
2479
+ ConflictPolicy policy() const;
2480
+
2481
+ /// \brief Set the conflict resolution method.
2482
+ void SetPolicy(ConflictPolicy resolution);
2483
+
2484
+ /// \brief Add a field to the constructed schema.
2485
+ ///
2486
+ /// \param[in] field to add to the constructed Schema.
2487
+ /// \return A failure if encountered.
2488
+ Status AddField(const std::shared_ptr<Field>& field);
2489
+
2490
+ /// \brief Add multiple fields to the constructed schema.
2491
+ ///
2492
+ /// \param[in] fields to add to the constructed Schema.
2493
+ /// \return The first failure encountered, if any.
2494
+ Status AddFields(const FieldVector& fields);
2495
+
2496
+ /// \brief Add fields of a Schema to the constructed Schema.
2497
+ ///
2498
+ /// \param[in] schema to take fields to add to the constructed Schema.
2499
+ /// \return The first failure encountered, if any.
2500
+ Status AddSchema(const std::shared_ptr<Schema>& schema);
2501
+
2502
+ /// \brief Add fields of multiple Schemas to the constructed Schema.
2503
+ ///
2504
+ /// \param[in] schemas to take fields to add to the constructed Schema.
2505
+ /// \return The first failure encountered, if any.
2506
+ Status AddSchemas(const std::vector<std::shared_ptr<Schema>>& schemas);
2507
+
2508
+ Status AddMetadata(const KeyValueMetadata& metadata);
2509
+
2510
+ /// \brief Return the constructed Schema.
2511
+ ///
2512
+ /// The builder internal state is not affected by invoking this method, i.e.
2513
+ /// a single builder can yield multiple incrementally constructed schemas.
2514
+ ///
2515
+ /// \return the constructed schema.
2516
+ Result<std::shared_ptr<Schema>> Finish() const;
2517
+
2518
+ /// \brief Merge schemas in a unified schema according to policy.
2519
+ static Result<std::shared_ptr<Schema>> Merge(
2520
+ const std::vector<std::shared_ptr<Schema>>& schemas,
2521
+ ConflictPolicy policy = CONFLICT_MERGE);
2522
+
2523
+ /// \brief Indicate if schemas are compatible to merge according to policy.
2524
+ static Status AreCompatible(const std::vector<std::shared_ptr<Schema>>& schemas,
2525
+ ConflictPolicy policy = CONFLICT_MERGE);
2526
+
2527
+ /// \brief Reset internal state with an empty schema (and metadata).
2528
+ void Reset();
2529
+
2530
+ ~SchemaBuilder();
2531
+
2532
+ private:
2533
+ class Impl;
2534
+ std::unique_ptr<Impl> impl_;
2535
+
2536
+ Status AppendField(const std::shared_ptr<Field>& field);
2537
+ };
2538
+
2539
+ /// \brief Unifies schemas by merging fields by name.
2540
+ ///
2541
+ /// The behavior of field merging can be controlled via `Field::MergeOptions`.
2542
+ ///
2543
+ /// The resulting schema will contain the union of fields from all schemas.
2544
+ /// Fields with the same name will be merged. See `Field::MergeOptions`.
2545
+ /// - They are expected to be mergeable under provided `field_merge_options`.
2546
+ /// - The unified field will inherit the metadata from the schema where
2547
+ /// that field is first defined.
2548
+ /// - The first N fields in the schema will be ordered the same as the
2549
+ /// N fields in the first schema.
2550
+ /// The resulting schema will inherit its metadata from the first input schema.
2551
+ /// Returns an error if:
2552
+ /// - Any input schema contains fields with duplicate names.
2553
+ /// - Fields of the same name are not mergeable.
2554
+ ARROW_EXPORT
2555
+ Result<std::shared_ptr<Schema>> UnifySchemas(
2556
+ const std::vector<std::shared_ptr<Schema>>& schemas,
2557
+ Field::MergeOptions field_merge_options = Field::MergeOptions::Defaults());
2558
+
2559
+ namespace internal {
2560
+
2561
+ constexpr bool may_have_validity_bitmap(Type::type id) {
2562
+ switch (id) {
2563
+ case Type::NA:
2564
+ case Type::DENSE_UNION:
2565
+ case Type::SPARSE_UNION:
2566
+ case Type::RUN_END_ENCODED:
2567
+ return false;
2568
+ default:
2569
+ return true;
2570
+ }
2571
+ }
2572
+
2573
+ ARROW_DEPRECATED("Deprecated in 17.0.0. Use may_have_validity_bitmap() instead.")
2574
+ constexpr bool HasValidityBitmap(Type::type id) { return may_have_validity_bitmap(id); }
2575
+
2576
+ ARROW_EXPORT
2577
+ std::string ToString(Type::type id);
2578
+
2579
+ ARROW_EXPORT
2580
+ std::string ToTypeName(Type::type id);
2581
+
2582
+ ARROW_EXPORT
2583
+ std::string ToString(TimeUnit::type unit);
2584
+
2585
+ } // namespace internal
2586
+
2587
+ // Helpers to get instances of data types based on general categories
2588
+
2589
+ /// \brief Signed integer types
2590
+ ARROW_EXPORT
2591
+ const std::vector<std::shared_ptr<DataType>>& SignedIntTypes();
2592
+ /// \brief Unsigned integer types
2593
+ ARROW_EXPORT
2594
+ const std::vector<std::shared_ptr<DataType>>& UnsignedIntTypes();
2595
+ /// \brief Signed and unsigned integer types
2596
+ ARROW_EXPORT
2597
+ const std::vector<std::shared_ptr<DataType>>& IntTypes();
2598
+ /// \brief Floating point types
2599
+ ARROW_EXPORT
2600
+ const std::vector<std::shared_ptr<DataType>>& FloatingPointTypes();
2601
+ /// \brief Number types without boolean - integer and floating point types
2602
+ ARROW_EXPORT
2603
+ const std::vector<std::shared_ptr<DataType>>& NumericTypes();
2604
+ /// \brief Binary and string-like types (except fixed-size binary)
2605
+ ARROW_EXPORT
2606
+ const std::vector<std::shared_ptr<DataType>>& BaseBinaryTypes();
2607
+ /// \brief Binary and large-binary types
2608
+ ARROW_EXPORT
2609
+ const std::vector<std::shared_ptr<DataType>>& BinaryTypes();
2610
+ /// \brief String and large-string types
2611
+ ARROW_EXPORT
2612
+ const std::vector<std::shared_ptr<DataType>>& StringTypes();
2613
+ /// \brief String-view and Binary-view
2614
+ ARROW_EXPORT
2615
+ const std::vector<std::shared_ptr<DataType>>& BinaryViewTypes();
2616
+ /// \brief Temporal types including date, time and timestamps for each unit
2617
+ ARROW_EXPORT
2618
+ const std::vector<std::shared_ptr<DataType>>& TemporalTypes();
2619
+ /// \brief Interval types
2620
+ ARROW_EXPORT
2621
+ const std::vector<std::shared_ptr<DataType>>& IntervalTypes();
2622
+ /// \brief Duration types for each unit
2623
+ ARROW_EXPORT
2624
+ const std::vector<std::shared_ptr<DataType>>& DurationTypes();
2625
+ /// \brief Numeric, base binary, date, boolean and null types
2626
+ ARROW_EXPORT
2627
+ const std::vector<std::shared_ptr<DataType>>& PrimitiveTypes();
2628
+
2629
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/arrow/visit_array_inline.h ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include "arrow/array.h"
21
+ #include "arrow/extension_type.h"
22
+ #include "arrow/visitor_generate.h"
23
+
24
+ namespace arrow {
25
+
26
+ #define ARRAY_VISIT_INLINE(TYPE_CLASS) \
27
+ case TYPE_CLASS##Type::type_id: \
28
+ return visitor->Visit( \
29
+ internal::checked_cast<const typename TypeTraits<TYPE_CLASS##Type>::ArrayType&>( \
30
+ array), \
31
+ std::forward<ARGS>(args)...);
32
+
33
+ /// \brief Apply the visitors Visit() method specialized to the array type
34
+ ///
35
+ /// \tparam VISITOR Visitor type that implements Visit() for all array types.
36
+ /// \tparam ARGS Additional arguments, if any, will be passed to the Visit function after
37
+ /// the `arr` argument
38
+ /// \return Status
39
+ ///
40
+ /// A visitor is a type that implements specialized logic for each Arrow type.
41
+ /// Example usage:
42
+ ///
43
+ /// ```
44
+ /// class ExampleVisitor {
45
+ /// arrow::Status Visit(arrow::NumericArray<Int32Type> arr) { ... }
46
+ /// arrow::Status Visit(arrow::NumericArray<Int64Type> arr) { ... }
47
+ /// ...
48
+ /// }
49
+ /// ExampleVisitor visitor;
50
+ /// VisitArrayInline(some_array, &visitor);
51
+ /// ```
52
+ template <typename VISITOR, typename... ARGS>
53
+ inline Status VisitArrayInline(const Array& array, VISITOR* visitor, ARGS&&... args) {
54
+ switch (array.type_id()) {
55
+ ARROW_GENERATE_FOR_ALL_TYPES(ARRAY_VISIT_INLINE);
56
+ default:
57
+ break;
58
+ }
59
+ return Status::NotImplemented("Type not implemented");
60
+ }
61
+
62
+ #undef ARRAY_VISIT_INLINE
63
+
64
+ } // namespace arrow
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/api/io.h ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include "parquet/exception.h"
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/api/reader.h ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ // Column reader API
21
+ #include "parquet/column_reader.h"
22
+ #include "parquet/column_scanner.h"
23
+ #include "parquet/exception.h"
24
+ #include "parquet/file_reader.h"
25
+ #include "parquet/metadata.h"
26
+ #include "parquet/platform.h"
27
+ #include "parquet/printer.h"
28
+ #include "parquet/properties.h"
29
+ #include "parquet/statistics.h"
30
+
31
+ // Schemas
32
+ #include "parquet/api/schema.h"
33
+
34
+ // IO
35
+ #include "parquet/api/io.h"
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/api/schema.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ // Schemas
21
+ #include "parquet/schema.h"
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/api/writer.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include "parquet/api/io.h"
21
+ #include "parquet/api/schema.h"
22
+ #include "parquet/column_writer.h"
23
+ #include "parquet/exception.h"
24
+ #include "parquet/file_writer.h"
25
+ #include "parquet/statistics.h"
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/reader.h ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ // N.B. we don't include async_generator.h as it's relatively heavy
22
+ #include <functional>
23
+ #include <memory>
24
+ #include <vector>
25
+
26
+ #include "parquet/file_reader.h"
27
+ #include "parquet/platform.h"
28
+ #include "parquet/properties.h"
29
+
30
+ namespace arrow {
31
+
32
+ class ChunkedArray;
33
+ class KeyValueMetadata;
34
+ class RecordBatchReader;
35
+ struct Scalar;
36
+ class Schema;
37
+ class Table;
38
+ class RecordBatch;
39
+
40
+ } // namespace arrow
41
+
42
+ namespace parquet {
43
+
44
+ class FileMetaData;
45
+ class SchemaDescriptor;
46
+
47
+ namespace arrow {
48
+
49
+ class ColumnChunkReader;
50
+ class ColumnReader;
51
+ struct SchemaManifest;
52
+ class RowGroupReader;
53
+
54
+ /// \brief Arrow read adapter class for deserializing Parquet files as Arrow row batches.
55
+ ///
56
+ /// This interfaces caters for different use cases and thus provides different
57
+ /// interfaces. In its most simplistic form, we cater for a user that wants to
58
+ /// read the whole Parquet at once with the `FileReader::ReadTable` method.
59
+ ///
60
+ /// More advanced users that also want to implement parallelism on top of each
61
+ /// single Parquet files should do this on the RowGroup level. For this, they can
62
+ /// call `FileReader::RowGroup(i)->ReadTable` to receive only the specified
63
+ /// RowGroup as a table.
64
+ ///
65
+ /// In the most advanced situation, where a consumer wants to independently read
66
+ /// RowGroups in parallel and consume each column individually, they can call
67
+ /// `FileReader::RowGroup(i)->Column(j)->Read` and receive an `arrow::Column`
68
+ /// instance.
69
+ ///
70
+ /// Finally, one can also get a stream of record batches using
71
+ /// `FileReader::GetRecordBatchReader()`. This can internally decode columns
72
+ /// in parallel if use_threads was enabled in the ArrowReaderProperties.
73
+ ///
74
+ /// The parquet format supports an optional integer field_id which can be assigned
75
+ /// to a field. Arrow will convert these field IDs to a metadata key named
76
+ /// PARQUET:field_id on the appropriate field.
77
+ // TODO(wesm): nested data does not always make sense with this user
78
+ // interface unless you are only reading a single leaf node from a branch of
79
+ // a table. For example:
80
+ //
81
+ // repeated group data {
82
+ // optional group record {
83
+ // optional int32 val1;
84
+ // optional byte_array val2;
85
+ // optional bool val3;
86
+ // }
87
+ // optional int32 val4;
88
+ // }
89
+ //
90
+ // In the Parquet file, there are 4 leaf nodes:
91
+ //
92
+ // * data.record.val1
93
+ // * data.record.val2
94
+ // * data.record.val3
95
+ // * data.val4
96
+ //
97
+ // When materializing this data in an Arrow array, we would have:
98
+ //
99
+ // data: list<struct<
100
+ // record: struct<
101
+ // val1: int32,
102
+ // val2: string (= list<uint8>),
103
+ // val3: bool,
104
+ // >,
105
+ // val4: int32
106
+ // >>
107
+ //
108
+ // However, in the Parquet format, each leaf node has its own repetition and
109
+ // definition levels describing the structure of the intermediate nodes in
110
+ // this array structure. Thus, we will need to scan the leaf data for a group
111
+ // of leaf nodes part of the same type tree to create a single result Arrow
112
+ // nested array structure.
113
+ //
114
+ // This is additionally complicated "chunky" repeated fields or very large byte
115
+ // arrays
116
+ class PARQUET_EXPORT FileReader {
117
+ public:
118
+ /// Factory function to create a FileReader from a ParquetFileReader and properties
119
+ static ::arrow::Status Make(::arrow::MemoryPool* pool,
120
+ std::unique_ptr<ParquetFileReader> reader,
121
+ const ArrowReaderProperties& properties,
122
+ std::unique_ptr<FileReader>* out);
123
+
124
+ /// Factory function to create a FileReader from a ParquetFileReader
125
+ static ::arrow::Status Make(::arrow::MemoryPool* pool,
126
+ std::unique_ptr<ParquetFileReader> reader,
127
+ std::unique_ptr<FileReader>* out);
128
+
129
+ // Since the distribution of columns amongst a Parquet file's row groups may
130
+ // be uneven (the number of values in each column chunk can be different), we
131
+ // provide a column-oriented read interface. The ColumnReader hides the
132
+ // details of paging through the file's row groups and yielding
133
+ // fully-materialized arrow::Array instances
134
+ //
135
+ // Returns error status if the column of interest is not flat.
136
+ // The indicated column index is relative to the schema
137
+ virtual ::arrow::Status GetColumn(int i, std::unique_ptr<ColumnReader>* out) = 0;
138
+
139
+ /// \brief Return arrow schema for all the columns.
140
+ virtual ::arrow::Status GetSchema(std::shared_ptr<::arrow::Schema>* out) = 0;
141
+
142
+ /// \brief Read column as a whole into a chunked array.
143
+ ///
144
+ /// The index i refers the index of the top level schema field, which may
145
+ /// be nested or flat - e.g.
146
+ ///
147
+ /// 0 foo.bar
148
+ /// foo.bar.baz
149
+ /// foo.qux
150
+ /// 1 foo2
151
+ /// 2 foo3
152
+ ///
153
+ /// i=0 will read the entire foo struct, i=1 the foo2 primitive column etc
154
+ virtual ::arrow::Status ReadColumn(int i,
155
+ std::shared_ptr<::arrow::ChunkedArray>* out) = 0;
156
+
157
+ /// \brief Return a RecordBatchReader of all row groups and columns.
158
+ virtual ::arrow::Status GetRecordBatchReader(
159
+ std::unique_ptr<::arrow::RecordBatchReader>* out) = 0;
160
+
161
+ /// \brief Return a RecordBatchReader of row groups selected from row_group_indices.
162
+ ///
163
+ /// Note that the ordering in row_group_indices matters. FileReaders must outlive
164
+ /// their RecordBatchReaders.
165
+ ///
166
+ /// \returns error Status if row_group_indices contains an invalid index
167
+ virtual ::arrow::Status GetRecordBatchReader(
168
+ const std::vector<int>& row_group_indices,
169
+ std::unique_ptr<::arrow::RecordBatchReader>* out) = 0;
170
+
171
+ /// \brief Return a RecordBatchReader of row groups selected from
172
+ /// row_group_indices, whose columns are selected by column_indices.
173
+ ///
174
+ /// Note that the ordering in row_group_indices and column_indices
175
+ /// matter. FileReaders must outlive their RecordBatchReaders.
176
+ ///
177
+ /// \returns error Status if either row_group_indices or column_indices
178
+ /// contains an invalid index
179
+ virtual ::arrow::Status GetRecordBatchReader(
180
+ const std::vector<int>& row_group_indices, const std::vector<int>& column_indices,
181
+ std::unique_ptr<::arrow::RecordBatchReader>* out) = 0;
182
+
183
+ /// \brief Return a RecordBatchReader of row groups selected from
184
+ /// row_group_indices, whose columns are selected by column_indices.
185
+ ///
186
+ /// Note that the ordering in row_group_indices and column_indices
187
+ /// matter. FileReaders must outlive their RecordBatchReaders.
188
+ ///
189
+ /// \param row_group_indices which row groups to read (order determines read order).
190
+ /// \param column_indices which columns to read (order determines output schema).
191
+ /// \param[out] out record batch stream from parquet data.
192
+ ///
193
+ /// \returns error Status if either row_group_indices or column_indices
194
+ /// contains an invalid index
195
+ ::arrow::Status GetRecordBatchReader(const std::vector<int>& row_group_indices,
196
+ const std::vector<int>& column_indices,
197
+ std::shared_ptr<::arrow::RecordBatchReader>* out);
198
+ ::arrow::Status GetRecordBatchReader(const std::vector<int>& row_group_indices,
199
+ std::shared_ptr<::arrow::RecordBatchReader>* out);
200
+ ::arrow::Status GetRecordBatchReader(std::shared_ptr<::arrow::RecordBatchReader>* out);
201
+
202
+ /// \brief Return a generator of record batches.
203
+ ///
204
+ /// The FileReader must outlive the generator, so this requires that you pass in a
205
+ /// shared_ptr.
206
+ ///
207
+ /// \returns error Result if either row_group_indices or column_indices contains an
208
+ /// invalid index
209
+ virtual ::arrow::Result<
210
+ std::function<::arrow::Future<std::shared_ptr<::arrow::RecordBatch>>()>>
211
+ GetRecordBatchGenerator(std::shared_ptr<FileReader> reader,
212
+ const std::vector<int> row_group_indices,
213
+ const std::vector<int> column_indices,
214
+ ::arrow::internal::Executor* cpu_executor = NULLPTR,
215
+ int64_t rows_to_readahead = 0) = 0;
216
+
217
+ /// Read all columns into a Table
218
+ virtual ::arrow::Status ReadTable(std::shared_ptr<::arrow::Table>* out) = 0;
219
+
220
+ /// \brief Read the given columns into a Table
221
+ ///
222
+ /// The indicated column indices are relative to the internal representation
223
+ /// of the parquet table. For instance :
224
+ /// 0 foo.bar
225
+ /// foo.bar.baz 0
226
+ /// foo.bar.baz2 1
227
+ /// foo.qux 2
228
+ /// 1 foo2 3
229
+ /// 2 foo3 4
230
+ ///
231
+ /// i=0 will read foo.bar.baz, i=1 will read only foo.bar.baz2 and so on.
232
+ /// Only leaf fields have indices; foo itself doesn't have an index.
233
+ /// To get the index for a particular leaf field, one can use
234
+ /// manifest().schema_fields to get the top level fields, and then walk the
235
+ /// tree to identify the relevant leaf fields and access its column_index.
236
+ /// To get the total number of leaf fields, use FileMetadata.num_columns().
237
+ virtual ::arrow::Status ReadTable(const std::vector<int>& column_indices,
238
+ std::shared_ptr<::arrow::Table>* out) = 0;
239
+
240
+ virtual ::arrow::Status ReadRowGroup(int i, const std::vector<int>& column_indices,
241
+ std::shared_ptr<::arrow::Table>* out) = 0;
242
+
243
+ virtual ::arrow::Status ReadRowGroup(int i, std::shared_ptr<::arrow::Table>* out) = 0;
244
+
245
+ virtual ::arrow::Status ReadRowGroups(const std::vector<int>& row_groups,
246
+ const std::vector<int>& column_indices,
247
+ std::shared_ptr<::arrow::Table>* out) = 0;
248
+
249
+ virtual ::arrow::Status ReadRowGroups(const std::vector<int>& row_groups,
250
+ std::shared_ptr<::arrow::Table>* out) = 0;
251
+
252
+ /// \brief Scan file contents with one thread, return number of rows
253
+ virtual ::arrow::Status ScanContents(std::vector<int> columns,
254
+ const int32_t column_batch_size,
255
+ int64_t* num_rows) = 0;
256
+
257
+ /// \brief Return a reader for the RowGroup, this object must not outlive the
258
+ /// FileReader.
259
+ virtual std::shared_ptr<RowGroupReader> RowGroup(int row_group_index) = 0;
260
+
261
+ /// \brief The number of row groups in the file
262
+ virtual int num_row_groups() const = 0;
263
+
264
+ virtual ParquetFileReader* parquet_reader() const = 0;
265
+
266
+ /// Set whether to use multiple threads during reads of multiple columns.
267
+ /// By default only one thread is used.
268
+ virtual void set_use_threads(bool use_threads) = 0;
269
+
270
+ /// Set number of records to read per batch for the RecordBatchReader.
271
+ virtual void set_batch_size(int64_t batch_size) = 0;
272
+
273
+ virtual const ArrowReaderProperties& properties() const = 0;
274
+
275
+ virtual const SchemaManifest& manifest() const = 0;
276
+
277
+ virtual ~FileReader() = default;
278
+ };
279
+
280
+ class RowGroupReader {
281
+ public:
282
+ virtual ~RowGroupReader() = default;
283
+ virtual std::shared_ptr<ColumnChunkReader> Column(int column_index) = 0;
284
+ virtual ::arrow::Status ReadTable(const std::vector<int>& column_indices,
285
+ std::shared_ptr<::arrow::Table>* out) = 0;
286
+ virtual ::arrow::Status ReadTable(std::shared_ptr<::arrow::Table>* out) = 0;
287
+
288
+ private:
289
+ struct Iterator;
290
+ };
291
+
292
+ class ColumnChunkReader {
293
+ public:
294
+ virtual ~ColumnChunkReader() = default;
295
+ virtual ::arrow::Status Read(std::shared_ptr<::arrow::ChunkedArray>* out) = 0;
296
+ };
297
+
298
+ // At this point, the column reader is a stream iterator. It only knows how to
299
+ // read the next batch of values for a particular column from the file until it
300
+ // runs out.
301
+ //
302
+ // We also do not expose any internal Parquet details, such as row groups. This
303
+ // might change in the future.
304
+ class PARQUET_EXPORT ColumnReader {
305
+ public:
306
+ virtual ~ColumnReader() = default;
307
+
308
+ // Scan the next array of the indicated size. The actual size of the
309
+ // returned array may be less than the passed size depending how much data is
310
+ // available in the file.
311
+ //
312
+ // When all the data in the file has been exhausted, the result is set to
313
+ // nullptr.
314
+ //
315
+ // Returns Status::OK on a successful read, including if you have exhausted
316
+ // the data available in the file.
317
+ virtual ::arrow::Status NextBatch(int64_t batch_size,
318
+ std::shared_ptr<::arrow::ChunkedArray>* out) = 0;
319
+ };
320
+
321
+ /// \brief Experimental helper class for bindings (like Python) that struggle
322
+ /// either with std::move or C++ exceptions
323
+ class PARQUET_EXPORT FileReaderBuilder {
324
+ public:
325
+ FileReaderBuilder();
326
+
327
+ /// Create FileReaderBuilder from Arrow file and optional properties / metadata
328
+ ::arrow::Status Open(std::shared_ptr<::arrow::io::RandomAccessFile> file,
329
+ const ReaderProperties& properties = default_reader_properties(),
330
+ std::shared_ptr<FileMetaData> metadata = NULLPTR);
331
+
332
+ /// Create FileReaderBuilder from file path and optional properties / metadata
333
+ ::arrow::Status OpenFile(const std::string& path, bool memory_map = false,
334
+ const ReaderProperties& props = default_reader_properties(),
335
+ std::shared_ptr<FileMetaData> metadata = NULLPTR);
336
+
337
+ ParquetFileReader* raw_reader() { return raw_reader_.get(); }
338
+
339
+ /// Set Arrow MemoryPool for memory allocation
340
+ FileReaderBuilder* memory_pool(::arrow::MemoryPool* pool);
341
+ /// Set Arrow reader properties
342
+ FileReaderBuilder* properties(const ArrowReaderProperties& arg_properties);
343
+ /// Build FileReader instance
344
+ ::arrow::Status Build(std::unique_ptr<FileReader>* out);
345
+ ::arrow::Result<std::unique_ptr<FileReader>> Build();
346
+
347
+ private:
348
+ ::arrow::MemoryPool* pool_;
349
+ ArrowReaderProperties properties_;
350
+ std::unique_ptr<ParquetFileReader> raw_reader_;
351
+ };
352
+
353
+ /// \defgroup parquet-arrow-reader-factories Factory functions for Parquet Arrow readers
354
+ ///
355
+ /// @{
356
+
357
+ /// \brief Build FileReader from Arrow file and MemoryPool
358
+ ///
359
+ /// Advanced settings are supported through the FileReaderBuilder class.
360
+ PARQUET_EXPORT
361
+ ::arrow::Status OpenFile(std::shared_ptr<::arrow::io::RandomAccessFile>,
362
+ ::arrow::MemoryPool* allocator,
363
+ std::unique_ptr<FileReader>* reader);
364
+
365
+ /// @}
366
+
367
+ PARQUET_EXPORT
368
+ ::arrow::Status StatisticsAsScalars(const Statistics& Statistics,
369
+ std::shared_ptr<::arrow::Scalar>* min,
370
+ std::shared_ptr<::arrow::Scalar>* max);
371
+
372
+ namespace internal {
373
+
374
+ PARQUET_EXPORT
375
+ ::arrow::Status FuzzReader(const uint8_t* data, int64_t size);
376
+
377
+ } // namespace internal
378
+ } // namespace arrow
379
+ } // namespace parquet
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/schema.h ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cassert>
21
+ #include <memory>
22
+ #include <unordered_map>
23
+ #include <unordered_set>
24
+ #include <vector>
25
+
26
+ #include "arrow/result.h"
27
+ #include "arrow/status.h"
28
+ #include "arrow/type.h"
29
+ #include "arrow/type_fwd.h"
30
+
31
+ #include "parquet/level_conversion.h"
32
+ #include "parquet/platform.h"
33
+ #include "parquet/schema.h"
34
+
35
+ namespace parquet {
36
+
37
+ class ArrowReaderProperties;
38
+ class ArrowWriterProperties;
39
+ class WriterProperties;
40
+
41
+ namespace arrow {
42
+
43
+ /// \defgroup arrow-to-parquet-schema-conversion Functions to convert an Arrow
44
+ /// schema into a Parquet schema.
45
+ ///
46
+ /// @{
47
+
48
+ PARQUET_EXPORT
49
+ ::arrow::Status FieldToNode(const std::shared_ptr<::arrow::Field>& field,
50
+ const WriterProperties& properties,
51
+ const ArrowWriterProperties& arrow_properties,
52
+ schema::NodePtr* out);
53
+
54
+ PARQUET_EXPORT
55
+ ::arrow::Status ToParquetSchema(const ::arrow::Schema* arrow_schema,
56
+ const WriterProperties& properties,
57
+ const ArrowWriterProperties& arrow_properties,
58
+ std::shared_ptr<SchemaDescriptor>* out);
59
+
60
+ PARQUET_EXPORT
61
+ ::arrow::Status ToParquetSchema(const ::arrow::Schema* arrow_schema,
62
+ const WriterProperties& properties,
63
+ std::shared_ptr<SchemaDescriptor>* out);
64
+
65
+ /// @}
66
+
67
+ /// \defgroup parquet-to-arrow-schema-conversion Functions to convert a Parquet
68
+ /// schema into an Arrow schema.
69
+ ///
70
+ /// @{
71
+
72
+ PARQUET_EXPORT
73
+ ::arrow::Status FromParquetSchema(
74
+ const SchemaDescriptor* parquet_schema, const ArrowReaderProperties& properties,
75
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& key_value_metadata,
76
+ std::shared_ptr<::arrow::Schema>* out);
77
+
78
+ PARQUET_EXPORT
79
+ ::arrow::Status FromParquetSchema(const SchemaDescriptor* parquet_schema,
80
+ const ArrowReaderProperties& properties,
81
+ std::shared_ptr<::arrow::Schema>* out);
82
+
83
+ PARQUET_EXPORT
84
+ ::arrow::Status FromParquetSchema(const SchemaDescriptor* parquet_schema,
85
+ std::shared_ptr<::arrow::Schema>* out);
86
+
87
+ /// @}
88
+
89
+ /// \brief Bridge between an arrow::Field and parquet column indices.
90
+ struct PARQUET_EXPORT SchemaField {
91
+ std::shared_ptr<::arrow::Field> field;
92
+ std::vector<SchemaField> children;
93
+
94
+ // Only set for leaf nodes
95
+ int column_index = -1;
96
+
97
+ parquet::internal::LevelInfo level_info;
98
+
99
+ bool is_leaf() const { return column_index != -1; }
100
+ };
101
+
102
+ /// \brief Bridge between a parquet Schema and an arrow Schema.
103
+ ///
104
+ /// Expose parquet columns as a tree structure. Useful traverse and link
105
+ /// between arrow's Schema and parquet's Schema.
106
+ struct PARQUET_EXPORT SchemaManifest {
107
+ static ::arrow::Status Make(
108
+ const SchemaDescriptor* schema,
109
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& metadata,
110
+ const ArrowReaderProperties& properties, SchemaManifest* manifest);
111
+
112
+ const SchemaDescriptor* descr;
113
+ std::shared_ptr<::arrow::Schema> origin_schema;
114
+ std::shared_ptr<const ::arrow::KeyValueMetadata> schema_metadata;
115
+ std::vector<SchemaField> schema_fields;
116
+
117
+ std::unordered_map<int, const SchemaField*> column_index_to_field;
118
+ std::unordered_map<const SchemaField*, const SchemaField*> child_to_parent;
119
+
120
+ ::arrow::Status GetColumnField(int column_index, const SchemaField** out) const {
121
+ auto it = column_index_to_field.find(column_index);
122
+ if (it == column_index_to_field.end()) {
123
+ return ::arrow::Status::KeyError("Column index ", column_index,
124
+ " not found in schema manifest, may be malformed");
125
+ }
126
+ *out = it->second;
127
+ return ::arrow::Status::OK();
128
+ }
129
+
130
+ const SchemaField* GetParent(const SchemaField* field) const {
131
+ // Returns nullptr also if not found
132
+ auto it = child_to_parent.find(field);
133
+ if (it == child_to_parent.end()) {
134
+ return NULLPTR;
135
+ }
136
+ return it->second;
137
+ }
138
+
139
+ /// Coalesce a list of field indices (relative to the equivalent arrow::Schema) which
140
+ /// correspond to the column root (first node below the parquet schema's root group) of
141
+ /// each leaf referenced in column_indices.
142
+ ///
143
+ /// For example, for leaves `a.b.c`, `a.b.d.e`, and `i.j.k` (column_indices=[0,1,3])
144
+ /// the roots are `a` and `i` (return=[0,2]).
145
+ ///
146
+ /// root
147
+ /// -- a <------
148
+ /// -- -- b | |
149
+ /// -- -- -- c |
150
+ /// -- -- -- d |
151
+ /// -- -- -- -- e
152
+ /// -- f
153
+ /// -- -- g
154
+ /// -- -- -- h
155
+ /// -- i <---
156
+ /// -- -- j |
157
+ /// -- -- -- k
158
+ ::arrow::Result<std::vector<int>> GetFieldIndices(
159
+ const std::vector<int>& column_indices) const {
160
+ const schema::GroupNode* group = descr->group_node();
161
+ std::unordered_set<int> already_added;
162
+
163
+ std::vector<int> out;
164
+ for (int column_idx : column_indices) {
165
+ if (column_idx < 0 || column_idx >= descr->num_columns()) {
166
+ return ::arrow::Status::IndexError("Column index ", column_idx, " is not valid");
167
+ }
168
+
169
+ auto field_node = descr->GetColumnRoot(column_idx);
170
+ auto field_idx = group->FieldIndex(*field_node);
171
+ if (field_idx == -1) {
172
+ return ::arrow::Status::IndexError("Column index ", column_idx, " is not valid");
173
+ }
174
+
175
+ if (already_added.insert(field_idx).second) {
176
+ out.push_back(field_idx);
177
+ }
178
+ }
179
+ return out;
180
+ }
181
+ };
182
+
183
+ } // namespace arrow
184
+ } // namespace parquet
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/test_util.h ADDED
@@ -0,0 +1,528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <limits>
21
+ #include <memory>
22
+ #include <random>
23
+ #include <string>
24
+ #include <utility>
25
+ #include <vector>
26
+
27
+ #include "arrow/array.h"
28
+ #include "arrow/array/builder_binary.h"
29
+ #include "arrow/array/builder_decimal.h"
30
+ #include "arrow/array/builder_primitive.h"
31
+ #include "arrow/testing/gtest_util.h"
32
+ #include "arrow/testing/random.h"
33
+ #include "arrow/type_fwd.h"
34
+ #include "arrow/type_traits.h"
35
+ #include "arrow/util/decimal.h"
36
+ #include "arrow/util/float16.h"
37
+ #include "parquet/column_reader.h"
38
+ #include "parquet/test_util.h"
39
+
40
+ namespace parquet {
41
+
42
+ using internal::RecordReader;
43
+
44
+ namespace arrow {
45
+
46
+ using ::arrow::Array;
47
+ using ::arrow::ChunkedArray;
48
+ using ::arrow::Status;
49
+
50
+ template <int32_t PRECISION>
51
+ struct Decimal128WithPrecisionAndScale {
52
+ static_assert(PRECISION >= 1 && PRECISION <= 38, "Invalid precision value");
53
+
54
+ using type = ::arrow::Decimal128Type;
55
+ static constexpr ::arrow::Type::type type_id = ::arrow::Decimal128Type::type_id;
56
+ static constexpr int32_t precision = PRECISION;
57
+ static constexpr int32_t scale = PRECISION - 1;
58
+ };
59
+
60
+ template <int32_t PRECISION>
61
+ struct Decimal256WithPrecisionAndScale {
62
+ static_assert(PRECISION >= 1 && PRECISION <= 76, "Invalid precision value");
63
+
64
+ using type = ::arrow::Decimal256Type;
65
+ static constexpr ::arrow::Type::type type_id = ::arrow::Decimal256Type::type_id;
66
+ static constexpr int32_t precision = PRECISION;
67
+ static constexpr int32_t scale = PRECISION - 1;
68
+ };
69
+
70
+ template <class ArrowType>
71
+ ::arrow::enable_if_floating_point<ArrowType, Status> NonNullArray(
72
+ size_t size, std::shared_ptr<Array>* out) {
73
+ using c_type = typename ArrowType::c_type;
74
+ std::vector<c_type> values;
75
+ if constexpr (::arrow::is_half_float_type<ArrowType>::value) {
76
+ values.resize(size);
77
+ test::random_float16_numbers(static_cast<int>(size), 0, ::arrow::util::Float16(0.0f),
78
+ ::arrow::util::Float16(1.0f), values.data());
79
+ } else {
80
+ ::arrow::random_real(size, 0, static_cast<c_type>(0), static_cast<c_type>(1),
81
+ &values);
82
+ }
83
+ ::arrow::NumericBuilder<ArrowType> builder;
84
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size()));
85
+ return builder.Finish(out);
86
+ }
87
+
88
+ template <class ArrowType>
89
+ ::arrow::enable_if_integer<ArrowType, Status> NonNullArray(size_t size,
90
+ std::shared_ptr<Array>* out) {
91
+ std::vector<typename ArrowType::c_type> values;
92
+ ::arrow::randint(size, 0, 64, &values);
93
+
94
+ // Passing data type so this will work with TimestampType too
95
+ ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(),
96
+ ::arrow::default_memory_pool());
97
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size()));
98
+ return builder.Finish(out);
99
+ }
100
+
101
+ template <class ArrowType>
102
+ ::arrow::enable_if_date<ArrowType, Status> NonNullArray(size_t size,
103
+ std::shared_ptr<Array>* out) {
104
+ std::vector<typename ArrowType::c_type> values;
105
+ ::arrow::randint(size, 0, 24, &values);
106
+ for (size_t i = 0; i < size; i++) {
107
+ values[i] *= 86400000;
108
+ }
109
+
110
+ // Passing data type so this will work with TimestampType too
111
+ ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(),
112
+ ::arrow::default_memory_pool());
113
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size()));
114
+ return builder.Finish(out);
115
+ }
116
+
117
+ template <class ArrowType>
118
+ ::arrow::enable_if_base_binary<ArrowType, Status> NonNullArray(
119
+ size_t size, std::shared_ptr<Array>* out) {
120
+ using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType;
121
+ BuilderType builder;
122
+ for (size_t i = 0; i < size; i++) {
123
+ RETURN_NOT_OK(builder.Append("test-string"));
124
+ }
125
+ return builder.Finish(out);
126
+ }
127
+
128
+ template <typename ArrowType>
129
+ ::arrow::enable_if_fixed_size_binary<ArrowType, Status> NonNullArray(
130
+ size_t size, std::shared_ptr<Array>* out) {
131
+ using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType;
132
+ // set byte_width to the length of "fixed": 5
133
+ // todo: find a way to generate test data with more diversity.
134
+ BuilderType builder(::arrow::fixed_size_binary(5));
135
+ for (size_t i = 0; i < size; i++) {
136
+ RETURN_NOT_OK(builder.Append("fixed"));
137
+ }
138
+ return builder.Finish(out);
139
+ }
140
+
141
+ template <int32_t byte_width>
142
+ static void random_decimals(int64_t n, uint32_t seed, int32_t precision, uint8_t* out) {
143
+ auto gen = ::arrow::random::RandomArrayGenerator(seed);
144
+ std::shared_ptr<Array> decimals;
145
+ if constexpr (byte_width == 4) {
146
+ decimals = gen.Decimal32(::arrow::decimal32(precision, 0), n);
147
+ } else if constexpr (byte_width == 8) {
148
+ decimals = gen.Decimal64(::arrow::decimal64(precision, 0), n);
149
+ } else if constexpr (byte_width == 16) {
150
+ decimals = gen.Decimal128(::arrow::decimal128(precision, 0), n);
151
+ } else {
152
+ decimals = gen.Decimal256(::arrow::decimal256(precision, 0), n);
153
+ }
154
+ std::memcpy(out, decimals->data()->GetValues<uint8_t>(1, 0), byte_width * n);
155
+ }
156
+
157
+ template <typename ArrowType, int32_t precision = ArrowType::precision>
158
+ ::arrow::enable_if_t<
159
+ std::is_same<ArrowType, Decimal128WithPrecisionAndScale<precision>>::value, Status>
160
+ NonNullArray(size_t size, std::shared_ptr<Array>* out) {
161
+ constexpr int32_t kDecimalPrecision = precision;
162
+ constexpr int32_t kDecimalScale = Decimal128WithPrecisionAndScale<precision>::scale;
163
+
164
+ const auto type = ::arrow::decimal128(kDecimalPrecision, kDecimalScale);
165
+ ::arrow::Decimal128Builder builder(type);
166
+ const int32_t byte_width =
167
+ static_cast<const ::arrow::Decimal128Type&>(*type).byte_width();
168
+
169
+ constexpr int32_t seed = 0;
170
+
171
+ ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width));
172
+ random_decimals<::arrow::Decimal128Type::kByteWidth>(size, seed, kDecimalPrecision,
173
+ out_buf->mutable_data());
174
+
175
+ RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size));
176
+ return builder.Finish(out);
177
+ }
178
+
179
+ template <typename ArrowType, int32_t precision = ArrowType::precision>
180
+ ::arrow::enable_if_t<
181
+ std::is_same<ArrowType, Decimal256WithPrecisionAndScale<precision>>::value, Status>
182
+ NonNullArray(size_t size, std::shared_ptr<Array>* out) {
183
+ constexpr int32_t kDecimalPrecision = precision;
184
+ constexpr int32_t kDecimalScale = Decimal256WithPrecisionAndScale<precision>::scale;
185
+
186
+ const auto type = ::arrow::decimal256(kDecimalPrecision, kDecimalScale);
187
+ ::arrow::Decimal256Builder builder(type);
188
+ const int32_t byte_width =
189
+ static_cast<const ::arrow::Decimal256Type&>(*type).byte_width();
190
+
191
+ constexpr int32_t seed = 0;
192
+
193
+ ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width));
194
+ random_decimals<::arrow::Decimal256Type::kByteWidth>(size, seed, kDecimalPrecision,
195
+ out_buf->mutable_data());
196
+
197
+ RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size));
198
+ return builder.Finish(out);
199
+ }
200
+
201
+ template <class ArrowType>
202
+ ::arrow::enable_if_boolean<ArrowType, Status> NonNullArray(size_t size,
203
+ std::shared_ptr<Array>* out) {
204
+ std::vector<uint8_t> values;
205
+ ::arrow::randint(size, 0, 1, &values);
206
+ ::arrow::BooleanBuilder builder;
207
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size()));
208
+ return builder.Finish(out);
209
+ }
210
+
211
+ // This helper function only supports (size/2) nulls.
212
+ template <typename ArrowType>
213
+ ::arrow::enable_if_floating_point<ArrowType, Status> NullableArray(
214
+ size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<Array>* out) {
215
+ using c_type = typename ArrowType::c_type;
216
+ std::vector<c_type> values;
217
+ if constexpr (::arrow::is_half_float_type<ArrowType>::value) {
218
+ values.resize(size);
219
+ test::random_float16_numbers(static_cast<int>(size), 0, ::arrow::util::Float16(-1e4f),
220
+ ::arrow::util::Float16(1e4f), values.data());
221
+ } else {
222
+ ::arrow::random_real(size, seed, static_cast<c_type>(-1e10),
223
+ static_cast<c_type>(1e10), &values);
224
+ }
225
+ std::vector<uint8_t> valid_bytes(size, 1);
226
+
227
+ for (size_t i = 0; i < num_nulls; i++) {
228
+ valid_bytes[i * 2] = 0;
229
+ }
230
+
231
+ ::arrow::NumericBuilder<ArrowType> builder;
232
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data()));
233
+ return builder.Finish(out);
234
+ }
235
+
236
+ // This helper function only supports (size/2) nulls.
237
+ template <typename ArrowType>
238
+ ::arrow::enable_if_integer<ArrowType, Status> NullableArray(size_t size, size_t num_nulls,
239
+ uint32_t seed,
240
+ std::shared_ptr<Array>* out) {
241
+ std::vector<typename ArrowType::c_type> values;
242
+
243
+ // Seed is random in Arrow right now
244
+ (void)seed;
245
+ ::arrow::randint(size, 0, 64, &values);
246
+ std::vector<uint8_t> valid_bytes(size, 1);
247
+
248
+ for (size_t i = 0; i < num_nulls; i++) {
249
+ valid_bytes[i * 2] = 0;
250
+ }
251
+
252
+ // Passing data type so this will work with TimestampType too
253
+ ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(),
254
+ ::arrow::default_memory_pool());
255
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data()));
256
+ return builder.Finish(out);
257
+ }
258
+
259
+ template <typename ArrowType>
260
+ ::arrow::enable_if_date<ArrowType, Status> NullableArray(size_t size, size_t num_nulls,
261
+ uint32_t seed,
262
+ std::shared_ptr<Array>* out) {
263
+ std::vector<typename ArrowType::c_type> values;
264
+
265
+ // Seed is random in Arrow right now
266
+ (void)seed;
267
+ ::arrow::randint(size, 0, 24, &values);
268
+ for (size_t i = 0; i < size; i++) {
269
+ values[i] *= 86400000;
270
+ }
271
+ std::vector<uint8_t> valid_bytes(size, 1);
272
+
273
+ for (size_t i = 0; i < num_nulls; i++) {
274
+ valid_bytes[i * 2] = 0;
275
+ }
276
+
277
+ // Passing data type so this will work with TimestampType too
278
+ ::arrow::NumericBuilder<ArrowType> builder(std::make_shared<ArrowType>(),
279
+ ::arrow::default_memory_pool());
280
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data()));
281
+ return builder.Finish(out);
282
+ }
283
+
284
+ // This helper function only supports (size/2) nulls yet.
285
+ template <typename ArrowType>
286
+ ::arrow::enable_if_base_binary<ArrowType, Status> NullableArray(
287
+ size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<::arrow::Array>* out) {
288
+ std::vector<uint8_t> valid_bytes(size, 1);
289
+
290
+ for (size_t i = 0; i < num_nulls; i++) {
291
+ valid_bytes[i * 2] = 0;
292
+ }
293
+
294
+ using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType;
295
+ BuilderType builder;
296
+
297
+ const int kBufferSize = 10;
298
+ uint8_t buffer[kBufferSize];
299
+ for (size_t i = 0; i < size; i++) {
300
+ if (!valid_bytes[i]) {
301
+ RETURN_NOT_OK(builder.AppendNull());
302
+ } else {
303
+ ::arrow::random_bytes(kBufferSize, seed + static_cast<uint32_t>(i), buffer);
304
+ if (ArrowType::is_utf8) {
305
+ // Trivially force data to be valid UTF8 by making it all ASCII
306
+ for (auto& byte : buffer) {
307
+ byte &= 0x7f;
308
+ }
309
+ }
310
+ RETURN_NOT_OK(builder.Append(buffer, kBufferSize));
311
+ }
312
+ }
313
+ return builder.Finish(out);
314
+ }
315
+
316
+ // This helper function only supports (size/2) nulls yet,
317
+ // same as NullableArray<String|Binary>(..)
318
+ template <typename ArrowType>
319
+ ::arrow::enable_if_fixed_size_binary<ArrowType, Status> NullableArray(
320
+ size_t size, size_t num_nulls, uint32_t seed, std::shared_ptr<::arrow::Array>* out) {
321
+ std::vector<uint8_t> valid_bytes(size, 1);
322
+
323
+ for (size_t i = 0; i < num_nulls; i++) {
324
+ valid_bytes[i * 2] = 0;
325
+ }
326
+
327
+ using BuilderType = typename ::arrow::TypeTraits<ArrowType>::BuilderType;
328
+ const int byte_width = 10;
329
+ BuilderType builder(::arrow::fixed_size_binary(byte_width));
330
+
331
+ const int kBufferSize = byte_width;
332
+ uint8_t buffer[kBufferSize];
333
+ for (size_t i = 0; i < size; i++) {
334
+ if (!valid_bytes[i]) {
335
+ RETURN_NOT_OK(builder.AppendNull());
336
+ } else {
337
+ ::arrow::random_bytes(kBufferSize, seed + static_cast<uint32_t>(i), buffer);
338
+ RETURN_NOT_OK(builder.Append(buffer));
339
+ }
340
+ }
341
+ return builder.Finish(out);
342
+ }
343
+
344
+ template <typename ArrowType, int32_t precision = ArrowType::precision>
345
+ ::arrow::enable_if_t<
346
+ std::is_same<ArrowType, Decimal128WithPrecisionAndScale<precision>>::value, Status>
347
+ NullableArray(size_t size, size_t num_nulls, uint32_t seed,
348
+ std::shared_ptr<::arrow::Array>* out) {
349
+ std::vector<uint8_t> valid_bytes(size, '\1');
350
+
351
+ for (size_t i = 0; i < num_nulls; ++i) {
352
+ valid_bytes[i * 2] = '\0';
353
+ }
354
+
355
+ constexpr int32_t kDecimalPrecision = precision;
356
+ constexpr int32_t kDecimalScale = Decimal128WithPrecisionAndScale<precision>::scale;
357
+ const auto type = ::arrow::decimal128(kDecimalPrecision, kDecimalScale);
358
+ const int32_t byte_width =
359
+ static_cast<const ::arrow::Decimal128Type&>(*type).byte_width();
360
+
361
+ ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width));
362
+
363
+ random_decimals<::arrow::Decimal128Type::kByteWidth>(size, seed, precision,
364
+ out_buf->mutable_data());
365
+
366
+ ::arrow::Decimal128Builder builder(type);
367
+ RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size, valid_bytes.data()));
368
+ return builder.Finish(out);
369
+ }
370
+
371
+ template <typename ArrowType, int32_t precision = ArrowType::precision>
372
+ ::arrow::enable_if_t<
373
+ std::is_same<ArrowType, Decimal256WithPrecisionAndScale<precision>>::value, Status>
374
+ NullableArray(size_t size, size_t num_nulls, uint32_t seed,
375
+ std::shared_ptr<::arrow::Array>* out) {
376
+ std::vector<uint8_t> valid_bytes(size, '\1');
377
+
378
+ for (size_t i = 0; i < num_nulls; ++i) {
379
+ valid_bytes[i * 2] = '\0';
380
+ }
381
+
382
+ constexpr int32_t kDecimalPrecision = precision;
383
+ constexpr int32_t kDecimalScale = Decimal256WithPrecisionAndScale<precision>::scale;
384
+ const auto type = ::arrow::decimal256(kDecimalPrecision, kDecimalScale);
385
+ const int32_t byte_width =
386
+ static_cast<const ::arrow::Decimal256Type&>(*type).byte_width();
387
+
388
+ ARROW_ASSIGN_OR_RAISE(auto out_buf, ::arrow::AllocateBuffer(size * byte_width));
389
+
390
+ random_decimals<::arrow::Decimal256Type::kByteWidth>(size, seed, precision,
391
+ out_buf->mutable_data());
392
+
393
+ ::arrow::Decimal256Builder builder(type);
394
+ RETURN_NOT_OK(builder.AppendValues(out_buf->data(), size, valid_bytes.data()));
395
+ return builder.Finish(out);
396
+ }
397
+
398
+ // This helper function only supports (size/2) nulls yet.
399
+ template <class ArrowType>
400
+ ::arrow::enable_if_boolean<ArrowType, Status> NullableArray(size_t size, size_t num_nulls,
401
+ uint32_t seed,
402
+ std::shared_ptr<Array>* out) {
403
+ std::vector<uint8_t> values;
404
+
405
+ // Seed is random in Arrow right now
406
+ (void)seed;
407
+
408
+ ::arrow::randint(size, 0, 1, &values);
409
+ std::vector<uint8_t> valid_bytes(size, 1);
410
+
411
+ for (size_t i = 0; i < num_nulls; i++) {
412
+ valid_bytes[i * 2] = 0;
413
+ }
414
+
415
+ ::arrow::BooleanBuilder builder;
416
+ RETURN_NOT_OK(builder.AppendValues(values.data(), values.size(), valid_bytes.data()));
417
+ return builder.Finish(out);
418
+ }
419
+
420
+ /// Wrap an Array into a ListArray by splitting it up into size lists.
421
+ ///
422
+ /// This helper function only supports (size/2) nulls.
423
+ Status MakeListArray(const std::shared_ptr<Array>& values, int64_t size,
424
+ int64_t null_count, const std::string& item_name,
425
+ bool nullable_values, std::shared_ptr<::arrow::ListArray>* out) {
426
+ // We always include an empty list
427
+ int64_t non_null_entries = size - null_count - 1;
428
+ int64_t length_per_entry = values->length() / non_null_entries;
429
+
430
+ auto offsets = AllocateBuffer();
431
+ RETURN_NOT_OK(offsets->Resize((size + 1) * sizeof(int32_t)));
432
+ int32_t* offsets_ptr = reinterpret_cast<int32_t*>(offsets->mutable_data());
433
+
434
+ auto null_bitmap = AllocateBuffer();
435
+ int64_t bitmap_size = ::arrow::bit_util::BytesForBits(size);
436
+ RETURN_NOT_OK(null_bitmap->Resize(bitmap_size));
437
+ uint8_t* null_bitmap_ptr = null_bitmap->mutable_data();
438
+ memset(null_bitmap_ptr, 0, bitmap_size);
439
+
440
+ int32_t current_offset = 0;
441
+ for (int64_t i = 0; i < size; i++) {
442
+ offsets_ptr[i] = current_offset;
443
+ if (!(((i % 2) == 0) && ((i / 2) < null_count))) {
444
+ // Non-null list (list with index 1 is always empty).
445
+ ::arrow::bit_util::SetBit(null_bitmap_ptr, i);
446
+ if (i != 1) {
447
+ current_offset += static_cast<int32_t>(length_per_entry);
448
+ }
449
+ }
450
+ }
451
+ offsets_ptr[size] = static_cast<int32_t>(values->length());
452
+
453
+ auto value_field = ::arrow::field(item_name, values->type(), nullable_values);
454
+ *out = std::make_shared<::arrow::ListArray>(::arrow::list(value_field), size, offsets,
455
+ values, null_bitmap, null_count);
456
+
457
+ return Status::OK();
458
+ }
459
+
460
+ // Make an array containing only empty lists, with a null values array
461
+ Status MakeEmptyListsArray(int64_t size, std::shared_ptr<Array>* out_array) {
462
+ // Allocate an offsets buffer containing only zeroes
463
+ const int64_t offsets_nbytes = (size + 1) * sizeof(int32_t);
464
+ ARROW_ASSIGN_OR_RAISE(auto offsets_buffer, ::arrow::AllocateBuffer(offsets_nbytes));
465
+ memset(offsets_buffer->mutable_data(), 0, offsets_nbytes);
466
+
467
+ auto value_field =
468
+ ::arrow::field("item", ::arrow::float64(), false /* nullable_values */);
469
+ auto list_type = ::arrow::list(value_field);
470
+
471
+ std::vector<std::shared_ptr<Buffer>> child_buffers = {nullptr /* null bitmap */,
472
+ nullptr /* values */};
473
+ auto child_data =
474
+ ::arrow::ArrayData::Make(value_field->type(), 0, std::move(child_buffers));
475
+
476
+ std::vector<std::shared_ptr<Buffer>> buffers = {nullptr /* bitmap */,
477
+ std::move(offsets_buffer)};
478
+ auto array_data = ::arrow::ArrayData::Make(list_type, size, std::move(buffers));
479
+ array_data->child_data.push_back(child_data);
480
+
481
+ *out_array = ::arrow::MakeArray(array_data);
482
+ return Status::OK();
483
+ }
484
+
485
+ std::shared_ptr<::arrow::Table> MakeSimpleTable(
486
+ const std::shared_ptr<ChunkedArray>& values, bool nullable) {
487
+ auto schema = ::arrow::schema({::arrow::field("col", values->type(), nullable)});
488
+ return ::arrow::Table::Make(schema, {values});
489
+ }
490
+
491
+ std::shared_ptr<::arrow::Table> MakeSimpleTable(const std::shared_ptr<Array>& values,
492
+ bool nullable) {
493
+ auto carr = std::make_shared<::arrow::ChunkedArray>(values);
494
+ return MakeSimpleTable(carr, nullable);
495
+ }
496
+
497
+ template <typename T>
498
+ void ExpectArray(T* expected, Array* result) {
499
+ auto p_array = static_cast<::arrow::PrimitiveArray*>(result);
500
+ for (int i = 0; i < result->length(); i++) {
501
+ EXPECT_EQ(expected[i], reinterpret_cast<const T*>(p_array->values()->data())[i]);
502
+ }
503
+ }
504
+
505
+ template <typename ArrowType>
506
+ void ExpectArrayT(void* expected, Array* result) {
507
+ ::arrow::PrimitiveArray* p_array = static_cast<::arrow::PrimitiveArray*>(result);
508
+ for (int64_t i = 0; i < result->length(); i++) {
509
+ EXPECT_EQ(reinterpret_cast<typename ArrowType::c_type*>(expected)[i],
510
+ reinterpret_cast<const typename ArrowType::c_type*>(
511
+ p_array->values()->data())[i]);
512
+ }
513
+ }
514
+
515
+ template <>
516
+ void ExpectArrayT<::arrow::BooleanType>(void* expected, Array* result) {
517
+ ::arrow::BooleanBuilder builder;
518
+ ARROW_EXPECT_OK(
519
+ builder.AppendValues(reinterpret_cast<uint8_t*>(expected), result->length()));
520
+
521
+ std::shared_ptr<Array> expected_array;
522
+ ARROW_EXPECT_OK(builder.Finish(&expected_array));
523
+ EXPECT_TRUE(result->Equals(*expected_array));
524
+ }
525
+
526
+ } // namespace arrow
527
+
528
+ } // namespace parquet
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/arrow/writer.h ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <memory>
22
+
23
+ #include "parquet/platform.h"
24
+ #include "parquet/properties.h"
25
+
26
+ namespace arrow {
27
+
28
+ class Array;
29
+ class ChunkedArray;
30
+ class RecordBatch;
31
+ class Schema;
32
+ class Table;
33
+
34
+ } // namespace arrow
35
+
36
+ namespace parquet {
37
+
38
+ class FileMetaData;
39
+ class ParquetFileWriter;
40
+
41
+ namespace arrow {
42
+
43
+ /// \brief Iterative FileWriter class
44
+ ///
45
+ /// For basic usage, can write a Table at a time, creating one or more row
46
+ /// groups per write call.
47
+ ///
48
+ /// For advanced usage, can write column-by-column: Start a new RowGroup or
49
+ /// Chunk with NewRowGroup, then write column-by-column the whole column chunk.
50
+ ///
51
+ /// If PARQUET:field_id is present as a metadata key on a field, and the corresponding
52
+ /// value is a nonnegative integer, then it will be used as the field_id in the parquet
53
+ /// file.
54
+ class PARQUET_EXPORT FileWriter {
55
+ public:
56
+ static ::arrow::Status Make(MemoryPool* pool, std::unique_ptr<ParquetFileWriter> writer,
57
+ std::shared_ptr<::arrow::Schema> schema,
58
+ std::shared_ptr<ArrowWriterProperties> arrow_properties,
59
+ std::unique_ptr<FileWriter>* out);
60
+
61
+ /// \brief Try to create an Arrow to Parquet file writer.
62
+ ///
63
+ /// \param schema schema of data that will be passed.
64
+ /// \param pool memory pool to use.
65
+ /// \param sink output stream to write Parquet data.
66
+ /// \param properties general Parquet writer properties.
67
+ /// \param arrow_properties Arrow-specific writer properties.
68
+ ///
69
+ /// \since 11.0.0
70
+ static ::arrow::Result<std::unique_ptr<FileWriter>> Open(
71
+ const ::arrow::Schema& schema, MemoryPool* pool,
72
+ std::shared_ptr<::arrow::io::OutputStream> sink,
73
+ std::shared_ptr<WriterProperties> properties = default_writer_properties(),
74
+ std::shared_ptr<ArrowWriterProperties> arrow_properties =
75
+ default_arrow_writer_properties());
76
+
77
+ /// Return the Arrow schema to be written to.
78
+ virtual std::shared_ptr<::arrow::Schema> schema() const = 0;
79
+
80
+ /// \brief Write a Table to Parquet.
81
+ ///
82
+ /// \param table Arrow table to write.
83
+ /// \param chunk_size maximum number of rows to write per row group.
84
+ virtual ::arrow::Status WriteTable(
85
+ const ::arrow::Table& table, int64_t chunk_size = DEFAULT_MAX_ROW_GROUP_LENGTH) = 0;
86
+
87
+ /// \brief Start a new row group.
88
+ ///
89
+ /// Returns an error if not all columns have been written.
90
+ ///
91
+ /// \param chunk_size the number of rows in the next row group.
92
+ virtual ::arrow::Status NewRowGroup(int64_t chunk_size) = 0;
93
+
94
+ /// \brief Write ColumnChunk in row group using an array.
95
+ virtual ::arrow::Status WriteColumnChunk(const ::arrow::Array& data) = 0;
96
+
97
+ /// \brief Write ColumnChunk in row group using slice of a ChunkedArray
98
+ virtual ::arrow::Status WriteColumnChunk(
99
+ const std::shared_ptr<::arrow::ChunkedArray>& data, int64_t offset,
100
+ int64_t size) = 0;
101
+
102
+ /// \brief Write ColumnChunk in a row group using a ChunkedArray
103
+ virtual ::arrow::Status WriteColumnChunk(
104
+ const std::shared_ptr<::arrow::ChunkedArray>& data) = 0;
105
+
106
+ /// \brief Start a new buffered row group.
107
+ ///
108
+ /// Returns an error if not all columns have been written.
109
+ virtual ::arrow::Status NewBufferedRowGroup() = 0;
110
+
111
+ /// \brief Write a RecordBatch into the buffered row group.
112
+ ///
113
+ /// Multiple RecordBatches can be written into the same row group
114
+ /// through this method.
115
+ ///
116
+ /// WriterProperties.max_row_group_length() is respected and a new
117
+ /// row group will be created if the current row group exceeds the
118
+ /// limit.
119
+ ///
120
+ /// Batches get flushed to the output stream once NewBufferedRowGroup()
121
+ /// or Close() is called.
122
+ ///
123
+ /// WARNING: If you are writing multiple files in parallel in the same
124
+ /// executor, deadlock may occur if ArrowWriterProperties::use_threads
125
+ /// is set to true to write columns in parallel. Please disable use_threads
126
+ /// option in this case.
127
+ virtual ::arrow::Status WriteRecordBatch(const ::arrow::RecordBatch& batch) = 0;
128
+
129
+ /// \brief Write the footer and close the file.
130
+ virtual ::arrow::Status Close() = 0;
131
+ virtual ~FileWriter();
132
+
133
+ virtual MemoryPool* memory_pool() const = 0;
134
+ /// \brief Add key-value metadata to the file.
135
+ /// \param[in] key_value_metadata the metadata to add.
136
+ /// \note This will overwrite any existing metadata with the same key.
137
+ /// \return Error if Close() has been called.
138
+ ///
139
+ /// WARNING: If `store_schema` is enabled, `ARROW:schema` would be stored
140
+ /// in the key-value metadata. Overwriting this key would result in
141
+ /// `store_schema` being unusable during read.
142
+ virtual ::arrow::Status AddKeyValueMetadata(
143
+ const std::shared_ptr<const ::arrow::KeyValueMetadata>& key_value_metadata) = 0;
144
+ /// \brief Return the file metadata, only available after calling Close().
145
+ virtual const std::shared_ptr<FileMetaData> metadata() const = 0;
146
+ };
147
+
148
+ /// \brief Write Parquet file metadata only to indicated Arrow OutputStream
149
+ PARQUET_EXPORT
150
+ ::arrow::Status WriteFileMetaData(const FileMetaData& file_metadata,
151
+ ::arrow::io::OutputStream* sink);
152
+
153
+ /// \brief Write metadata-only Parquet file to indicated Arrow OutputStream
154
+ PARQUET_EXPORT
155
+ ::arrow::Status WriteMetaDataFile(const FileMetaData& file_metadata,
156
+ ::arrow::io::OutputStream* sink);
157
+
158
+ /// \brief Write a Table to Parquet.
159
+ ///
160
+ /// This writes one table in a single shot. To write a Parquet file with
161
+ /// multiple tables iteratively, see parquet::arrow::FileWriter.
162
+ ///
163
+ /// \param table Table to write.
164
+ /// \param pool memory pool to use.
165
+ /// \param sink output stream to write Parquet data.
166
+ /// \param chunk_size maximum number of rows to write per row group.
167
+ /// \param properties general Parquet writer properties.
168
+ /// \param arrow_properties Arrow-specific writer properties.
169
+ ::arrow::Status PARQUET_EXPORT
170
+ WriteTable(const ::arrow::Table& table, MemoryPool* pool,
171
+ std::shared_ptr<::arrow::io::OutputStream> sink,
172
+ int64_t chunk_size = DEFAULT_MAX_ROW_GROUP_LENGTH,
173
+ std::shared_ptr<WriterProperties> properties = default_writer_properties(),
174
+ std::shared_ptr<ArrowWriterProperties> arrow_properties =
175
+ default_arrow_writer_properties());
176
+
177
+ } // namespace arrow
178
+ } // namespace parquet
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/benchmark_util.h ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <random>
21
+ #include <string>
22
+ #include <vector>
23
+
24
+ #include "parquet/types.h"
25
+
26
+ namespace parquet::benchmark {
27
+
28
+ template <typename T>
29
+ void GenerateBenchmarkData(uint32_t size, uint32_t seed, T* data,
30
+ std::vector<uint8_t>* heap, uint32_t data_string_length);
31
+
32
+ #define _GENERATE_BENCHMARK_DATA_DECL(KLASS) \
33
+ template <> \
34
+ void GenerateBenchmarkData(uint32_t size, uint32_t seed, KLASS* data, \
35
+ std::vector<uint8_t>* heap, uint32_t data_string_length);
36
+
37
+ _GENERATE_BENCHMARK_DATA_DECL(int32_t)
38
+ _GENERATE_BENCHMARK_DATA_DECL(int64_t)
39
+ _GENERATE_BENCHMARK_DATA_DECL(float)
40
+ _GENERATE_BENCHMARK_DATA_DECL(double)
41
+ _GENERATE_BENCHMARK_DATA_DECL(ByteArray)
42
+ _GENERATE_BENCHMARK_DATA_DECL(FLBA)
43
+ _GENERATE_BENCHMARK_DATA_DECL(Int96)
44
+
45
+ #undef _GENERATE_BENCHMARK_DATA_DECL
46
+
47
+ } // namespace parquet::benchmark
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/encoding.h ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <cstdint>
21
+ #include <cstring>
22
+ #include <memory>
23
+ #include <vector>
24
+
25
+ #include "arrow/type_fwd.h"
26
+
27
+ #include "parquet/exception.h"
28
+ #include "parquet/platform.h"
29
+ #include "parquet/types.h"
30
+
31
+ namespace arrow {
32
+ template <typename T>
33
+ class Dictionary32Builder;
34
+ }
35
+
36
+ namespace parquet {
37
+
38
+ template <typename DType>
39
+ class TypedEncoder;
40
+
41
+ using BooleanEncoder = TypedEncoder<BooleanType>;
42
+ using Int32Encoder = TypedEncoder<Int32Type>;
43
+ using Int64Encoder = TypedEncoder<Int64Type>;
44
+ using Int96Encoder = TypedEncoder<Int96Type>;
45
+ using FloatEncoder = TypedEncoder<FloatType>;
46
+ using DoubleEncoder = TypedEncoder<DoubleType>;
47
+ using ByteArrayEncoder = TypedEncoder<ByteArrayType>;
48
+ using FLBAEncoder = TypedEncoder<FLBAType>;
49
+
50
+ template <typename DType>
51
+ class TypedDecoder;
52
+
53
+ class BooleanDecoder;
54
+ using Int32Decoder = TypedDecoder<Int32Type>;
55
+ using Int64Decoder = TypedDecoder<Int64Type>;
56
+ using Int96Decoder = TypedDecoder<Int96Type>;
57
+ using FloatDecoder = TypedDecoder<FloatType>;
58
+ using DoubleDecoder = TypedDecoder<DoubleType>;
59
+ using ByteArrayDecoder = TypedDecoder<ByteArrayType>;
60
+ class FLBADecoder;
61
+
62
+ template <typename T>
63
+ struct EncodingTraits;
64
+
65
+ template <>
66
+ struct EncodingTraits<BooleanType> {
67
+ using Encoder = BooleanEncoder;
68
+ using Decoder = BooleanDecoder;
69
+
70
+ using ArrowType = ::arrow::BooleanType;
71
+ using Accumulator = ::arrow::BooleanBuilder;
72
+ struct DictAccumulator {};
73
+ };
74
+
75
+ template <>
76
+ struct EncodingTraits<Int32Type> {
77
+ using Encoder = Int32Encoder;
78
+ using Decoder = Int32Decoder;
79
+
80
+ using ArrowType = ::arrow::Int32Type;
81
+ using Accumulator = ::arrow::NumericBuilder<::arrow::Int32Type>;
82
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::Int32Type>;
83
+ };
84
+
85
+ template <>
86
+ struct EncodingTraits<Int64Type> {
87
+ using Encoder = Int64Encoder;
88
+ using Decoder = Int64Decoder;
89
+
90
+ using ArrowType = ::arrow::Int64Type;
91
+ using Accumulator = ::arrow::NumericBuilder<::arrow::Int64Type>;
92
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::Int64Type>;
93
+ };
94
+
95
+ template <>
96
+ struct EncodingTraits<Int96Type> {
97
+ using Encoder = Int96Encoder;
98
+ using Decoder = Int96Decoder;
99
+
100
+ struct Accumulator {};
101
+ struct DictAccumulator {};
102
+ };
103
+
104
+ template <>
105
+ struct EncodingTraits<FloatType> {
106
+ using Encoder = FloatEncoder;
107
+ using Decoder = FloatDecoder;
108
+
109
+ using ArrowType = ::arrow::FloatType;
110
+ using Accumulator = ::arrow::NumericBuilder<::arrow::FloatType>;
111
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::FloatType>;
112
+ };
113
+
114
+ template <>
115
+ struct EncodingTraits<DoubleType> {
116
+ using Encoder = DoubleEncoder;
117
+ using Decoder = DoubleDecoder;
118
+
119
+ using ArrowType = ::arrow::DoubleType;
120
+ using Accumulator = ::arrow::NumericBuilder<::arrow::DoubleType>;
121
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::DoubleType>;
122
+ };
123
+
124
+ template <>
125
+ struct EncodingTraits<ByteArrayType> {
126
+ using Encoder = ByteArrayEncoder;
127
+ using Decoder = ByteArrayDecoder;
128
+
129
+ using ArrowType = ::arrow::BinaryType;
130
+ /// \brief Internal helper class for decoding BYTE_ARRAY data where we can
131
+ /// overflow the capacity of a single arrow::BinaryArray
132
+ struct Accumulator {
133
+ std::unique_ptr<::arrow::BinaryBuilder> builder;
134
+ std::vector<std::shared_ptr<::arrow::Array>> chunks;
135
+ };
136
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::BinaryType>;
137
+ };
138
+
139
+ template <>
140
+ struct EncodingTraits<FLBAType> {
141
+ using Encoder = FLBAEncoder;
142
+ using Decoder = FLBADecoder;
143
+
144
+ using ArrowType = ::arrow::FixedSizeBinaryType;
145
+ using Accumulator = ::arrow::FixedSizeBinaryBuilder;
146
+ using DictAccumulator = ::arrow::Dictionary32Builder<::arrow::FixedSizeBinaryType>;
147
+ };
148
+
149
+ class ColumnDescriptor;
150
+
151
+ // Untyped base for all encoders
152
+ class Encoder {
153
+ public:
154
+ virtual ~Encoder() = default;
155
+
156
+ virtual int64_t EstimatedDataEncodedSize() = 0;
157
+ virtual std::shared_ptr<Buffer> FlushValues() = 0;
158
+ virtual Encoding::type encoding() const = 0;
159
+
160
+ virtual void Put(const ::arrow::Array& values) = 0;
161
+
162
+ virtual MemoryPool* memory_pool() const = 0;
163
+ };
164
+
165
+ // Base class for value encoders. Since encoders may or not have state (e.g.,
166
+ // dictionary encoding) we use a class instance to maintain any state.
167
+ //
168
+ // Encode interfaces are internal, subject to change without deprecation.
169
+ template <typename DType>
170
+ class TypedEncoder : virtual public Encoder {
171
+ public:
172
+ using T = typename DType::c_type;
173
+
174
+ using Encoder::Put;
175
+
176
+ virtual void Put(const T* src, int num_values) = 0;
177
+
178
+ virtual void Put(const std::vector<T>& src, int num_values = -1);
179
+
180
+ virtual void PutSpaced(const T* src, int num_values, const uint8_t* valid_bits,
181
+ int64_t valid_bits_offset) = 0;
182
+ };
183
+
184
+ template <typename DType>
185
+ void TypedEncoder<DType>::Put(const std::vector<T>& src, int num_values) {
186
+ if (num_values == -1) {
187
+ num_values = static_cast<int>(src.size());
188
+ }
189
+ Put(src.data(), num_values);
190
+ }
191
+
192
+ template <>
193
+ inline void TypedEncoder<BooleanType>::Put(const std::vector<bool>& src, int num_values) {
194
+ // NOTE(wesm): This stub is here only to satisfy the compiler; it is
195
+ // overridden later with the actual implementation
196
+ }
197
+
198
+ // Base class for dictionary encoders
199
+ template <typename DType>
200
+ class DictEncoder : virtual public TypedEncoder<DType> {
201
+ public:
202
+ /// Writes out any buffered indices to buffer preceded by the bit width of this data.
203
+ /// Returns the number of bytes written.
204
+ /// If the supplied buffer is not big enough, returns -1.
205
+ /// buffer must be preallocated with buffer_len bytes. Use EstimatedDataEncodedSize()
206
+ /// to size buffer.
207
+ virtual int WriteIndices(uint8_t* buffer, int buffer_len) = 0;
208
+
209
+ virtual int dict_encoded_size() const = 0;
210
+
211
+ virtual int bit_width() const = 0;
212
+
213
+ /// Writes out the encoded dictionary to buffer. buffer must be preallocated to
214
+ /// dict_encoded_size() bytes.
215
+ virtual void WriteDict(uint8_t* buffer) const = 0;
216
+
217
+ virtual int num_entries() const = 0;
218
+
219
+ /// \brief EXPERIMENTAL: Append dictionary indices into the encoder. It is
220
+ /// assumed (without any boundschecking) that the indices reference
221
+ /// preexisting dictionary values
222
+ /// \param[in] indices the dictionary index values. Only Int32Array currently
223
+ /// supported
224
+ virtual void PutIndices(const ::arrow::Array& indices) = 0;
225
+
226
+ /// \brief EXPERIMENTAL: Append dictionary into encoder, inserting indices
227
+ /// separately. Currently throws exception if the current dictionary memo is
228
+ /// non-empty
229
+ /// \param[in] values the dictionary values. Only valid for certain
230
+ /// Parquet/Arrow type combinations, like BYTE_ARRAY/BinaryArray
231
+ virtual void PutDictionary(const ::arrow::Array& values) = 0;
232
+ };
233
+
234
+ // ----------------------------------------------------------------------
235
+ // Value decoding
236
+
237
+ class Decoder {
238
+ public:
239
+ virtual ~Decoder() = default;
240
+
241
+ // Sets the data for a new page. This will be called multiple times on the same
242
+ // decoder and should reset all internal state.
243
+ //
244
+ // `num_values` comes from the data page header, and may be greater than the number of
245
+ // physical values in the data buffer if there are some omitted (null) values.
246
+ // `len`, on the other hand, is the size in bytes of the data buffer and
247
+ // directly relates to the number of physical values.
248
+ virtual void SetData(int num_values, const uint8_t* data, int len) = 0;
249
+
250
+ // Returns the number of values left (for the last call to SetData()). This is
251
+ // the number of values left in this page.
252
+ virtual int values_left() const = 0;
253
+ virtual Encoding::type encoding() const = 0;
254
+ };
255
+
256
+ template <typename DType>
257
+ class TypedDecoder : virtual public Decoder {
258
+ public:
259
+ using T = typename DType::c_type;
260
+
261
+ /// \brief Decode values into a buffer
262
+ ///
263
+ /// Subclasses may override the more specialized Decode methods below.
264
+ ///
265
+ /// \param[in] buffer destination for decoded values
266
+ /// \param[in] max_values maximum number of values to decode
267
+ /// \return The number of values decoded. Should be identical to max_values except
268
+ /// at the end of the current data page.
269
+ virtual int Decode(T* buffer, int max_values) = 0;
270
+
271
+ /// \brief Decode the values in this data page but leave spaces for null entries.
272
+ ///
273
+ /// \param[in] buffer destination for decoded values
274
+ /// \param[in] num_values size of the def_levels and buffer arrays including the number
275
+ /// of null slots
276
+ /// \param[in] null_count number of null slots
277
+ /// \param[in] valid_bits bitmap data indicating position of valid slots
278
+ /// \param[in] valid_bits_offset offset into valid_bits
279
+ /// \return The number of values decoded, including nulls.
280
+ virtual int DecodeSpaced(T* buffer, int num_values, int null_count,
281
+ const uint8_t* valid_bits, int64_t valid_bits_offset) = 0;
282
+
283
+ /// \brief Decode into an ArrayBuilder or other accumulator
284
+ ///
285
+ /// This function assumes the definition levels were already decoded
286
+ /// as a validity bitmap in the given `valid_bits`. `null_count`
287
+ /// is the number of 0s in `valid_bits`.
288
+ /// As a space optimization, it is allowed for `valid_bits` to be null
289
+ /// if `null_count` is zero.
290
+ ///
291
+ /// \return number of values decoded
292
+ virtual int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
293
+ int64_t valid_bits_offset,
294
+ typename EncodingTraits<DType>::Accumulator* out) = 0;
295
+
296
+ /// \brief Decode into an ArrayBuilder or other accumulator ignoring nulls
297
+ ///
298
+ /// \return number of values decoded
299
+ int DecodeArrowNonNull(int num_values,
300
+ typename EncodingTraits<DType>::Accumulator* out) {
301
+ return DecodeArrow(num_values, 0, /*valid_bits=*/NULLPTR, 0, out);
302
+ }
303
+
304
+ /// \brief Decode into a DictionaryBuilder
305
+ ///
306
+ /// This function assumes the definition levels were already decoded
307
+ /// as a validity bitmap in the given `valid_bits`. `null_count`
308
+ /// is the number of 0s in `valid_bits`.
309
+ /// As a space optimization, it is allowed for `valid_bits` to be null
310
+ /// if `null_count` is zero.
311
+ ///
312
+ /// \return number of values decoded
313
+ virtual int DecodeArrow(int num_values, int null_count, const uint8_t* valid_bits,
314
+ int64_t valid_bits_offset,
315
+ typename EncodingTraits<DType>::DictAccumulator* builder) = 0;
316
+
317
+ /// \brief Decode into a DictionaryBuilder ignoring nulls
318
+ ///
319
+ /// \return number of values decoded
320
+ int DecodeArrowNonNull(int num_values,
321
+ typename EncodingTraits<DType>::DictAccumulator* builder) {
322
+ return DecodeArrow(num_values, 0, /*valid_bits=*/NULLPTR, 0, builder);
323
+ }
324
+ };
325
+
326
+ template <typename DType>
327
+ class DictDecoder : virtual public TypedDecoder<DType> {
328
+ public:
329
+ using T = typename DType::c_type;
330
+
331
+ virtual void SetDict(TypedDecoder<DType>* dictionary) = 0;
332
+
333
+ /// \brief Insert dictionary values into the Arrow dictionary builder's memo,
334
+ /// but do not append any indices
335
+ virtual void InsertDictionary(::arrow::ArrayBuilder* builder) = 0;
336
+
337
+ /// \brief Decode only dictionary indices and append to dictionary
338
+ /// builder. The builder must have had the dictionary from this decoder
339
+ /// inserted already.
340
+ ///
341
+ /// \warning Remember to reset the builder each time the dict decoder is initialized
342
+ /// with a new dictionary page
343
+ virtual int DecodeIndicesSpaced(int num_values, int null_count,
344
+ const uint8_t* valid_bits, int64_t valid_bits_offset,
345
+ ::arrow::ArrayBuilder* builder) = 0;
346
+
347
+ /// \brief Decode only dictionary indices (no nulls)
348
+ ///
349
+ /// \warning Remember to reset the builder each time the dict decoder is initialized
350
+ /// with a new dictionary page
351
+ virtual int DecodeIndices(int num_values, ::arrow::ArrayBuilder* builder) = 0;
352
+
353
+ /// \brief Decode only dictionary indices (no nulls). Same as above
354
+ /// DecodeIndices but target is an array instead of a builder.
355
+ ///
356
+ /// \note API EXPERIMENTAL
357
+ virtual int DecodeIndices(int num_values, int32_t* indices) = 0;
358
+
359
+ /// \brief Get dictionary. The reader will call this API when it encounters a
360
+ /// new dictionary.
361
+ ///
362
+ /// @param[out] dictionary The pointer to dictionary values. Dictionary is owned by
363
+ /// the decoder and is destroyed when the decoder is destroyed.
364
+ /// @param[out] dictionary_length The dictionary length.
365
+ ///
366
+ /// \note API EXPERIMENTAL
367
+ virtual void GetDictionary(const T** dictionary, int32_t* dictionary_length) = 0;
368
+ };
369
+
370
+ // ----------------------------------------------------------------------
371
+ // TypedEncoder specializations, traits, and factory functions
372
+
373
+ class BooleanDecoder : virtual public TypedDecoder<BooleanType> {
374
+ public:
375
+ using TypedDecoder<BooleanType>::Decode;
376
+
377
+ /// \brief Decode and bit-pack values into a buffer
378
+ ///
379
+ /// \param[in] buffer destination for decoded values
380
+ /// This buffer will contain bit-packed values. If
381
+ /// max_values is not a multiple of 8, the trailing bits
382
+ /// of the last byte will be undefined.
383
+ /// \param[in] max_values max values to decode.
384
+ /// \return The number of values decoded. Should be identical to max_values except
385
+ /// at the end of the current data page.
386
+ virtual int Decode(uint8_t* buffer, int max_values) = 0;
387
+ };
388
+
389
+ class FLBADecoder : virtual public TypedDecoder<FLBAType> {
390
+ public:
391
+ using TypedDecoder<FLBAType>::DecodeSpaced;
392
+
393
+ // TODO(wesm): As possible follow-up to PARQUET-1508, we should examine if
394
+ // there is value in adding specialized read methods for
395
+ // FIXED_LEN_BYTE_ARRAY. If only Decimal data can occur with this data type
396
+ // then perhaps not
397
+ };
398
+
399
+ PARQUET_EXPORT
400
+ std::unique_ptr<Encoder> MakeEncoder(
401
+ Type::type type_num, Encoding::type encoding, bool use_dictionary = false,
402
+ const ColumnDescriptor* descr = NULLPTR,
403
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
404
+
405
+ template <typename DType>
406
+ std::unique_ptr<typename EncodingTraits<DType>::Encoder> MakeTypedEncoder(
407
+ Encoding::type encoding, bool use_dictionary = false,
408
+ const ColumnDescriptor* descr = NULLPTR,
409
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) {
410
+ using OutType = typename EncodingTraits<DType>::Encoder;
411
+ std::unique_ptr<Encoder> base =
412
+ MakeEncoder(DType::type_num, encoding, use_dictionary, descr, pool);
413
+ return std::unique_ptr<OutType>(dynamic_cast<OutType*>(base.release()));
414
+ }
415
+
416
+ PARQUET_EXPORT
417
+ std::unique_ptr<Decoder> MakeDecoder(
418
+ Type::type type_num, Encoding::type encoding, const ColumnDescriptor* descr = NULLPTR,
419
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool());
420
+
421
+ namespace detail {
422
+
423
+ PARQUET_EXPORT
424
+ std::unique_ptr<Decoder> MakeDictDecoder(Type::type type_num,
425
+ const ColumnDescriptor* descr,
426
+ ::arrow::MemoryPool* pool);
427
+
428
+ } // namespace detail
429
+
430
+ template <typename DType>
431
+ std::unique_ptr<DictDecoder<DType>> MakeDictDecoder(
432
+ const ColumnDescriptor* descr = NULLPTR,
433
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) {
434
+ using OutType = DictDecoder<DType>;
435
+ auto decoder = detail::MakeDictDecoder(DType::type_num, descr, pool);
436
+ return std::unique_ptr<OutType>(dynamic_cast<OutType*>(decoder.release()));
437
+ }
438
+
439
+ template <typename DType>
440
+ std::unique_ptr<typename EncodingTraits<DType>::Decoder> MakeTypedDecoder(
441
+ Encoding::type encoding, const ColumnDescriptor* descr = NULLPTR,
442
+ ::arrow::MemoryPool* pool = ::arrow::default_memory_pool()) {
443
+ using OutType = typename EncodingTraits<DType>::Decoder;
444
+ std::unique_ptr<Decoder> base = MakeDecoder(DType::type_num, encoding, descr, pool);
445
+ return std::unique_ptr<OutType>(dynamic_cast<OutType*>(base.release()));
446
+ }
447
+
448
+ } // namespace parquet
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/crypto_factory.h ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <memory>
21
+
22
+ #include "parquet/encryption/encryption.h"
23
+ #include "parquet/encryption/file_key_wrapper.h"
24
+ #include "parquet/encryption/key_toolkit.h"
25
+ #include "parquet/encryption/kms_client_factory.h"
26
+ #include "parquet/platform.h"
27
+
28
+ namespace parquet::encryption {
29
+
30
+ static constexpr ParquetCipher::type kDefaultEncryptionAlgorithm =
31
+ ParquetCipher::AES_GCM_V1;
32
+ static constexpr bool kDefaultPlaintextFooter = false;
33
+ static constexpr bool kDefaultDoubleWrapping = true;
34
+ static constexpr double kDefaultCacheLifetimeSeconds = 600; // 10 minutes
35
+ static constexpr bool kDefaultInternalKeyMaterial = true;
36
+ static constexpr bool kDefaultUniformEncryption = false;
37
+ static constexpr int32_t kDefaultDataKeyLengthBits = 128;
38
+
39
+ struct PARQUET_EXPORT EncryptionConfiguration {
40
+ explicit EncryptionConfiguration(const std::string& footer_key)
41
+ : footer_key(footer_key) {}
42
+
43
+ /// ID of the master key for footer encryption/signing
44
+ std::string footer_key;
45
+
46
+ /// List of columns to encrypt, with master key IDs (see HIVE-21848).
47
+ /// Format: "masterKeyID:colName,colName;masterKeyID:colName..."
48
+ /// Either
49
+ /// (1) column_keys must be set
50
+ /// or
51
+ /// (2) uniform_encryption must be set to true
52
+ /// If none of (1) and (2) are true, or if both are true, an exception will be
53
+ /// thrown.
54
+ std::string column_keys;
55
+
56
+ /// Encrypt footer and all columns with the same encryption key.
57
+ bool uniform_encryption = kDefaultUniformEncryption;
58
+
59
+ /// Parquet encryption algorithm. Can be "AES_GCM_V1" (default), or "AES_GCM_CTR_V1".
60
+ ParquetCipher::type encryption_algorithm = kDefaultEncryptionAlgorithm;
61
+
62
+ /// Write files with plaintext footer.
63
+ /// The default is false - files are written with encrypted footer.
64
+ bool plaintext_footer = kDefaultPlaintextFooter;
65
+
66
+ /// Use double wrapping - where data encryption keys (DEKs) are encrypted with key
67
+ /// encryption keys (KEKs), which in turn are encrypted with master keys.
68
+ /// The default is true. If set to false, use single wrapping - where DEKs are
69
+ /// encrypted directly with master keys.
70
+ bool double_wrapping = kDefaultDoubleWrapping;
71
+
72
+ /// Lifetime of cached entities (key encryption keys, local wrapping keys, KMS client
73
+ /// objects).
74
+ /// The default is 600 (10 minutes).
75
+ double cache_lifetime_seconds = kDefaultCacheLifetimeSeconds;
76
+
77
+ /// Store key material inside Parquet file footers; this mode doesn’t produce
78
+ /// additional files. By default, true. If set to false, key material is stored in
79
+ /// separate files in the same folder, which enables key rotation for immutable
80
+ /// Parquet files.
81
+ bool internal_key_material = kDefaultInternalKeyMaterial;
82
+
83
+ /// Length of data encryption keys (DEKs), randomly generated by parquet key
84
+ /// management tools. Can be 128, 192 or 256 bits.
85
+ /// The default is 128 bits.
86
+ int32_t data_key_length_bits = kDefaultDataKeyLengthBits;
87
+ };
88
+
89
+ struct PARQUET_EXPORT DecryptionConfiguration {
90
+ /// Lifetime of cached entities (key encryption keys, local wrapping keys, KMS client
91
+ /// objects).
92
+ /// The default is 600 (10 minutes).
93
+ double cache_lifetime_seconds = kDefaultCacheLifetimeSeconds;
94
+ };
95
+
96
+ /// This is a core class, that translates the parameters of high level encryption (like
97
+ /// the names of encrypted columns, names of master keys, etc), into parameters of low
98
+ /// level encryption (like the key metadata, DEK, etc). A factory that produces the low
99
+ /// level FileEncryptionProperties and FileDecryptionProperties objects, from the high
100
+ /// level parameters.
101
+ class PARQUET_EXPORT CryptoFactory {
102
+ public:
103
+ /// a KmsClientFactory object must be registered via this method before calling any of
104
+ /// GetFileEncryptionProperties()/GetFileDecryptionProperties() methods.
105
+ void RegisterKmsClientFactory(std::shared_ptr<KmsClientFactory> kms_client_factory);
106
+
107
+ /// Get the encryption properties for a Parquet file.
108
+ /// If external key material is used then a file system and path to the
109
+ /// parquet file must be provided.
110
+ std::shared_ptr<FileEncryptionProperties> GetFileEncryptionProperties(
111
+ const KmsConnectionConfig& kms_connection_config,
112
+ const EncryptionConfiguration& encryption_config, const std::string& file_path = "",
113
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system = NULLPTR);
114
+
115
+ /// Get decryption properties for a Parquet file.
116
+ /// If external key material is used then a file system and path to the
117
+ /// parquet file must be provided.
118
+ std::shared_ptr<FileDecryptionProperties> GetFileDecryptionProperties(
119
+ const KmsConnectionConfig& kms_connection_config,
120
+ const DecryptionConfiguration& decryption_config, const std::string& file_path = "",
121
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system = NULLPTR);
122
+
123
+ void RemoveCacheEntriesForToken(const std::string& access_token) {
124
+ key_toolkit_->RemoveCacheEntriesForToken(access_token);
125
+ }
126
+
127
+ void RemoveCacheEntriesForAllTokens() {
128
+ key_toolkit_->RemoveCacheEntriesForAllTokens();
129
+ }
130
+
131
+ /// Rotates master encryption keys for a Parquet file that uses external key material.
132
+ /// In single wrapping mode, data encryption keys are decrypted with the old master keys
133
+ /// and then re-encrypted with new master keys.
134
+ /// In double wrapping mode, key encryption keys are decrypted with the old master keys
135
+ /// and then re-encrypted with new master keys.
136
+ /// This relies on the KMS supporting versioning, such that the old master key is
137
+ /// used when unwrapping a key, and the latest version is used when wrapping a key.
138
+ void RotateMasterKeys(const KmsConnectionConfig& kms_connection_config,
139
+ const std::string& parquet_file_path,
140
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system,
141
+ bool double_wrapping = kDefaultDoubleWrapping,
142
+ double cache_lifetime_seconds = kDefaultCacheLifetimeSeconds);
143
+
144
+ private:
145
+ ColumnPathToEncryptionPropertiesMap GetColumnEncryptionProperties(
146
+ int dek_length, const std::string& column_keys, FileKeyWrapper* key_wrapper);
147
+
148
+ /// Key utilities object for kms client initialization and cache control
149
+ std::shared_ptr<KeyToolkit> key_toolkit_ = std::make_shared<KeyToolkit>();
150
+ };
151
+
152
+ } // namespace parquet::encryption
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/encryption.h ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <map>
21
+ #include <memory>
22
+ #include <string>
23
+ #include <utility>
24
+
25
+ #include "parquet/exception.h"
26
+ #include "parquet/schema.h"
27
+ #include "parquet/types.h"
28
+
29
+ namespace parquet {
30
+
31
+ static constexpr ParquetCipher::type kDefaultEncryptionAlgorithm =
32
+ ParquetCipher::AES_GCM_V1;
33
+ static constexpr int32_t kMaximalAadMetadataLength = 256;
34
+ static constexpr bool kDefaultEncryptedFooter = true;
35
+ static constexpr bool kDefaultCheckSignature = true;
36
+ static constexpr bool kDefaultAllowPlaintextFiles = false;
37
+ static constexpr int32_t kAadFileUniqueLength = 8;
38
+
39
+ class ColumnDecryptionProperties;
40
+ using ColumnPathToDecryptionPropertiesMap =
41
+ std::map<std::string, std::shared_ptr<ColumnDecryptionProperties>>;
42
+
43
+ class ColumnEncryptionProperties;
44
+ using ColumnPathToEncryptionPropertiesMap =
45
+ std::map<std::string, std::shared_ptr<ColumnEncryptionProperties>>;
46
+
47
+ class PARQUET_EXPORT DecryptionKeyRetriever {
48
+ public:
49
+ virtual std::string GetKey(const std::string& key_metadata) = 0;
50
+ virtual ~DecryptionKeyRetriever() {}
51
+ };
52
+
53
+ /// Simple integer key retriever
54
+ class PARQUET_EXPORT IntegerKeyIdRetriever : public DecryptionKeyRetriever {
55
+ public:
56
+ void PutKey(uint32_t key_id, const std::string& key);
57
+ std::string GetKey(const std::string& key_metadata) override;
58
+
59
+ private:
60
+ std::map<uint32_t, std::string> key_map_;
61
+ };
62
+
63
+ // Simple string key retriever
64
+ class PARQUET_EXPORT StringKeyIdRetriever : public DecryptionKeyRetriever {
65
+ public:
66
+ void PutKey(const std::string& key_id, const std::string& key);
67
+ std::string GetKey(const std::string& key_metadata) override;
68
+
69
+ private:
70
+ std::map<std::string, std::string> key_map_;
71
+ };
72
+
73
+ class PARQUET_EXPORT HiddenColumnException : public ParquetException {
74
+ public:
75
+ explicit HiddenColumnException(const std::string& columnPath)
76
+ : ParquetException(columnPath.c_str()) {}
77
+ };
78
+
79
+ class PARQUET_EXPORT KeyAccessDeniedException : public ParquetException {
80
+ public:
81
+ explicit KeyAccessDeniedException(const std::string& columnPath)
82
+ : ParquetException(columnPath.c_str()) {}
83
+ };
84
+
85
+ inline const uint8_t* str2bytes(const std::string& str) {
86
+ if (str.empty()) return NULLPTR;
87
+
88
+ char* cbytes = const_cast<char*>(str.c_str());
89
+ return reinterpret_cast<const uint8_t*>(cbytes);
90
+ }
91
+
92
+ inline ::arrow::util::span<const uint8_t> str2span(const std::string& str) {
93
+ if (str.empty()) {
94
+ return {};
95
+ }
96
+
97
+ return {reinterpret_cast<const uint8_t*>(str.data()), str.size()};
98
+ }
99
+
100
+ class PARQUET_EXPORT ColumnEncryptionProperties {
101
+ public:
102
+ class PARQUET_EXPORT Builder {
103
+ public:
104
+ /// Convenience builder for encrypted columns.
105
+ explicit Builder(const std::string& name) : Builder(name, true) {}
106
+
107
+ /// Convenience builder for encrypted columns.
108
+ explicit Builder(const std::shared_ptr<schema::ColumnPath>& path)
109
+ : Builder(path->ToDotString(), true) {}
110
+
111
+ /// Set a column-specific key.
112
+ /// If key is not set on an encrypted column, the column will
113
+ /// be encrypted with the footer key.
114
+ /// keyBytes Key length must be either 16, 24 or 32 bytes.
115
+ /// The key is cloned, and will be wiped out (array values set to 0) upon completion
116
+ /// of file writing.
117
+ /// Caller is responsible for wiping out the input key array.
118
+ Builder* key(std::string column_key);
119
+
120
+ /// Set a key retrieval metadata.
121
+ /// use either key_metadata() or key_id(), not both
122
+ Builder* key_metadata(const std::string& key_metadata);
123
+
124
+ /// A convenience function to set key metadata using a string id.
125
+ /// Set a key retrieval metadata (converted from String).
126
+ /// use either key_metadata() or key_id(), not both
127
+ /// key_id will be converted to metadata (UTF-8 array).
128
+ Builder* key_id(const std::string& key_id);
129
+
130
+ std::shared_ptr<ColumnEncryptionProperties> build() {
131
+ return std::shared_ptr<ColumnEncryptionProperties>(
132
+ new ColumnEncryptionProperties(encrypted_, column_path_, key_, key_metadata_));
133
+ }
134
+
135
+ private:
136
+ const std::string column_path_;
137
+ bool encrypted_;
138
+ std::string key_;
139
+ std::string key_metadata_;
140
+
141
+ Builder(const std::string path, bool encrypted)
142
+ : column_path_(path), encrypted_(encrypted) {}
143
+ };
144
+
145
+ std::string column_path() const { return column_path_; }
146
+ bool is_encrypted() const { return encrypted_; }
147
+ bool is_encrypted_with_footer_key() const { return encrypted_with_footer_key_; }
148
+ std::string key() const { return key_; }
149
+ std::string key_metadata() const { return key_metadata_; }
150
+
151
+ /// Upon completion of file writing, the encryption key
152
+ /// will be wiped out.
153
+ void WipeOutEncryptionKey() { key_.clear(); }
154
+
155
+ bool is_utilized() {
156
+ if (key_.empty())
157
+ return false; // can re-use column properties without encryption keys
158
+ return utilized_;
159
+ }
160
+
161
+ /// ColumnEncryptionProperties object can be used for writing one file only.
162
+ /// Mark ColumnEncryptionProperties as utilized once it is used in
163
+ /// FileEncryptionProperties as the encryption key will be wiped out upon
164
+ /// completion of file writing.
165
+ void set_utilized() { utilized_ = true; }
166
+
167
+ std::shared_ptr<ColumnEncryptionProperties> DeepClone() {
168
+ std::string key_copy = key_;
169
+ return std::shared_ptr<ColumnEncryptionProperties>(new ColumnEncryptionProperties(
170
+ encrypted_, column_path_, key_copy, key_metadata_));
171
+ }
172
+
173
+ ColumnEncryptionProperties() = default;
174
+ ColumnEncryptionProperties(const ColumnEncryptionProperties& other) = default;
175
+ ColumnEncryptionProperties(ColumnEncryptionProperties&& other) = default;
176
+
177
+ private:
178
+ const std::string column_path_;
179
+ bool encrypted_;
180
+ bool encrypted_with_footer_key_;
181
+ std::string key_;
182
+ std::string key_metadata_;
183
+ bool utilized_;
184
+ explicit ColumnEncryptionProperties(bool encrypted, const std::string& column_path,
185
+ const std::string& key,
186
+ const std::string& key_metadata);
187
+ };
188
+
189
+ class PARQUET_EXPORT ColumnDecryptionProperties {
190
+ public:
191
+ class PARQUET_EXPORT Builder {
192
+ public:
193
+ explicit Builder(const std::string& name) : column_path_(name) {}
194
+
195
+ explicit Builder(const std::shared_ptr<schema::ColumnPath>& path)
196
+ : Builder(path->ToDotString()) {}
197
+
198
+ /// Set an explicit column key. If applied on a file that contains
199
+ /// key metadata for this column the metadata will be ignored,
200
+ /// the column will be decrypted with this key.
201
+ /// key length must be either 16, 24 or 32 bytes.
202
+ Builder* key(const std::string& key);
203
+
204
+ std::shared_ptr<ColumnDecryptionProperties> build();
205
+
206
+ private:
207
+ const std::string column_path_;
208
+ std::string key_;
209
+ };
210
+
211
+ ColumnDecryptionProperties() = default;
212
+ ColumnDecryptionProperties(const ColumnDecryptionProperties& other) = default;
213
+ ColumnDecryptionProperties(ColumnDecryptionProperties&& other) = default;
214
+
215
+ std::string column_path() const { return column_path_; }
216
+ std::string key() const { return key_; }
217
+ bool is_utilized() { return utilized_; }
218
+
219
+ /// ColumnDecryptionProperties object can be used for reading one file only.
220
+ /// Mark ColumnDecryptionProperties as utilized once it is used in
221
+ /// FileDecryptionProperties as the encryption key will be wiped out upon
222
+ /// completion of file reading.
223
+ void set_utilized() { utilized_ = true; }
224
+
225
+ /// Upon completion of file reading, the encryption key
226
+ /// will be wiped out.
227
+ void WipeOutDecryptionKey();
228
+
229
+ std::shared_ptr<ColumnDecryptionProperties> DeepClone();
230
+
231
+ private:
232
+ const std::string column_path_;
233
+ std::string key_;
234
+ bool utilized_;
235
+
236
+ /// This class is only required for setting explicit column decryption keys -
237
+ /// to override key retriever (or to provide keys when key metadata and/or
238
+ /// key retriever are not available)
239
+ explicit ColumnDecryptionProperties(const std::string& column_path,
240
+ const std::string& key);
241
+ };
242
+
243
+ class PARQUET_EXPORT AADPrefixVerifier {
244
+ public:
245
+ /// Verifies identity (AAD Prefix) of individual file,
246
+ /// or of file collection in a data set.
247
+ /// Throws exception if an AAD prefix is wrong.
248
+ /// In a data set, AAD Prefixes should be collected,
249
+ /// and then checked for missing files.
250
+ virtual void Verify(const std::string& aad_prefix) = 0;
251
+ virtual ~AADPrefixVerifier() {}
252
+ };
253
+
254
+ class PARQUET_EXPORT FileDecryptionProperties {
255
+ public:
256
+ class PARQUET_EXPORT Builder {
257
+ public:
258
+ Builder() {
259
+ check_plaintext_footer_integrity_ = kDefaultCheckSignature;
260
+ plaintext_files_allowed_ = kDefaultAllowPlaintextFiles;
261
+ }
262
+
263
+ /// Set an explicit footer key. If applied on a file that contains
264
+ /// footer key metadata the metadata will be ignored, the footer
265
+ /// will be decrypted/verified with this key.
266
+ /// If explicit key is not set, footer key will be fetched from
267
+ /// key retriever.
268
+ /// With explicit keys or AAD prefix, new encryption properties object must be
269
+ /// created for each encrypted file.
270
+ /// Explicit encryption keys (footer and column) are cloned.
271
+ /// Upon completion of file reading, the cloned encryption keys in the properties
272
+ /// will be wiped out (array values set to 0).
273
+ /// Caller is responsible for wiping out the input key array.
274
+ /// param footerKey Key length must be either 16, 24 or 32 bytes.
275
+ Builder* footer_key(const std::string footer_key);
276
+
277
+ /// Set explicit column keys (decryption properties).
278
+ /// Its also possible to set a key retriever on this property object.
279
+ /// Upon file decryption, availability of explicit keys is checked before
280
+ /// invocation of the retriever callback.
281
+ /// If an explicit key is available for a footer or a column,
282
+ /// its key metadata will be ignored.
283
+ Builder* column_keys(
284
+ const ColumnPathToDecryptionPropertiesMap& column_decryption_properties);
285
+
286
+ /// Set a key retriever callback. Its also possible to
287
+ /// set explicit footer or column keys on this file property object.
288
+ /// Upon file decryption, availability of explicit keys is checked before
289
+ /// invocation of the retriever callback.
290
+ /// If an explicit key is available for a footer or a column,
291
+ /// its key metadata will be ignored.
292
+ Builder* key_retriever(const std::shared_ptr<DecryptionKeyRetriever>& key_retriever);
293
+
294
+ /// Skip integrity verification of plaintext footers.
295
+ /// If not called, integrity of plaintext footers will be checked in runtime,
296
+ /// and an exception will be thrown in the following situations:
297
+ /// - footer signing key is not available
298
+ /// (not passed, or not found by key retriever)
299
+ /// - footer content and signature don't match
300
+ Builder* disable_footer_signature_verification() {
301
+ check_plaintext_footer_integrity_ = false;
302
+ return this;
303
+ }
304
+
305
+ /// Explicitly supply the file AAD prefix.
306
+ /// A must when a prefix is used for file encryption, but not stored in file.
307
+ /// If AAD prefix is stored in file, it will be compared to the explicitly
308
+ /// supplied value and an exception will be thrown if they differ.
309
+ Builder* aad_prefix(const std::string& aad_prefix);
310
+
311
+ /// Set callback for verification of AAD Prefixes stored in file.
312
+ Builder* aad_prefix_verifier(std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier);
313
+
314
+ /// By default, reading plaintext (unencrypted) files is not
315
+ /// allowed when using a decryptor
316
+ /// - in order to detect files that were not encrypted by mistake.
317
+ /// However, the default behavior can be overridden by calling this method.
318
+ /// The caller should use then a different method to ensure encryption
319
+ /// of files with sensitive data.
320
+ Builder* plaintext_files_allowed() {
321
+ plaintext_files_allowed_ = true;
322
+ return this;
323
+ }
324
+
325
+ std::shared_ptr<FileDecryptionProperties> build() {
326
+ return std::shared_ptr<FileDecryptionProperties>(new FileDecryptionProperties(
327
+ footer_key_, key_retriever_, check_plaintext_footer_integrity_, aad_prefix_,
328
+ aad_prefix_verifier_, column_decryption_properties_, plaintext_files_allowed_));
329
+ }
330
+
331
+ private:
332
+ std::string footer_key_;
333
+ std::string aad_prefix_;
334
+ std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier_;
335
+ ColumnPathToDecryptionPropertiesMap column_decryption_properties_;
336
+
337
+ std::shared_ptr<DecryptionKeyRetriever> key_retriever_;
338
+ bool check_plaintext_footer_integrity_;
339
+ bool plaintext_files_allowed_;
340
+ };
341
+
342
+ std::string column_key(const std::string& column_path) const;
343
+
344
+ std::string footer_key() const { return footer_key_; }
345
+
346
+ std::string aad_prefix() const { return aad_prefix_; }
347
+
348
+ const std::shared_ptr<DecryptionKeyRetriever>& key_retriever() const {
349
+ return key_retriever_;
350
+ }
351
+
352
+ bool check_plaintext_footer_integrity() const {
353
+ return check_plaintext_footer_integrity_;
354
+ }
355
+
356
+ bool plaintext_files_allowed() const { return plaintext_files_allowed_; }
357
+
358
+ const std::shared_ptr<AADPrefixVerifier>& aad_prefix_verifier() const {
359
+ return aad_prefix_verifier_;
360
+ }
361
+
362
+ /// Upon completion of file reading, the encryption keys in the properties
363
+ /// will be wiped out (array values set to 0).
364
+ void WipeOutDecryptionKeys();
365
+
366
+ bool is_utilized();
367
+
368
+ /// FileDecryptionProperties object can be used for reading one file only.
369
+ /// Mark FileDecryptionProperties as utilized once it is used to read a file as the
370
+ /// encryption keys will be wiped out upon completion of file reading.
371
+ void set_utilized() { utilized_ = true; }
372
+
373
+ /// FileDecryptionProperties object can be used for reading one file only.
374
+ /// (unless this object keeps the keyRetrieval callback only, and no explicit
375
+ /// keys or aadPrefix).
376
+ /// At the end, keys are wiped out in the memory.
377
+ /// This method allows to clone identical properties for another file,
378
+ /// with an option to update the aadPrefix (if newAadPrefix is null,
379
+ /// aadPrefix will be cloned too)
380
+ std::shared_ptr<FileDecryptionProperties> DeepClone(std::string new_aad_prefix = "");
381
+
382
+ private:
383
+ std::string footer_key_;
384
+ std::string aad_prefix_;
385
+ std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier_;
386
+
387
+ const std::string empty_string_ = "";
388
+ ColumnPathToDecryptionPropertiesMap column_decryption_properties_;
389
+
390
+ std::shared_ptr<DecryptionKeyRetriever> key_retriever_;
391
+ bool check_plaintext_footer_integrity_;
392
+ bool plaintext_files_allowed_;
393
+ bool utilized_;
394
+
395
+ FileDecryptionProperties(
396
+ const std::string& footer_key,
397
+ std::shared_ptr<DecryptionKeyRetriever> key_retriever,
398
+ bool check_plaintext_footer_integrity, const std::string& aad_prefix,
399
+ std::shared_ptr<AADPrefixVerifier> aad_prefix_verifier,
400
+ const ColumnPathToDecryptionPropertiesMap& column_decryption_properties,
401
+ bool plaintext_files_allowed);
402
+ };
403
+
404
+ class PARQUET_EXPORT FileEncryptionProperties {
405
+ public:
406
+ class PARQUET_EXPORT Builder {
407
+ public:
408
+ explicit Builder(const std::string& footer_key)
409
+ : parquet_cipher_(kDefaultEncryptionAlgorithm),
410
+ encrypted_footer_(kDefaultEncryptedFooter) {
411
+ footer_key_ = footer_key;
412
+ store_aad_prefix_in_file_ = false;
413
+ }
414
+
415
+ /// Create files with plaintext footer.
416
+ /// If not called, the files will be created with encrypted footer (default).
417
+ Builder* set_plaintext_footer() {
418
+ encrypted_footer_ = false;
419
+ return this;
420
+ }
421
+
422
+ /// Set encryption algorithm.
423
+ /// If not called, files will be encrypted with AES_GCM_V1 (default).
424
+ Builder* algorithm(ParquetCipher::type parquet_cipher) {
425
+ parquet_cipher_ = parquet_cipher;
426
+ return this;
427
+ }
428
+
429
+ /// Set a key retrieval metadata (converted from String).
430
+ /// use either footer_key_metadata or footer_key_id, not both.
431
+ Builder* footer_key_id(const std::string& key_id);
432
+
433
+ /// Set a key retrieval metadata.
434
+ /// use either footer_key_metadata or footer_key_id, not both.
435
+ Builder* footer_key_metadata(const std::string& footer_key_metadata);
436
+
437
+ /// Set the file AAD Prefix.
438
+ Builder* aad_prefix(const std::string& aad_prefix);
439
+
440
+ /// Skip storing AAD Prefix in file.
441
+ /// If not called, and if AAD Prefix is set, it will be stored.
442
+ Builder* disable_aad_prefix_storage();
443
+
444
+ /// Set the list of encrypted columns and their properties (keys etc).
445
+ /// If not called, all columns will be encrypted with the footer key.
446
+ /// If called, the file columns not in the list will be left unencrypted.
447
+ Builder* encrypted_columns(
448
+ const ColumnPathToEncryptionPropertiesMap& encrypted_columns);
449
+
450
+ std::shared_ptr<FileEncryptionProperties> build() {
451
+ return std::shared_ptr<FileEncryptionProperties>(new FileEncryptionProperties(
452
+ parquet_cipher_, footer_key_, footer_key_metadata_, encrypted_footer_,
453
+ aad_prefix_, store_aad_prefix_in_file_, encrypted_columns_));
454
+ }
455
+
456
+ private:
457
+ ParquetCipher::type parquet_cipher_;
458
+ bool encrypted_footer_;
459
+ std::string footer_key_;
460
+ std::string footer_key_metadata_;
461
+
462
+ std::string aad_prefix_;
463
+ bool store_aad_prefix_in_file_;
464
+ ColumnPathToEncryptionPropertiesMap encrypted_columns_;
465
+ };
466
+ bool encrypted_footer() const { return encrypted_footer_; }
467
+
468
+ EncryptionAlgorithm algorithm() const { return algorithm_; }
469
+
470
+ std::string footer_key() const { return footer_key_; }
471
+
472
+ std::string footer_key_metadata() const { return footer_key_metadata_; }
473
+
474
+ std::string file_aad() const { return file_aad_; }
475
+
476
+ std::shared_ptr<ColumnEncryptionProperties> column_encryption_properties(
477
+ const std::string& column_path);
478
+
479
+ bool is_utilized() const { return utilized_; }
480
+
481
+ /// FileEncryptionProperties object can be used for writing one file only.
482
+ /// Mark FileEncryptionProperties as utilized once it is used to write a file as the
483
+ /// encryption keys will be wiped out upon completion of file writing.
484
+ void set_utilized() { utilized_ = true; }
485
+
486
+ /// Upon completion of file writing, the encryption keys
487
+ /// will be wiped out (array values set to 0).
488
+ void WipeOutEncryptionKeys();
489
+
490
+ /// FileEncryptionProperties object can be used for writing one file only.
491
+ /// (at the end, keys are wiped out in the memory).
492
+ /// This method allows to clone identical properties for another file,
493
+ /// with an option to update the aadPrefix (if newAadPrefix is null,
494
+ /// aadPrefix will be cloned too)
495
+ std::shared_ptr<FileEncryptionProperties> DeepClone(std::string new_aad_prefix = "");
496
+
497
+ ColumnPathToEncryptionPropertiesMap encrypted_columns() const {
498
+ return encrypted_columns_;
499
+ }
500
+
501
+ private:
502
+ EncryptionAlgorithm algorithm_;
503
+ std::string footer_key_;
504
+ std::string footer_key_metadata_;
505
+ bool encrypted_footer_;
506
+ std::string file_aad_;
507
+ std::string aad_prefix_;
508
+ bool utilized_;
509
+ bool store_aad_prefix_in_file_;
510
+ ColumnPathToEncryptionPropertiesMap encrypted_columns_;
511
+
512
+ FileEncryptionProperties(ParquetCipher::type cipher, const std::string& footer_key,
513
+ const std::string& footer_key_metadata, bool encrypted_footer,
514
+ const std::string& aad_prefix, bool store_aad_prefix_in_file,
515
+ const ColumnPathToEncryptionPropertiesMap& encrypted_columns);
516
+ };
517
+
518
+ } // namespace parquet
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_material_store.h ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include <set>
21
+ #include <string>
22
+ #include <unordered_map>
23
+
24
+ #include "arrow/filesystem/filesystem.h"
25
+ #include "parquet/platform.h"
26
+
27
+ namespace parquet::encryption {
28
+
29
+ /// Stores encryption key material outside the Parquet file, for example in a separate
30
+ /// small file in the same folder. This is important for “key rotation”, when MEKs have to
31
+ /// be changed (if compromised; or periodically, just in case) - without modifying the
32
+ /// Parquet files (often immutable).
33
+ class PARQUET_EXPORT FileKeyMaterialStore {
34
+ public:
35
+ /// Add key material for one encryption key.
36
+ virtual void AddKeyMaterial(std::string key_id_in_file, std::string key_material) = 0;
37
+
38
+ /// Get key material
39
+ virtual std::string GetKeyMaterial(std::string key_id_in_file) = 0;
40
+
41
+ /// After key material was added for all keys in the given Parquet file,
42
+ /// save material in persistent store.
43
+ virtual void SaveMaterial() = 0;
44
+
45
+ /// Remove key material from persistent store. Used in key rotation.
46
+ virtual void RemoveMaterial() = 0;
47
+
48
+ /// Move key material to another store. Used in key rotation.
49
+ virtual void MoveMaterialTo(std::shared_ptr<FileKeyMaterialStore> target_key_store) = 0;
50
+
51
+ /// Returns the Set of all key IDs in this store (for the given Parquet file)
52
+ virtual std::vector<std::string> GetKeyIDSet() = 0;
53
+
54
+ virtual ~FileKeyMaterialStore() {}
55
+ };
56
+
57
+ } // namespace parquet::encryption
vllm/lib/python3.10/site-packages/pyarrow/include/parquet/encryption/file_key_unwrapper.h ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Licensed to the Apache Software Foundation (ASF) under one
2
+ // or more contributor license agreements. See the NOTICE file
3
+ // distributed with this work for additional information
4
+ // regarding copyright ownership. The ASF licenses this file
5
+ // to you under the Apache License, Version 2.0 (the
6
+ // "License"); you may not use this file except in compliance
7
+ // with the License. You may obtain a copy of the License at
8
+ //
9
+ // http://www.apache.org/licenses/LICENSE-2.0
10
+ //
11
+ // Unless required by applicable law or agreed to in writing,
12
+ // software distributed under the License is distributed on an
13
+ // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ // KIND, either express or implied. See the License for the
15
+ // specific language governing permissions and limitations
16
+ // under the License.
17
+
18
+ #pragma once
19
+
20
+ #include "arrow/util/concurrent_map.h"
21
+
22
+ #include "parquet/encryption/encryption.h"
23
+ #include "parquet/encryption/file_system_key_material_store.h"
24
+ #include "parquet/encryption/key_material.h"
25
+ #include "parquet/encryption/key_toolkit.h"
26
+ #include "parquet/encryption/key_toolkit_internal.h"
27
+ #include "parquet/encryption/kms_client.h"
28
+ #include "parquet/platform.h"
29
+
30
+ namespace parquet::encryption {
31
+
32
+ // This class will retrieve the key from "key metadata", following these steps:
33
+ // 1. Parse "key metadata" (see structure in KeyMetadata class).
34
+ // 2. Retrieve "key material" which can be stored inside or outside "key metadata".
35
+ // 3. Unwrap the "data encryption key" from "key material". There are 2 modes:
36
+ // 3.1. single wrapping: decrypt the wrapped "data encryption key" directly with "master
37
+ // encryption key" 3.2. double wrapping: 2 steps: 3.2.1. "key encryption key" is decrypted
38
+ // with "master encryption key" 3.2.2. "data encryption key" is decrypted with the above
39
+ // "key encryption key"
40
+ class PARQUET_EXPORT FileKeyUnwrapper : public DecryptionKeyRetriever {
41
+ public:
42
+ /// key_toolkit and kms_connection_config is to get KmsClient from cache or create
43
+ /// KmsClient if it's not in the cache yet. cache_entry_lifetime_seconds is life time of
44
+ /// KmsClient in the cache.
45
+ /// If the file uses external key material then the Parquet file path and file
46
+ /// system must be specified.
47
+ FileKeyUnwrapper(std::shared_ptr<KeyToolkit> key_toolkit,
48
+ const KmsConnectionConfig& kms_connection_config,
49
+ double cache_lifetime_seconds, const std::string& file_path = "",
50
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system = NULLPTR);
51
+
52
+ /// Constructor overload that takes a raw pointer to the KeyToolkit
53
+ FileKeyUnwrapper(KeyToolkit* key_toolkit,
54
+ const KmsConnectionConfig& kms_connection_config,
55
+ double cache_lifetime_seconds, const std::string& file_path = "",
56
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system = NULLPTR);
57
+
58
+ /// Constructor overload that takes a raw pointer to the KeyToolkit and
59
+ /// accepts an existing key_material_store rather than using
60
+ /// the file path and file system to create one when needed.
61
+ FileKeyUnwrapper(KeyToolkit* key_toolkit,
62
+ const KmsConnectionConfig& kms_connection_config,
63
+ double cache_lifetime_seconds,
64
+ std::shared_ptr<FileKeyMaterialStore> key_material_store);
65
+
66
+ /// Get the data key from key metadata
67
+ std::string GetKey(const std::string& key_metadata) override;
68
+
69
+ /// Get the data key along with the master key id from key material
70
+ KeyWithMasterId GetDataEncryptionKey(const KeyMaterial& key_material);
71
+
72
+ private:
73
+ FileKeyUnwrapper(std::shared_ptr<KeyToolkit> key_toolkit_owner, KeyToolkit* key_toolkit,
74
+ const KmsConnectionConfig& kms_connection_config,
75
+ double cache_lifetime_seconds,
76
+ std::shared_ptr<FileKeyMaterialStore> key_material_store,
77
+ const std::string& file_path,
78
+ const std::shared_ptr<::arrow::fs::FileSystem>& file_system);
79
+
80
+ std::shared_ptr<KmsClient> GetKmsClientFromConfigOrKeyMaterial(
81
+ const KeyMaterial& key_material);
82
+
83
+ /// A map of Key Encryption Key (KEK) ID -> KEK bytes, for the current token
84
+ std::shared_ptr<::arrow::util::ConcurrentMap<std::string, std::string>> kek_per_kek_id_;
85
+ std::shared_ptr<KeyToolkit> key_toolkit_owner_;
86
+ KeyToolkit* key_toolkit_;
87
+ KmsConnectionConfig kms_connection_config_;
88
+ const double cache_entry_lifetime_seconds_;
89
+ std::shared_ptr<FileKeyMaterialStore> key_material_store_;
90
+ const std::string file_path_;
91
+ std::shared_ptr<::arrow::fs::FileSystem> file_system_;
92
+ };
93
+
94
+ } // namespace parquet::encryption