ADAPT-Chase commited on
Commit
80f1300
·
verified ·
1 Parent(s): 795d7e2

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/pt2e/representation/__pycache__/rewrite.cpython-312.pyc +0 -0
  3. tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/__init__.cpython-312.pyc +0 -0
  4. tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/composable_quantizer.cpython-312.pyc +0 -0
  5. tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/embedding_quantizer.cpython-312.pyc +0 -0
  6. tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/quantizer.cpython-312.pyc +0 -0
  7. tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/utils.cpython-312.pyc +0 -0
  8. tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/x86_inductor_quantizer.cpython-312.pyc +0 -0
  9. tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer.cpython-312.pyc +0 -0
  10. tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer_utils.cpython-312.pyc +0 -0
  11. tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/xpu_inductor_quantizer.cpython-312.pyc +0 -0
  12. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/__init__.cpython-312.pyc +0 -0
  13. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/anomaly_mode.cpython-312.pyc +0 -0
  14. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/forward_ad.cpython-312.pyc +0 -0
  15. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/function.cpython-312.pyc +0 -0
  16. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/functional.cpython-312.pyc +0 -0
  17. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/grad_mode.cpython-312.pyc +0 -0
  18. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/gradcheck.cpython-312.pyc +0 -0
  19. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/graph.cpython-312.pyc +0 -0
  20. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/profiler.cpython-312.pyc +0 -0
  21. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/profiler_legacy.cpython-312.pyc +0 -0
  22. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/profiler_util.cpython-312.pyc +0 -0
  23. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/variable.cpython-312.pyc +0 -0
  24. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/__init__.py +1 -0
  25. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/__pycache__/__init__.cpython-312.pyc +0 -0
  26. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/__pycache__/tensor.cpython-312.pyc +0 -0
  27. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/__pycache__/utils.cpython-312.pyc +0 -0
  28. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/tensor.py +65 -0
  29. tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/utils.py +63 -0
  30. tool_server/.venv/lib/python3.12/site-packages/torch/backends/__pycache__/__init__.cpython-312.pyc +0 -0
  31. tool_server/.venv/lib/python3.12/site-packages/torch/backends/_coreml/__init__.py +0 -0
  32. tool_server/.venv/lib/python3.12/site-packages/torch/backends/_coreml/__pycache__/__init__.cpython-312.pyc +0 -0
  33. tool_server/.venv/lib/python3.12/site-packages/torch/backends/_coreml/__pycache__/preprocess.cpython-312.pyc +0 -0
  34. tool_server/.venv/lib/python3.12/site-packages/torch/backends/_coreml/preprocess.py +147 -0
  35. tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__init__.py +0 -0
  36. tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/__init__.cpython-312.pyc +0 -0
  37. tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/prepare.cpython-312.pyc +0 -0
  38. tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/serializer.cpython-312.pyc +3 -0
  39. tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/prepare.py +199 -0
  40. tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/serializer.py +2228 -0
  41. tool_server/.venv/lib/python3.12/site-packages/torch/backends/cpu/__init__.py +21 -0
  42. tool_server/.venv/lib/python3.12/site-packages/torch/backends/cpu/__pycache__/__init__.cpython-312.pyc +0 -0
  43. tool_server/.venv/lib/python3.12/site-packages/torch/backends/cuda/__init__.py +536 -0
  44. tool_server/.venv/lib/python3.12/site-packages/torch/backends/cuda/__pycache__/__init__.cpython-312.pyc +0 -0
  45. tool_server/.venv/lib/python3.12/site-packages/torch/backends/cudnn/__init__.py +208 -0
  46. tool_server/.venv/lib/python3.12/site-packages/torch/backends/cudnn/__pycache__/__init__.cpython-312.pyc +0 -0
  47. tool_server/.venv/lib/python3.12/site-packages/torch/backends/cudnn/__pycache__/rnn.cpython-312.pyc +0 -0
  48. tool_server/.venv/lib/python3.12/site-packages/torch/backends/cudnn/rnn.py +64 -0
  49. tool_server/.venv/lib/python3.12/site-packages/torch/backends/cusparselt/__init__.py +57 -0
  50. tool_server/.venv/lib/python3.12/site-packages/torch/backends/cusparselt/__pycache__/__init__.cpython-312.pyc +0 -0
.gitattributes CHANGED
@@ -4479,3 +4479,4 @@ tool_server/.venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycac
4479
  tool_server/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/flex_attention.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4480
  tool_server/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4481
  tool_server/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
4479
  tool_server/.venv/lib/python3.12/site-packages/torch/_inductor/kernel/__pycache__/flex_attention.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4480
  tool_server/.venv/lib/python3.12/site-packages/torch/_refs/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4481
  tool_server/.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
4482
+ tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/serializer.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/pt2e/representation/__pycache__/rewrite.cpython-312.pyc ADDED
Binary file (30.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (543 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/composable_quantizer.cpython-312.pyc ADDED
Binary file (3.86 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/embedding_quantizer.cpython-312.pyc ADDED
Binary file (4.72 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/quantizer.cpython-312.pyc ADDED
Binary file (7.63 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/utils.cpython-312.pyc ADDED
Binary file (4.06 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/x86_inductor_quantizer.cpython-312.pyc ADDED
Binary file (62.4 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer.cpython-312.pyc ADDED
Binary file (17.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/xnnpack_quantizer_utils.cpython-312.pyc ADDED
Binary file (44.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/ao/quantization/quantizer/__pycache__/xpu_inductor_quantizer.cpython-312.pyc ADDED
Binary file (4.34 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (24.6 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/anomaly_mode.cpython-312.pyc ADDED
Binary file (6.25 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/forward_ad.cpython-312.pyc ADDED
Binary file (8.64 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/function.cpython-312.pyc ADDED
Binary file (37.9 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/functional.cpython-312.pyc ADDED
Binary file (47.3 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/grad_mode.cpython-312.pyc ADDED
Binary file (19 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/gradcheck.cpython-312.pyc ADDED
Binary file (95.2 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/graph.cpython-312.pyc ADDED
Binary file (39.1 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/profiler.cpython-312.pyc ADDED
Binary file (54.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/profiler_legacy.cpython-312.pyc ADDED
Binary file (13 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/profiler_util.cpython-312.pyc ADDED
Binary file (49.8 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/__pycache__/variable.cpython-312.pyc ADDED
Binary file (1.02 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .tensor import * # noqa: F403
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (223 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/__pycache__/tensor.cpython-312.pyc ADDED
Binary file (3.79 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/__pycache__/utils.cpython-312.pyc ADDED
Binary file (2.12 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/tensor.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import operator
3
+ from functools import reduce
4
+ from typing_extensions import deprecated
5
+
6
+ import torch
7
+ import torch._utils
8
+ from torch.autograd.function import Function
9
+
10
+
11
+ class Type(Function):
12
+ @staticmethod
13
+ @deprecated(
14
+ "`torch.autograd._functions.Type` is deprecated as of PyTorch 2.1, "
15
+ "please use `torch.tensor.to(dtype=dtype)` instead.",
16
+ category=FutureWarning,
17
+ )
18
+ def forward(ctx, i, dest_type):
19
+ ctx.input_type = type(i)
20
+ ctx.input_device = -1 if not i.is_cuda else i.get_device()
21
+ return i.type(dest_type)
22
+
23
+ @staticmethod
24
+ def backward(ctx, grad_output):
25
+ if ctx.input_device == -1:
26
+ return grad_output.type(ctx.input_type), None
27
+ else:
28
+ with torch.cuda.device(ctx.input_device):
29
+ return grad_output.type(ctx.input_type), None
30
+
31
+
32
+ # TODO: deprecate this
33
+ class Resize(Function):
34
+ @staticmethod
35
+ def forward(ctx, tensor, sizes):
36
+ ctx.sizes = sizes
37
+ ctx.numel = reduce(operator.mul, sizes, 1)
38
+ if tensor.numel() != ctx.numel:
39
+ raise RuntimeError(
40
+ (
41
+ "requested resize to {} ({} elements in total), "
42
+ "but the given tensor has a size of {} ({} elements). "
43
+ "autograd's resize can only change the shape of a given "
44
+ "tensor, while preserving the number of elements. "
45
+ ).format(
46
+ "x".join(map(str, sizes)),
47
+ ctx.numel,
48
+ "x".join(map(str, tensor.size())),
49
+ tensor.numel(),
50
+ )
51
+ )
52
+ ctx.input_sizes = tensor.size()
53
+ if tensor.is_quantized:
54
+ tensor.copy_(tensor)
55
+ return tensor.contiguous().view(*sizes)
56
+ if tensor.is_contiguous():
57
+ result = tensor.new(tensor).contiguous().view(*sizes)
58
+ return result
59
+ else:
60
+ return tensor.contiguous().view(*sizes)
61
+
62
+ @staticmethod
63
+ def backward(ctx, grad_output):
64
+ assert grad_output.numel() == ctx.numel
65
+ return grad_output.contiguous().view(ctx.input_sizes), None
tool_server/.venv/lib/python3.12/site-packages/torch/autograd/_functions/utils.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import operator
3
+ from functools import reduce
4
+
5
+
6
+ def maybe_view(tensor, size, check_same_size=True):
7
+ if check_same_size and tensor.size() == size:
8
+ return tensor
9
+ return tensor.contiguous().view(size)
10
+
11
+
12
+ def maybe_unexpand(tensor, old_size, check_same_size=True):
13
+ if check_same_size and tensor.size() == old_size:
14
+ return tensor
15
+ num_unsqueezed = tensor.dim() - len(old_size)
16
+ expanded_dims = [
17
+ dim
18
+ for dim, (expanded, original) in enumerate(
19
+ zip(tensor.size()[num_unsqueezed:], old_size)
20
+ )
21
+ if expanded != original
22
+ ]
23
+
24
+ for _ in range(num_unsqueezed):
25
+ tensor = tensor.sum(0, keepdim=False)
26
+ for dim in expanded_dims:
27
+ tensor = tensor.sum(dim, keepdim=True)
28
+ return tensor
29
+
30
+
31
+ # Check whether the op enable broadcasting, and whether it is supported by ONNX.
32
+ # If dims1 and dims2 are different, then broadcast is True.
33
+ # We always assume the combination of dims1 and dims2 is broadcastable.
34
+ # The following types of broadcasting are supported in ONNX:
35
+ # 1) Only one element in dims2, such as dims2 = [1, 1]
36
+ # 2) dims2 is suffix of dims1, such as dims1 = [2, 3, 4], and dims2 = [3, 4]
37
+ # Details can be found here: https://github.com/onnx/onnx/blob/master/docs/Operators.md#Gemm
38
+ def check_onnx_broadcast(dims1, dims2):
39
+ broadcast = False
40
+ supported = True
41
+ len1 = len(dims1)
42
+ len2 = len(dims2)
43
+
44
+ numel2 = reduce(operator.mul, dims2)
45
+ if len1 < len2:
46
+ broadcast = True
47
+ if numel2 != 1:
48
+ supported = False
49
+ elif len1 > len2:
50
+ broadcast = True
51
+ if numel2 != 1 and dims1[len1 - len2 :] != dims2:
52
+ supported = False
53
+ else:
54
+ if dims1 != dims2:
55
+ broadcast = True
56
+ if numel2 != 1:
57
+ supported = False
58
+
59
+ if not supported:
60
+ raise ValueError(
61
+ f"Numpy style broadcasting is not supported in ONNX. Input dims are: {dims1}, {dims2}"
62
+ )
63
+ return broadcast
tool_server/.venv/lib/python3.12/site-packages/torch/backends/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (2.68 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/backends/_coreml/__init__.py ADDED
File without changes
tool_server/.venv/lib/python3.12/site-packages/torch/backends/_coreml/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (192 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/backends/_coreml/__pycache__/preprocess.cpython-312.pyc ADDED
Binary file (5.88 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/backends/_coreml/preprocess.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import hashlib
3
+ import json
4
+
5
+ import coremltools as ct # type: ignore[import]
6
+ from coremltools.converters.mil.input_types import TensorType # type: ignore[import]
7
+ from coremltools.converters.mil.mil import types # type: ignore[import]
8
+ from coremltools.models.neural_network import quantization_utils # type: ignore[import]
9
+
10
+ import torch
11
+
12
+
13
+ CT_METADATA_VERSION = "com.github.apple.coremltools.version"
14
+ CT_METADATA_SOURCE = "com.github.apple.coremltools.source"
15
+
16
+
17
+ class ScalarType:
18
+ Float = 0
19
+ Double = 1
20
+ Int = 2
21
+ Long = 3
22
+ Undefined = 4
23
+
24
+
25
+ # Supported Tensor types in coremltools:
26
+ # https://github.com/apple/coremltools/blob/main/coremltools/converters/mil/frontend/torch/converter.py#L28
27
+ torch_to_mil_types = {
28
+ ScalarType.Float: types.fp32,
29
+ ScalarType.Double: types.fp64,
30
+ ScalarType.Int: types.int32,
31
+ ScalarType.Long: types.int64,
32
+ }
33
+
34
+
35
+ class CoreMLComputeUnit:
36
+ CPU = "cpuOnly"
37
+ CPUAndGPU = "cpuAndGPU"
38
+ ALL = "all"
39
+
40
+
41
+ class CoreMLQuantizationMode:
42
+ LINEAR = "linear"
43
+ LINEAR_SYMMETRIC = "linear_symmetric"
44
+ NONE = "none"
45
+
46
+
47
+ def TensorSpec(shape, dtype=ScalarType.Float):
48
+ return (shape, dtype)
49
+
50
+
51
+ def CompileSpec(
52
+ inputs,
53
+ outputs,
54
+ backend=CoreMLComputeUnit.CPU,
55
+ allow_low_precision=True,
56
+ quantization_mode=CoreMLQuantizationMode.NONE,
57
+ mlmodel_export_path=None,
58
+ ):
59
+ return (
60
+ inputs,
61
+ outputs,
62
+ backend,
63
+ allow_low_precision,
64
+ quantization_mode,
65
+ mlmodel_export_path,
66
+ )
67
+
68
+
69
+ def _check_enumerated_shape(shape):
70
+ for s in shape:
71
+ if not isinstance(s, (list, tuple)):
72
+ return False
73
+ return True
74
+
75
+
76
+ def _convert_to_mil_type(shape, dtype, name: str):
77
+ mil_shape = shape
78
+ if _check_enumerated_shape(shape):
79
+ mil_shape = ct.EnumeratedShapes(shape)
80
+ ml_type = TensorType(shape=mil_shape, dtype=torch_to_mil_types[dtype])
81
+ ml_type.name = name
82
+ return ml_type
83
+
84
+
85
+ def preprocess(script_module: torch._C.ScriptObject, compile_spec: dict[str, tuple]):
86
+ spec = compile_spec["forward"]
87
+ (
88
+ input_specs,
89
+ output_specs,
90
+ backend,
91
+ allow_low_precision,
92
+ quantization_mode,
93
+ mlmodel_export_path,
94
+ ) = spec
95
+ mil_inputs = []
96
+ inputs = []
97
+ for index, input in enumerate(input_specs):
98
+ shape, dtype = input
99
+ name = "input_" + str(index)
100
+ inputs.append([name, str(dtype), str(shape)])
101
+ ml_type = _convert_to_mil_type(shape, dtype, name)
102
+ mil_inputs.append(ml_type)
103
+ model = torch.jit.RecursiveScriptModule._construct(script_module, lambda x: None)
104
+ mlmodel = ct.convert(model, inputs=mil_inputs)
105
+
106
+ if quantization_mode != CoreMLQuantizationMode.NONE:
107
+ quant_model_spec = quantization_utils.quantize_weights(
108
+ mlmodel, nbits=8, quantization_mode=quantization_mode
109
+ )
110
+ mlmodel = ct.models.MLModel(quant_model_spec)
111
+
112
+ spec = mlmodel.get_spec()
113
+ assert len(spec.description.output) == len(output_specs) # type: ignore[attr-defined]
114
+ outputs = []
115
+ for index, output in enumerate(output_specs):
116
+ shape, dtype = output
117
+ name = spec.description.output[index].name # type: ignore[attr-defined]
118
+ outputs.append([name, str(dtype), str(shape)])
119
+ mlmodel = ct.models.model.MLModel(spec)
120
+ print(mlmodel)
121
+
122
+ if mlmodel_export_path is not None:
123
+ print(f"Saving CoreML .mlmodel file to {mlmodel_export_path}")
124
+ mlmodel.save(mlmodel_export_path)
125
+
126
+ config = {
127
+ "spec_ver": str(spec.specificationVersion), # type: ignore[attr-defined]
128
+ "backend": backend,
129
+ "allow_low_precision": str(allow_low_precision),
130
+ }
131
+ metadata = {
132
+ "coremltool_ver": mlmodel.user_defined_metadata[CT_METADATA_VERSION],
133
+ "torch_ver": mlmodel.user_defined_metadata[CT_METADATA_SOURCE],
134
+ }
135
+ coreml_compile_spec = {
136
+ "inputs": inputs,
137
+ "outputs": outputs,
138
+ "config": config,
139
+ "metadata": metadata,
140
+ }
141
+ mlmodel = spec.SerializeToString() # type: ignore[attr-defined]
142
+
143
+ return {
144
+ "model": mlmodel,
145
+ "hash": str(hashlib.sha256(mlmodel).hexdigest()),
146
+ "extra": json.dumps(coreml_compile_spec),
147
+ }
tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__init__.py ADDED
File without changes
tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (191 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/prepare.cpython-312.pyc ADDED
Binary file (8.85 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/serializer.cpython-312.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e82ab73d8d43f99ff8dbdad38c66f55d2f3f1ed0c3abb6e4d462f0acaaa660a
3
+ size 107979
tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/prepare.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ from typing import Optional
4
+
5
+ import torch
6
+ from torch.backends._nnapi.serializer import _NnapiSerializer
7
+
8
+
9
+ ANEURALNETWORKS_PREFER_LOW_POWER = 0
10
+ ANEURALNETWORKS_PREFER_FAST_SINGLE_ANSWER = 1
11
+ ANEURALNETWORKS_PREFER_SUSTAINED_SPEED = 2
12
+
13
+
14
+ class NnapiModule(torch.nn.Module):
15
+ """Torch Module that wraps an NNAPI Compilation.
16
+
17
+ This module handles preparing the weights, initializing the
18
+ NNAPI TorchBind object, and adjusting the memory formats
19
+ of all inputs and outputs.
20
+ """
21
+
22
+ # _nnapi.Compilation is defined
23
+ comp: Optional[torch.classes._nnapi.Compilation] # type: ignore[name-defined]
24
+ weights: list[torch.Tensor]
25
+ out_templates: list[torch.Tensor]
26
+
27
+ def __init__(
28
+ self,
29
+ shape_compute_module: torch.nn.Module,
30
+ ser_model: torch.Tensor,
31
+ weights: list[torch.Tensor],
32
+ inp_mem_fmts: list[int],
33
+ out_mem_fmts: list[int],
34
+ compilation_preference: int,
35
+ relax_f32_to_f16: bool,
36
+ ):
37
+ super().__init__()
38
+ self.shape_compute_module = shape_compute_module
39
+ self.ser_model = ser_model
40
+ self.weights = weights
41
+ self.inp_mem_fmts = inp_mem_fmts
42
+ self.out_mem_fmts = out_mem_fmts
43
+ self.out_templates = []
44
+ self.comp = None
45
+ self.compilation_preference = compilation_preference
46
+ self.relax_f32_to_f16 = relax_f32_to_f16
47
+
48
+ @torch.jit.export
49
+ def init(self, args: list[torch.Tensor]):
50
+ assert self.comp is None
51
+ self.out_templates = self.shape_compute_module.prepare(self.ser_model, args) # type: ignore[operator]
52
+ self.weights = [w.contiguous() for w in self.weights]
53
+ comp = torch.classes._nnapi.Compilation()
54
+ comp.init2(
55
+ self.ser_model,
56
+ self.weights,
57
+ self.compilation_preference,
58
+ self.relax_f32_to_f16,
59
+ )
60
+
61
+ self.comp = comp
62
+
63
+ def forward(self, args: list[torch.Tensor]) -> list[torch.Tensor]:
64
+ if self.comp is None:
65
+ self.init(args)
66
+ comp = self.comp
67
+ assert comp is not None
68
+ outs = [torch.empty_like(out) for out in self.out_templates]
69
+
70
+ assert len(args) == len(self.inp_mem_fmts)
71
+ fixed_args = []
72
+ for idx in range(len(args)):
73
+ fmt = self.inp_mem_fmts[idx]
74
+ # These constants match the values in DimOrder in serializer.py
75
+ # TODO: See if it's possible to use those directly.
76
+ if fmt == 0:
77
+ fixed_args.append(args[idx].contiguous())
78
+ elif fmt == 1:
79
+ fixed_args.append(args[idx].permute(0, 2, 3, 1).contiguous())
80
+ else:
81
+ raise ValueError("Invalid mem_fmt")
82
+ comp.run(fixed_args, outs)
83
+ assert len(outs) == len(self.out_mem_fmts)
84
+ for idx in range(len(self.out_templates)):
85
+ fmt = self.out_mem_fmts[idx]
86
+ # These constants match the values in DimOrder in serializer.py
87
+ # TODO: See if it's possible to use those directly.
88
+ if fmt in (0, 2):
89
+ pass
90
+ elif fmt == 1:
91
+ outs[idx] = outs[idx].permute(0, 3, 1, 2)
92
+ else:
93
+ raise ValueError("Invalid mem_fmt")
94
+ return outs
95
+
96
+
97
+ def convert_model_to_nnapi(
98
+ model,
99
+ inputs,
100
+ serializer=None,
101
+ return_shapes=None,
102
+ use_int16_for_qint16=False,
103
+ compilation_preference=ANEURALNETWORKS_PREFER_SUSTAINED_SPEED,
104
+ relax_f32_to_f16=False,
105
+ ):
106
+ (
107
+ shape_compute_module,
108
+ ser_model_tensor,
109
+ used_weights,
110
+ inp_mem_fmts,
111
+ out_mem_fmts,
112
+ retval_count,
113
+ ) = process_for_nnapi(
114
+ model, inputs, serializer, return_shapes, use_int16_for_qint16
115
+ )
116
+
117
+ nnapi_model = NnapiModule(
118
+ shape_compute_module,
119
+ ser_model_tensor,
120
+ used_weights,
121
+ inp_mem_fmts,
122
+ out_mem_fmts,
123
+ compilation_preference,
124
+ relax_f32_to_f16,
125
+ )
126
+
127
+ class NnapiInterfaceWrapper(torch.nn.Module):
128
+ """NNAPI list-ifying and de-list-ifying wrapper.
129
+
130
+ NNAPI always expects a list of inputs and provides a list of outputs.
131
+ This module allows us to accept inputs as separate arguments.
132
+ It returns results as either a single tensor or tuple,
133
+ matching the original module.
134
+ """
135
+
136
+ def __init__(self, mod):
137
+ super().__init__()
138
+ self.mod = mod
139
+
140
+ wrapper_model_py = NnapiInterfaceWrapper(nnapi_model)
141
+ wrapper_model = torch.jit.script(wrapper_model_py)
142
+ # TODO: Maybe make these names match the original.
143
+ arg_list = ", ".join(f"arg_{idx}" for idx in range(len(inputs)))
144
+ if retval_count < 0:
145
+ ret_expr = "retvals[0]"
146
+ else:
147
+ ret_expr = "".join(f"retvals[{idx}], " for idx in range(retval_count))
148
+ wrapper_model.define(
149
+ f"def forward(self, {arg_list}):\n"
150
+ f" retvals = self.mod([{arg_list}])\n"
151
+ f" return {ret_expr}\n"
152
+ )
153
+ return wrapper_model
154
+
155
+
156
+ def process_for_nnapi(
157
+ model, inputs, serializer=None, return_shapes=None, use_int16_for_qint16=False
158
+ ):
159
+ model = torch.jit.freeze(model)
160
+
161
+ if isinstance(inputs, torch.Tensor):
162
+ inputs = [inputs]
163
+
164
+ serializer = serializer or _NnapiSerializer(
165
+ config=None, use_int16_for_qint16=use_int16_for_qint16
166
+ )
167
+ (
168
+ ser_model,
169
+ used_weights,
170
+ inp_mem_fmts,
171
+ out_mem_fmts,
172
+ shape_compute_lines,
173
+ retval_count,
174
+ ) = serializer.serialize_model(model, inputs, return_shapes)
175
+ ser_model_tensor = torch.tensor(ser_model, dtype=torch.int32)
176
+
177
+ # We have to create a new class here every time this function is called
178
+ # because module.define adds a method to the *class*, not the instance.
179
+ class ShapeComputeModule(torch.nn.Module):
180
+ """Code-gen-ed module for tensor shape computation.
181
+
182
+ module.prepare will mutate ser_model according to the computed operand
183
+ shapes, based on the shapes of args. Returns a list of output templates.
184
+ """
185
+
186
+ shape_compute_module = torch.jit.script(ShapeComputeModule())
187
+ real_shape_compute_lines = [
188
+ "def prepare(self, ser_model: torch.Tensor, args: List[torch.Tensor]) -> List[torch.Tensor]:\n",
189
+ ] + [f" {line}\n" for line in shape_compute_lines]
190
+ shape_compute_module.define("".join(real_shape_compute_lines))
191
+
192
+ return (
193
+ shape_compute_module,
194
+ ser_model_tensor,
195
+ used_weights,
196
+ inp_mem_fmts,
197
+ out_mem_fmts,
198
+ retval_count,
199
+ )
tool_server/.venv/lib/python3.12/site-packages/torch/backends/_nnapi/serializer.py ADDED
@@ -0,0 +1,2228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import array
3
+ import enum
4
+ import functools
5
+ import logging
6
+ import operator
7
+ import struct
8
+ import sys
9
+ from typing import NamedTuple, Optional
10
+
11
+ import torch
12
+
13
+
14
+ # TODO: Add type annotations
15
+ # TODO: Check tensor types for ops
16
+
17
+
18
+ LOG = logging.getLogger("nnapi_serialize")
19
+
20
+
21
+ class NNAPI_OperandCode:
22
+ FLOAT32 = 0
23
+ INT32 = 1
24
+ UINT32 = 2
25
+ TENSOR_FLOAT32 = 3
26
+ TENSOR_INT32 = 4
27
+ TENSOR_QUANT8_ASYMM = 5
28
+ BOOL = 6
29
+ TENSOR_QUANT16_SYMM = 7
30
+ TENSOR_FLOAT16 = 8
31
+ TENSOR_BOOL8 = 9
32
+ FLOAT16 = 10
33
+ TENSOR_QUANT8_SYMM_PER_CHANNEL = 11
34
+ TENSOR_QUANT16_ASYMM = 12
35
+
36
+
37
+ class NNAPI_OperationCode:
38
+ ADD = 0
39
+ AVERAGE_POOL_2D = 1
40
+ CONCATENATION = 2
41
+ CONV_2D = 3
42
+ DEPTHWISE_CONV_2D = 4
43
+ DEPTH_TO_SPACE = 5
44
+ DEQUANTIZE = 6
45
+ EMBEDDING_LOOKUP = 7
46
+ FLOOR = 8
47
+ FULLY_CONNECTED = 9
48
+ HASHTABLE_LOOKUP = 10
49
+ L2_NORMALIZATION = 11
50
+ L2_POOL_2D = 12
51
+ LOCAL_RESPONSE_NORMALIZATION = 13
52
+ LOGISTIC = 14
53
+ LSH_PROJECTION = 15
54
+ LSTM = 16
55
+ MAX_POOL_2D = 17
56
+ MUL = 18
57
+ RELU = 19
58
+ RELU1 = 20
59
+ RELU6 = 21
60
+ RESHAPE = 22
61
+ RESIZE_BILINEAR = 23
62
+ RNN = 24
63
+ SOFTMAX = 25
64
+ SPACE_TO_DEPTH = 26
65
+ SVDF = 27
66
+ TANH = 28
67
+ BATCH_TO_SPACE_ND = 29
68
+ DIV = 30
69
+ MEAN = 31
70
+ PAD = 32
71
+ SPACE_TO_BATCH_ND = 33
72
+ SQUEEZE = 34
73
+ STRIDED_SLICE = 35
74
+ SUB = 36
75
+ TRANSPOSE = 37
76
+ ABS = 38
77
+ ARGMAX = 39
78
+ ARGMIN = 40
79
+ AXIS_ALIGNED_BBOX_TRANSFORM = 41
80
+ BIDIRECTIONAL_SEQUENCE_LSTM = 42
81
+ BIDIRECTIONAL_SEQUENCE_RNN = 43
82
+ BOX_WITH_NMS_LIMIT = 44
83
+ CAST = 45
84
+ CHANNEL_SHUFFLE = 46
85
+ DETECTION_POSTPROCESSING = 47
86
+ EQUAL = 48
87
+ EXP = 49
88
+ EXPAND_DIMS = 50
89
+ GATHER = 51
90
+ GENERATE_PROPOSALS = 52
91
+ GREATER = 53
92
+ GREATER_EQUAL = 54
93
+ GROUPED_CONV_2D = 55
94
+ HEATMAP_MAX_KEYPOINT = 56
95
+ INSTANCE_NORMALIZATION = 57
96
+ LESS = 58
97
+ LESS_EQUAL = 59
98
+ LOG = 60
99
+ LOGICAL_AND = 61
100
+ LOGICAL_NOT = 62
101
+ LOGICAL_OR = 63
102
+ LOG_SOFTMAX = 64
103
+ MAXIMUM = 65
104
+ MINIMUM = 66
105
+ NEG = 67
106
+ NOT_EQUAL = 68
107
+ PAD_V2 = 69
108
+ POW = 70
109
+ PRELU = 71
110
+ QUANTIZE = 72
111
+ QUANTIZED_16BIT_LSTM = 73
112
+ RANDOM_MULTINOMIAL = 74
113
+ REDUCE_ALL = 75
114
+ REDUCE_ANY = 76
115
+ REDUCE_MAX = 77
116
+ REDUCE_MIN = 78
117
+ REDUCE_PROD = 79
118
+ REDUCE_SUM = 80
119
+ ROI_ALIGN = 81
120
+ ROI_POOLING = 82
121
+ RSQRT = 83
122
+ SELECT = 84
123
+ SIN = 85
124
+ SLICE = 86
125
+ SPLIT = 87
126
+ SQRT = 88
127
+ TILE = 89
128
+ TOPK_V2 = 90
129
+ TRANSPOSE_CONV_2D = 91
130
+ UNIDIRECTIONAL_SEQUENCE_LSTM = 92
131
+ UNIDIRECTIONAL_SEQUENCE_RNN = 93
132
+ RESIZE_NEAREST_NEIGHBOR = 94
133
+
134
+
135
+ class NNAPI_FuseCode:
136
+ FUSED_NONE = 0
137
+ FUSED_RELU = 1
138
+ FUSED_RELU1 = 2
139
+ FUSED_RELU6 = 3
140
+
141
+
142
+ class OperandValueSourceType:
143
+ IMMEDIATE = 0
144
+ NUMBERED_BUFFER = 2
145
+ NUMBERED_MEMORY = 3
146
+
147
+
148
+ # Scalar types that appear explicitly in models.
149
+ # These must be kept in sync with
150
+ # AT_FORALL_SCALAR_TYPES_WITH_COMPLEX_AND_QINTS.
151
+ # TODO: Expose these directly to Python to avoid maintaining this list.
152
+ class TorchScalarTypes(enum.Enum):
153
+ QUINT8 = 13
154
+
155
+
156
+ def approx_equal(lhs, rhs, tolerance=1e-6):
157
+ return abs(lhs - rhs) <= tolerance * min(lhs, rhs)
158
+
159
+
160
+ def tensor_size(op_type, dims):
161
+ ITEM_SIZES = {
162
+ NNAPI_OperandCode.TENSOR_FLOAT32: 4,
163
+ NNAPI_OperandCode.TENSOR_INT32: 4,
164
+ NNAPI_OperandCode.TENSOR_QUANT8_ASYMM: 1,
165
+ NNAPI_OperandCode.TENSOR_QUANT16_SYMM: 2,
166
+ NNAPI_OperandCode.TENSOR_QUANT16_ASYMM: 2,
167
+ }
168
+ size = ITEM_SIZES[op_type]
169
+ for d in dims:
170
+ size *= d
171
+ return size
172
+
173
+
174
+ def change_element(tup, index, value):
175
+ ls = list(tup)
176
+ ls[index] = value
177
+ return tuple(ls)
178
+
179
+
180
+ class ConvPoolArgs2d(NamedTuple):
181
+ """Configuration arguments for a convolution."""
182
+
183
+ kernel_h: int
184
+ kernel_w: int
185
+ stride_h: int
186
+ stride_w: int
187
+ pad_t: int
188
+ pad_b: int
189
+ pad_l: int
190
+ pad_r: int
191
+ dilation_h: int
192
+ dilation_w: int
193
+ group: int
194
+
195
+
196
+ class DimOrder(enum.Enum):
197
+ PRESUMED_CONTIGUOUS = 0
198
+ CHANNELS_LAST = 1
199
+ SCALAR_OR_VECTOR = 2
200
+ UNKNOWN_CONSTANT = 999
201
+
202
+
203
+ class Operand(NamedTuple):
204
+ """Represenation of an NNAPI operand."""
205
+
206
+ # NNAPI operand type. One of NNAPI_OperandCode.
207
+ # TODO: Make this an enum.
208
+ op_type: int
209
+
210
+ # This is always the PyTorch shape, which is NCHW for feature maps.
211
+ # The actual NNAPI operand might have a transposed shape.
212
+ # we use 0 for load time dynamic shapes & -1 for runtime dynamic shapes
213
+ shape: tuple[int, ...]
214
+
215
+ # Specifies how the shape of the operand that we define in NNAPI
216
+ # relates to the shape we track above.
217
+ # - PRESUMED_CONTIGUOUS: physical NNAPI operand will exactly match
218
+ # the shape of the PyTorch tensor.
219
+ # - CHANNELS_LAST: The PyTorch tensor is expected to be NCHW, and
220
+ # the NNAPI operand will be represented explicitly as NHWC.
221
+ dim_order: DimOrder
222
+
223
+ # Quantization params
224
+ scale: float
225
+ zero_point: int
226
+
227
+ def use_nchw(self):
228
+ if self.dim_order is DimOrder.PRESUMED_CONTIGUOUS:
229
+ return True
230
+ if self.dim_order is DimOrder.CHANNELS_LAST:
231
+ return False
232
+ raise Exception("Unknown dim order") # noqa: TRY002
233
+
234
+
235
+ def broadcast_shapes(shape1, shape2):
236
+ assert len(shape1) > 0
237
+ assert len(shape2) > 0
238
+ s1 = list(shape1)
239
+ s2 = list(shape2)
240
+ # TODO: Support non-equal-rank broadcast where semantics match.
241
+ # This can be tricky for NHWC tensors because dimension orders
242
+ # don't match between PT and NNAPI, even though semantics match.
243
+ if len(s1) > len(s2):
244
+ # s2 = [1] * (len(s1) - len(s2)) + s2
245
+ raise Exception( # noqa: TRY002
246
+ "Non-equal-rank broadcast is not supported yet."
247
+ ) # noqa: TRY002
248
+ if len(s2) > len(s1):
249
+ # s3 = [1] * (len(s2) - len(s1)) + s1
250
+ raise Exception( # noqa: TRY002
251
+ "Non-equal-rank broadcast is not supported yet."
252
+ ) # noqa: TRY002
253
+ ret = []
254
+ for d1, d2 in zip(s1, s2):
255
+ if d1 == 1:
256
+ ret.append(d2)
257
+ elif d2 == 1:
258
+ ret.append(d1)
259
+ elif d1 == d2:
260
+ ret.append(d1)
261
+ else:
262
+ raise Exception( # noqa: TRY002
263
+ f"Cannot broadcast shapes: {shape1} and {shape2}"
264
+ ) # noqa: TRY002
265
+ return tuple(ret)
266
+
267
+
268
+ def get_conv_pool_shape(image_shape, args, out_ch, transpose):
269
+ batch, _in_c, in_h, in_w = image_shape
270
+
271
+ # TODO: Handle dilation
272
+ if args.dilation_h != 1 or args.dilation_w != 1:
273
+ raise Exception("Dilation not supported yet.") # noqa: TRY002
274
+
275
+ if transpose:
276
+ out_h = (in_h - 1) * args.stride_h + args.kernel_h - args.pad_t - args.pad_b
277
+ out_w = (in_w - 1) * args.stride_w + args.kernel_w - args.pad_l - args.pad_l
278
+ else:
279
+ out_h = (in_h - args.kernel_h + args.pad_t + args.pad_b) // args.stride_h + 1
280
+ out_w = (in_w - args.kernel_w + args.pad_l + args.pad_r) // args.stride_w + 1
281
+
282
+ # Handle variable-sized tensors.
283
+ if in_h == 0:
284
+ out_h = 0
285
+ if in_w == 0:
286
+ out_w = 0
287
+
288
+ out_shape = (batch, out_ch, out_h, out_w)
289
+ return out_shape
290
+
291
+
292
+ def fix_shape(shape, dim_order):
293
+ # Return the actual shape that an operand should have in NNAPI,
294
+ # given a PyTorch shape and dimension order. This is where we
295
+ # convert from PyTorch's "always NCHW" shape to explicit NHWC.
296
+ if dim_order is DimOrder.PRESUMED_CONTIGUOUS:
297
+ return shape
298
+ if dim_order is DimOrder.CHANNELS_LAST:
299
+ return tuple([shape[0]] + list(shape[2:]) + [shape[1]])
300
+ if dim_order is DimOrder.SCALAR_OR_VECTOR:
301
+ assert len(shape) == 0 or len(shape) == 1
302
+ return shape
303
+ if dim_order is DimOrder.UNKNOWN_CONSTANT:
304
+ # XXX think this through
305
+ return shape
306
+ raise Exception(f"Bad dim_order: {dim_order!r}.") # noqa: TRY002
307
+
308
+
309
+ def reverse_map_dim(dim_order, d):
310
+ # Return the original PyTorch dimension position for a given dimension.
311
+ # d should be the dimension that NNAPI will see.
312
+ # reverse_map_dim(PRESUMED_CONTIGUOUS, x) == x
313
+ # reverse_map_dim(CHANNELS_LAST, 3) == 1
314
+ if dim_order in (DimOrder.PRESUMED_CONTIGUOUS, DimOrder.SCALAR_OR_VECTOR):
315
+ return d
316
+ assert dim_order is DimOrder.CHANNELS_LAST
317
+ return [0, 2, 3, 1][d]
318
+
319
+
320
+ def flex_name(op_id, dim):
321
+ # Return the local variable name for the computed flexible size
322
+ # for a given op and dimension.
323
+ return f"s_{op_id}_{dim}"
324
+
325
+
326
+ class _NnapiSerializer:
327
+ def __init__(self, config, use_int16_for_qint16=False):
328
+ self.operands = []
329
+ self.values = []
330
+ self.operations = []
331
+ self.value_data = []
332
+ self.operation_args = []
333
+ self.inputs = []
334
+ self.outputs = []
335
+ self.flexible_shape_computation_lines = []
336
+
337
+ self.modules = {}
338
+ self.constants = {}
339
+ self.tensor_sequences = {}
340
+ self.jitval_operand_map = {}
341
+ self.cached_immediates = {}
342
+ self.used_weights = []
343
+ self.weight_offset = 0
344
+ self.use_int16_for_qint16 = use_int16_for_qint16
345
+
346
+ if config is None:
347
+ config = {}
348
+
349
+ def get_next_operand_id(self):
350
+ return len(self.operands)
351
+
352
+ # Add a tensor operand corresponding to a JIT Value.
353
+ # Returns the NNAPI operand ID. Can be looked up later with
354
+ # get_tensor_operand_by_jitval.
355
+ def add_tensor_operand(self, jitval, oper):
356
+ assert isinstance(oper, Operand)
357
+ if jitval in self.jitval_operand_map:
358
+ raise Exception(f"Duplicate tensor: {jitval!r}") # noqa: TRY002
359
+
360
+ operand_id = self.get_next_operand_id()
361
+ self.operands.append(oper)
362
+ self.jitval_operand_map[jitval] = operand_id
363
+ return operand_id
364
+
365
+ # Add a tensor operand that does not correspond to a JIT Value.
366
+ # Useful for cases where multiple NNAPI operands are required
367
+ # to implement one JIT IR node. Returns the NNAPI operand ID.
368
+ def add_anonymous_tensor_operand(self, oper):
369
+ assert isinstance(oper, Operand)
370
+ operand_id = self.get_next_operand_id()
371
+ self.operands.append(oper)
372
+ return operand_id
373
+
374
+ def torch_tensor_to_operand(self, tensor, dim_order):
375
+ dtype = str(tensor.dtype).replace("torch.", "")
376
+ scale = 0.0
377
+ zero_point = 0
378
+ if dtype == "float32":
379
+ op_type = NNAPI_OperandCode.TENSOR_FLOAT32
380
+ elif dtype == "int32":
381
+ op_type = NNAPI_OperandCode.TENSOR_INT32
382
+ elif dtype == "quint8":
383
+ op_type = NNAPI_OperandCode.TENSOR_QUANT8_ASYMM
384
+ scale = tensor.q_scale()
385
+ zero_point = tensor.q_zero_point()
386
+ elif dtype == "qint32":
387
+ op_type = NNAPI_OperandCode.TENSOR_INT32
388
+ scale = tensor.q_scale()
389
+ zero_point = tensor.q_zero_point()
390
+ assert zero_point == 0
391
+ elif dtype == "int16":
392
+ if self.use_int16_for_qint16:
393
+ nnapi_dtype = getattr(tensor, "nnapi_dtype", None)
394
+ op_codes = (
395
+ NNAPI_OperandCode.TENSOR_QUANT16_SYMM,
396
+ NNAPI_OperandCode.TENSOR_QUANT16_ASYMM,
397
+ )
398
+ if nnapi_dtype in op_codes:
399
+ op_type = nnapi_dtype
400
+ scale = tensor.nnapi_scale
401
+ zero_point = tensor.nnapi_zero_point
402
+ else:
403
+ raise Exception( # noqa: TRY002
404
+ f"`nnapi_type` needs to be one of {op_codes} for `int16`"
405
+ )
406
+ else:
407
+ raise Exception( # noqa: TRY002
408
+ "`int16` isn't supported. If you're trying to represent NNAPI"
409
+ " qint16 with Pytorch int16, set `use_int16_for_qint16 = True`"
410
+ )
411
+ else:
412
+ raise Exception( # noqa: TRY002
413
+ f"Can't handle input with dtype '{tensor.dtype}'"
414
+ ) # noqa: TRY002
415
+ return Operand(
416
+ shape=tuple(tensor.shape),
417
+ op_type=op_type,
418
+ dim_order=dim_order,
419
+ scale=scale,
420
+ zero_point=zero_point,
421
+ )
422
+
423
+ def add_tensor_operand_for_input(self, arg_idx, jitval, tensor):
424
+ dim_order = (
425
+ DimOrder.CHANNELS_LAST
426
+ if getattr(tensor, "nnapi_nhwc", False)
427
+ else DimOrder.PRESUMED_CONTIGUOUS
428
+ )
429
+ toper = self.torch_tensor_to_operand(tensor, dim_order)
430
+ operand_id = self.add_tensor_operand(jitval, toper)
431
+ self.inputs.append(operand_id)
432
+ for dim, size in enumerate(tensor.shape):
433
+ if size == 0:
434
+ self.compute_operand_shape(
435
+ operand_id, dim, f"args[{arg_idx}].shape[{dim}]"
436
+ )
437
+ return operand_id
438
+
439
+ def add_tensor_operand_for_weight(
440
+ self, tensor, dim_order=DimOrder.UNKNOWN_CONSTANT
441
+ ):
442
+ toper = self.torch_tensor_to_operand(tensor, dim_order)
443
+ operand_id = len(self.operands)
444
+ self.operands.append(toper)
445
+ tsize = tensor_size(toper.op_type, toper.shape)
446
+ self.values.append((operand_id, OperandValueSourceType.NUMBERED_BUFFER))
447
+ buf_num = len(self.used_weights)
448
+ offset = 0
449
+ self.value_data.append(struct.pack("iii", buf_num, offset, tsize))
450
+ # For NHWC NNAPI op, lay out data in the same dim order by permuting torch tensor
451
+ if dim_order == DimOrder.CHANNELS_LAST:
452
+ tensor = tensor.permute(0, 2, 3, 1)
453
+ self.used_weights.append(tensor)
454
+ return operand_id
455
+
456
+ def add_immediate_operand(self, code, value, dims):
457
+ assert isinstance(dims, tuple)
458
+ cache_key = (code, value)
459
+ if cache_key not in self.cached_immediates:
460
+ operand_id = len(self.operands)
461
+ self.operands.append(Operand(code, dims, DimOrder.SCALAR_OR_VECTOR, 0.0, 0))
462
+ self.values.append((operand_id, OperandValueSourceType.IMMEDIATE))
463
+ self.value_data.append(value)
464
+ self.cached_immediates[cache_key] = operand_id
465
+ return self.cached_immediates[cache_key]
466
+
467
+ def add_immediate_int_scalar(self, value):
468
+ return self.add_immediate_operand(
469
+ NNAPI_OperandCode.INT32, struct.pack("i", value), ()
470
+ )
471
+
472
+ def add_immediate_float_scalar(self, value):
473
+ return self.add_immediate_operand(
474
+ NNAPI_OperandCode.FLOAT32, struct.pack("f", value), ()
475
+ )
476
+
477
+ def add_immediate_bool_scalar(self, value):
478
+ return self.add_immediate_operand(
479
+ NNAPI_OperandCode.BOOL, b"\x01" if value else b"\x00", ()
480
+ )
481
+
482
+ def add_immediate_int_vector(self, value):
483
+ return self.add_immediate_operand(
484
+ NNAPI_OperandCode.TENSOR_INT32,
485
+ array.array("i", value).tobytes(),
486
+ (len(value),),
487
+ )
488
+
489
+ def has_operand_for_jitval(self, jitval):
490
+ return jitval in self.jitval_operand_map
491
+
492
+ def get_tensor_operand_by_jitval(self, jitval):
493
+ operand_id = self.jitval_operand_map[jitval]
494
+ return (operand_id, self.operands[operand_id])
495
+
496
+ def get_tensor_operand_by_jitval_fixed_size(self, jitval):
497
+ op_id, oper = self.get_tensor_operand_by_jitval(jitval)
498
+ for s in oper.shape:
499
+ if s == 0:
500
+ # TODO: Improve this error message, possibly after converting
501
+ # many callsites to support flexible size.
502
+ raise Exception( # noqa: TRY002
503
+ "Flexible size is not supported for this operand."
504
+ ) # noqa: TRY002
505
+ if s < 0:
506
+ # runtime flex
507
+ LOG.warning("Operand %s has runtime flex shape", oper)
508
+ return op_id, oper
509
+
510
+ def get_tensor_operand_or_constant(
511
+ self, jitval, dim_order=DimOrder.PRESUMED_CONTIGUOUS
512
+ ):
513
+ operand_id = self.jitval_operand_map.get(jitval)
514
+ if operand_id is None:
515
+ _, value = self.get_constant_value(jitval, "TensorType")
516
+ operand_id = self.add_tensor_operand_for_weight(value, dim_order)
517
+ return (operand_id, self.operands[operand_id])
518
+
519
+ def get_tensor_operand_for_weight(self, jitval):
520
+ _, value = self.get_constant_value(jitval, "TensorType")
521
+ operand_id = self.add_tensor_operand_for_weight(value)
522
+ return (operand_id, self.operands[operand_id])
523
+
524
+ def add_operation(self, opcode, inputs, outputs):
525
+ self.operations.append((opcode, len(inputs), len(outputs)))
526
+ self.operation_args.extend(inputs + outputs)
527
+
528
+ def add_tensor_sequence(self, jitval, values):
529
+ assert jitval not in self.tensor_sequences
530
+ self.tensor_sequences[jitval] = values
531
+
532
+ def add_constant_value(self, jitval, ctype, value):
533
+ assert jitval not in self.constants
534
+ self.constants[jitval] = (ctype, value)
535
+
536
+ def get_constant_value(self, jitval, typekind=None):
537
+ record = self.constants.get(jitval)
538
+ if record is None:
539
+ raise Exception( # noqa: TRY002
540
+ f"Could not find constant value for '{jitval!r}'."
541
+ ) # noqa: TRY002
542
+ ctype, _ = record
543
+ if typekind is not None and ctype.kind() != typekind:
544
+ raise Exception( # noqa: TRY002
545
+ f"Expected constant value of type {typekind}, but got {ctype.kind()} for value '{jitval!r}'"
546
+ )
547
+ return record
548
+
549
+ def operand_to_template_torchscript(self, op_id, oper, shape=None):
550
+ """Return a TorchScript expression to build a template for a given operand."""
551
+ if shape is None:
552
+ shape = oper.shape
553
+ else:
554
+ assert len(shape) == len(oper.shape)
555
+
556
+ shape_parts = ["("]
557
+ for d, s in enumerate(shape):
558
+ if s > 0:
559
+ # Fixed shape dimension: just add the value.
560
+ shape_parts.append(str(s))
561
+ elif s == 0:
562
+ # Load time flexible shape dimension: it should have been computed in a variable.
563
+ shape_parts.append(flex_name(op_id, d))
564
+ elif s == -1:
565
+ # Runtime flexible shape
566
+ shape_parts.append("0")
567
+ else:
568
+ raise Exception( # noqa: TRY002
569
+ "Unknown dim value, dimensions should be >= -1"
570
+ ) # noqa: TRY002
571
+ shape_parts.append(",")
572
+ shape_parts.append(")")
573
+ shape_code = "".join(shape_parts)
574
+ if oper.op_type == NNAPI_OperandCode.TENSOR_FLOAT32:
575
+ return f"torch.zeros({shape_code}, dtype=torch.float32)"
576
+ elif oper.op_type == NNAPI_OperandCode.TENSOR_INT32:
577
+ return f"torch.zeros({shape_code}, dtype=torch.int32)"
578
+ elif oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM:
579
+ return (
580
+ f"torch.quantize_per_tensor("
581
+ f"torch.zeros(1), scale={oper.scale}, zero_point={oper.zero_point}, dtype=torch.quint8)"
582
+ f".expand({shape_code}).contiguous()"
583
+ )
584
+ elif oper.op_type in (
585
+ NNAPI_OperandCode.TENSOR_QUANT16_ASYMM,
586
+ NNAPI_OperandCode.TENSOR_QUANT16_SYMM,
587
+ ):
588
+ if self.use_int16_for_qint16:
589
+ return f"torch.zeros({shape_code}, dtype=torch.int16)"
590
+ else:
591
+ raise Exception( # noqa: TRY002
592
+ "`int16` isn't supported. If you're trying to represent NNAPI"
593
+ " qint16 with Pytorch int16, set `use_int16_for_qint16 = True`"
594
+ )
595
+
596
+ raise Exception( # noqa: TRY002
597
+ f"Unsupported output operand type: {oper.op_type}"
598
+ ) # noqa: TRY002
599
+
600
+ def forward_operand_shape(self, out_op_id, out_dim, in_op_id, in_dim):
601
+ self.compute_operand_shape(out_op_id, out_dim, flex_name(in_op_id, in_dim))
602
+
603
+ def compute_operand_shape(self, op_id, dim, expr):
604
+ self.flexible_shape_computation_lines.append(
605
+ f"{flex_name(op_id, dim)} = {expr}"
606
+ )
607
+
608
+ def transpose_to_nhwc(self, in_id, oper):
609
+ if oper.shape[2:] != (1, 1):
610
+ raise Exception( # noqa: TRY002
611
+ "Automatic transpose only supported for H,W == 1,1"
612
+ ) # noqa: TRY002
613
+
614
+ out_oper = oper._replace(dim_order=DimOrder.CHANNELS_LAST)
615
+
616
+ inputs = [None] * 2
617
+ inputs[0] = in_id
618
+ inputs[1] = self.add_immediate_int_vector([0, 2, 3, 1])
619
+
620
+ outputs = [None] * 1
621
+ outputs[0] = self.add_anonymous_tensor_operand(out_oper)
622
+
623
+ self.add_operation(NNAPI_OperationCode.TRANSPOSE, inputs, outputs)
624
+
625
+ return outputs[0], out_oper
626
+
627
+ # Transpose inputs as necessary to allow broadcasting.
628
+ def transpose_for_broadcast(self, in0_id, in0_oper, in1_id, in1_oper):
629
+ if in0_oper.dim_order == in1_oper.dim_order:
630
+ return in0_id, in0_oper, in1_id, in1_oper
631
+
632
+ # Assume NHWC is preferred if there is a mismatch.
633
+ orders = (in0_oper.dim_order, in1_oper.dim_order)
634
+ if orders == (DimOrder.PRESUMED_CONTIGUOUS, DimOrder.CHANNELS_LAST):
635
+ return self.transpose_to_nhwc(in0_id, in0_oper) + (in1_id, in1_oper)
636
+ if orders == (DimOrder.CHANNELS_LAST, DimOrder.PRESUMED_CONTIGUOUS):
637
+ return (in0_id, in0_oper) + self.transpose_to_nhwc(in1_id, in1_oper)
638
+
639
+ raise Exception( # noqa: TRY002
640
+ f"Automatic transpose not supported for dim_orders: {in0_oper.dim_order!r}, {in1_oper.dim_order!r}"
641
+ )
642
+
643
+ def get_size_arg(self, jitval):
644
+ ctype, value = self.get_constant_value(jitval)
645
+ if ctype.kind() == "ListType":
646
+ assert ctype.getElementType().kind() == "IntType"
647
+ return value
648
+ raise Exception( # noqa: TRY002
649
+ f"Can't handle size arg of type '{ctype!r}' for '{jitval!r}'"
650
+ ) # noqa: TRY002
651
+
652
+ def get_conv_pool_args_2d_from_pack(self, kernel_size, packed_config):
653
+ pc = [i.item() for i in packed_config]
654
+ assert pc[0] == 2
655
+ strides = [pc[1], pc[2]]
656
+ paddings = [pc[3], pc[4]]
657
+ dilations = [pc[5], pc[6]]
658
+ output_padding = [pc[7], pc[8]]
659
+ group_num = pc[9]
660
+
661
+ assert len(pc) == 11
662
+ assert output_padding == [0, 0]
663
+
664
+ return self.get_conv_pool_args_2d_common(
665
+ kernel_size, strides, paddings, dilations, group_num
666
+ )
667
+
668
+ def get_conv_pool_args_2d_from_jit(
669
+ self, kernel_size, stride, padding, dilation=None, group=None
670
+ ):
671
+ strides = self.get_size_arg(stride)
672
+ paddings = self.get_size_arg(padding)
673
+ if dilation is None:
674
+ dilations = [1, 1]
675
+ else:
676
+ dilations = self.get_size_arg(dilation)
677
+ if group is not None:
678
+ _, group_num = self.get_constant_value(group, "IntType")
679
+ else:
680
+ group_num = None
681
+ return self.get_conv_pool_args_2d_common(
682
+ kernel_size, strides, paddings, dilations, group_num
683
+ )
684
+
685
+ def get_conv_pool_args_2d_common(
686
+ self, kernel_size, strides, paddings, dilations, group_num
687
+ ):
688
+ kernels = list(kernel_size)
689
+
690
+ assert len(kernels) == 2
691
+ assert len(strides) == 2
692
+ assert len(paddings) == 2
693
+ assert len(dilations) == 2
694
+
695
+ # NNAPI uses 4 values for padding.
696
+ ph, pw = paddings
697
+ real_paddings = [ph, ph, pw, pw]
698
+
699
+ return ConvPoolArgs2d(
700
+ *(kernels + strides + real_paddings + dilations + [group_num])
701
+ )
702
+
703
+ def serialize_model(self, model, inputs, return_shapes=None):
704
+ self.add_immediate_bool_scalar(False)
705
+ self.add_immediate_bool_scalar(True)
706
+
707
+ inp_dim_orders = []
708
+ out_dim_orders = []
709
+
710
+ self_jitval = next(model.graph.inputs())
711
+ self.add_constant_value(self_jitval, self_jitval.type(), model)
712
+
713
+ for arg_idx, (input_value, input_tensor) in enumerate(
714
+ zip(list(model.graph.inputs())[1:], inputs)
715
+ ):
716
+ op_id = self.add_tensor_operand_for_input(
717
+ arg_idx, input_value, input_tensor
718
+ )
719
+ inp_dim_orders.append(self.operands[op_id].dim_order.value)
720
+
721
+ for idx, node in enumerate(model.graph.nodes()):
722
+ LOG.debug("Processing node #%d: %r", idx, node)
723
+ self.add_node(node)
724
+
725
+ retn = model.graph.return_node()
726
+ assert retn.inputsSize() == 1
727
+ assert retn.outputsSize() == 0
728
+ retn_input = retn.inputsAt(0)
729
+ template_return_lines = ["return ["]
730
+ if retn_input.type().kind() == "TensorType":
731
+ return_values = [retn_input]
732
+ retval_count = -1
733
+ elif retn_input.type().kind() == "TupleType":
734
+ return_values = self.tensor_sequences[retn_input]
735
+ retval_count = len(return_values)
736
+ else:
737
+ raise Exception( # noqa: TRY002
738
+ f"Unsupported return type: {retn_input.type()}"
739
+ ) # noqa: TRY002
740
+
741
+ if return_shapes is not None:
742
+ assert len(return_shapes) == len(return_values)
743
+ for i, v in enumerate(return_values):
744
+ op_id = self.jitval_operand_map[v]
745
+ self.outputs.append(op_id)
746
+ out_dim_orders.append(self.operands[op_id].dim_order.value)
747
+ shape = return_shapes[i] if return_shapes else None
748
+ template_return_lines.append(
749
+ self.operand_to_template_torchscript(op_id, self.operands[op_id], shape)
750
+ + ","
751
+ )
752
+ template_return_lines.append("]")
753
+
754
+ model = []
755
+
756
+ version = 1
757
+ header = struct.pack(
758
+ "iiiiii",
759
+ version,
760
+ len(self.operands),
761
+ len(self.values),
762
+ len(self.operations),
763
+ len(self.inputs),
764
+ len(self.outputs),
765
+ )
766
+ model.append(header)
767
+
768
+ serialized_values, serialized_value_data = self.serialize_values()
769
+
770
+ model.extend(
771
+ struct.pack("iifi", t, len(d), s, z) for (t, d, _m, s, z) in self.operands
772
+ )
773
+ model.extend(serialized_values)
774
+ model.extend(struct.pack("iii", *x) for x in self.operations)
775
+
776
+ # Compact the model so we can get its length so far.
777
+ model = [b"".join(model)]
778
+ model_offset = len(model[0])
779
+ # Model offset is the index into the model (in 32-bit words, not bytes)
780
+ # of the next dimension we're about to serialize. If it's 0,
781
+ # generate code to mutate it before passing to NNAPI.
782
+ assert model_offset % 4 == 0
783
+ model_offset = int(model_offset / 4)
784
+
785
+ for op_id, (_, dims, dim_order, _, _) in enumerate(self.operands):
786
+ shape = fix_shape(dims, dim_order)
787
+ for d, s in enumerate(shape):
788
+ if s == 0:
789
+ pt_d = reverse_map_dim(dim_order, d)
790
+ self.flexible_shape_computation_lines.append(
791
+ f"ser_model[{model_offset}] = {flex_name(op_id, pt_d)}"
792
+ )
793
+ model_offset += 1
794
+
795
+ # convert runtime flex shape from -1 to 0
796
+ shape = tuple(d if d != -1 else 0 for d in shape)
797
+ model.append(self.serialize_ints(shape))
798
+
799
+ model.extend(serialized_value_data)
800
+ model.append(self.serialize_ints(self.operation_args))
801
+ model.append(self.serialize_ints(self.inputs))
802
+ model.append(self.serialize_ints(self.outputs))
803
+
804
+ self.flexible_shape_computation_lines.extend(template_return_lines)
805
+
806
+ return (
807
+ array.array("i", b"".join(model)),
808
+ self.used_weights,
809
+ inp_dim_orders,
810
+ out_dim_orders,
811
+ self.flexible_shape_computation_lines,
812
+ retval_count,
813
+ )
814
+
815
+ def serialize_values(self):
816
+ serialized_values = []
817
+ serialized_value_data = []
818
+ assert len(self.values) == len(self.value_data)
819
+ for (op_index, source_type), data in zip(self.values, self.value_data):
820
+ source_length = len(data)
821
+
822
+ # Pad with 0 bytes out to a multiple of 4 for alignment.
823
+ physical_length = ((source_length - 1) | 0x3) + 1
824
+ padded_data = data + (b"\0" * (physical_length - source_length))
825
+
826
+ serialized_values.append(
827
+ struct.pack("iii", op_index, source_type, source_length)
828
+ )
829
+ serialized_value_data.append(padded_data)
830
+
831
+ return serialized_values, serialized_value_data
832
+
833
+ @staticmethod
834
+ def serialize_ints(ints):
835
+ return array.array("i", ints).tobytes()
836
+
837
+ ADDER_MAP = {
838
+ "prim::GetAttr": lambda self, node: self.add_getattr(node),
839
+ "prim::Constant": lambda self, node: self.add_constant_node(node),
840
+ "prim::ListConstruct": lambda self, node: self.add_list_construct(node),
841
+ "prim::TupleConstruct": lambda self, node: self.add_tuple_construct(node),
842
+ "aten::unsqueeze": lambda self, node: self.add_unsqueeze(node),
843
+ "aten::to": lambda self, node: self.add_to(node),
844
+ "aten::detach": lambda self, node: self._identity(node),
845
+ "aten::reshape": lambda self, node: self.add_reshape(node),
846
+ "aten::flatten": lambda self, node: self.add_flatten(node),
847
+ "aten::slice": lambda self, node: self.add_slice(node),
848
+ "aten::size": lambda self, node: self.add_size(node),
849
+ "aten::cat": lambda self, node: self.add_cat(node),
850
+ "aten::mean": lambda self, node: self.add_mean(node),
851
+ "aten::quantize_per_tensor": lambda self, node: self.add_quantize(node),
852
+ "aten::dequantize": lambda self, node: self.add_dequantize(node),
853
+ "aten::add": lambda self, node: self.add_add_sub_op(
854
+ node, NNAPI_OperationCode.ADD, NNAPI_FuseCode.FUSED_NONE
855
+ ),
856
+ "aten::sub": lambda self, node: self.add_add_sub_op(
857
+ node, NNAPI_OperationCode.SUB, NNAPI_FuseCode.FUSED_NONE
858
+ ),
859
+ "aten::mul": lambda self, node: self.add_pointwise_simple_binary_broadcast_op(
860
+ node, NNAPI_OperationCode.MUL, NNAPI_FuseCode.FUSED_NONE
861
+ ),
862
+ "aten::div": lambda self, node: self.add_pointwise_simple_binary_broadcast_op(
863
+ node, NNAPI_OperationCode.DIV, NNAPI_FuseCode.FUSED_NONE
864
+ ),
865
+ "aten::relu": lambda self, node: self.add_pointwise_simple_unary_op(
866
+ node, NNAPI_OperationCode.RELU
867
+ ),
868
+ "aten::sigmoid": lambda self, node: self.add_pointwise_simple_unary_op(
869
+ node, NNAPI_OperationCode.LOGISTIC
870
+ ),
871
+ "aten::softmax": lambda self, node: self.add_softmax(node),
872
+ "aten::hardtanh": lambda self, node: self.add_hardtanh(node),
873
+ "aten::avg_pool2d": lambda self, node: self.add_avg_pool2d(node),
874
+ "aten::max_pool2d": lambda self, node: self.add_pool2d_node(
875
+ node, NNAPI_OperationCode.MAX_POOL_2D
876
+ ),
877
+ "aten::adaptive_avg_pool2d": lambda self, node: self.add_adaptive_avg_pool2d(
878
+ node
879
+ ),
880
+ "aten::upsample_nearest2d": lambda self, node: self.add_upsample_nearest2d(
881
+ node
882
+ ),
883
+ "aten::prelu": lambda self, node: self.add_prelu_op(node),
884
+ "aten::addmm": lambda self, node: self.add_addmm(node),
885
+ "aten::linear": lambda self, node: self.add_linear(node),
886
+ "aten::_convolution": lambda self, node: self.add_conv_underscore(node),
887
+ "aten::conv2d": lambda self, node: self.add_conv2d(node),
888
+ "aten::log_softmax": lambda self, node: self.add_log_softmax(node),
889
+ "quantized::linear": lambda self, node: self.add_qlinear(node),
890
+ "quantized::conv2d": lambda self, node: self.add_qconv2d(
891
+ node, NNAPI_FuseCode.FUSED_NONE
892
+ ),
893
+ "quantized::conv2d_relu": lambda self, node: self.add_qconv2d(
894
+ node, NNAPI_FuseCode.FUSED_RELU
895
+ ),
896
+ "quantized::conv_transpose2d": lambda self, node: self.add_qconv2d(
897
+ node, NNAPI_FuseCode.FUSED_NONE, transpose=True
898
+ ),
899
+ "quantized::add": lambda self, node: self.add_qadd(
900
+ node, NNAPI_OperationCode.ADD, NNAPI_FuseCode.FUSED_NONE
901
+ ),
902
+ "quantized::add_relu": lambda self, node: self.add_qadd(
903
+ node, NNAPI_OperationCode.ADD, NNAPI_FuseCode.FUSED_RELU
904
+ ),
905
+ "quantized::mul": lambda self, node: self.add_qadd(
906
+ node, NNAPI_OperationCode.MUL, NNAPI_FuseCode.FUSED_NONE
907
+ ),
908
+ }
909
+
910
+ def add_node(self, node):
911
+ adder = self.ADDER_MAP.get(node.kind())
912
+ if not adder:
913
+ raise Exception( # noqa: TRY002
914
+ f"Unsupported node kind ({node.kind()!r}) in node {node!r}"
915
+ ) # noqa: TRY002
916
+ adder(self, node)
917
+
918
+ def _identity(self, node):
919
+ in_id, _in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
920
+ jitval = node.outputsAt(0)
921
+ self.jitval_operand_map[jitval] = in_id
922
+
923
+ def add_getattr(self, node):
924
+ assert node.inputsSize() == 1
925
+ assert node.outputsSize() == 1
926
+ obj_ctype, obj = self.get_constant_value(node.inputsAt(0))
927
+ assert str(obj_ctype).startswith("__torch__.")
928
+ name = node.s("name")
929
+ value = getattr(obj, name)
930
+ output = node.outputsAt(0)
931
+ ctype = output.type()
932
+ self.add_constant_value(output, ctype, value)
933
+
934
+ def add_constant_node(self, node):
935
+ assert node.inputsSize() == 0
936
+ assert node.outputsSize() == 1
937
+ output = node.outputsAt(0)
938
+ ctype = output.type()
939
+ value = output.toIValue()
940
+ self.add_constant_value(output, ctype, value)
941
+
942
+ def add_list_construct(self, node):
943
+ assert node.outputsSize() == 1
944
+ output = node.outputsAt(0)
945
+ ctype = output.type()
946
+ const_vals: Optional[list] = []
947
+ tensors: Optional[list] = []
948
+ for inp in node.inputs():
949
+ if const_vals is not None and inp in self.constants:
950
+ _, val = self.get_constant_value(inp)
951
+ const_vals.append(val)
952
+ else:
953
+ const_vals = None
954
+ if tensors is not None and inp.type().kind() == "TensorType":
955
+ tensors.append(inp)
956
+ else:
957
+ tensors = None
958
+
959
+ if const_vals is not None:
960
+ # NOTE: Now that TorchScript supports list constants,
961
+ # this code path might not be used anymore.
962
+ self.add_constant_value(output, ctype, const_vals)
963
+ if tensors is not None:
964
+ self.add_tensor_sequence(output, tensors)
965
+ if const_vals is None and tensors is None:
966
+ raise Exception( # noqa: TRY002
967
+ f"Unable to handle ListConstruct node. Neither all constants nor all tensors. {node!r}"
968
+ )
969
+
970
+ def add_tuple_construct(self, node):
971
+ assert node.outputsSize() == 1
972
+ output = node.outputsAt(0)
973
+ values = list(node.inputs())
974
+ self.add_tensor_sequence(output, values)
975
+
976
+ def add_unsqueeze(self, node):
977
+ assert node.inputsSize() == 2
978
+ assert node.outputsSize() == 1
979
+
980
+ in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
981
+
982
+ _, dim = self.get_constant_value(node.inputsAt(1), "IntType")
983
+ assert in_oper.dim_order == DimOrder.PRESUMED_CONTIGUOUS
984
+
985
+ real_dim = dim if dim >= 0 else dim + len(in_oper.shape) + 1
986
+ out_shape_list = list(in_oper.shape)
987
+ out_shape_list.insert(real_dim, 1)
988
+ out_shape = tuple(out_shape_list)
989
+ out_oper = in_oper._replace(shape=out_shape)
990
+
991
+ inputs = [None] * 2
992
+ inputs[0] = in_id
993
+ inputs[1] = self.add_immediate_int_scalar(dim)
994
+
995
+ outputs = [None] * 1
996
+ outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
997
+
998
+ self.add_operation(NNAPI_OperationCode.EXPAND_DIMS, inputs, outputs)
999
+
1000
+ def add_to(self, node):
1001
+ # Handle to("cpu") / to("gpu") case
1002
+ self._identity(node)
1003
+
1004
+ def add_reshape(self, node):
1005
+ assert node.inputsSize() == 2
1006
+ assert node.outputsSize() == 1
1007
+
1008
+ in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
1009
+
1010
+ shape_ctype, shape = self.get_constant_value(node.inputsAt(1))
1011
+ assert shape_ctype.kind() == "ListType"
1012
+ assert shape_ctype.getElementType().kind() == "IntType"
1013
+ is_trivial_reshape = len(shape) == 2 and shape[1] == -1
1014
+
1015
+ if in_oper.dim_order != DimOrder.PRESUMED_CONTIGUOUS and not is_trivial_reshape:
1016
+ raise Exception( # noqa: TRY002
1017
+ "Currently, reshape is only supported on NHWC tensors if the target size is [X, -1]."
1018
+ )
1019
+
1020
+ # Bit of a hack here. Use a real tensor to infer the output shape.
1021
+ out_shape = torch.zeros(1).expand(in_oper.shape).reshape(shape).shape
1022
+ out_oper = in_oper._replace(
1023
+ shape=out_shape, dim_order=DimOrder.PRESUMED_CONTIGUOUS
1024
+ )
1025
+
1026
+ inputs = [None] * 2
1027
+ inputs[0] = in_id
1028
+ inputs[1] = self.add_immediate_int_vector(shape)
1029
+
1030
+ outputs = [None] * 1
1031
+ outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
1032
+
1033
+ self.add_operation(NNAPI_OperationCode.RESHAPE, inputs, outputs)
1034
+
1035
+ def add_flatten(self, node):
1036
+ assert node.inputsSize() == 3
1037
+ assert node.outputsSize() == 1
1038
+
1039
+ in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
1040
+
1041
+ _start_ctype, start_dim = self.get_constant_value(node.inputsAt(1), "IntType")
1042
+ _end_ctype, end_dim = self.get_constant_value(node.inputsAt(2), "IntType")
1043
+
1044
+ # channels last with channels == 1 or (height & width both 1)
1045
+ is_trivial_flatten = len(in_oper.shape) == 4 and (
1046
+ in_oper.shape[1] == 1 or (in_oper.shape[2] == 1 and in_oper.shape[3] == 1)
1047
+ )
1048
+ if in_oper.dim_order != DimOrder.PRESUMED_CONTIGUOUS and not is_trivial_flatten:
1049
+ raise Exception( # noqa: TRY002
1050
+ "Currently, flatten is not supported on NHWC tensors unless C=1 or H=W=1"
1051
+ )
1052
+
1053
+ if start_dim < 0:
1054
+ start_dim += len(in_oper.shape)
1055
+ if end_dim < 0:
1056
+ end_dim += len(in_oper.shape)
1057
+
1058
+ out_shape = (
1059
+ in_oper.shape[:start_dim]
1060
+ + (functools.reduce(operator.mul, in_oper.shape[start_dim : end_dim + 1]),)
1061
+ + in_oper.shape[end_dim + 1 :]
1062
+ )
1063
+
1064
+ if any(dim == 0 for dim in in_oper.shape[start_dim : end_dim + 1]):
1065
+ raise Exception( # noqa: TRY002
1066
+ "Flattening flexible dims is not supported yet"
1067
+ ) # noqa: TRY002
1068
+ non_flattened_dims = in_oper.shape[:start_dim] + in_oper.shape[end_dim + 1 :]
1069
+ if non_flattened_dims.count(0) > 1:
1070
+ raise Exception("Only 1 dim can be flexible") # noqa: TRY002
1071
+
1072
+ out_oper = in_oper._replace(
1073
+ shape=out_shape, dim_order=DimOrder.PRESUMED_CONTIGUOUS
1074
+ )
1075
+ out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
1076
+
1077
+ for idx, dim in enumerate(out_shape):
1078
+ if dim == 0:
1079
+ self.forward_operand_shape(out_id, idx, in_id, in_oper.shape.index(0))
1080
+
1081
+ inputs_1 = tuple(dim if dim != 0 else -1 for dim in out_shape)
1082
+ inputs = [None] * 2
1083
+ inputs[0] = in_id
1084
+ inputs[1] = self.add_immediate_int_vector(inputs_1)
1085
+
1086
+ outputs = [None] * 1
1087
+ outputs[0] = out_id
1088
+
1089
+ self.add_operation(NNAPI_OperationCode.RESHAPE, inputs, outputs)
1090
+
1091
+ def add_slice(self, node):
1092
+ assert node.inputsSize() == 5
1093
+ assert node.outputsSize() == 1
1094
+
1095
+ in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
1096
+ _, dim_value = self.get_constant_value(node.inputsAt(1))
1097
+ _, start_value = self.get_constant_value(node.inputsAt(2))
1098
+ _, stop_value = self.get_constant_value(node.inputsAt(3))
1099
+ _, step_value = self.get_constant_value(node.inputsAt(4))
1100
+
1101
+ if start_value is None:
1102
+ start_value = 0
1103
+ if stop_value is None:
1104
+ stop_value = sys.maxsize
1105
+
1106
+ if start_value < 0:
1107
+ start_value += in_oper.shape[dim_value]
1108
+ elif start_value == sys.maxsize:
1109
+ start_value = 0
1110
+
1111
+ if start_value == 0 and stop_value == sys.maxsize:
1112
+ self._identity(node)
1113
+ return
1114
+
1115
+ if in_oper.shape[dim_value] == 0:
1116
+ raise Exception("Unable to slice with flexible shape") # noqa: TRY002
1117
+
1118
+ if stop_value < 0:
1119
+ stop_value += in_oper.shape[dim_value]
1120
+ elif stop_value == sys.maxsize:
1121
+ stop_value = in_oper.shape[dim_value]
1122
+
1123
+ if start_value >= stop_value:
1124
+ raise Exception( # noqa: TRY002
1125
+ "Slice start value should be less than stop value"
1126
+ ) # noqa: TRY002
1127
+
1128
+ out_len = (stop_value - start_value) // step_value
1129
+ out_shape = tuple(
1130
+ out_len if i == dim_value else dim for i, dim in enumerate(in_oper.shape)
1131
+ )
1132
+ out_id = self.add_tensor_operand(
1133
+ node.outputsAt(0), in_oper._replace(shape=out_shape)
1134
+ )
1135
+
1136
+ # flex inputs
1137
+ end_mask = 0
1138
+ for idx, dim in enumerate(out_shape):
1139
+ if dim == 0:
1140
+ self.forward_operand_shape(out_id, idx, in_id, idx)
1141
+ end_mask |= 1 << idx
1142
+
1143
+ inputs = [None] * 7
1144
+ inputs[0] = in_id
1145
+ inputs[1] = self.add_immediate_int_vector(
1146
+ [start_value if i == dim_value else 0 for i in range(len(in_oper.shape))]
1147
+ )
1148
+ inputs[2] = self.add_immediate_int_vector(
1149
+ [
1150
+ stop_value if i == dim_value else dim
1151
+ for i, dim in enumerate(in_oper.shape)
1152
+ ]
1153
+ )
1154
+ inputs[3] = self.add_immediate_int_vector(
1155
+ [step_value if i == dim_value else 1 for i in range(len(in_oper.shape))]
1156
+ )
1157
+ inputs[4] = self.add_immediate_int_scalar(0) # begin mask
1158
+ inputs[5] = self.add_immediate_int_scalar(end_mask)
1159
+ inputs[6] = self.add_immediate_int_scalar(0) # shrink axis mas
1160
+
1161
+ outputs = [None] * 1
1162
+ outputs[0] = out_id
1163
+
1164
+ self.add_operation(NNAPI_OperationCode.STRIDED_SLICE, inputs, outputs)
1165
+
1166
+ def add_size(self, node):
1167
+ assert node.inputsSize() == 2
1168
+ assert node.outputsSize() == 1
1169
+
1170
+ _, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
1171
+ _, value = self.constants[node.inputsAt(1)]
1172
+ res = in_oper.shape[value]
1173
+ output = node.outputsAt(0)
1174
+ self.add_constant_value(output, output.type(), res)
1175
+
1176
+ def add_cat(self, node):
1177
+ assert node.inputsSize() == 2
1178
+ assert node.outputsSize() == 1
1179
+
1180
+ tensors = self.tensor_sequences[node.inputsAt(0)]
1181
+ _, dim = self.get_constant_value(node.inputsAt(1), "IntType")
1182
+
1183
+ assert len(tensors) > 0
1184
+ in_ids = []
1185
+ out_oper = None
1186
+ out_dim_size = 0
1187
+ for inp in tensors:
1188
+ in_id, in_oper = self.get_tensor_operand_by_jitval(inp)
1189
+ if out_oper is None:
1190
+ out_shape = change_element(in_oper.shape, dim, -1)
1191
+ out_oper = in_oper._replace(shape=out_shape)
1192
+ assert in_oper.op_type == out_oper.op_type
1193
+ assert in_oper.dim_order == out_oper.dim_order
1194
+ assert change_element(in_oper.shape, dim, -1) == change_element(
1195
+ out_oper.shape, dim, -1
1196
+ )
1197
+ # TODO: Possibly check scale and zero point.
1198
+ in_ids.append(in_id)
1199
+ # TODO: Possibly support variable-sized inputs.
1200
+ out_dim_size += in_oper.shape[dim]
1201
+
1202
+ assert out_oper is not None
1203
+ out_oper = out_oper._replace(
1204
+ shape=change_element(out_oper.shape, dim, out_dim_size)
1205
+ )
1206
+
1207
+ if in_oper.dim_order == DimOrder.CHANNELS_LAST: # type: ignore[possibly-undefined]
1208
+ assert len(out_oper.shape) == 4
1209
+ nnapi_dim = [0, 3, 1, 2][dim]
1210
+ else:
1211
+ nnapi_dim = dim
1212
+
1213
+ out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
1214
+ for idx, d in enumerate(out_oper.shape):
1215
+ if d == 0:
1216
+ if idx == dim:
1217
+ shape = " + ".join(flex_name(ip_id, dim) for ip_id in in_ids)
1218
+ self.compute_operand_shape(out_id, idx, shape)
1219
+ else:
1220
+ self.forward_operand_shape(out_id, idx, in_ids[0], idx)
1221
+
1222
+ inputs = in_ids + [self.add_immediate_int_scalar(nnapi_dim)]
1223
+
1224
+ outputs = [None] * 1
1225
+ outputs[0] = out_id
1226
+
1227
+ self.add_operation(NNAPI_OperationCode.CONCATENATION, inputs, outputs)
1228
+
1229
+ def add_mean(self, node):
1230
+ assert node.inputsSize() == 4
1231
+ assert node.outputsSize() == 1
1232
+
1233
+ in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
1234
+ dim_ctype, dim = self.get_constant_value(node.inputsAt(1))
1235
+ assert dim_ctype.kind() == "ListType"
1236
+ assert dim_ctype.getElementType().kind() == "IntType"
1237
+ _, keep_dim = self.get_constant_value(node.inputsAt(2), "BoolType")
1238
+ # Expect None for dtype
1239
+ self.get_constant_value(node.inputsAt(3), "NoneType")
1240
+
1241
+ if in_oper.dim_order == DimOrder.CHANNELS_LAST:
1242
+ assert len(in_oper.shape) == 4
1243
+ nnapi_dim = [[0, 3, 1, 2][d] for d in dim]
1244
+ else:
1245
+ nnapi_dim = dim
1246
+
1247
+ collapsed_dims = set()
1248
+ for d in dim:
1249
+ if d < 0:
1250
+ d += len(in_oper.shape)
1251
+ collapsed_dims.add(d)
1252
+
1253
+ if in_oper.dim_order == DimOrder.CHANNELS_LAST and not keep_dim:
1254
+ assert collapsed_dims.issuperset({2, 3})
1255
+ out_dim_order = DimOrder.PRESUMED_CONTIGUOUS
1256
+ else:
1257
+ out_dim_order = in_oper.dim_order
1258
+
1259
+ out_shape = []
1260
+ for i, s in enumerate(in_oper.shape):
1261
+ if i not in collapsed_dims:
1262
+ out_shape.append(s)
1263
+ elif keep_dim:
1264
+ out_shape.append(1)
1265
+
1266
+ out_oper = in_oper._replace(shape=out_shape, dim_order=out_dim_order)
1267
+
1268
+ inputs = [None] * 3
1269
+ inputs[0] = in_id
1270
+ inputs[1] = self.add_immediate_int_vector(nnapi_dim)
1271
+ inputs[2] = self.add_immediate_int_scalar(keep_dim)
1272
+
1273
+ outputs = [None] * 1
1274
+ outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
1275
+
1276
+ self.add_operation(NNAPI_OperationCode.MEAN, inputs, outputs)
1277
+
1278
+ def add_quantize(self, node):
1279
+ assert node.inputsSize() == 4
1280
+ assert node.outputsSize() == 1
1281
+
1282
+ in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
1283
+ if in_oper.dim_order != DimOrder.CHANNELS_LAST:
1284
+ raise Exception( # noqa: TRY002
1285
+ "Most hardware backends prefer NHWC quantized tensors. "
1286
+ "Try setting `t.nnapi_nhwc = True` on your tensor inputs. "
1287
+ )
1288
+ _, scale = self.get_constant_value(node.inputsAt(1), "FloatType")
1289
+ _, zero_point = self.get_constant_value(node.inputsAt(2), "IntType")
1290
+ _, scalar_type = self.get_constant_value(node.inputsAt(3), "IntType")
1291
+ if scalar_type != TorchScalarTypes.QUINT8.value:
1292
+ raise Exception( # noqa: TRY002
1293
+ "PyTorch NNAPI export only supports quantized tensors "
1294
+ "with the quint8 dtype."
1295
+ )
1296
+ op_type = NNAPI_OperandCode.TENSOR_QUANT8_ASYMM
1297
+
1298
+ out_oper = in_oper._replace(
1299
+ op_type=op_type,
1300
+ scale=scale,
1301
+ zero_point=zero_point,
1302
+ )
1303
+
1304
+ inputs = [None] * 1
1305
+ inputs[0] = in_id
1306
+
1307
+ outputs = [None] * 1
1308
+ outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
1309
+
1310
+ self.add_operation(NNAPI_OperationCode.QUANTIZE, inputs, outputs)
1311
+
1312
+ def add_dequantize(self, node):
1313
+ assert node.inputsSize() == 1
1314
+ assert node.outputsSize() == 1
1315
+
1316
+ in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
1317
+ out_oper = in_oper._replace(
1318
+ op_type=NNAPI_OperandCode.TENSOR_FLOAT32,
1319
+ scale=0.0,
1320
+ zero_point=0,
1321
+ )
1322
+
1323
+ inputs = [None] * 1
1324
+ inputs[0] = in_id
1325
+
1326
+ outputs = [None] * 1
1327
+ outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
1328
+
1329
+ self.add_operation(NNAPI_OperationCode.DEQUANTIZE, inputs, outputs)
1330
+
1331
+ def add_pointwise_simple_unary_op(self, node, opcode):
1332
+ assert node.inputsSize() == 1
1333
+ assert node.outputsSize() == 1
1334
+
1335
+ in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
1336
+
1337
+ out_oper = in_oper
1338
+ if opcode == NNAPI_OperationCode.LOGISTIC:
1339
+ # NNAPI docs: For ANEURALNETWORKS_TENSOR_QUANT8_ASYMM, the scale
1340
+ # must be 1.f / 256 and the zeroPoint must be 0.
1341
+ # https://fburl.com/h52stoog
1342
+ if in_oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM:
1343
+ out_oper = in_oper._replace(zero_point=0, scale=1.0 / 256)
1344
+
1345
+ out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
1346
+
1347
+ for idx, dim in enumerate(in_oper.shape):
1348
+ if dim == 0:
1349
+ self.forward_operand_shape(out_id, idx, in_id, idx)
1350
+
1351
+ inputs = [None] * 1
1352
+ inputs[0] = in_id
1353
+
1354
+ outputs = [None] * 1
1355
+ outputs[0] = out_id
1356
+
1357
+ self.add_operation(opcode, inputs, outputs)
1358
+
1359
+ def _do_add_binary(self, node, opcode, fuse_code, *, qparams=None): # noqa: D401
1360
+ """Helper for pointwise binary broadcast ops with superfluous extra args."""
1361
+ assert node.outputsSize() == 1
1362
+
1363
+ assert node.inputsAt(0).type().kind() == "TensorType"
1364
+ assert node.inputsAt(1).type().kind() == "TensorType"
1365
+
1366
+ if self.has_operand_for_jitval(node.inputsAt(0)):
1367
+ in0_id, in0_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
1368
+ in1_id, in1_oper = self.get_tensor_operand_or_constant(
1369
+ node.inputsAt(1), in0_oper.dim_order
1370
+ )
1371
+ elif self.has_operand_for_jitval(node.inputsAt(1)):
1372
+ in1_id, in1_oper = self.get_tensor_operand_by_jitval(node.inputsAt(1))
1373
+ in0_id, in0_oper = self.get_tensor_operand_or_constant(
1374
+ node.inputsAt(0), in1_oper.dim_order
1375
+ )
1376
+ else:
1377
+ raise Exception( # noqa: TRY002
1378
+ f"Can't do a NNAPI binary op: {opcode} on two constants"
1379
+ ) # noqa: TRY002
1380
+
1381
+ assert in0_oper.op_type == in1_oper.op_type
1382
+ in0_id, in0_oper, in1_id, in1_oper = self.transpose_for_broadcast(
1383
+ in0_id, in0_oper, in1_id, in1_oper
1384
+ )
1385
+ # NOTE: PyTorch and NNAPI have the same broadcast semantics.
1386
+ out_shape = broadcast_shapes(in0_oper.shape, in1_oper.shape)
1387
+ out_oper = in0_oper._replace(shape=out_shape)
1388
+ if qparams is not None:
1389
+ scale, zp = qparams
1390
+ out_oper = out_oper._replace(scale=scale, zero_point=zp)
1391
+
1392
+ out_id = self.add_tensor_operand(node.outputsAt(0), out_oper)
1393
+ for idx, (d0, d1) in enumerate(zip(in0_oper.shape, in1_oper.shape)):
1394
+ if d0 == 1 and d1 == 0:
1395
+ self.forward_operand_shape(out_id, idx, in1_id, idx)
1396
+ elif d0 == 0 and d1 == 1:
1397
+ self.forward_operand_shape(out_id, idx, in0_id, idx)
1398
+ elif d0 == 0 and d1 == 0:
1399
+ self.flexible_shape_computation_lines.append(
1400
+ f"assert {flex_name(in0_id, idx)} == {flex_name(in1_id, idx)}"
1401
+ )
1402
+ self.forward_operand_shape(out_id, idx, in0_id, idx)
1403
+
1404
+ inputs = [None] * 3
1405
+ inputs[0] = in0_id
1406
+ inputs[1] = in1_id
1407
+ inputs[2] = self.add_immediate_int_scalar(fuse_code)
1408
+
1409
+ outputs = [None] * 1
1410
+ outputs[0] = out_id
1411
+
1412
+ self.add_operation(opcode, inputs, outputs)
1413
+
1414
+ def add_pointwise_simple_binary_broadcast_op(self, node, opcode, fuse_code):
1415
+ assert node.inputsSize() == 2
1416
+ self._do_add_binary(node, opcode, fuse_code)
1417
+
1418
+ def add_add_sub_op(self, node, opcode, fuse_code):
1419
+ assert node.inputsSize() == 3
1420
+
1421
+ _, alpha = self.get_constant_value(node.inputsAt(2), "IntType")
1422
+ if alpha != 1:
1423
+ raise Exception( # noqa: TRY002
1424
+ "NNAPI does not support add/sub with alpha."
1425
+ ) # noqa: TRY002
1426
+
1427
+ self._do_add_binary(node, opcode, fuse_code)
1428
+
1429
+ def add_qadd(self, node, opcode, fuse_code):
1430
+ assert node.inputsSize() == 4
1431
+
1432
+ _, scale = self.get_constant_value(node.inputsAt(2), "FloatType")
1433
+ _, zero_point = self.get_constant_value(node.inputsAt(3), "IntType")
1434
+
1435
+ self._do_add_binary(node, opcode, fuse_code, qparams=(scale, zero_point))
1436
+
1437
+ def add_softmax(self, node):
1438
+ assert node.inputsSize() == 3
1439
+ in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
1440
+
1441
+ _, softmax_dim = self.get_constant_value(node.inputsAt(1), "IntType")
1442
+
1443
+ out_id = self.add_tensor_operand(node.outputsAt(0), in_oper)
1444
+ for dim, size in enumerate(in_oper.shape):
1445
+ if size == 0:
1446
+ self.forward_operand_shape(out_id, dim, in_id, dim)
1447
+
1448
+ inputs = [None] * 3
1449
+ inputs[0] = in_id
1450
+ inputs[1] = self.add_immediate_float_scalar(
1451
+ 1.0
1452
+ ) # positive scaling factor of exponent, beta
1453
+ inputs[2] = self.add_immediate_int_scalar(softmax_dim)
1454
+
1455
+ outputs = [None] * 1
1456
+ outputs[0] = out_id
1457
+
1458
+ self.add_operation(NNAPI_OperationCode.SOFTMAX, inputs, outputs)
1459
+
1460
+ def add_hardtanh(self, node):
1461
+ assert node.inputsSize() == 3
1462
+ assert node.outputsSize() == 1
1463
+
1464
+ in_id, in_oper = self.get_tensor_operand_by_jitval_fixed_size(node.inputsAt(0))
1465
+ _, min_val = self.get_constant_value(node.inputsAt(1), "FloatType")
1466
+ _, max_val = self.get_constant_value(node.inputsAt(2), "FloatType")
1467
+
1468
+ op_map = {
1469
+ (-1, 1): NNAPI_OperationCode.RELU1,
1470
+ (0, 6): NNAPI_OperationCode.RELU6, # noqa: E201
1471
+ }
1472
+
1473
+ opcode = op_map.get((min_val, max_val))
1474
+ if opcode is None:
1475
+ raise Exception( # noqa: TRY002
1476
+ "NNAPI only supports hardtanh with args (-1, 1) or (0, 6)."
1477
+ ) # noqa: TRY002
1478
+
1479
+ inputs = [None] * 1
1480
+ inputs[0] = in_id
1481
+
1482
+ outputs = [None] * 1
1483
+ outputs[0] = self.add_tensor_operand(node.outputsAt(0), in_oper)
1484
+
1485
+ self.add_operation(opcode, inputs, outputs)
1486
+
1487
+ def add_prelu_op(self, node):
1488
+ assert node.inputsSize() == 2
1489
+ assert node.outputsSize() == 1
1490
+
1491
+ assert node.inputsAt(0).type().kind() == "TensorType"
1492
+ assert node.inputsAt(1).type().kind() == "TensorType"
1493
+
1494
+ in_id, in_oper = self.get_tensor_operand_by_jitval(node.inputsAt(0))
1495
+ w_id, w_oper = self.get_tensor_operand_for_weight(node.inputsAt(1))
1496
+ assert len(w_oper.shape) == 1
1497
+ assert w_oper.shape[0] > 0
1498
+ if w_oper.shape[0] > 1:
1499
+ if in_oper.use_nchw():
1500
+ # TODO: Support this by adding trailing 1 dims.
1501
+ raise Exception( # noqa: TRY002
1502
+ "Per-channel PReLU only supports channels_last right now."
1503
+ )
1504
+
1505
+ out_id = self.add_tensor_operand(node.outputsAt(0), in_oper)
1506
+ for dim, size in enumerate(in_oper.shape):
1507
+ if size > 0:
1508
+ pass
1509
+ elif dim <= 1:
1510
+ raise Exception( # noqa: TRY002
1511
+ "PReLU requires fixed size for dim 0 and dim 1."
1512
+ ) # noqa: TRY002
1513
+ else:
1514
+ self.forward_operand_shape(out_id, dim, in_id, dim)
1515
+
1516
+ inputs = [None] * 2
1517
+ inputs[0] = in_id
1518
+ inputs[1] = w_id
1519
+
1520
+ outputs = [None] * 1
1521
+ outputs[0] = out_id
1522
+
1523
+ self.add_operation(NNAPI_OperationCode.PRELU, inputs, outputs)
1524
+
1525
+ def add_pool2d_node(self, node, opcode):
1526
+ assert node.inputsSize() == 6
1527
+ assert node.outputsSize() == 1
1528
+ image, kernel, stride, padding, dilation, _ceil_mode = node.inputs()
1529
+
1530
+ stride = stride or kernel
1531
+
1532
+ # TODO: Validate ceil_mode semantics.
1533
+
1534
+ args = self.get_conv_pool_args_2d_from_jit(
1535
+ self.get_size_arg(kernel), stride, padding, dilation
1536
+ )
1537
+ if args.dilation_h != 1 or args.dilation_w != 1:
1538
+ raise Exception("NNAPI does not support dilated pooling.") # noqa: TRY002
1539
+
1540
+ image_id, image_oper = self.get_tensor_operand_by_jitval_fixed_size(image)
1541
+ assert len(image_oper.shape) == 4
1542
+
1543
+ out_shape = get_conv_pool_shape(
1544
+ image_oper.shape, args, image_oper.shape[1], False
1545
+ )
1546
+ use_nchw = image_oper.use_nchw()
1547
+
1548
+ inputs = [None] * 11
1549
+ inputs[0] = image_id
1550
+ inputs[1] = self.add_immediate_int_scalar(args.pad_l)
1551
+ inputs[2] = self.add_immediate_int_scalar(args.pad_r)
1552
+ inputs[3] = self.add_immediate_int_scalar(args.pad_t)
1553
+ inputs[4] = self.add_immediate_int_scalar(args.pad_b)
1554
+ inputs[5] = self.add_immediate_int_scalar(args.stride_w)
1555
+ inputs[6] = self.add_immediate_int_scalar(args.stride_h)
1556
+ inputs[7] = self.add_immediate_int_scalar(args.kernel_w)
1557
+ inputs[8] = self.add_immediate_int_scalar(args.kernel_h)
1558
+ inputs[9] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
1559
+ inputs[10] = self.add_immediate_bool_scalar(use_nchw)
1560
+
1561
+ outputs = [None] * 1
1562
+ outputs[0] = self.add_tensor_operand(
1563
+ node.outputsAt(0), image_oper._replace(shape=out_shape)
1564
+ )
1565
+
1566
+ self.add_operation(opcode, inputs, outputs)
1567
+
1568
+ def add_avg_pool2d(self, node):
1569
+ assert node.inputsSize() == 7
1570
+ assert node.outputsSize() == 1
1571
+ (
1572
+ image,
1573
+ kernel,
1574
+ stride,
1575
+ padding,
1576
+ _ceil_mode,
1577
+ count_include_pad,
1578
+ divisor_override,
1579
+ ) = node.inputs()
1580
+
1581
+ _, count_include_pad_value = self.get_constant_value(count_include_pad)
1582
+ _, divisor_override_value = self.get_constant_value(divisor_override)
1583
+ if not count_include_pad_value or divisor_override_value:
1584
+ raise Exception( # noqa: TRY002
1585
+ "NNAPI doesn't support count_include_pad=False or divisor_override"
1586
+ )
1587
+
1588
+ args = self.get_conv_pool_args_2d_from_jit(
1589
+ self.get_size_arg(kernel), stride, padding
1590
+ )
1591
+
1592
+ image_id, image_oper = self.get_tensor_operand_by_jitval(image)
1593
+ assert len(image_oper.shape) == 4
1594
+
1595
+ out_shape = get_conv_pool_shape(
1596
+ image_oper.shape, args, image_oper.shape[1], False
1597
+ )
1598
+ use_nchw = image_oper.use_nchw()
1599
+
1600
+ inputs = [None] * 11
1601
+ inputs[0] = image_id
1602
+ inputs[1] = self.add_immediate_int_scalar(args.pad_l)
1603
+ inputs[2] = self.add_immediate_int_scalar(args.pad_r)
1604
+ inputs[3] = self.add_immediate_int_scalar(args.pad_t)
1605
+ inputs[4] = self.add_immediate_int_scalar(args.pad_b)
1606
+ inputs[5] = self.add_immediate_int_scalar(args.stride_w)
1607
+ inputs[6] = self.add_immediate_int_scalar(args.stride_h)
1608
+ inputs[7] = self.add_immediate_int_scalar(args.kernel_w)
1609
+ inputs[8] = self.add_immediate_int_scalar(args.kernel_h)
1610
+ inputs[9] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
1611
+ inputs[10] = self.add_immediate_bool_scalar(use_nchw)
1612
+
1613
+ outputs = [None] * 1
1614
+ out_id = self.add_tensor_operand(
1615
+ node.outputsAt(0), image_oper._replace(shape=out_shape)
1616
+ )
1617
+ self._handle_conv_pool_flexible_input(out_id, image, args, False)
1618
+ outputs[0] = out_id
1619
+
1620
+ self.add_operation(NNAPI_OperationCode.AVERAGE_POOL_2D, inputs, outputs)
1621
+
1622
+ def add_adaptive_avg_pool2d(self, node):
1623
+ assert node.inputsSize() == 2
1624
+ assert node.outputsSize() == 1
1625
+
1626
+ image_id, image_oper = self.get_tensor_operand_by_jitval_fixed_size(
1627
+ node.inputsAt(0)
1628
+ )
1629
+ assert len(image_oper.shape) == 4
1630
+
1631
+ size_ctype, size_arg = self.get_constant_value(node.inputsAt(1))
1632
+ assert size_ctype.kind() == "ListType"
1633
+ assert size_ctype.getElementType().kind() == "IntType"
1634
+ if size_arg != [1, 1]:
1635
+ raise Exception( # noqa: TRY002
1636
+ "NNAPI only supports adaptive_avg_pool2d with output size (1, 1)."
1637
+ )
1638
+
1639
+ out_shape = image_oper.shape[0:2] + tuple(size_arg)
1640
+ use_nchw = image_oper.use_nchw()
1641
+
1642
+ inputs = [None] * 11
1643
+ inputs[0] = image_id
1644
+ inputs[1] = self.add_immediate_int_scalar(0)
1645
+ inputs[2] = self.add_immediate_int_scalar(0)
1646
+ inputs[3] = self.add_immediate_int_scalar(0)
1647
+ inputs[4] = self.add_immediate_int_scalar(0)
1648
+ inputs[5] = self.add_immediate_int_scalar(1)
1649
+ inputs[6] = self.add_immediate_int_scalar(1)
1650
+ inputs[7] = self.add_immediate_int_scalar(image_oper.shape[3])
1651
+ inputs[8] = self.add_immediate_int_scalar(image_oper.shape[2])
1652
+ inputs[9] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
1653
+ inputs[10] = self.add_immediate_bool_scalar(use_nchw)
1654
+
1655
+ outputs = [None] * 1
1656
+ outputs[0] = self.add_tensor_operand(
1657
+ node.outputsAt(0), image_oper._replace(shape=out_shape)
1658
+ )
1659
+
1660
+ self.add_operation(NNAPI_OperationCode.AVERAGE_POOL_2D, inputs, outputs)
1661
+
1662
+ def add_upsample_nearest2d(self, node):
1663
+ assert node.inputsSize() == 3 or node.inputsSize() == 4
1664
+ assert node.outputsSize() == 1
1665
+ if node.inputsSize() == 3:
1666
+ image, size_jit, scale_jit = node.inputs()
1667
+ else:
1668
+ image, size_jit, scale_h_jit, scale_w_jit = node.inputs()
1669
+ size_ctype, size_arg = self.get_constant_value(size_jit)
1670
+
1671
+ if node.inputsSize() == 3:
1672
+ scale_ctype, scale_arg = self.get_constant_value(scale_jit) # type: ignore[possibly-undefined]
1673
+ else:
1674
+ scale_h_ctype, scale_h_arg = self.get_constant_value(scale_h_jit) # type: ignore[possibly-undefined]
1675
+ scale_w_ctype, _scale_w_arg = self.get_constant_value(scale_w_jit) # type: ignore[possibly-undefined]
1676
+
1677
+ # The only way for the 4-argument overload of upsample_nearest2d to
1678
+ # have been added to the graph without error is if the scale_h and
1679
+ # scale_w arguments are None
1680
+ assert scale_h_ctype.kind() == "NoneType"
1681
+ assert scale_w_ctype.kind() == "NoneType"
1682
+
1683
+ scale_ctype = scale_h_ctype
1684
+ scale_arg = scale_h_arg
1685
+
1686
+ image_id, image_oper = self.get_tensor_operand_by_jitval(image)
1687
+ assert len(image_oper.shape) == 4
1688
+
1689
+ if size_ctype.kind() != "NoneType" and scale_ctype.kind() != "NoneType":
1690
+ raise Exception("Size and scale cannot both be non-None.") # noqa: TRY002
1691
+ elif size_ctype.kind() != "NoneType":
1692
+ assert size_ctype.kind() == "ListType"
1693
+ assert size_ctype.getElementType().kind() == "IntType"
1694
+ assert scale_ctype.kind() == "NoneType"
1695
+ assert scale_arg is None
1696
+ assert isinstance(size_arg, list)
1697
+ assert size_arg
1698
+ assert all(isinstance(val, int) for val in size_arg)
1699
+ if len(size_arg) == 1:
1700
+ size_arg = size_arg * 2
1701
+ assert len(size_arg) == 2
1702
+ out_h = size_arg[0]
1703
+ out_w = size_arg[1]
1704
+ arg_h = self.add_immediate_int_scalar(out_h)
1705
+ arg_w = self.add_immediate_int_scalar(out_w)
1706
+ elif scale_ctype.kind() != "NoneType":
1707
+ assert scale_ctype.kind() == "ListType"
1708
+ assert scale_ctype.getElementType().kind() == "FloatType"
1709
+ assert size_ctype.kind() == "NoneType"
1710
+ assert size_arg is None
1711
+ assert isinstance(scale_arg, list)
1712
+ assert scale_arg
1713
+ assert all(isinstance(val, float) for val in scale_arg)
1714
+ if len(scale_arg) == 1:
1715
+ scale_arg = scale_arg * 2
1716
+ assert len(scale_arg) == 2
1717
+ out_h = int(scale_arg[0] * image_oper.shape[2])
1718
+ out_w = int(scale_arg[1] * image_oper.shape[3])
1719
+ arg_h = self.add_immediate_float_scalar(scale_arg[0])
1720
+ arg_w = self.add_immediate_float_scalar(scale_arg[1])
1721
+ else:
1722
+ raise Exception("Size and scale cannot both be None.") # noqa: TRY002
1723
+
1724
+ out_shape = (image_oper.shape[0], image_oper.shape[1], out_h, out_w)
1725
+ use_nchw = image_oper.use_nchw()
1726
+ out_id = self.add_tensor_operand(
1727
+ node.outputsAt(0), image_oper._replace(shape=out_shape)
1728
+ )
1729
+
1730
+ if image_oper.shape[0] == 0 or image_oper.shape[1] == 0:
1731
+ raise Exception("Flexible batch or channels not supported") # noqa: TRY002
1732
+
1733
+ # Handle variable input size
1734
+ for dim in (2, 3): # h, w indices
1735
+ if image_oper.shape[dim] == 0:
1736
+ if size_ctype.kind() != "NoneType":
1737
+ self.compute_operand_shape(out_id, dim, size_arg[dim - 2])
1738
+ elif scale_ctype.kind() != "NoneType":
1739
+ self.compute_operand_shape(
1740
+ out_id,
1741
+ dim,
1742
+ f"int({scale_arg[dim - 2]} * {flex_name(image_id, dim)})",
1743
+ )
1744
+ else:
1745
+ raise Exception( # noqa: TRY002
1746
+ "Size and scale cannot both be None."
1747
+ ) # noqa: TRY002
1748
+
1749
+ inputs = [None] * 4
1750
+ inputs[0] = image_id
1751
+ inputs[1] = arg_w
1752
+ inputs[2] = arg_h
1753
+ inputs[3] = self.add_immediate_bool_scalar(use_nchw)
1754
+
1755
+ outputs = [None] * 1
1756
+ outputs[0] = out_id
1757
+
1758
+ self.add_operation(NNAPI_OperationCode.RESIZE_NEAREST_NEIGHBOR, inputs, outputs)
1759
+
1760
+ def add_addmm(self, node):
1761
+ assert node.inputsSize() == 5
1762
+ assert node.outputsSize() == 1
1763
+ jit_bias, jit_input, jit_weight, jit_beta, jit_alpha = node.inputs()
1764
+
1765
+ for jitval in (jit_beta, jit_alpha):
1766
+ scale_ctype, scale_value = self.get_constant_value(jitval)
1767
+ assert scale_ctype.kind() in ("IntType", "FloatType")
1768
+ if scale_value != 1:
1769
+ raise Exception( # noqa: TRY002
1770
+ "NNAPI Fully-Connected does not support alpha and beta."
1771
+ )
1772
+
1773
+ self.add_addmm_or_linear(node, True, jit_input, jit_weight, jit_bias)
1774
+
1775
+ def add_linear(self, node):
1776
+ assert node.inputsSize() == 3
1777
+ assert node.outputsSize() == 1
1778
+ jit_input, jit_weight, jit_bias = node.inputs()
1779
+
1780
+ self.add_addmm_or_linear(node, False, jit_input, jit_weight, jit_bias)
1781
+
1782
+ def add_addmm_or_linear(
1783
+ self, node, transpose_weight, jit_input, jit_weight, jit_bias
1784
+ ):
1785
+ input_id, input_oper = self.get_tensor_operand_by_jitval(jit_input)
1786
+ bias_id, bias_oper = self.get_tensor_operand_for_weight(jit_bias)
1787
+
1788
+ assert len(input_oper.shape) == 2
1789
+ assert len(bias_oper.shape) == 1
1790
+
1791
+ # TODO: Transform at load time to share weights with CPU model.
1792
+ _, weight_tensor = self.get_constant_value(jit_weight, "TensorType")
1793
+ assert len(weight_tensor.shape) == 2
1794
+ if transpose_weight:
1795
+ nnapi_weight_tensor = weight_tensor.t().contiguous()
1796
+ else:
1797
+ nnapi_weight_tensor = weight_tensor.contiguous()
1798
+ weight_id = self.add_tensor_operand_for_weight(nnapi_weight_tensor)
1799
+ weight_oper = self.operands[weight_id]
1800
+
1801
+ out_shape = (input_oper.shape[0], weight_oper.shape[0])
1802
+ out_id = self.add_tensor_operand(
1803
+ node.outputsAt(0), input_oper._replace(shape=out_shape)
1804
+ )
1805
+
1806
+ if input_oper.shape[0] == 0:
1807
+ self.forward_operand_shape(out_id, 0, input_id, 0)
1808
+
1809
+ inputs = [None] * 4
1810
+ inputs[0] = input_id
1811
+ inputs[1] = weight_id
1812
+ inputs[2] = bias_id
1813
+ inputs[3] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
1814
+
1815
+ outputs = [None] * 1
1816
+ outputs[0] = out_id
1817
+
1818
+ self.add_operation(NNAPI_OperationCode.FULLY_CONNECTED, inputs, outputs)
1819
+
1820
+ def add_qlinear(self, node):
1821
+ assert node.inputsSize() == 4
1822
+ assert node.outputsSize() == 1
1823
+ (
1824
+ jit_input,
1825
+ jit_packed_weight,
1826
+ jit_scale,
1827
+ jit_zero_point,
1828
+ ) = node.inputs()
1829
+
1830
+ input_id, input_oper = self.get_tensor_operand_by_jitval_fixed_size(jit_input)
1831
+ # TODO: Support automatic reshape
1832
+ assert len(input_oper.shape) == 2
1833
+
1834
+ _, out_scale = self.get_constant_value(jit_scale, "FloatType")
1835
+ _, out_zero_point = self.get_constant_value(jit_zero_point, "IntType")
1836
+ weight_ctype, packed_weight = self.get_constant_value(jit_packed_weight)
1837
+ assert weight_ctype.name() == "LinearPackedParamsBase"
1838
+ raw_weight, raw_bias = packed_weight.__getstate__()[0]
1839
+ assert raw_bias is not None
1840
+
1841
+ assert len(raw_weight.shape) == 2
1842
+ assert len(raw_bias.shape) == 1
1843
+ assert raw_bias.shape[0] == raw_weight.shape[0]
1844
+ assert raw_weight.shape[1] == input_oper.shape[1]
1845
+
1846
+ assert raw_weight.qscheme() == torch.per_tensor_affine
1847
+ if raw_weight.dtype == torch.quint8:
1848
+ unsigned_weight = raw_weight
1849
+ else:
1850
+ assert raw_weight.dtype == torch.qint8
1851
+ unsigned_weight = torch._make_per_tensor_quantized_tensor(
1852
+ (raw_weight.int_repr().int() + 128).to(torch.uint8),
1853
+ scale=raw_weight.q_scale(),
1854
+ zero_point=raw_weight.q_zero_point() + 128,
1855
+ )
1856
+ weight_scale = unsigned_weight.q_scale()
1857
+ bias_scale = input_oper.scale * weight_scale
1858
+ int_bias = torch.quantize_per_tensor(raw_bias, bias_scale, 0, torch.qint32)
1859
+ bias_id = self.add_tensor_operand_for_weight(int_bias)
1860
+
1861
+ multiplier = input_oper.scale * weight_scale / out_scale
1862
+ assert multiplier > 0
1863
+ if multiplier >= 1:
1864
+ raise Exception( # noqa: TRY002
1865
+ "Quantized convolution multiplier is greater than 1. "
1866
+ "This is supported by NNAPI, but not by most hardware backends. "
1867
+ "Try training a model without quantization-aware training. "
1868
+ )
1869
+
1870
+ # TODO: Transform at load time to share weights with CPU model.
1871
+ nnapi_weight_tensor = unsigned_weight.contiguous()
1872
+ weight_id = self.add_tensor_operand_for_weight(nnapi_weight_tensor)
1873
+ weight_oper = self.operands[weight_id]
1874
+
1875
+ out_shape = (input_oper.shape[0], weight_oper.shape[0])
1876
+ out_oper = input_oper._replace(
1877
+ shape=out_shape,
1878
+ scale=out_scale,
1879
+ zero_point=out_zero_point,
1880
+ )
1881
+
1882
+ inputs = [None] * 4
1883
+ inputs[0] = input_id
1884
+ inputs[1] = weight_id
1885
+ inputs[2] = bias_id
1886
+ inputs[3] = self.add_immediate_int_scalar(NNAPI_FuseCode.FUSED_NONE)
1887
+
1888
+ outputs = [None] * 1
1889
+ outputs[0] = self.add_tensor_operand(node.outputsAt(0), out_oper)
1890
+
1891
+ self.add_operation(NNAPI_OperationCode.FULLY_CONNECTED, inputs, outputs)
1892
+
1893
+ def get_optional_bias(self, jit_bias, weight_tensor, transpose=False):
1894
+ ctype, _value = self.get_constant_value(jit_bias)
1895
+ if ctype.kind() == "NoneType":
1896
+ bias_idx = 1 if transpose else 0
1897
+ nnapi_bias_tensor = torch.zeros(
1898
+ weight_tensor.size()[bias_idx], dtype=weight_tensor.dtype
1899
+ )
1900
+ bias_id = self.add_tensor_operand_for_weight(nnapi_bias_tensor)
1901
+ bias_oper = self.operands[bias_id]
1902
+ return bias_id, bias_oper
1903
+ else:
1904
+ return self.get_tensor_operand_for_weight(jit_bias)
1905
+
1906
+ def add_conv2d(self, node):
1907
+ assert node.inputsSize() == 7
1908
+ assert node.outputsSize() == 1
1909
+
1910
+ (
1911
+ jit_image,
1912
+ jit_weight,
1913
+ jit_bias,
1914
+ jit_stride,
1915
+ jit_pad,
1916
+ jit_dilation,
1917
+ jit_groups,
1918
+ ) = node.inputs()
1919
+
1920
+ _, weight_tensor = self.get_constant_value(jit_weight, "TensorType")
1921
+ bias_id, _bias_oper = self.get_optional_bias(jit_bias, weight_tensor)
1922
+ args = self.get_conv_pool_args_2d_from_jit(
1923
+ weight_tensor.shape[2:4], jit_stride, jit_pad, jit_dilation, jit_groups
1924
+ )
1925
+
1926
+ return self.add_conv2d_common(
1927
+ node.outputsAt(0),
1928
+ 0.0,
1929
+ 0,
1930
+ jit_image,
1931
+ weight_tensor,
1932
+ bias_id,
1933
+ args,
1934
+ False, # transpose
1935
+ NNAPI_FuseCode.FUSED_NONE,
1936
+ )
1937
+
1938
+ def add_conv_underscore(self, node):
1939
+ assert node.inputsSize() == 13
1940
+ assert node.outputsSize() == 1
1941
+
1942
+ (
1943
+ jit_image,
1944
+ jit_weight,
1945
+ jit_bias,
1946
+ jit_stride,
1947
+ jit_pad,
1948
+ jit_dilation,
1949
+ jit_transpose,
1950
+ _,
1951
+ jit_groups,
1952
+ _,
1953
+ _,
1954
+ _,
1955
+ _,
1956
+ ) = node.inputs()
1957
+
1958
+ _, weight_tensor = self.get_constant_value(jit_weight, "TensorType")
1959
+ _, transpose = self.get_constant_value(jit_transpose)
1960
+ bias_id, _bias_oper = self.get_optional_bias(jit_bias, weight_tensor, transpose)
1961
+ args = self.get_conv_pool_args_2d_from_jit(
1962
+ weight_tensor.shape[2:4], jit_stride, jit_pad, jit_dilation, jit_groups
1963
+ )
1964
+
1965
+ return self.add_conv2d_common(
1966
+ node.outputsAt(0),
1967
+ 0.0,
1968
+ 0,
1969
+ jit_image,
1970
+ weight_tensor,
1971
+ bias_id,
1972
+ args,
1973
+ transpose,
1974
+ NNAPI_FuseCode.FUSED_NONE,
1975
+ )
1976
+
1977
+ def add_log_softmax(self, node):
1978
+ assert node.inputsSize() == 3
1979
+ assert node.outputsSize() == 1
1980
+
1981
+ jit_input, jit_dim, _jit_half_to_float = node.inputs()
1982
+ input_id, input_oper = self.get_tensor_operand_by_jitval_fixed_size(jit_input)
1983
+ _, dim = self.get_constant_value(jit_dim, "IntType")
1984
+
1985
+ out_shape = input_oper.shape
1986
+
1987
+ inputs = [None] * 3
1988
+ inputs[0] = input_id
1989
+ # specifying 1 as the scaling factor for the exponent, beta
1990
+ inputs[1] = self.add_immediate_float_scalar(1)
1991
+ inputs[2] = self.add_immediate_int_scalar(dim)
1992
+
1993
+ outputs = [None] * 1
1994
+ outputs[0] = self.add_tensor_operand(
1995
+ node.outputsAt(0), input_oper._replace(shape=out_shape)
1996
+ )
1997
+ self.add_operation(NNAPI_OperationCode.LOG_SOFTMAX, inputs, outputs)
1998
+
1999
+ def add_qconv2d(self, node, fuse_code, transpose=False):
2000
+ assert node.inputsSize() == 4
2001
+ assert node.outputsSize() == 1
2002
+
2003
+ (
2004
+ jit_image,
2005
+ jit_packed_weight,
2006
+ jit_scale,
2007
+ jit_zero_point,
2008
+ ) = node.inputs()
2009
+
2010
+ _, out_scale = self.get_constant_value(jit_scale, "FloatType")
2011
+ _, out_zero_point = self.get_constant_value(jit_zero_point, "IntType")
2012
+ weight_ctype, packed_weight = self.get_constant_value(jit_packed_weight)
2013
+ assert weight_ctype.name() == "Conv2dPackedParamsBase"
2014
+ (
2015
+ pack_version,
2016
+ tensors,
2017
+ opt_tensors,
2018
+ ) = packed_weight.__getstate__()[0]
2019
+ assert pack_version == "2"
2020
+ packed_config, raw_weight = tensors
2021
+ (raw_bias,) = opt_tensors
2022
+ assert raw_bias is not None
2023
+ args = self.get_conv_pool_args_2d_from_pack(
2024
+ raw_weight.shape[2:4], packed_config
2025
+ )
2026
+
2027
+ assert raw_weight.qscheme() == torch.per_tensor_affine
2028
+ if raw_weight.dtype == torch.quint8:
2029
+ unsigned_weight = raw_weight
2030
+ else:
2031
+ assert raw_weight.dtype == torch.qint8
2032
+ unsigned_weight = torch._make_per_tensor_quantized_tensor(
2033
+ (raw_weight.int_repr().int() + 128).to(torch.uint8),
2034
+ scale=raw_weight.q_scale(),
2035
+ zero_point=raw_weight.q_zero_point() + 128,
2036
+ )
2037
+ weight_scale = unsigned_weight.q_scale()
2038
+ _, image_oper = self.get_tensor_operand_by_jitval(jit_image)
2039
+ bias_scale = image_oper.scale * weight_scale
2040
+ int_bias = torch.quantize_per_tensor(raw_bias, bias_scale, 0, torch.qint32)
2041
+ bias_id = self.add_tensor_operand_for_weight(int_bias)
2042
+
2043
+ multiplier = image_oper.scale * weight_scale / out_scale
2044
+ assert multiplier > 0
2045
+ if multiplier >= 1:
2046
+ raise Exception( # noqa: TRY002
2047
+ "Quantized convolution multiplier is greater than 1. "
2048
+ "This is supported by NNAPI, but not by most hardware backends. "
2049
+ "Try training a model without quantization-aware training. "
2050
+ )
2051
+
2052
+ return self.add_conv2d_common(
2053
+ node.outputsAt(0),
2054
+ out_scale,
2055
+ out_zero_point,
2056
+ jit_image,
2057
+ unsigned_weight,
2058
+ bias_id,
2059
+ args,
2060
+ transpose,
2061
+ fuse_code,
2062
+ )
2063
+
2064
+ def add_conv2d_common(
2065
+ self,
2066
+ jit_out,
2067
+ out_scale,
2068
+ out_zero_point,
2069
+ jit_image,
2070
+ weight_tensor,
2071
+ bias_id,
2072
+ args,
2073
+ transpose,
2074
+ fuse_code,
2075
+ ):
2076
+ image_id, image_oper = self.get_tensor_operand_by_jitval(jit_image)
2077
+ in_c = image_oper.shape[1]
2078
+
2079
+ if args.group == 1:
2080
+ # Full convolution
2081
+ depthwise = False
2082
+ if transpose:
2083
+ weight_permutation = (1, 2, 3, 0)
2084
+ else:
2085
+ weight_permutation = (0, 2, 3, 1)
2086
+ elif args.group == in_c:
2087
+ # Depthwise convolution
2088
+ depthwise = True
2089
+ weight_permutation = (1, 2, 3, 0)
2090
+ else:
2091
+ raise Exception("Group convolution not supported yet.") # noqa: TRY002
2092
+
2093
+ # TODO: Transform at load time to share weights with CPU model.
2094
+ nnapi_weight_tensor = weight_tensor.permute(*weight_permutation).contiguous()
2095
+ weight_id = self.add_tensor_operand_for_weight(nnapi_weight_tensor)
2096
+ weight_oper = self.operands[weight_id]
2097
+
2098
+ bias_oper = self.operands[bias_id]
2099
+
2100
+ if image_oper.op_type == NNAPI_OperandCode.TENSOR_FLOAT32:
2101
+ assert weight_oper.op_type == NNAPI_OperandCode.TENSOR_FLOAT32
2102
+ assert bias_oper.op_type == NNAPI_OperandCode.TENSOR_FLOAT32
2103
+ elif image_oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM:
2104
+ assert weight_oper.op_type == NNAPI_OperandCode.TENSOR_QUANT8_ASYMM
2105
+ assert bias_oper.op_type == NNAPI_OperandCode.TENSOR_INT32
2106
+ assert approx_equal(image_oper.scale * weight_oper.scale, bias_oper.scale)
2107
+ assert bias_oper.zero_point == 0
2108
+ else:
2109
+ raise Exception( # noqa: TRY002
2110
+ f"Unsupported input type for conv2d: {image_oper.op_type}"
2111
+ ) # noqa: TRY002
2112
+
2113
+ assert len(image_oper.shape) == 4
2114
+ assert len(weight_oper.shape) == 4
2115
+ assert len(bias_oper.shape) == 1
2116
+
2117
+ if depthwise:
2118
+ # Depthwise convolution
2119
+ one, _kern_h, _kern_w, out_c = weight_oper.shape
2120
+ assert one == 1
2121
+ assert out_c % in_c == 0
2122
+ channel_multiplier = out_c // in_c
2123
+ assert channel_multiplier == 1 # Don't support multiplier
2124
+ assert out_c == in_c
2125
+ else:
2126
+ # Full convolution
2127
+ out_c, _kern_h, _kern_w, kern_d = weight_oper.shape
2128
+ assert kern_d == in_c
2129
+
2130
+ assert out_c == bias_oper.shape[0]
2131
+
2132
+ use_nchw = image_oper.use_nchw()
2133
+
2134
+ if depthwise:
2135
+ num_args = 12
2136
+ opcode = NNAPI_OperationCode.DEPTHWISE_CONV_2D
2137
+ else:
2138
+ num_args = 11
2139
+ if transpose:
2140
+ opcode = NNAPI_OperationCode.TRANSPOSE_CONV_2D
2141
+ else:
2142
+ opcode = NNAPI_OperationCode.CONV_2D
2143
+
2144
+ inputs = [None] * num_args
2145
+ inputs[0] = image_id
2146
+ inputs[1] = weight_id
2147
+ inputs[2] = bias_id
2148
+ inputs[3] = self.add_immediate_int_scalar(args.pad_l)
2149
+ inputs[4] = self.add_immediate_int_scalar(args.pad_r)
2150
+ inputs[5] = self.add_immediate_int_scalar(args.pad_t)
2151
+ inputs[6] = self.add_immediate_int_scalar(args.pad_b)
2152
+ inputs[7] = self.add_immediate_int_scalar(args.stride_w)
2153
+ inputs[8] = self.add_immediate_int_scalar(args.stride_h)
2154
+ if depthwise:
2155
+ inputs[9] = self.add_immediate_int_scalar(1)
2156
+ inputs[10] = self.add_immediate_int_scalar(fuse_code)
2157
+ inputs[11] = self.add_immediate_bool_scalar(use_nchw)
2158
+ else:
2159
+ inputs[9] = self.add_immediate_int_scalar(fuse_code)
2160
+ inputs[10] = self.add_immediate_bool_scalar(use_nchw)
2161
+
2162
+ outputs = [None] * 1
2163
+ out_shape = get_conv_pool_shape(image_oper.shape, args, out_c, transpose)
2164
+ out_oper = image_oper._replace(
2165
+ shape=out_shape,
2166
+ scale=out_scale,
2167
+ zero_point=out_zero_point,
2168
+ )
2169
+ out_id = self.add_tensor_operand(jit_out, out_oper)
2170
+ self._handle_conv_pool_flexible_input(out_id, jit_image, args, transpose)
2171
+
2172
+ outputs[0] = out_id
2173
+ self.add_operation(opcode, inputs, outputs)
2174
+
2175
+ def _handle_conv_pool_flexible_input(self, out_id, jit_image, args, transpose):
2176
+ image_id, image_oper = self.get_tensor_operand_by_jitval(jit_image)
2177
+ batch, in_ch, in_h, in_w = image_oper.shape
2178
+
2179
+ if batch == 0:
2180
+ self.forward_operand_shape(out_id, 0, image_id, 0)
2181
+ if in_ch == 0:
2182
+ raise Exception("Input channels can't be flexible") # noqa: TRY002
2183
+ # H & W
2184
+ if transpose:
2185
+ if in_h == 0:
2186
+ self.compute_operand_shape(
2187
+ out_id,
2188
+ 2,
2189
+ f"({flex_name(image_id, 2)} - 1) * {args.stride_h} + {args.kernel_h} - {args.pad_t} - {args.pad_b}",
2190
+ )
2191
+ if in_w == 0:
2192
+ self.compute_operand_shape(
2193
+ out_id,
2194
+ 3,
2195
+ f"({flex_name(image_id, 3)} - 1) * {args.stride_w} + {args.kernel_w} - {args.pad_l} - {args.pad_r}",
2196
+ )
2197
+ else:
2198
+ if in_h == 0:
2199
+ self.compute_operand_shape(
2200
+ out_id,
2201
+ 2,
2202
+ f"({flex_name(image_id, 2)} - {args.kernel_h} + {args.pad_t} + {args.pad_b}) // {args.stride_h} + 1",
2203
+ )
2204
+ if in_w == 0:
2205
+ self.compute_operand_shape(
2206
+ out_id,
2207
+ 3,
2208
+ f"({flex_name(image_id, 3)} - {args.kernel_w} + {args.pad_l} + {args.pad_r}) // {args.stride_w} + 1",
2209
+ )
2210
+
2211
+
2212
+ def serialize_model(
2213
+ module, inputs, *, config=None, return_shapes=None, use_int16_for_qint16=False
2214
+ ):
2215
+ """Convert to NNAPI and serialize torchscript module.
2216
+
2217
+ Parameters:
2218
+ module: Torchscript module to convert
2219
+ inputs: Tensors used to specify input details for NNAPI
2220
+ config (optional): Optional config to attach to module
2221
+ return_shapes (optional): Specify shape of outputs if
2222
+ your module uses runtime flexible shapes to set output
2223
+ buffer size for NNAPI
2224
+ use_int16_for_qint16 (optional): Use Pytorch int16 to represent NNAPI qint16 values
2225
+ """
2226
+ return _NnapiSerializer(config, use_int16_for_qint16).serialize_model(
2227
+ module, inputs, return_shapes
2228
+ )
tool_server/.venv/lib/python3.12/site-packages/torch/backends/cpu/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ __all__ = [
5
+ "get_cpu_capability",
6
+ ]
7
+
8
+
9
+ def get_cpu_capability() -> str:
10
+ r"""Return cpu capability as a string value.
11
+
12
+ Possible values:
13
+ - "DEFAULT"
14
+ - "VSX"
15
+ - "Z VECTOR"
16
+ - "NO AVX"
17
+ - "AVX2"
18
+ - "AVX512"
19
+ - "SVE256"
20
+ """
21
+ return torch._C._get_cpu_capability()
tool_server/.venv/lib/python3.12/site-packages/torch/backends/cpu/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (653 Bytes). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/backends/cuda/__init__.py ADDED
@@ -0,0 +1,536 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ from typing import Union
4
+ from typing_extensions import deprecated
5
+
6
+ import torch
7
+
8
+
9
+ __all__ = [
10
+ "is_built",
11
+ "cuFFTPlanCacheAttrContextProp",
12
+ "cuFFTPlanCache",
13
+ "cuFFTPlanCacheManager",
14
+ "cuBLASModule",
15
+ "preferred_linalg_library",
16
+ "preferred_blas_library",
17
+ "preferred_rocm_fa_library",
18
+ "cufft_plan_cache",
19
+ "matmul",
20
+ "SDPAParams",
21
+ "enable_cudnn_sdp",
22
+ "cudnn_sdp_enabled",
23
+ "enable_flash_sdp",
24
+ "flash_sdp_enabled",
25
+ "enable_mem_efficient_sdp",
26
+ "mem_efficient_sdp_enabled",
27
+ "math_sdp_enabled",
28
+ "enable_math_sdp",
29
+ "allow_fp16_bf16_reduction_math_sdp",
30
+ "fp16_bf16_reduction_math_sdp_allowed",
31
+ "is_flash_attention_available",
32
+ "can_use_flash_attention",
33
+ "can_use_efficient_attention",
34
+ "can_use_cudnn_attention",
35
+ "sdp_kernel",
36
+ ]
37
+
38
+
39
+ def is_built():
40
+ r"""
41
+ Return whether PyTorch is built with CUDA support.
42
+
43
+ Note that this doesn't necessarily mean CUDA is available; just that if this PyTorch
44
+ binary were run on a machine with working CUDA drivers and devices, we would be able to use it.
45
+ """
46
+ return torch._C._has_cuda
47
+
48
+
49
+ class cuFFTPlanCacheAttrContextProp:
50
+ # Like regular ContextProp, but uses the `.device_index` attribute from the
51
+ # calling object as the first argument to the getter and setter.
52
+ def __init__(self, getter, setter):
53
+ self.getter = getter
54
+ self.setter = setter
55
+
56
+ def __get__(self, obj, objtype):
57
+ return self.getter(obj.device_index)
58
+
59
+ def __set__(self, obj, val):
60
+ if isinstance(self.setter, str):
61
+ raise RuntimeError(self.setter)
62
+ self.setter(obj.device_index, val)
63
+
64
+
65
+ class cuFFTPlanCache:
66
+ r"""
67
+ Represent a specific plan cache for a specific `device_index`.
68
+
69
+ The attributes `size` and `max_size`, and method `clear`, can fetch and/ or
70
+ change properties of the C++ cuFFT plan cache.
71
+ """
72
+
73
+ def __init__(self, device_index):
74
+ self.device_index = device_index
75
+
76
+ size = cuFFTPlanCacheAttrContextProp(
77
+ torch._cufft_get_plan_cache_size,
78
+ ".size is a read-only property showing the number of plans currently in the "
79
+ "cache. To change the cache capacity, set cufft_plan_cache.max_size.",
80
+ )
81
+
82
+ max_size = cuFFTPlanCacheAttrContextProp(
83
+ torch._cufft_get_plan_cache_max_size, torch._cufft_set_plan_cache_max_size
84
+ )
85
+
86
+ def clear(self):
87
+ return torch._cufft_clear_plan_cache(self.device_index)
88
+
89
+
90
+ class cuFFTPlanCacheManager:
91
+ r"""
92
+ Represent all cuFFT plan caches, return the cuFFTPlanCache for a given device when indexed.
93
+
94
+ Finally, this object, when used directly as a `cuFFTPlanCache` object (e.g.,
95
+ setting the `.max_size`) attribute, the current device's cuFFT plan cache is
96
+ used.
97
+ """
98
+
99
+ __initialized = False
100
+
101
+ def __init__(self):
102
+ self.caches = []
103
+ self.__initialized = True
104
+
105
+ def __getitem__(self, device):
106
+ index = torch.cuda._utils._get_device_index(device)
107
+ if index < 0 or index >= torch.cuda.device_count():
108
+ raise RuntimeError(
109
+ f"cufft_plan_cache: expected 0 <= device index < {torch.cuda.device_count()}, but got "
110
+ f"device with index {index}"
111
+ )
112
+ if len(self.caches) == 0:
113
+ self.caches.extend(
114
+ cuFFTPlanCache(index) for index in range(torch.cuda.device_count())
115
+ )
116
+ return self.caches[index]
117
+
118
+ def __getattr__(self, name):
119
+ return getattr(self[torch.cuda.current_device()], name)
120
+
121
+ def __setattr__(self, name, value):
122
+ if self.__initialized:
123
+ return setattr(self[torch.cuda.current_device()], name, value)
124
+ else:
125
+ return super().__setattr__(name, value)
126
+
127
+
128
+ class cuBLASModule:
129
+ def __getattr__(self, name):
130
+ if name == "allow_tf32":
131
+ return torch._C._get_cublas_allow_tf32()
132
+ elif name == "allow_fp16_reduced_precision_reduction":
133
+ return torch._C._get_cublas_allow_fp16_reduced_precision_reduction()
134
+ elif name == "allow_bf16_reduced_precision_reduction":
135
+ return torch._C._get_cublas_allow_bf16_reduced_precision_reduction()
136
+ elif name == "allow_fp16_accumulation":
137
+ return torch._C._get_cublas_allow_fp16_accumulation()
138
+ raise AttributeError("Unknown attribute " + name)
139
+
140
+ def __setattr__(self, name, value):
141
+ if name == "allow_tf32":
142
+ return torch._C._set_cublas_allow_tf32(value)
143
+ elif name == "allow_fp16_reduced_precision_reduction":
144
+ return torch._C._set_cublas_allow_fp16_reduced_precision_reduction(value)
145
+ elif name == "allow_bf16_reduced_precision_reduction":
146
+ return torch._C._set_cublas_allow_bf16_reduced_precision_reduction(value)
147
+ elif name == "allow_fp16_accumulation":
148
+ return torch._C._set_cublas_allow_fp16_accumulation(value)
149
+ raise AttributeError("Unknown attribute " + name)
150
+
151
+
152
+ _LinalgBackends = {
153
+ "default": torch._C._LinalgBackend.Default,
154
+ "cusolver": torch._C._LinalgBackend.Cusolver,
155
+ "magma": torch._C._LinalgBackend.Magma,
156
+ }
157
+ _LinalgBackends_str = ", ".join(_LinalgBackends.keys())
158
+
159
+
160
+ def preferred_linalg_library(
161
+ backend: Union[None, str, torch._C._LinalgBackend] = None
162
+ ) -> torch._C._LinalgBackend:
163
+ r"""
164
+ Override the heuristic PyTorch uses to choose between cuSOLVER and MAGMA for CUDA linear algebra operations.
165
+
166
+ .. warning:: This flag is experimental and subject to change.
167
+
168
+ When PyTorch runs a CUDA linear algebra operation it often uses the cuSOLVER or MAGMA libraries,
169
+ and if both are available it decides which to use with a heuristic.
170
+ This flag (a :class:`str`) allows overriding those heuristics.
171
+
172
+ * If `"cusolver"` is set then cuSOLVER will be used wherever possible.
173
+ * If `"magma"` is set then MAGMA will be used wherever possible.
174
+ * If `"default"` (the default) is set then heuristics will be used to pick between
175
+ cuSOLVER and MAGMA if both are available.
176
+ * When no input is given, this function returns the currently preferred library.
177
+ * User may use the environment variable TORCH_LINALG_PREFER_CUSOLVER=1 to set the preferred library to cuSOLVER
178
+ globally.
179
+ This flag only sets the initial value of the preferred library and the preferred library
180
+ may still be overridden by this function call later in your script.
181
+
182
+ Note: When a library is preferred other libraries may still be used if the preferred library
183
+ doesn't implement the operation(s) called.
184
+ This flag may achieve better performance if PyTorch's heuristic library selection is incorrect
185
+ for your application's inputs.
186
+
187
+ Currently supported linalg operators:
188
+
189
+ * :func:`torch.linalg.inv`
190
+ * :func:`torch.linalg.inv_ex`
191
+ * :func:`torch.linalg.cholesky`
192
+ * :func:`torch.linalg.cholesky_ex`
193
+ * :func:`torch.cholesky_solve`
194
+ * :func:`torch.cholesky_inverse`
195
+ * :func:`torch.linalg.lu_factor`
196
+ * :func:`torch.linalg.lu`
197
+ * :func:`torch.linalg.lu_solve`
198
+ * :func:`torch.linalg.qr`
199
+ * :func:`torch.linalg.eigh`
200
+ * :func:`torch.linalg.eighvals`
201
+ * :func:`torch.linalg.svd`
202
+ * :func:`torch.linalg.svdvals`
203
+ """
204
+ if backend is None:
205
+ pass
206
+ elif isinstance(backend, str):
207
+ if backend not in _LinalgBackends:
208
+ raise RuntimeError(
209
+ "Unknown input value. " f"Choose from: {_LinalgBackends_str}."
210
+ )
211
+ torch._C._set_linalg_preferred_backend(_LinalgBackends[backend])
212
+ elif isinstance(backend, torch._C._LinalgBackend):
213
+ torch._C._set_linalg_preferred_backend(backend)
214
+ else:
215
+ raise RuntimeError("Unknown input value type.")
216
+
217
+ return torch._C._get_linalg_preferred_backend()
218
+
219
+
220
+ _BlasBackends = {
221
+ "default": torch._C._BlasBackend.Default,
222
+ "cublas": torch._C._BlasBackend.Cublas,
223
+ "hipblas": torch._C._BlasBackend.Cublas, # alias
224
+ "cublaslt": torch._C._BlasBackend.Cublaslt,
225
+ "hipblaslt": torch._C._BlasBackend.Cublaslt, # alias
226
+ "ck": torch._C._BlasBackend.Ck,
227
+ }
228
+ _BlasBackends_str = ", ".join(_BlasBackends.keys())
229
+
230
+
231
+ def preferred_blas_library(
232
+ backend: Union[None, str, torch._C._BlasBackend] = None
233
+ ) -> torch._C._BlasBackend:
234
+ r"""
235
+ Override the library PyTorch uses for BLAS operations. Choose between cuBLAS, cuBLASLt, and CK [ROCm-only].
236
+
237
+ .. warning:: This flag is experimental and subject to change.
238
+
239
+ When PyTorch runs a CUDA BLAS operation it defaults to cuBLAS even if both cuBLAS and cuBLASLt are available.
240
+ For PyTorch built for ROCm, hipBLAS, hipBLASLt, and CK may offer different performance.
241
+ This flag (a :class:`str`) allows overriding which BLAS library to use.
242
+
243
+ * If `"cublas"` is set then cuBLAS will be used wherever possible.
244
+ * If `"cublaslt"` is set then cuBLASLt will be used wherever possible.
245
+ * If `"ck"` is set then CK will be used wherever possible.
246
+ * If `"default"` (the default) is set then heuristics will be used to pick between the other options.
247
+ * When no input is given, this function returns the currently preferred library.
248
+ * User may use the environment variable TORCH_BLAS_PREFER_CUBLASLT=1 to set the preferred library to cuBLASLt
249
+ globally.
250
+ This flag only sets the initial value of the preferred library and the preferred library
251
+ may still be overridden by this function call later in your script.
252
+
253
+ Note: When a library is preferred other libraries may still be used if the preferred library
254
+ doesn't implement the operation(s) called.
255
+ This flag may achieve better performance if PyTorch's library selection is incorrect
256
+ for your application's inputs.
257
+
258
+ """
259
+ if backend is None:
260
+ pass
261
+ elif isinstance(backend, str):
262
+ if backend not in _BlasBackends:
263
+ raise RuntimeError(
264
+ "Unknown input value. " f"Choose from: {_BlasBackends_str}."
265
+ )
266
+ torch._C._set_blas_preferred_backend(_BlasBackends[backend])
267
+ elif isinstance(backend, torch._C._BlasBackend):
268
+ torch._C._set_blas_preferred_backend(backend)
269
+ else:
270
+ raise RuntimeError("Unknown input value type.")
271
+
272
+ return torch._C._get_blas_preferred_backend()
273
+
274
+
275
+ _ROCmFABackends = {
276
+ "default": torch._C._ROCmFABackend.Default,
277
+ "aotriton": torch._C._ROCmFABackend.AOTriton,
278
+ "ck": torch._C._ROCmFABackend.Ck,
279
+ }
280
+ _ROCmFABackends_str = ", ".join(_ROCmFABackends.keys())
281
+
282
+
283
+ from torch._C import _SDPAParams as SDPAParams, _SDPBackend as SDPBackend
284
+
285
+
286
+ def preferred_rocm_fa_library(
287
+ backend: Union[None, str, torch._C._ROCmFABackend] = None
288
+ ) -> torch._C._ROCmFABackend:
289
+ r"""
290
+ [ROCm-only]
291
+ Override the backend PyTorch uses in ROCm environments for Flash Attention. Choose between AOTriton and CK
292
+
293
+ .. warning:: This flag is experimeental and subject to change.
294
+
295
+ When Flash Attention is enabled and desired, PyTorch defaults to using AOTriton as the backend.
296
+ This flag (a :class:`str`) allows users to override this backend to use composable_kernel
297
+
298
+ * If `"default"` is set then the default backend will be used wherever possible. Currently AOTriton.
299
+ * If `"aotriton"` is set then AOTriton will be used wherever possible.
300
+ * If `"ck"` is set then CK will be used wherever possible.
301
+ * When no input is given, this function returns the currently preferred library.
302
+ * User may use the environment variable TORCH_ROCM_FA_PREFER_CK=1 to set the preferred library to CK
303
+ globally.
304
+
305
+ Note: When a library is preferred other libraries may still be used if the preferred library
306
+ doesn't implement the operation(s) called.
307
+ This flag may achieve better performance if PyTorch's library selection is incorrect
308
+ for your application's inputs.
309
+ """
310
+ if backend is None:
311
+ pass
312
+ elif isinstance(backend, str):
313
+ if backend not in _ROCmFABackends:
314
+ raise RuntimeError(
315
+ "Unknown input value. " f"Choose from: {_ROCmFABackends_str}."
316
+ )
317
+ torch._C._set_rocm_fa_preferred_backend(_ROCmFABackends[backend])
318
+ elif isinstance(backend, torch._C._ROCmFABackend):
319
+ torch._C._set_rocm_fa_preferred_backend(backend)
320
+ else:
321
+ raise ValueError("Unknown input value. " f"Choose from: {_ROCmFABackends_str}.")
322
+
323
+ return torch._C._get_rocm_fa_preferred_backend()
324
+
325
+
326
+ # Set the __module__ attribute
327
+ SDPAParams.__module__ = "torch.backends.cuda"
328
+ SDPAParams.__name__ = "SDPAParams"
329
+
330
+
331
+ def flash_sdp_enabled():
332
+ r"""
333
+ .. warning:: This flag is beta and subject to change.
334
+
335
+ Returns whether flash scaled dot product attention is enabled or not.
336
+ """
337
+ return torch._C._get_flash_sdp_enabled()
338
+
339
+
340
+ def enable_flash_sdp(enabled: bool):
341
+ r"""
342
+ .. warning:: This flag is beta and subject to change.
343
+
344
+ Enables or disables flash scaled dot product attention.
345
+ """
346
+ torch._C._set_sdp_use_flash(enabled)
347
+
348
+
349
+ def mem_efficient_sdp_enabled():
350
+ r"""
351
+ .. warning:: This flag is beta and subject to change.
352
+
353
+ Returns whether memory efficient scaled dot product attention is enabled or not.
354
+ """
355
+ return torch._C._get_mem_efficient_sdp_enabled()
356
+
357
+
358
+ def enable_mem_efficient_sdp(enabled: bool):
359
+ r"""
360
+ .. warning:: This flag is beta and subject to change.
361
+
362
+ Enables or disables memory efficient scaled dot product attention.
363
+ """
364
+ torch._C._set_sdp_use_mem_efficient(enabled)
365
+
366
+
367
+ def math_sdp_enabled():
368
+ r"""
369
+ .. warning:: This flag is beta and subject to change.
370
+
371
+ Returns whether math scaled dot product attention is enabled or not.
372
+ """
373
+ return torch._C._get_math_sdp_enabled()
374
+
375
+
376
+ def enable_math_sdp(enabled: bool):
377
+ r"""
378
+ .. warning:: This flag is beta and subject to change.
379
+
380
+ Enables or disables math scaled dot product attention.
381
+ """
382
+ torch._C._set_sdp_use_math(enabled)
383
+
384
+
385
+ def allow_fp16_bf16_reduction_math_sdp(enabled: bool):
386
+ r"""
387
+ .. warning:: This flag is beta and subject to change.
388
+
389
+ Enables or disables fp16/bf16 reduction in math scaled dot product attention.
390
+ """
391
+ torch._C._set_math_sdp_allow_fp16_bf16_reduction(enabled)
392
+
393
+
394
+ def fp16_bf16_reduction_math_sdp_allowed():
395
+ r"""
396
+ .. warning:: This flag is beta and subject to change.
397
+
398
+ Returns whether fp16/bf16 reduction in math scaled dot product attention is enabled or not.
399
+ """
400
+ return torch._C._get_math_sdp_allow_fp16_bf16_reduction()
401
+
402
+
403
+ def is_flash_attention_available() -> bool:
404
+ r"""Check if PyTorch was built with FlashAttention for scaled_dot_product_attention.
405
+
406
+ Returns:
407
+ True if FlashAttention is built and available; otherwise, False.
408
+
409
+ Note:
410
+ This function is dependent on a CUDA-enabled build of PyTorch. It will return False
411
+ in non-CUDA environments.
412
+ """
413
+ return torch._C._is_flash_attention_available()
414
+
415
+
416
+ def can_use_flash_attention(params: SDPAParams, debug: bool = False) -> bool:
417
+ r"""Check if FlashAttention can be utilized in scaled_dot_product_attention.
418
+
419
+ Args:
420
+ params: An instance of SDPAParams containing the tensors for query,
421
+ key, value, an optional attention mask, dropout rate, and
422
+ a flag indicating if the attention is causal.
423
+ debug: Whether to logging.warn debug information as to why FlashAttention could not be run.
424
+ Defaults to False.
425
+
426
+ Returns:
427
+ True if FlashAttention can be used with the given parameters; otherwise, False.
428
+
429
+ Note:
430
+ This function is dependent on a CUDA-enabled build of PyTorch. It will return False
431
+ in non-CUDA environments.
432
+ """
433
+ return torch._C._can_use_flash_attention(params, debug)
434
+
435
+
436
+ def can_use_efficient_attention(params: SDPAParams, debug: bool = False) -> bool:
437
+ r"""Check if efficient_attention can be utilized in scaled_dot_product_attention.
438
+
439
+ Args:
440
+ params: An instance of SDPAParams containing the tensors for query,
441
+ key, value, an optional attention mask, dropout rate, and
442
+ a flag indicating if the attention is causal.
443
+ debug: Whether to logging.warn with information as to why efficient_attention could not be run.
444
+ Defaults to False.
445
+
446
+ Returns:
447
+ True if efficient_attention can be used with the given parameters; otherwise, False.
448
+
449
+ Note:
450
+ This function is dependent on a CUDA-enabled build of PyTorch. It will return False
451
+ in non-CUDA environments.
452
+ """
453
+ return torch._C._can_use_mem_efficient_attention(params, debug)
454
+
455
+
456
+ def can_use_cudnn_attention(params: SDPAParams, debug: bool = False) -> bool:
457
+ r"""Check if cudnn_attention can be utilized in scaled_dot_product_attention.
458
+
459
+ Args:
460
+ params: An instance of SDPAParams containing the tensors for query,
461
+ key, value, an optional attention mask, dropout rate, and
462
+ a flag indicating if the attention is causal.
463
+ debug: Whether to logging.warn with information as to why cuDNN attention could not be run.
464
+ Defaults to False.
465
+
466
+ Returns:
467
+ True if cuDNN can be used with the given parameters; otherwise, False.
468
+
469
+ Note:
470
+ This function is dependent on a CUDA-enabled build of PyTorch. It will return False
471
+ in non-CUDA environments.
472
+ """
473
+ return torch._C._can_use_cudnn_attention(params, debug)
474
+
475
+
476
+ def cudnn_sdp_enabled():
477
+ r"""
478
+ .. warning:: This flag is beta and subject to change.
479
+
480
+ Returns whether cuDNN scaled dot product attention is enabled or not.
481
+ """
482
+ return torch._C._get_cudnn_sdp_enabled()
483
+
484
+
485
+ def enable_cudnn_sdp(enabled: bool):
486
+ r"""
487
+ .. warning:: This flag is beta and subject to change.
488
+
489
+ Enables or disables cuDNN scaled dot product attention.
490
+ """
491
+ torch._C._set_sdp_use_cudnn(enabled)
492
+
493
+
494
+ @contextlib.contextmanager
495
+ @deprecated(
496
+ (
497
+ "`torch.backends.cuda.sdp_kernel()` is deprecated. "
498
+ "In the future, this context manager will be removed. "
499
+ "Please see `torch.nn.attention.sdpa_kernel()` for the new context manager, "
500
+ "with updated signature."
501
+ ),
502
+ category=FutureWarning,
503
+ )
504
+ def sdp_kernel(
505
+ enable_flash: bool = True,
506
+ enable_math: bool = True,
507
+ enable_mem_efficient: bool = True,
508
+ enable_cudnn: bool = True,
509
+ ):
510
+ r"""
511
+ .. warning:: This flag is beta and subject to change.
512
+
513
+ This context manager can be used to temporarily enable or disable any of the three backends for scaled dot product attention.
514
+ Upon exiting the context manager, the previous state of the flags will be restored.
515
+ """
516
+ from torch.nn.attention import sdpa_kernel
517
+
518
+ backend_list = []
519
+ if enable_flash:
520
+ backend_list.append(SDPBackend.FLASH_ATTENTION)
521
+ if enable_mem_efficient:
522
+ backend_list.append(SDPBackend.EFFICIENT_ATTENTION)
523
+ if enable_math:
524
+ backend_list.append(SDPBackend.MATH)
525
+ if enable_cudnn:
526
+ backend_list.append(SDPBackend.CUDNN_ATTENTION)
527
+
528
+ with sdpa_kernel(backend_list) as context:
529
+ try:
530
+ yield context
531
+ finally:
532
+ pass
533
+
534
+
535
+ cufft_plan_cache = cuFFTPlanCacheManager()
536
+ matmul = cuBLASModule()
tool_server/.venv/lib/python3.12/site-packages/torch/backends/cuda/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (25.5 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/backends/cudnn/__init__.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import os
3
+ import sys
4
+ import warnings
5
+ from contextlib import contextmanager
6
+ from typing import Optional
7
+
8
+ import torch
9
+ from torch.backends import __allow_nonbracketed_mutation, ContextProp, PropModule
10
+
11
+
12
+ try:
13
+ from torch._C import _cudnn
14
+ except ImportError:
15
+ _cudnn = None # type: ignore[assignment]
16
+
17
+ # Write:
18
+ #
19
+ # torch.backends.cudnn.enabled = False
20
+ #
21
+ # to globally disable CuDNN/MIOpen
22
+
23
+ __cudnn_version: Optional[int] = None
24
+
25
+ if _cudnn is not None:
26
+
27
+ def _init():
28
+ global __cudnn_version
29
+ if __cudnn_version is None:
30
+ __cudnn_version = _cudnn.getVersionInt()
31
+ runtime_version = _cudnn.getRuntimeVersion()
32
+ compile_version = _cudnn.getCompileVersion()
33
+ runtime_major, runtime_minor, _ = runtime_version
34
+ compile_major, compile_minor, _ = compile_version
35
+ # Different major versions are always incompatible
36
+ # Starting with cuDNN 7, minor versions are backwards-compatible
37
+ # Not sure about MIOpen (ROCm), so always do a strict check
38
+ if runtime_major != compile_major:
39
+ cudnn_compatible = False
40
+ elif runtime_major < 7 or not _cudnn.is_cuda:
41
+ cudnn_compatible = runtime_minor == compile_minor
42
+ else:
43
+ cudnn_compatible = runtime_minor >= compile_minor
44
+ if not cudnn_compatible:
45
+ if os.environ.get("PYTORCH_SKIP_CUDNN_COMPATIBILITY_CHECK", "0") == "1":
46
+ return True
47
+ base_error_msg = (
48
+ f"cuDNN version incompatibility: "
49
+ f"PyTorch was compiled against {compile_version} "
50
+ f"but found runtime version {runtime_version}. "
51
+ f"PyTorch already comes bundled with cuDNN. "
52
+ f"One option to resolving this error is to ensure PyTorch "
53
+ f"can find the bundled cuDNN. "
54
+ )
55
+
56
+ if "LD_LIBRARY_PATH" in os.environ:
57
+ ld_library_path = os.environ.get("LD_LIBRARY_PATH", "")
58
+ if any(
59
+ substring in ld_library_path for substring in ["cuda", "cudnn"]
60
+ ):
61
+ raise RuntimeError(
62
+ f"{base_error_msg}"
63
+ f"Looks like your LD_LIBRARY_PATH contains incompatible version of cudnn. "
64
+ f"Please either remove it from the path or install cudnn {compile_version}"
65
+ )
66
+ else:
67
+ raise RuntimeError(
68
+ f"{base_error_msg}"
69
+ f"one possibility is that there is a "
70
+ f"conflicting cuDNN in LD_LIBRARY_PATH."
71
+ )
72
+ else:
73
+ raise RuntimeError(base_error_msg)
74
+
75
+ return True
76
+
77
+ else:
78
+
79
+ def _init():
80
+ return False
81
+
82
+
83
+ def version():
84
+ """Return the version of cuDNN."""
85
+ if not _init():
86
+ return None
87
+ return __cudnn_version
88
+
89
+
90
+ CUDNN_TENSOR_DTYPES = {
91
+ torch.half,
92
+ torch.float,
93
+ torch.double,
94
+ }
95
+
96
+
97
+ def is_available():
98
+ r"""Return a bool indicating if CUDNN is currently available."""
99
+ return torch._C._has_cudnn
100
+
101
+
102
+ def is_acceptable(tensor):
103
+ if not torch._C._get_cudnn_enabled():
104
+ return False
105
+ if tensor.device.type != "cuda" or tensor.dtype not in CUDNN_TENSOR_DTYPES:
106
+ return False
107
+ if not is_available():
108
+ warnings.warn(
109
+ "PyTorch was compiled without cuDNN/MIOpen support. To use cuDNN/MIOpen, rebuild "
110
+ "PyTorch making sure the library is visible to the build system."
111
+ )
112
+ return False
113
+ if not _init():
114
+ warnings.warn(
115
+ "cuDNN/MIOpen library not found. Check your {libpath}".format(
116
+ libpath={"darwin": "DYLD_LIBRARY_PATH", "win32": "PATH"}.get(
117
+ sys.platform, "LD_LIBRARY_PATH"
118
+ )
119
+ )
120
+ )
121
+ return False
122
+ return True
123
+
124
+
125
+ def set_flags(
126
+ _enabled=None,
127
+ _benchmark=None,
128
+ _benchmark_limit=None,
129
+ _deterministic=None,
130
+ _allow_tf32=None,
131
+ ):
132
+ orig_flags = (
133
+ torch._C._get_cudnn_enabled(),
134
+ torch._C._get_cudnn_benchmark(),
135
+ None if not is_available() else torch._C._cuda_get_cudnn_benchmark_limit(),
136
+ torch._C._get_cudnn_deterministic(),
137
+ torch._C._get_cudnn_allow_tf32(),
138
+ )
139
+ if _enabled is not None:
140
+ torch._C._set_cudnn_enabled(_enabled)
141
+ if _benchmark is not None:
142
+ torch._C._set_cudnn_benchmark(_benchmark)
143
+ if _benchmark_limit is not None and is_available():
144
+ torch._C._cuda_set_cudnn_benchmark_limit(_benchmark_limit)
145
+ if _deterministic is not None:
146
+ torch._C._set_cudnn_deterministic(_deterministic)
147
+ if _allow_tf32 is not None:
148
+ torch._C._set_cudnn_allow_tf32(_allow_tf32)
149
+ return orig_flags
150
+
151
+
152
+ @contextmanager
153
+ def flags(
154
+ enabled=False,
155
+ benchmark=False,
156
+ benchmark_limit=10,
157
+ deterministic=False,
158
+ allow_tf32=True,
159
+ ):
160
+ with __allow_nonbracketed_mutation():
161
+ orig_flags = set_flags(
162
+ enabled, benchmark, benchmark_limit, deterministic, allow_tf32
163
+ )
164
+ try:
165
+ yield
166
+ finally:
167
+ # recover the previous values
168
+ with __allow_nonbracketed_mutation():
169
+ set_flags(*orig_flags)
170
+
171
+
172
+ # The magic here is to allow us to intercept code like this:
173
+ #
174
+ # torch.backends.<cudnn|mkldnn>.enabled = True
175
+
176
+
177
+ class CudnnModule(PropModule):
178
+ def __init__(self, m, name):
179
+ super().__init__(m, name)
180
+
181
+ enabled = ContextProp(torch._C._get_cudnn_enabled, torch._C._set_cudnn_enabled)
182
+ deterministic = ContextProp(
183
+ torch._C._get_cudnn_deterministic, torch._C._set_cudnn_deterministic
184
+ )
185
+ benchmark = ContextProp(
186
+ torch._C._get_cudnn_benchmark, torch._C._set_cudnn_benchmark
187
+ )
188
+ benchmark_limit = None
189
+ if is_available():
190
+ benchmark_limit = ContextProp(
191
+ torch._C._cuda_get_cudnn_benchmark_limit,
192
+ torch._C._cuda_set_cudnn_benchmark_limit,
193
+ )
194
+ allow_tf32 = ContextProp(
195
+ torch._C._get_cudnn_allow_tf32, torch._C._set_cudnn_allow_tf32
196
+ )
197
+
198
+
199
+ # This is the sys.modules replacement trick, see
200
+ # https://stackoverflow.com/questions/2447353/getattr-on-a-module/7668273#7668273
201
+ sys.modules[__name__] = CudnnModule(sys.modules[__name__], __name__)
202
+
203
+ # Add type annotation for the replaced module
204
+ enabled: bool
205
+ deterministic: bool
206
+ benchmark: bool
207
+ allow_tf32: bool
208
+ benchmark_limit: int
tool_server/.venv/lib/python3.12/site-packages/torch/backends/cudnn/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (7.87 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/backends/cudnn/__pycache__/rnn.cpython-312.pyc ADDED
Binary file (2.68 kB). View file
 
tool_server/.venv/lib/python3.12/site-packages/torch/backends/cudnn/rnn.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch.cuda
3
+
4
+
5
+ try:
6
+ from torch._C import _cudnn
7
+ except ImportError:
8
+ # Uses of all the functions below should be guarded by torch.backends.cudnn.is_available(),
9
+ # so it's safe to not emit any checks here.
10
+ _cudnn = None # type: ignore[assignment]
11
+
12
+
13
+ def get_cudnn_mode(mode):
14
+ if mode == "RNN_RELU":
15
+ return int(_cudnn.RNNMode.rnn_relu)
16
+ elif mode == "RNN_TANH":
17
+ return int(_cudnn.RNNMode.rnn_tanh)
18
+ elif mode == "LSTM":
19
+ return int(_cudnn.RNNMode.lstm)
20
+ elif mode == "GRU":
21
+ return int(_cudnn.RNNMode.gru)
22
+ else:
23
+ raise Exception(f"Unknown mode: {mode}") # noqa: TRY002
24
+
25
+
26
+ # NB: We don't actually need this class anymore (in fact, we could serialize the
27
+ # dropout state for even better reproducibility), but it is kept for backwards
28
+ # compatibility for old models.
29
+ class Unserializable:
30
+ def __init__(self, inner):
31
+ self.inner = inner
32
+
33
+ def get(self):
34
+ return self.inner
35
+
36
+ def __getstate__(self):
37
+ # Note: can't return {}, because python2 won't call __setstate__
38
+ # if the value evaluates to False
39
+ return "<unserializable>"
40
+
41
+ def __setstate__(self, state):
42
+ self.inner = None
43
+
44
+
45
+ def init_dropout_state(dropout, train, dropout_seed, dropout_state):
46
+ dropout_desc_name = "desc_" + str(torch.cuda.current_device())
47
+ dropout_p = dropout if train else 0
48
+ if (dropout_desc_name not in dropout_state) or (
49
+ dropout_state[dropout_desc_name].get() is None
50
+ ):
51
+ if dropout_p == 0:
52
+ dropout_state[dropout_desc_name] = Unserializable(None)
53
+ else:
54
+ dropout_state[dropout_desc_name] = Unserializable(
55
+ torch._cudnn_init_dropout_state( # type: ignore[call-arg]
56
+ dropout_p,
57
+ train,
58
+ dropout_seed,
59
+ self_ty=torch.uint8,
60
+ device=torch.device("cuda"),
61
+ )
62
+ )
63
+ dropout_ts = dropout_state[dropout_desc_name].get()
64
+ return dropout_ts
tool_server/.venv/lib/python3.12/site-packages/torch/backends/cusparselt/__init__.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Optional
3
+
4
+ import torch
5
+
6
+
7
+ __all__ = [
8
+ "version",
9
+ "is_available",
10
+ "get_max_alg_id",
11
+ ]
12
+
13
+ try:
14
+ from torch._C import _cusparselt
15
+ except ImportError:
16
+ _cusparselt = None # type: ignore[assignment]
17
+
18
+ __cusparselt_version: Optional[int] = None
19
+ __MAX_ALG_ID: Optional[int] = None
20
+
21
+ if _cusparselt is not None:
22
+
23
+ def _init():
24
+ global __cusparselt_version
25
+ global __MAX_ALG_ID
26
+ if __cusparselt_version is None:
27
+ __cusparselt_version = _cusparselt.getVersionInt()
28
+ if __cusparselt_version == 400:
29
+ __MAX_ALG_ID = 4
30
+ elif __cusparselt_version == 502:
31
+ __MAX_ALG_ID = 5
32
+ elif __cusparselt_version == 602:
33
+ __MAX_ALG_ID = 37
34
+ return True
35
+
36
+ else:
37
+
38
+ def _init():
39
+ return False
40
+
41
+
42
+ def version() -> Optional[int]:
43
+ """Return the version of cuSPARSELt"""
44
+ if not _init():
45
+ return None
46
+ return __cusparselt_version
47
+
48
+
49
+ def is_available() -> bool:
50
+ r"""Return a bool indicating if cuSPARSELt is currently available."""
51
+ return torch._C._has_cusparselt
52
+
53
+
54
+ def get_max_alg_id() -> Optional[int]:
55
+ if not _init():
56
+ return None
57
+ return __MAX_ALG_ID
tool_server/.venv/lib/python3.12/site-packages/torch/backends/cusparselt/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (1.7 kB). View file