Upload folder using huggingface_hub (part 23)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +26 -0
- .venv/lib/python3.12/site-packages/torch/backends/_coreml/preprocess.py +154 -0
- .venv/lib/python3.12/site-packages/torch/backends/_nnapi/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/prepare.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/serializer.cpython-312.pyc +3 -0
- .venv/lib/python3.12/site-packages/torch/backends/_nnapi/prepare.py +208 -0
- .venv/lib/python3.12/site-packages/torch/backends/_nnapi/serializer.py +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/cpu/__init__.py +21 -0
- .venv/lib/python3.12/site-packages/torch/backends/cpu/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/cuda/__init__.py +715 -0
- .venv/lib/python3.12/site-packages/torch/backends/cuda/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/cudnn/__init__.py +261 -0
- .venv/lib/python3.12/site-packages/torch/backends/cudnn/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/cudnn/__pycache__/rnn.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/cudnn/rnn.py +128 -0
- .venv/lib/python3.12/site-packages/torch/backends/cusparselt/__init__.py +57 -0
- .venv/lib/python3.12/site-packages/torch/backends/cusparselt/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/kleidiai/__init__.py +7 -0
- .venv/lib/python3.12/site-packages/torch/backends/kleidiai/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/mha/__init__.py +25 -0
- .venv/lib/python3.12/site-packages/torch/backends/mha/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/miopen/__init__.py +50 -0
- .venv/lib/python3.12/site-packages/torch/backends/miopen/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/mkl/__init__.py +59 -0
- .venv/lib/python3.12/site-packages/torch/backends/mkl/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/mkldnn/__init__.py +139 -0
- .venv/lib/python3.12/site-packages/torch/backends/mkldnn/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/mps/__init__.py +60 -0
- .venv/lib/python3.12/site-packages/torch/backends/mps/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/nnpack/__init__.py +32 -0
- .venv/lib/python3.12/site-packages/torch/backends/nnpack/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/openmp/__init__.py +7 -0
- .venv/lib/python3.12/site-packages/torch/backends/openmp/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/opt_einsum/__init__.py +117 -0
- .venv/lib/python3.12/site-packages/torch/backends/opt_einsum/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/python_native/__init__.py +395 -0
- .venv/lib/python3.12/site-packages/torch/backends/python_native/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/quantized/__init__.py +65 -0
- .venv/lib/python3.12/site-packages/torch/backends/quantized/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/xeon/__init__.py +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/xeon/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/xeon/__pycache__/run_cpu.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/backends/xeon/run_cpu.py +1028 -0
- .venv/lib/python3.12/site-packages/torch/backends/xnnpack/__init__.py +29 -0
- .venv/lib/python3.12/site-packages/torch/backends/xnnpack/__pycache__/__init__.cpython-312.pyc +0 -0
- .venv/lib/python3.12/site-packages/torch/bin/FileStoreTest +3 -0
- .venv/lib/python3.12/site-packages/torch/bin/HashStoreTest +3 -0
- .venv/lib/python3.12/site-packages/torch/bin/TCPStoreTest +3 -0
- .venv/lib/python3.12/site-packages/torch/bin/protoc +3 -0
.gitattributes
CHANGED
|
@@ -553,3 +553,29 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 553 |
.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 554 |
.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 555 |
.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 554 |
.venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 555 |
.venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 556 |
+
.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/serializer.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 557 |
+
.venv/lib/python3.12/site-packages/torch/bin/FileStoreTest filter=lfs diff=lfs merge=lfs -text
|
| 558 |
+
.venv/lib/python3.12/site-packages/torch/bin/HashStoreTest filter=lfs diff=lfs merge=lfs -text
|
| 559 |
+
.venv/lib/python3.12/site-packages/torch/bin/TCPStoreTest filter=lfs diff=lfs merge=lfs -text
|
| 560 |
+
.venv/lib/python3.12/site-packages/torch/bin/protoc filter=lfs diff=lfs merge=lfs -text
|
| 561 |
+
.venv/lib/python3.12/site-packages/torch/bin/protoc-3.21.12.0 filter=lfs diff=lfs merge=lfs -text
|
| 562 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_aoti_abi_check filter=lfs diff=lfs merge=lfs -text
|
| 563 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_api filter=lfs diff=lfs merge=lfs -text
|
| 564 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_comms_id filter=lfs diff=lfs merge=lfs -text
|
| 565 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_cpp_rpc filter=lfs diff=lfs merge=lfs -text
|
| 566 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_dist_autograd filter=lfs diff=lfs merge=lfs -text
|
| 567 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_global_state_manager filter=lfs diff=lfs merge=lfs -text
|
| 568 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_jit filter=lfs diff=lfs merge=lfs -text
|
| 569 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_lazy filter=lfs diff=lfs merge=lfs -text
|
| 570 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_privateuse1_profiler filter=lfs diff=lfs merge=lfs -text
|
| 571 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_profiler_collection filter=lfs diff=lfs merge=lfs -text
|
| 572 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_profiler_global_callback_stale_session filter=lfs diff=lfs merge=lfs -text
|
| 573 |
+
.venv/lib/python3.12/site-packages/torch/bin/test_shim filter=lfs diff=lfs merge=lfs -text
|
| 574 |
+
.venv/lib/python3.12/site-packages/torch/distributed/__pycache__/distributed_c10d.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 575 |
+
.venv/lib/python3.12/site-packages/torch/distributed/_local_tensor/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 576 |
+
.venv/lib/python3.12/site-packages/torch/distributed/_symmetric_memory/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 577 |
+
.venv/lib/python3.12/site-packages/torch/distributed/fsdp/__pycache__/_flat_param.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 578 |
+
.venv/lib/python3.12/site-packages/torch/distributed/fsdp/__pycache__/fully_sharded_data_parallel.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 579 |
+
.venv/lib/python3.12/site-packages/torch/distributed/pipelining/__pycache__/schedules.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 580 |
+
.venv/lib/python3.12/site-packages/torch/distributed/pipelining/__pycache__/stage.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 581 |
+
.venv/lib/python3.12/site-packages/torch/export/__pycache__/_trace.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
.venv/lib/python3.12/site-packages/torch/backends/_coreml/preprocess.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
convert_to=None,
|
| 59 |
+
):
|
| 60 |
+
return (
|
| 61 |
+
inputs,
|
| 62 |
+
outputs,
|
| 63 |
+
backend,
|
| 64 |
+
allow_low_precision,
|
| 65 |
+
quantization_mode,
|
| 66 |
+
mlmodel_export_path,
|
| 67 |
+
convert_to,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _check_enumerated_shape(shape):
|
| 72 |
+
for s in shape:
|
| 73 |
+
if not isinstance(s, (list, tuple)):
|
| 74 |
+
return False
|
| 75 |
+
return True
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _convert_to_mil_type(shape, dtype, name: str):
|
| 79 |
+
mil_shape = shape
|
| 80 |
+
if _check_enumerated_shape(shape):
|
| 81 |
+
mil_shape = ct.EnumeratedShapes(shape)
|
| 82 |
+
ml_type = TensorType(shape=mil_shape, dtype=torch_to_mil_types[dtype])
|
| 83 |
+
ml_type.name = name
|
| 84 |
+
return ml_type
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def preprocess(script_module: torch._C.ScriptObject, compile_spec: dict[str, tuple]):
|
| 88 |
+
spec = compile_spec["forward"]
|
| 89 |
+
(
|
| 90 |
+
input_specs,
|
| 91 |
+
output_specs,
|
| 92 |
+
backend,
|
| 93 |
+
allow_low_precision,
|
| 94 |
+
quantization_mode,
|
| 95 |
+
mlmodel_export_path,
|
| 96 |
+
convert_to,
|
| 97 |
+
) = spec
|
| 98 |
+
mil_inputs = []
|
| 99 |
+
inputs = []
|
| 100 |
+
for index, input in enumerate(input_specs):
|
| 101 |
+
shape, dtype = input
|
| 102 |
+
name = "input_" + str(index)
|
| 103 |
+
inputs.append([name, str(dtype), str(shape)])
|
| 104 |
+
ml_type = _convert_to_mil_type(shape, dtype, name)
|
| 105 |
+
mil_inputs.append(ml_type)
|
| 106 |
+
model = torch.jit.RecursiveScriptModule._construct(script_module, lambda x: None)
|
| 107 |
+
mlmodel = ct.convert(model, inputs=mil_inputs, convert_to=convert_to)
|
| 108 |
+
|
| 109 |
+
if quantization_mode != CoreMLQuantizationMode.NONE:
|
| 110 |
+
quant_model_spec = quantization_utils.quantize_weights(
|
| 111 |
+
mlmodel, nbits=8, quantization_mode=quantization_mode
|
| 112 |
+
)
|
| 113 |
+
mlmodel = ct.models.MLModel(quant_model_spec)
|
| 114 |
+
|
| 115 |
+
spec = mlmodel.get_spec()
|
| 116 |
+
if len(spec.description.output) != len(output_specs): # type: ignore[attr-defined]
|
| 117 |
+
raise AssertionError(
|
| 118 |
+
f"Number of outputs in spec ({len(spec.description.output)}) " # type: ignore[attr-defined]
|
| 119 |
+
f"does not match output_specs ({len(output_specs)})"
|
| 120 |
+
)
|
| 121 |
+
outputs = []
|
| 122 |
+
for index, output in enumerate(output_specs):
|
| 123 |
+
shape, dtype = output
|
| 124 |
+
name = spec.description.output[index].name # type: ignore[attr-defined]
|
| 125 |
+
outputs.append([name, str(dtype), str(shape)])
|
| 126 |
+
mlmodel = ct.models.model.MLModel(spec)
|
| 127 |
+
print(mlmodel)
|
| 128 |
+
|
| 129 |
+
if mlmodel_export_path is not None:
|
| 130 |
+
print(f"Saving CoreML .mlmodel file to {mlmodel_export_path}")
|
| 131 |
+
mlmodel.save(mlmodel_export_path)
|
| 132 |
+
|
| 133 |
+
config = {
|
| 134 |
+
"spec_ver": str(spec.specificationVersion), # type: ignore[attr-defined]
|
| 135 |
+
"backend": backend,
|
| 136 |
+
"allow_low_precision": str(allow_low_precision),
|
| 137 |
+
}
|
| 138 |
+
metadata = {
|
| 139 |
+
"coremltool_ver": mlmodel.user_defined_metadata[CT_METADATA_VERSION],
|
| 140 |
+
"torch_ver": mlmodel.user_defined_metadata[CT_METADATA_SOURCE],
|
| 141 |
+
}
|
| 142 |
+
coreml_compile_spec = {
|
| 143 |
+
"inputs": inputs,
|
| 144 |
+
"outputs": outputs,
|
| 145 |
+
"config": config,
|
| 146 |
+
"metadata": metadata,
|
| 147 |
+
}
|
| 148 |
+
mlmodel = spec.SerializeToString() # type: ignore[attr-defined]
|
| 149 |
+
|
| 150 |
+
return {
|
| 151 |
+
"model": mlmodel,
|
| 152 |
+
"hash": str(hashlib.sha256(mlmodel).hexdigest()),
|
| 153 |
+
"extra": json.dumps(coreml_compile_spec),
|
| 154 |
+
}
|
.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (196 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/_nnapi/__pycache__/prepare.cpython-312.pyc
ADDED
|
Binary file (9.32 kB). View file
|
|
|
.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:83cbb3cc33e05f17bd096eed4f8e97c3e30e7c90a4b37258f32c07400f9201a4
|
| 3 |
+
size 125075
|
.venv/lib/python3.12/site-packages/torch/backends/_nnapi/prepare.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-decorators
|
| 2 |
+
# mypy: allow-untyped-defs
|
| 3 |
+
|
| 4 |
+
from typing import Optional
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.backends._nnapi.serializer import _NnapiSerializer
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
ANEURALNETWORKS_PREFER_LOW_POWER = 0
|
| 11 |
+
ANEURALNETWORKS_PREFER_FAST_SINGLE_ANSWER = 1
|
| 12 |
+
ANEURALNETWORKS_PREFER_SUSTAINED_SPEED = 2
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class NnapiModule(torch.nn.Module):
|
| 16 |
+
"""Torch Module that wraps an NNAPI Compilation.
|
| 17 |
+
|
| 18 |
+
This module handles preparing the weights, initializing the
|
| 19 |
+
NNAPI TorchBind object, and adjusting the memory formats
|
| 20 |
+
of all inputs and outputs.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
# _nnapi.Compilation is defined
|
| 24 |
+
comp: Optional[torch.classes._nnapi.Compilation] # type: ignore[name-defined] # noqa: UP045
|
| 25 |
+
weights: list[torch.Tensor]
|
| 26 |
+
out_templates: list[torch.Tensor]
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
shape_compute_module: torch.nn.Module,
|
| 31 |
+
ser_model: torch.Tensor,
|
| 32 |
+
weights: list[torch.Tensor],
|
| 33 |
+
inp_mem_fmts: list[int],
|
| 34 |
+
out_mem_fmts: list[int],
|
| 35 |
+
compilation_preference: int,
|
| 36 |
+
relax_f32_to_f16: bool,
|
| 37 |
+
):
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.shape_compute_module = shape_compute_module
|
| 40 |
+
self.ser_model = ser_model
|
| 41 |
+
self.weights = weights
|
| 42 |
+
self.inp_mem_fmts = inp_mem_fmts
|
| 43 |
+
self.out_mem_fmts = out_mem_fmts
|
| 44 |
+
self.out_templates = []
|
| 45 |
+
self.comp = None
|
| 46 |
+
self.compilation_preference = compilation_preference
|
| 47 |
+
self.relax_f32_to_f16 = relax_f32_to_f16
|
| 48 |
+
|
| 49 |
+
@torch.jit.export
|
| 50 |
+
def init(self, args: list[torch.Tensor]):
|
| 51 |
+
if self.comp is not None:
|
| 52 |
+
raise AssertionError("comp must be None before initialization")
|
| 53 |
+
self.out_templates = self.shape_compute_module.prepare(self.ser_model, args) # type: ignore[operator]
|
| 54 |
+
self.weights = [w.contiguous() for w in self.weights]
|
| 55 |
+
comp = torch.classes._nnapi.Compilation()
|
| 56 |
+
comp.init2(
|
| 57 |
+
self.ser_model,
|
| 58 |
+
self.weights,
|
| 59 |
+
self.compilation_preference,
|
| 60 |
+
self.relax_f32_to_f16,
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
self.comp = comp
|
| 64 |
+
|
| 65 |
+
def forward(self, args: list[torch.Tensor]) -> list[torch.Tensor]:
|
| 66 |
+
if self.comp is None:
|
| 67 |
+
self.init(args)
|
| 68 |
+
comp = self.comp
|
| 69 |
+
if comp is None:
|
| 70 |
+
raise AssertionError("comp must not be None")
|
| 71 |
+
outs = [torch.empty_like(out) for out in self.out_templates]
|
| 72 |
+
|
| 73 |
+
if len(args) != len(self.inp_mem_fmts):
|
| 74 |
+
raise AssertionError(
|
| 75 |
+
f"args length {len(args)} != inp_mem_fmts length {len(self.inp_mem_fmts)}"
|
| 76 |
+
)
|
| 77 |
+
fixed_args = []
|
| 78 |
+
for idx in range(len(args)):
|
| 79 |
+
fmt = self.inp_mem_fmts[idx]
|
| 80 |
+
# These constants match the values in DimOrder in serializer.py
|
| 81 |
+
# TODO: See if it's possible to use those directly.
|
| 82 |
+
if fmt == 0:
|
| 83 |
+
fixed_args.append(args[idx].contiguous())
|
| 84 |
+
elif fmt == 1:
|
| 85 |
+
fixed_args.append(args[idx].permute(0, 2, 3, 1).contiguous())
|
| 86 |
+
else:
|
| 87 |
+
raise ValueError("Invalid mem_fmt")
|
| 88 |
+
comp.run(fixed_args, outs)
|
| 89 |
+
if len(outs) != len(self.out_mem_fmts):
|
| 90 |
+
raise AssertionError(
|
| 91 |
+
f"outs length {len(outs)} != out_mem_fmts length {len(self.out_mem_fmts)}"
|
| 92 |
+
)
|
| 93 |
+
for idx in range(len(self.out_templates)):
|
| 94 |
+
fmt = self.out_mem_fmts[idx]
|
| 95 |
+
# These constants match the values in DimOrder in serializer.py
|
| 96 |
+
# TODO: See if it's possible to use those directly.
|
| 97 |
+
if fmt in (0, 2):
|
| 98 |
+
pass
|
| 99 |
+
elif fmt == 1:
|
| 100 |
+
outs[idx] = outs[idx].permute(0, 3, 1, 2)
|
| 101 |
+
else:
|
| 102 |
+
raise ValueError("Invalid mem_fmt")
|
| 103 |
+
return outs
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def convert_model_to_nnapi(
|
| 107 |
+
model,
|
| 108 |
+
inputs,
|
| 109 |
+
serializer=None,
|
| 110 |
+
return_shapes=None,
|
| 111 |
+
use_int16_for_qint16=False,
|
| 112 |
+
compilation_preference=ANEURALNETWORKS_PREFER_SUSTAINED_SPEED,
|
| 113 |
+
relax_f32_to_f16=False,
|
| 114 |
+
):
|
| 115 |
+
(
|
| 116 |
+
shape_compute_module,
|
| 117 |
+
ser_model_tensor,
|
| 118 |
+
used_weights,
|
| 119 |
+
inp_mem_fmts,
|
| 120 |
+
out_mem_fmts,
|
| 121 |
+
retval_count,
|
| 122 |
+
) = process_for_nnapi(
|
| 123 |
+
model, inputs, serializer, return_shapes, use_int16_for_qint16
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
nnapi_model = NnapiModule(
|
| 127 |
+
shape_compute_module,
|
| 128 |
+
ser_model_tensor,
|
| 129 |
+
used_weights,
|
| 130 |
+
inp_mem_fmts,
|
| 131 |
+
out_mem_fmts,
|
| 132 |
+
compilation_preference,
|
| 133 |
+
relax_f32_to_f16,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
class NnapiInterfaceWrapper(torch.nn.Module):
|
| 137 |
+
"""NNAPI list-ifying and de-list-ifying wrapper.
|
| 138 |
+
|
| 139 |
+
NNAPI always expects a list of inputs and provides a list of outputs.
|
| 140 |
+
This module allows us to accept inputs as separate arguments.
|
| 141 |
+
It returns results as either a single tensor or tuple,
|
| 142 |
+
matching the original module.
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
def __init__(self, mod):
|
| 146 |
+
super().__init__()
|
| 147 |
+
self.mod = mod
|
| 148 |
+
|
| 149 |
+
wrapper_model_py = NnapiInterfaceWrapper(nnapi_model)
|
| 150 |
+
wrapper_model = torch.jit.script(wrapper_model_py)
|
| 151 |
+
# TODO: Maybe make these names match the original.
|
| 152 |
+
arg_list = ", ".join(f"arg_{idx}" for idx in range(len(inputs)))
|
| 153 |
+
if retval_count < 0:
|
| 154 |
+
ret_expr = "retvals[0]"
|
| 155 |
+
else:
|
| 156 |
+
ret_expr = "".join(f"retvals[{idx}], " for idx in range(retval_count))
|
| 157 |
+
wrapper_model.define(
|
| 158 |
+
f"def forward(self, {arg_list}):\n"
|
| 159 |
+
f" retvals = self.mod([{arg_list}])\n"
|
| 160 |
+
f" return {ret_expr}\n"
|
| 161 |
+
)
|
| 162 |
+
return wrapper_model
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def process_for_nnapi(
|
| 166 |
+
model, inputs, serializer=None, return_shapes=None, use_int16_for_qint16=False
|
| 167 |
+
):
|
| 168 |
+
model = torch.jit.freeze(model)
|
| 169 |
+
|
| 170 |
+
if isinstance(inputs, torch.Tensor):
|
| 171 |
+
inputs = [inputs]
|
| 172 |
+
|
| 173 |
+
serializer = serializer or _NnapiSerializer(
|
| 174 |
+
config=None, use_int16_for_qint16=use_int16_for_qint16
|
| 175 |
+
)
|
| 176 |
+
(
|
| 177 |
+
ser_model,
|
| 178 |
+
used_weights,
|
| 179 |
+
inp_mem_fmts,
|
| 180 |
+
out_mem_fmts,
|
| 181 |
+
shape_compute_lines,
|
| 182 |
+
retval_count,
|
| 183 |
+
) = serializer.serialize_model(model, inputs, return_shapes)
|
| 184 |
+
ser_model_tensor = torch.tensor(ser_model, dtype=torch.int32)
|
| 185 |
+
|
| 186 |
+
# We have to create a new class here every time this function is called
|
| 187 |
+
# because module.define adds a method to the *class*, not the instance.
|
| 188 |
+
class ShapeComputeModule(torch.nn.Module):
|
| 189 |
+
"""Code-gen-ed module for tensor shape computation.
|
| 190 |
+
|
| 191 |
+
module.prepare will mutate ser_model according to the computed operand
|
| 192 |
+
shapes, based on the shapes of args. Returns a list of output templates.
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
shape_compute_module = torch.jit.script(ShapeComputeModule())
|
| 196 |
+
real_shape_compute_lines = [
|
| 197 |
+
"def prepare(self, ser_model: torch.Tensor, args: List[torch.Tensor]) -> List[torch.Tensor]:\n",
|
| 198 |
+
] + [f" {line}\n" for line in shape_compute_lines]
|
| 199 |
+
shape_compute_module.define("".join(real_shape_compute_lines))
|
| 200 |
+
|
| 201 |
+
return (
|
| 202 |
+
shape_compute_module,
|
| 203 |
+
ser_model_tensor,
|
| 204 |
+
used_weights,
|
| 205 |
+
inp_mem_fmts,
|
| 206 |
+
out_mem_fmts,
|
| 207 |
+
retval_count,
|
| 208 |
+
)
|
.venv/lib/python3.12/site-packages/torch/backends/_nnapi/serializer.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
.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()
|
.venv/lib/python3.12/site-packages/torch/backends/cpu/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (658 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/cuda/__init__.py
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import contextlib
|
| 3 |
+
from typing import Any
|
| 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 |
+
"cublas_workspace_size",
|
| 18 |
+
"cublaslt_workspace_size",
|
| 19 |
+
"blas_workspace_size",
|
| 20 |
+
"preferred_rocm_fa_library",
|
| 21 |
+
"is_ck_sdpa_available",
|
| 22 |
+
"cufft_plan_cache",
|
| 23 |
+
"matmul",
|
| 24 |
+
"SDPAParams",
|
| 25 |
+
"enable_cudnn_sdp",
|
| 26 |
+
"cudnn_sdp_enabled",
|
| 27 |
+
"enable_flash_sdp",
|
| 28 |
+
"flash_sdp_enabled",
|
| 29 |
+
"enable_mem_efficient_sdp",
|
| 30 |
+
"mem_efficient_sdp_enabled",
|
| 31 |
+
"math_sdp_enabled",
|
| 32 |
+
"enable_math_sdp",
|
| 33 |
+
"allow_fp16_bf16_reduction_math_sdp",
|
| 34 |
+
"fp16_bf16_reduction_math_sdp_allowed",
|
| 35 |
+
"is_flash_attention_available",
|
| 36 |
+
"can_use_flash_attention",
|
| 37 |
+
"can_use_efficient_attention",
|
| 38 |
+
"can_use_cudnn_attention",
|
| 39 |
+
"sdp_kernel",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def is_built():
|
| 44 |
+
r"""
|
| 45 |
+
Return whether PyTorch is built with CUDA support.
|
| 46 |
+
|
| 47 |
+
Note that this doesn't necessarily mean CUDA is available; just that if this PyTorch
|
| 48 |
+
binary were run on a machine with working CUDA drivers and devices, we would be able to use it.
|
| 49 |
+
"""
|
| 50 |
+
return torch._C._has_cuda
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class cuFFTPlanCacheAttrContextProp:
|
| 54 |
+
# Like regular ContextProp, but uses the `.device_index` attribute from the
|
| 55 |
+
# calling object as the first argument to the getter and setter.
|
| 56 |
+
def __init__(self, getter, setter):
|
| 57 |
+
self.getter = getter
|
| 58 |
+
self.setter = setter
|
| 59 |
+
|
| 60 |
+
def __get__(self, obj, objtype):
|
| 61 |
+
return self.getter(obj.device_index)
|
| 62 |
+
|
| 63 |
+
def __set__(self, obj, val):
|
| 64 |
+
if isinstance(self.setter, str):
|
| 65 |
+
raise RuntimeError(self.setter)
|
| 66 |
+
self.setter(obj.device_index, val)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class cuFFTPlanCache:
|
| 70 |
+
r"""
|
| 71 |
+
Represent a specific plan cache for a specific `device_index`.
|
| 72 |
+
|
| 73 |
+
The attributes `size` and `max_size`, and method `clear`, can fetch and/ or
|
| 74 |
+
change properties of the C++ cuFFT plan cache.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
def __init__(self, device_index):
|
| 78 |
+
self.device_index = device_index
|
| 79 |
+
|
| 80 |
+
size = cuFFTPlanCacheAttrContextProp(
|
| 81 |
+
torch._cufft_get_plan_cache_size,
|
| 82 |
+
".size is a read-only property showing the number of plans currently in the "
|
| 83 |
+
"cache. To change the cache capacity, set cufft_plan_cache.max_size.",
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
max_size = cuFFTPlanCacheAttrContextProp(
|
| 87 |
+
torch._cufft_get_plan_cache_max_size, torch._cufft_set_plan_cache_max_size
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
def clear(self):
|
| 91 |
+
return torch._cufft_clear_plan_cache(self.device_index)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
class cuFFTPlanCacheManager:
|
| 95 |
+
r"""
|
| 96 |
+
Represent all cuFFT plan caches, return the cuFFTPlanCache for a given device when indexed.
|
| 97 |
+
|
| 98 |
+
Finally, this object, when used directly as a `cuFFTPlanCache` object (e.g.,
|
| 99 |
+
setting the `.max_size`) attribute, the current device's cuFFT plan cache is
|
| 100 |
+
used.
|
| 101 |
+
"""
|
| 102 |
+
|
| 103 |
+
__initialized = False
|
| 104 |
+
|
| 105 |
+
def __init__(self):
|
| 106 |
+
self.caches = []
|
| 107 |
+
self.__initialized = True
|
| 108 |
+
|
| 109 |
+
def __getitem__(self, device):
|
| 110 |
+
index = torch.cuda._utils._get_device_index(device)
|
| 111 |
+
if index < 0 or index >= torch.cuda.device_count():
|
| 112 |
+
raise RuntimeError(
|
| 113 |
+
f"cufft_plan_cache: expected 0 <= device index < {torch.cuda.device_count()}, but got "
|
| 114 |
+
f"device with index {index}"
|
| 115 |
+
)
|
| 116 |
+
if len(self.caches) == 0:
|
| 117 |
+
self.caches.extend(
|
| 118 |
+
cuFFTPlanCache(index) for index in range(torch.cuda.device_count())
|
| 119 |
+
)
|
| 120 |
+
return self.caches[index]
|
| 121 |
+
|
| 122 |
+
def __getattr__(self, name):
|
| 123 |
+
return getattr(self[torch.cuda.current_device()], name)
|
| 124 |
+
|
| 125 |
+
def __setattr__(self, name, value):
|
| 126 |
+
if self.__initialized:
|
| 127 |
+
return setattr(self[torch.cuda.current_device()], name, value)
|
| 128 |
+
else:
|
| 129 |
+
return super().__setattr__(name, value)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class cuBLASModule:
|
| 133 |
+
@staticmethod
|
| 134 |
+
def _parse_reduction_setting(value: Any, attr_name: str) -> tuple[bool, bool]:
|
| 135 |
+
def _ensure_bool(obj: Any, which: str) -> bool:
|
| 136 |
+
if isinstance(obj, bool):
|
| 137 |
+
return obj
|
| 138 |
+
raise TypeError(
|
| 139 |
+
f"{attr_name} expects a bool for {which}, but got {type(obj)!r}"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
if isinstance(value, bool):
|
| 143 |
+
return value, True
|
| 144 |
+
if isinstance(value, (list, tuple)):
|
| 145 |
+
if not value:
|
| 146 |
+
raise TypeError(f"{attr_name} expects at least one boolean argument")
|
| 147 |
+
if len(value) > 2:
|
| 148 |
+
raise TypeError(f"{attr_name} expects at most two boolean arguments")
|
| 149 |
+
allow_reduced_precision = _ensure_bool(value[0], "allow_reduced_precision")
|
| 150 |
+
if len(value) == 1:
|
| 151 |
+
return allow_reduced_precision, True
|
| 152 |
+
allow_splitk = _ensure_bool(value[1], "allow_splitk")
|
| 153 |
+
return allow_reduced_precision, allow_splitk
|
| 154 |
+
raise TypeError(
|
| 155 |
+
f"{attr_name} expects a bool or a tuple/list of bools, but got {type(value)!r}"
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def __getattr__(self, name):
|
| 159 |
+
if name == "allow_tf32":
|
| 160 |
+
return torch._C._get_cublas_allow_tf32()
|
| 161 |
+
elif name == "prefer_cublaslt_grouped_gemm":
|
| 162 |
+
return torch._C._get_cublaslt_prefer_grouped_gemm()
|
| 163 |
+
elif name == "allow_fp16_reduced_precision_reduction":
|
| 164 |
+
allow_reduced_precision, _ = (
|
| 165 |
+
torch._C._get_cublas_allow_fp16_reduced_precision_reduction()
|
| 166 |
+
)
|
| 167 |
+
return allow_reduced_precision
|
| 168 |
+
elif name == "allow_fp16_reduced_precision_reduction_split_k":
|
| 169 |
+
_, allow_splitk = (
|
| 170 |
+
torch._C._get_cublas_allow_fp16_reduced_precision_reduction()
|
| 171 |
+
)
|
| 172 |
+
return allow_splitk
|
| 173 |
+
elif name == "allow_bf16_reduced_precision_reduction":
|
| 174 |
+
allow_reduced_precision, _ = (
|
| 175 |
+
torch._C._get_cublas_allow_bf16_reduced_precision_reduction()
|
| 176 |
+
)
|
| 177 |
+
return allow_reduced_precision
|
| 178 |
+
elif name == "allow_bf16_reduced_precision_reduction_split_k":
|
| 179 |
+
_, allow_splitk = (
|
| 180 |
+
torch._C._get_cublas_allow_bf16_reduced_precision_reduction()
|
| 181 |
+
)
|
| 182 |
+
return allow_splitk
|
| 183 |
+
elif name == "allow_fp16_accumulation":
|
| 184 |
+
return torch._C._get_cublas_allow_fp16_accumulation()
|
| 185 |
+
elif name == "fp32_precision":
|
| 186 |
+
return torch._C._get_fp32_precision_getter("cuda", "matmul")
|
| 187 |
+
raise AttributeError("Unknown attribute " + name)
|
| 188 |
+
|
| 189 |
+
def __setattr__(self, name, value):
|
| 190 |
+
if name == "allow_tf32":
|
| 191 |
+
return torch._C._set_cublas_allow_tf32(value)
|
| 192 |
+
elif name == "prefer_cublaslt_grouped_gemm":
|
| 193 |
+
return torch._C._set_cublaslt_prefer_grouped_gemm(value)
|
| 194 |
+
elif name == "allow_fp16_reduced_precision_reduction":
|
| 195 |
+
allow_reduced_precision, allow_splitk = self._parse_reduction_setting(
|
| 196 |
+
value, "allow_fp16_reduced_precision_reduction"
|
| 197 |
+
)
|
| 198 |
+
return torch._C._set_cublas_allow_fp16_reduced_precision_reduction(
|
| 199 |
+
allow_reduced_precision,
|
| 200 |
+
allow_splitk,
|
| 201 |
+
)
|
| 202 |
+
elif name == "allow_bf16_reduced_precision_reduction":
|
| 203 |
+
allow_reduced_precision, allow_splitk = self._parse_reduction_setting(
|
| 204 |
+
value, "allow_bf16_reduced_precision_reduction"
|
| 205 |
+
)
|
| 206 |
+
return torch._C._set_cublas_allow_bf16_reduced_precision_reduction(
|
| 207 |
+
allow_reduced_precision,
|
| 208 |
+
allow_splitk,
|
| 209 |
+
)
|
| 210 |
+
elif name == "allow_fp16_accumulation":
|
| 211 |
+
return torch._C._set_cublas_allow_fp16_accumulation(value)
|
| 212 |
+
elif name == "fp32_precision":
|
| 213 |
+
return torch._C._set_fp32_precision_setter("cuda", "matmul", value)
|
| 214 |
+
raise AttributeError("Unknown attribute " + name)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
_LinalgBackends = {
|
| 218 |
+
"default": torch._C._LinalgBackend.Default,
|
| 219 |
+
"cusolver": torch._C._LinalgBackend.Cusolver,
|
| 220 |
+
"magma": torch._C._LinalgBackend.Magma,
|
| 221 |
+
}
|
| 222 |
+
_LinalgBackends_str = ", ".join(_LinalgBackends.keys())
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def preferred_linalg_library(
|
| 226 |
+
backend: None | str | torch._C._LinalgBackend = None,
|
| 227 |
+
) -> torch._C._LinalgBackend:
|
| 228 |
+
r"""
|
| 229 |
+
Override the heuristic PyTorch uses to choose between cuSOLVER and MAGMA for CUDA linear algebra operations.
|
| 230 |
+
|
| 231 |
+
.. warning:: This flag is experimental and subject to change.
|
| 232 |
+
|
| 233 |
+
When PyTorch runs a CUDA linear algebra operation it often uses the cuSOLVER or MAGMA libraries,
|
| 234 |
+
and if both are available it decides which to use with a heuristic.
|
| 235 |
+
This flag (a :class:`str`) allows overriding those heuristics.
|
| 236 |
+
|
| 237 |
+
* If `"cusolver"` is set then cuSOLVER will be used wherever possible.
|
| 238 |
+
* If `"magma"` is set then MAGMA will be used wherever possible.
|
| 239 |
+
* If `"default"` (the default) is set then heuristics will be used to pick between
|
| 240 |
+
cuSOLVER and MAGMA if both are available.
|
| 241 |
+
* When no input is given, this function returns the currently preferred library.
|
| 242 |
+
* User may use the environment variable TORCH_LINALG_PREFER_CUSOLVER=1 to set the preferred library to cuSOLVER
|
| 243 |
+
globally.
|
| 244 |
+
This flag only sets the initial value of the preferred library and the preferred library
|
| 245 |
+
may still be overridden by this function call later in your script.
|
| 246 |
+
|
| 247 |
+
Note: When a library is preferred other libraries may still be used if the preferred library
|
| 248 |
+
doesn't implement the operation(s) called.
|
| 249 |
+
This flag may achieve better performance if PyTorch's heuristic library selection is incorrect
|
| 250 |
+
for your application's inputs.
|
| 251 |
+
|
| 252 |
+
Currently supported linalg operators:
|
| 253 |
+
|
| 254 |
+
* :func:`torch.linalg.inv`
|
| 255 |
+
* :func:`torch.linalg.inv_ex`
|
| 256 |
+
* :func:`torch.linalg.cholesky`
|
| 257 |
+
* :func:`torch.linalg.cholesky_ex`
|
| 258 |
+
* :func:`torch.cholesky_solve`
|
| 259 |
+
* :func:`torch.cholesky_inverse`
|
| 260 |
+
* :func:`torch.linalg.lu_factor`
|
| 261 |
+
* :func:`torch.linalg.lu`
|
| 262 |
+
* :func:`torch.linalg.lu_solve`
|
| 263 |
+
* :func:`torch.linalg.qr`
|
| 264 |
+
* :func:`torch.linalg.eigh`
|
| 265 |
+
* :func:`torch.linalg.eigvals`
|
| 266 |
+
* :func:`torch.linalg.svd`
|
| 267 |
+
* :func:`torch.linalg.svdvals`
|
| 268 |
+
"""
|
| 269 |
+
if backend is None:
|
| 270 |
+
pass
|
| 271 |
+
elif isinstance(backend, str):
|
| 272 |
+
if backend not in _LinalgBackends:
|
| 273 |
+
raise RuntimeError(
|
| 274 |
+
f"Unknown input value. Choose from: {_LinalgBackends_str}."
|
| 275 |
+
)
|
| 276 |
+
torch._C._set_linalg_preferred_backend(_LinalgBackends[backend])
|
| 277 |
+
elif isinstance(backend, torch._C._LinalgBackend):
|
| 278 |
+
torch._C._set_linalg_preferred_backend(backend)
|
| 279 |
+
else:
|
| 280 |
+
raise RuntimeError("Unknown input value type.")
|
| 281 |
+
|
| 282 |
+
return torch._C._get_linalg_preferred_backend()
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
_BlasBackends = {
|
| 286 |
+
"default": torch._C._BlasBackend.Default,
|
| 287 |
+
"cublas": torch._C._BlasBackend.Cublas,
|
| 288 |
+
"hipblas": torch._C._BlasBackend.Cublas, # alias
|
| 289 |
+
"cublaslt": torch._C._BlasBackend.Cublaslt,
|
| 290 |
+
"hipblaslt": torch._C._BlasBackend.Cublaslt, # alias
|
| 291 |
+
"ck": torch._C._BlasBackend.Ck,
|
| 292 |
+
}
|
| 293 |
+
_BlasBackends_str = ", ".join(_BlasBackends.keys())
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def preferred_blas_library(
|
| 297 |
+
backend: None | str | torch._C._BlasBackend = None,
|
| 298 |
+
) -> torch._C._BlasBackend:
|
| 299 |
+
r"""
|
| 300 |
+
Override the library PyTorch uses for BLAS operations. Choose between cuBLAS, cuBLASLt, and CK [ROCm-only].
|
| 301 |
+
|
| 302 |
+
.. warning:: This flag is experimental and subject to change.
|
| 303 |
+
|
| 304 |
+
When PyTorch runs a CUDA BLAS operation it defaults to cuBLAS even if both cuBLAS and cuBLASLt are available.
|
| 305 |
+
For PyTorch built for ROCm, hipBLAS, hipBLASLt, and CK may offer different performance.
|
| 306 |
+
This flag (a :class:`str`) allows overriding which BLAS library to use.
|
| 307 |
+
|
| 308 |
+
* If `"cublas"` is set then cuBLAS will be used wherever possible.
|
| 309 |
+
* If `"cublaslt"` is set then cuBLASLt will be used wherever possible.
|
| 310 |
+
* If `"ck"` is set then CK will be used wherever possible.
|
| 311 |
+
* If `"default"` (the default) is set then heuristics will be used to pick between the other options.
|
| 312 |
+
* When no input is given, this function returns the currently preferred library.
|
| 313 |
+
* User may use the environment variable TORCH_BLAS_PREFER_CUBLASLT=1 to set the preferred library to cuBLASLt
|
| 314 |
+
globally.
|
| 315 |
+
This flag only sets the initial value of the preferred library and the preferred library
|
| 316 |
+
may still be overridden by this function call later in your script.
|
| 317 |
+
|
| 318 |
+
Note: When a library is preferred other libraries may still be used if the preferred library
|
| 319 |
+
doesn't implement the operation(s) called.
|
| 320 |
+
This flag may achieve better performance if PyTorch's library selection is incorrect
|
| 321 |
+
for your application's inputs.
|
| 322 |
+
|
| 323 |
+
"""
|
| 324 |
+
if backend is None:
|
| 325 |
+
pass
|
| 326 |
+
elif isinstance(backend, str):
|
| 327 |
+
if backend not in _BlasBackends:
|
| 328 |
+
raise RuntimeError(
|
| 329 |
+
f"Unknown input value. Choose from: {_BlasBackends_str}."
|
| 330 |
+
)
|
| 331 |
+
torch._C._set_blas_preferred_backend(_BlasBackends[backend])
|
| 332 |
+
elif isinstance(backend, torch._C._BlasBackend):
|
| 333 |
+
torch._C._set_blas_preferred_backend(backend)
|
| 334 |
+
else:
|
| 335 |
+
raise RuntimeError("Unknown input value type.")
|
| 336 |
+
|
| 337 |
+
return torch._C._get_blas_preferred_backend()
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def cublas_workspace_size(size: None | int = None) -> int:
|
| 341 |
+
r"""Query or set the cuBLAS workspace size in bytes.
|
| 342 |
+
|
| 343 |
+
When called with no arguments, returns the current workspace size.
|
| 344 |
+
When called with a size argument, sets the workspace size and returns the new value.
|
| 345 |
+
Setting the workspace size will take precedence over the CUBLAS_WORKSPACE_CONFIG environment variable.
|
| 346 |
+
Changes take effect lazily: only handles used after the change get new workspaces.
|
| 347 |
+
|
| 348 |
+
Args:
|
| 349 |
+
size (int, optional): workspace size in bytes. Must be non-negative.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
int: the current (or newly set) workspace size in bytes.
|
| 353 |
+
"""
|
| 354 |
+
if size is not None:
|
| 355 |
+
torch._C._cuda_setCublasWorkspaceSize(size)
|
| 356 |
+
return torch._C._cuda_getCublasWorkspaceSize()
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def cublaslt_workspace_size(size: None | int = None) -> int:
|
| 360 |
+
r"""Query or set the cuBLASLt workspace size in bytes.
|
| 361 |
+
|
| 362 |
+
When called with no arguments, returns the current workspace size.
|
| 363 |
+
When called with a size argument, sets the workspace size and returns the new value.
|
| 364 |
+
Setting the workspace size will take precedence over the CUBLASLT_WORKSPACE_SIZE environment variable.
|
| 365 |
+
Changes take effect lazily: only handles used after the change get new workspaces.
|
| 366 |
+
|
| 367 |
+
Args:
|
| 368 |
+
size (int, optional): workspace size in bytes. Must be non-negative.
|
| 369 |
+
|
| 370 |
+
Returns:
|
| 371 |
+
int: the current (or newly set) workspace size in bytes.
|
| 372 |
+
"""
|
| 373 |
+
if size is not None:
|
| 374 |
+
torch._C._cuda_setCublasLtWorkspaceSize(size)
|
| 375 |
+
return torch._C._cuda_getCublasLtWorkspaceSize()
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
def blas_workspace_size(
|
| 379 |
+
size: None | int = None,
|
| 380 |
+
backend: None | str | torch._C._BlasBackend = None,
|
| 381 |
+
) -> int:
|
| 382 |
+
r"""Query or set the BLAS workspace size for a given backend.
|
| 383 |
+
|
| 384 |
+
Convenience wrapper that dispatches to :func:`cublas_workspace_size` or
|
| 385 |
+
:func:`cublaslt_workspace_size` depending on the backend.
|
| 386 |
+
|
| 387 |
+
When *backend* is ``None`` the current :func:`preferred_blas_library` is
|
| 388 |
+
used. ``Default`` is resolved to the platform's default backend (cuBLAS
|
| 389 |
+
on NVIDIA, potentially hipBLASLt on supported ROCm architectures).
|
| 390 |
+
|
| 391 |
+
.. note::
|
| 392 |
+
|
| 393 |
+
When ``TORCH_CUBLASLT_UNIFIED_WORKSPACE`` is enabled (the default on
|
| 394 |
+
open-source CUDA builds), the cuBLASLt workspace is capped at the
|
| 395 |
+
cuBLAS workspace size and physically reuses the same allocation.
|
| 396 |
+
Setting a large cuBLASLt workspace via this function will therefore
|
| 397 |
+
*not* increase memory beyond the cuBLAS workspace size.
|
| 398 |
+
|
| 399 |
+
.. note::
|
| 400 |
+
|
| 401 |
+
Setting the workspace size for the cublas backend will take precedence
|
| 402 |
+
over the CUBLAS_WORKSPACE_CONFIG environment variable, and setting the
|
| 403 |
+
workspace size for the cublaslt backend will take precedence over the
|
| 404 |
+
CUBLASLT_WORKSPACE_SIZE environment variable.
|
| 405 |
+
|
| 406 |
+
Args:
|
| 407 |
+
size (int, optional): workspace size in bytes. Must be non-negative.
|
| 408 |
+
When omitted the current size is returned without modification.
|
| 409 |
+
backend (str | torch._C._BlasBackend, optional): which backend's
|
| 410 |
+
workspace to query/set. Accepts the same strings as
|
| 411 |
+
:func:`preferred_blas_library` (e.g. ``"cublas"``, ``"cublaslt"``).
|
| 412 |
+
|
| 413 |
+
Returns:
|
| 414 |
+
int: the current (or newly set) workspace size in bytes.
|
| 415 |
+
|
| 416 |
+
Raises:
|
| 417 |
+
RuntimeError: if the resolved backend is CK (no workspace concept).
|
| 418 |
+
"""
|
| 419 |
+
if backend is None:
|
| 420 |
+
resolved = preferred_blas_library()
|
| 421 |
+
elif isinstance(backend, str):
|
| 422 |
+
if backend not in _BlasBackends:
|
| 423 |
+
raise RuntimeError(
|
| 424 |
+
f"Unknown backend string. Choose from: {_BlasBackends_str}."
|
| 425 |
+
)
|
| 426 |
+
resolved = _BlasBackends[backend]
|
| 427 |
+
elif isinstance(backend, torch._C._BlasBackend):
|
| 428 |
+
resolved = backend
|
| 429 |
+
else:
|
| 430 |
+
raise RuntimeError("Unknown backend type.")
|
| 431 |
+
|
| 432 |
+
if resolved == torch._C._BlasBackend.Default:
|
| 433 |
+
resolved = torch._C._get_blas_default_backend()
|
| 434 |
+
|
| 435 |
+
if resolved == torch._C._BlasBackend.Ck:
|
| 436 |
+
raise RuntimeError("CK backend does not use a workspace.")
|
| 437 |
+
|
| 438 |
+
if resolved == torch._C._BlasBackend.Cublaslt:
|
| 439 |
+
return cublaslt_workspace_size(size)
|
| 440 |
+
return cublas_workspace_size(size)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
_ROCmFABackends = {
|
| 444 |
+
"default": torch._C._ROCmFABackend.Default,
|
| 445 |
+
"aotriton": torch._C._ROCmFABackend.AOTriton,
|
| 446 |
+
"ck": torch._C._ROCmFABackend.Ck,
|
| 447 |
+
}
|
| 448 |
+
_ROCmFABackends_str = ", ".join(_ROCmFABackends.keys())
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
from torch._C import _SDPAParams as SDPAParams, _SDPBackend as SDPBackend
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def preferred_rocm_fa_library(
|
| 455 |
+
backend: None | str | torch._C._ROCmFABackend = None,
|
| 456 |
+
) -> torch._C._ROCmFABackend:
|
| 457 |
+
r"""
|
| 458 |
+
[ROCm-only]
|
| 459 |
+
Override the backend PyTorch uses in ROCm environments for Flash Attention. Choose between AOTriton and CK
|
| 460 |
+
|
| 461 |
+
.. warning:: This flag is experimental and subject to change.
|
| 462 |
+
|
| 463 |
+
When Flash Attention is enabled and desired, PyTorch defaults to using AOTriton as the backend.
|
| 464 |
+
This flag (a :class:`str`) allows users to override this backend to use composable_kernel
|
| 465 |
+
|
| 466 |
+
* If `"default"` is set then the default backend will be used wherever possible. Currently AOTriton.
|
| 467 |
+
* If `"aotriton"` is set then AOTriton will be used wherever possible.
|
| 468 |
+
* If `"ck"` is set then CK will be used wherever possible.
|
| 469 |
+
* When no input is given, this function returns the currently preferred library.
|
| 470 |
+
* User may use the environment variable TORCH_ROCM_FA_PREFER_CK=1 to set the preferred library to CK
|
| 471 |
+
globally.
|
| 472 |
+
|
| 473 |
+
Note: When a library is preferred other libraries may still be used if the preferred library
|
| 474 |
+
doesn't implement the operation(s) called.
|
| 475 |
+
This flag may achieve better performance if PyTorch's library selection is incorrect
|
| 476 |
+
for your application's inputs.
|
| 477 |
+
"""
|
| 478 |
+
if backend is None:
|
| 479 |
+
pass
|
| 480 |
+
elif isinstance(backend, str):
|
| 481 |
+
if backend not in _ROCmFABackends:
|
| 482 |
+
raise RuntimeError(
|
| 483 |
+
f"Unknown input value. Choose from: {_ROCmFABackends_str}."
|
| 484 |
+
)
|
| 485 |
+
torch._C._set_rocm_fa_preferred_backend(_ROCmFABackends[backend])
|
| 486 |
+
elif isinstance(backend, torch._C._ROCmFABackend):
|
| 487 |
+
torch._C._set_rocm_fa_preferred_backend(backend)
|
| 488 |
+
else:
|
| 489 |
+
raise ValueError(f"Unknown input value. Choose from: {_ROCmFABackends_str}.")
|
| 490 |
+
|
| 491 |
+
return torch._C._get_rocm_fa_preferred_backend()
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
# Set the __module__ attribute
|
| 495 |
+
SDPAParams.__module__ = "torch.backends.cuda"
|
| 496 |
+
SDPAParams.__name__ = "SDPAParams"
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def is_ck_sdpa_available() -> bool:
|
| 500 |
+
r"""
|
| 501 |
+
.. warning:: This flag is beta and subject to change.
|
| 502 |
+
|
| 503 |
+
Returns whether composable_kernel may be used as the backend for
|
| 504 |
+
scaled-dot-product-attention.
|
| 505 |
+
"""
|
| 506 |
+
# pyrefly: ignore [missing-attribute]
|
| 507 |
+
return torch._C._is_ck_sdpa_available()
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def flash_sdp_enabled():
|
| 511 |
+
r"""
|
| 512 |
+
.. warning:: This flag is beta and subject to change.
|
| 513 |
+
|
| 514 |
+
Returns whether flash scaled dot product attention is enabled or not.
|
| 515 |
+
"""
|
| 516 |
+
return torch._C._get_flash_sdp_enabled()
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def enable_flash_sdp(enabled: bool):
|
| 520 |
+
r"""
|
| 521 |
+
.. warning:: This flag is beta and subject to change.
|
| 522 |
+
|
| 523 |
+
Enables or disables flash scaled dot product attention.
|
| 524 |
+
"""
|
| 525 |
+
torch._C._set_sdp_use_flash(enabled)
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def mem_efficient_sdp_enabled():
|
| 529 |
+
r"""
|
| 530 |
+
.. warning:: This flag is beta and subject to change.
|
| 531 |
+
|
| 532 |
+
Returns whether memory efficient scaled dot product attention is enabled or not.
|
| 533 |
+
"""
|
| 534 |
+
return torch._C._get_mem_efficient_sdp_enabled()
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def enable_mem_efficient_sdp(enabled: bool):
|
| 538 |
+
r"""
|
| 539 |
+
.. warning:: This flag is beta and subject to change.
|
| 540 |
+
|
| 541 |
+
Enables or disables memory efficient scaled dot product attention.
|
| 542 |
+
"""
|
| 543 |
+
torch._C._set_sdp_use_mem_efficient(enabled)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def math_sdp_enabled():
|
| 547 |
+
r"""
|
| 548 |
+
.. warning:: This flag is beta and subject to change.
|
| 549 |
+
|
| 550 |
+
Returns whether math scaled dot product attention is enabled or not.
|
| 551 |
+
"""
|
| 552 |
+
return torch._C._get_math_sdp_enabled()
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def enable_math_sdp(enabled: bool):
|
| 556 |
+
r"""
|
| 557 |
+
.. warning:: This flag is beta and subject to change.
|
| 558 |
+
|
| 559 |
+
Enables or disables math scaled dot product attention.
|
| 560 |
+
"""
|
| 561 |
+
torch._C._set_sdp_use_math(enabled)
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def allow_fp16_bf16_reduction_math_sdp(enabled: bool):
|
| 565 |
+
r"""
|
| 566 |
+
.. warning:: This flag is beta and subject to change.
|
| 567 |
+
|
| 568 |
+
Enables or disables fp16/bf16 reduction in math scaled dot product attention.
|
| 569 |
+
"""
|
| 570 |
+
torch._C._set_math_sdp_allow_fp16_bf16_reduction(enabled)
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def fp16_bf16_reduction_math_sdp_allowed():
|
| 574 |
+
r"""
|
| 575 |
+
.. warning:: This flag is beta and subject to change.
|
| 576 |
+
|
| 577 |
+
Returns whether fp16/bf16 reduction in math scaled dot product attention is enabled or not.
|
| 578 |
+
"""
|
| 579 |
+
return torch._C._get_math_sdp_allow_fp16_bf16_reduction()
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
def is_flash_attention_available() -> bool:
|
| 583 |
+
r"""Check if PyTorch was built with FlashAttention for scaled_dot_product_attention.
|
| 584 |
+
|
| 585 |
+
Returns:
|
| 586 |
+
True if FlashAttention is built and available; otherwise, False.
|
| 587 |
+
|
| 588 |
+
Note:
|
| 589 |
+
This function is dependent on a CUDA-enabled build of PyTorch. It will return False
|
| 590 |
+
in non-CUDA environments.
|
| 591 |
+
"""
|
| 592 |
+
return torch._C._is_flash_attention_available()
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def can_use_flash_attention(params: SDPAParams, debug: bool = False) -> bool:
|
| 596 |
+
r"""Check if FlashAttention can be utilized in scaled_dot_product_attention.
|
| 597 |
+
|
| 598 |
+
Args:
|
| 599 |
+
params: An instance of SDPAParams containing the tensors for query,
|
| 600 |
+
key, value, an optional attention mask, dropout rate, and
|
| 601 |
+
a flag indicating if the attention is causal.
|
| 602 |
+
debug: Whether to logging.warn debug information as to why FlashAttention could not be run.
|
| 603 |
+
Defaults to False.
|
| 604 |
+
|
| 605 |
+
Returns:
|
| 606 |
+
True if FlashAttention can be used with the given parameters; otherwise, False.
|
| 607 |
+
|
| 608 |
+
Note:
|
| 609 |
+
This function is dependent on a CUDA-enabled build of PyTorch. It will return False
|
| 610 |
+
in non-CUDA environments.
|
| 611 |
+
"""
|
| 612 |
+
return torch._C._can_use_flash_attention(params, debug)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def can_use_efficient_attention(params: SDPAParams, debug: bool = False) -> bool:
|
| 616 |
+
r"""Check if efficient_attention can be utilized in scaled_dot_product_attention.
|
| 617 |
+
|
| 618 |
+
Args:
|
| 619 |
+
params: An instance of SDPAParams containing the tensors for query,
|
| 620 |
+
key, value, an optional attention mask, dropout rate, and
|
| 621 |
+
a flag indicating if the attention is causal.
|
| 622 |
+
debug: Whether to logging.warn with information as to why efficient_attention could not be run.
|
| 623 |
+
Defaults to False.
|
| 624 |
+
|
| 625 |
+
Returns:
|
| 626 |
+
True if efficient_attention can be used with the given parameters; otherwise, False.
|
| 627 |
+
|
| 628 |
+
Note:
|
| 629 |
+
This function is dependent on a CUDA-enabled build of PyTorch. It will return False
|
| 630 |
+
in non-CUDA environments.
|
| 631 |
+
"""
|
| 632 |
+
return torch._C._can_use_mem_efficient_attention(params, debug)
|
| 633 |
+
|
| 634 |
+
|
| 635 |
+
def can_use_cudnn_attention(params: SDPAParams, debug: bool = False) -> bool:
|
| 636 |
+
r"""Check if cudnn_attention can be utilized in scaled_dot_product_attention.
|
| 637 |
+
|
| 638 |
+
Args:
|
| 639 |
+
params: An instance of SDPAParams containing the tensors for query,
|
| 640 |
+
key, value, an optional attention mask, dropout rate, and
|
| 641 |
+
a flag indicating if the attention is causal.
|
| 642 |
+
debug: Whether to logging.warn with information as to why cuDNN attention could not be run.
|
| 643 |
+
Defaults to False.
|
| 644 |
+
|
| 645 |
+
Returns:
|
| 646 |
+
True if cuDNN can be used with the given parameters; otherwise, False.
|
| 647 |
+
|
| 648 |
+
Note:
|
| 649 |
+
This function is dependent on a CUDA-enabled build of PyTorch. It will return False
|
| 650 |
+
in non-CUDA environments.
|
| 651 |
+
"""
|
| 652 |
+
return torch._C._can_use_cudnn_attention(params, debug)
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
def cudnn_sdp_enabled():
|
| 656 |
+
r"""
|
| 657 |
+
.. warning:: This flag is beta and subject to change.
|
| 658 |
+
|
| 659 |
+
Returns whether cuDNN scaled dot product attention is enabled or not.
|
| 660 |
+
"""
|
| 661 |
+
return torch._C._get_cudnn_sdp_enabled()
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def enable_cudnn_sdp(enabled: bool):
|
| 665 |
+
r"""
|
| 666 |
+
.. warning:: This flag is beta and subject to change.
|
| 667 |
+
|
| 668 |
+
Enables or disables cuDNN scaled dot product attention.
|
| 669 |
+
"""
|
| 670 |
+
torch._C._set_sdp_use_cudnn(enabled)
|
| 671 |
+
|
| 672 |
+
|
| 673 |
+
@contextlib.contextmanager
|
| 674 |
+
@deprecated(
|
| 675 |
+
(
|
| 676 |
+
"`torch.backends.cuda.sdp_kernel()` is deprecated. "
|
| 677 |
+
"In the future, this context manager will be removed. "
|
| 678 |
+
"Please see `torch.nn.attention.sdpa_kernel()` for the new context manager, "
|
| 679 |
+
"with updated signature."
|
| 680 |
+
),
|
| 681 |
+
category=FutureWarning,
|
| 682 |
+
)
|
| 683 |
+
def sdp_kernel(
|
| 684 |
+
enable_flash: bool = True,
|
| 685 |
+
enable_math: bool = True,
|
| 686 |
+
enable_mem_efficient: bool = True,
|
| 687 |
+
enable_cudnn: bool = True,
|
| 688 |
+
):
|
| 689 |
+
r"""
|
| 690 |
+
.. warning:: This flag is beta and subject to change.
|
| 691 |
+
|
| 692 |
+
This context manager can be used to temporarily enable or disable any of the three backends for scaled dot product attention.
|
| 693 |
+
Upon exiting the context manager, the previous state of the flags will be restored.
|
| 694 |
+
"""
|
| 695 |
+
from torch.nn.attention import sdpa_kernel
|
| 696 |
+
|
| 697 |
+
backend_list = []
|
| 698 |
+
if enable_flash:
|
| 699 |
+
backend_list.append(SDPBackend.FLASH_ATTENTION)
|
| 700 |
+
if enable_mem_efficient:
|
| 701 |
+
backend_list.append(SDPBackend.EFFICIENT_ATTENTION)
|
| 702 |
+
if enable_math:
|
| 703 |
+
backend_list.append(SDPBackend.MATH)
|
| 704 |
+
if enable_cudnn:
|
| 705 |
+
backend_list.append(SDPBackend.CUDNN_ATTENTION)
|
| 706 |
+
|
| 707 |
+
with sdpa_kernel(backend_list) as context:
|
| 708 |
+
try:
|
| 709 |
+
yield context
|
| 710 |
+
finally:
|
| 711 |
+
pass
|
| 712 |
+
|
| 713 |
+
|
| 714 |
+
cufft_plan_cache = cuFFTPlanCacheManager()
|
| 715 |
+
matmul = cuBLASModule()
|
.venv/lib/python3.12/site-packages/torch/backends/cuda/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (33.6 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/cudnn/__init__.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 (
|
| 10 |
+
__allow_nonbracketed_mutation,
|
| 11 |
+
_FP32Precision,
|
| 12 |
+
_get_fp32_precision_getter,
|
| 13 |
+
_set_fp32_precision_setter,
|
| 14 |
+
ContextProp,
|
| 15 |
+
PropModule,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
from . import rnn
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
from torch._C import _cudnn
|
| 23 |
+
except ImportError:
|
| 24 |
+
_cudnn = None # type: ignore[assignment]
|
| 25 |
+
|
| 26 |
+
# Write:
|
| 27 |
+
#
|
| 28 |
+
# torch.backends.cudnn.enabled = False
|
| 29 |
+
#
|
| 30 |
+
# to globally disable CuDNN/MIOpen
|
| 31 |
+
|
| 32 |
+
__cudnn_version: int | None = None
|
| 33 |
+
|
| 34 |
+
if _cudnn is not None:
|
| 35 |
+
|
| 36 |
+
def _init():
|
| 37 |
+
global __cudnn_version
|
| 38 |
+
if __cudnn_version is None:
|
| 39 |
+
# pyrefly: ignore [missing-attribute]
|
| 40 |
+
__cudnn_version = _cudnn.getVersionInt()
|
| 41 |
+
# pyrefly: ignore [missing-attribute]
|
| 42 |
+
runtime_version = _cudnn.getRuntimeVersion()
|
| 43 |
+
# pyrefly: ignore [missing-attribute]
|
| 44 |
+
compile_version = _cudnn.getCompileVersion()
|
| 45 |
+
runtime_major, runtime_minor, _ = runtime_version
|
| 46 |
+
compile_major, compile_minor, _ = compile_version
|
| 47 |
+
# Different major versions are always incompatible
|
| 48 |
+
# Starting with cuDNN 7, minor versions are backwards-compatible
|
| 49 |
+
# Not sure about MIOpen (ROCm), so always do a strict check
|
| 50 |
+
if runtime_major != compile_major:
|
| 51 |
+
cudnn_compatible = False
|
| 52 |
+
# pyrefly: ignore [missing-attribute]
|
| 53 |
+
elif runtime_major < 7 or not _cudnn.is_cuda:
|
| 54 |
+
cudnn_compatible = runtime_minor == compile_minor
|
| 55 |
+
else:
|
| 56 |
+
cudnn_compatible = runtime_minor >= compile_minor
|
| 57 |
+
if not cudnn_compatible:
|
| 58 |
+
if os.environ.get("PYTORCH_SKIP_CUDNN_COMPATIBILITY_CHECK", "0") == "1":
|
| 59 |
+
return True
|
| 60 |
+
base_error_msg = (
|
| 61 |
+
f"cuDNN version incompatibility: "
|
| 62 |
+
f"PyTorch was compiled against {compile_version} "
|
| 63 |
+
f"but found runtime version {runtime_version}. "
|
| 64 |
+
f"PyTorch already comes bundled with cuDNN. "
|
| 65 |
+
f"One option to resolving this error is to ensure PyTorch "
|
| 66 |
+
f"can find the bundled cuDNN. "
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
if "LD_LIBRARY_PATH" in os.environ:
|
| 70 |
+
ld_library_path = os.environ.get("LD_LIBRARY_PATH", "")
|
| 71 |
+
if any(
|
| 72 |
+
substring in ld_library_path for substring in ["cuda", "cudnn"]
|
| 73 |
+
):
|
| 74 |
+
raise RuntimeError(
|
| 75 |
+
f"{base_error_msg}"
|
| 76 |
+
f"Looks like your LD_LIBRARY_PATH contains incompatible version of cudnn. "
|
| 77 |
+
f"Please either remove it from the path or install cudnn {compile_version}"
|
| 78 |
+
)
|
| 79 |
+
else:
|
| 80 |
+
raise RuntimeError(
|
| 81 |
+
f"{base_error_msg}"
|
| 82 |
+
f"one possibility is that there is a "
|
| 83 |
+
f"conflicting cuDNN in LD_LIBRARY_PATH."
|
| 84 |
+
)
|
| 85 |
+
else:
|
| 86 |
+
raise RuntimeError(base_error_msg)
|
| 87 |
+
# Check if cuDNN version is compatible with available CUDA devices
|
| 88 |
+
if torch.cuda.is_available() and not torch.version.hip:
|
| 89 |
+
min_cc = min(
|
| 90 |
+
[
|
| 91 |
+
torch.cuda.get_device_capability(i)
|
| 92 |
+
for i in range(torch.cuda.device_count())
|
| 93 |
+
]
|
| 94 |
+
)
|
| 95 |
+
if __cudnn_version >= 91100 and min_cc < (7, 5):
|
| 96 |
+
raise RuntimeError(
|
| 97 |
+
f"cuDNN version {__cudnn_version} is not compatible with devices with SM < 7.5. "
|
| 98 |
+
f"Please install a version of PyTorch with a compatible cuDNN version. "
|
| 99 |
+
f"https://github.com/pytorch/pytorch/blob/main/RELEASE.md#release-compatibility-matrix"
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
return True
|
| 103 |
+
|
| 104 |
+
else:
|
| 105 |
+
|
| 106 |
+
def _init():
|
| 107 |
+
return False
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def version():
|
| 111 |
+
"""Return the version of cuDNN."""
|
| 112 |
+
if not _init():
|
| 113 |
+
return None
|
| 114 |
+
return __cudnn_version
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
CUDNN_TENSOR_DTYPES = {
|
| 118 |
+
torch.half,
|
| 119 |
+
torch.float,
|
| 120 |
+
torch.double,
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def is_available():
|
| 125 |
+
r"""Return a bool indicating if CUDNN is currently available."""
|
| 126 |
+
return torch._C._has_cudnn
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def is_acceptable(tensor):
|
| 130 |
+
if not torch._C._get_cudnn_enabled():
|
| 131 |
+
return False
|
| 132 |
+
if tensor.device.type != "cuda" or tensor.dtype not in CUDNN_TENSOR_DTYPES:
|
| 133 |
+
return False
|
| 134 |
+
if not is_available():
|
| 135 |
+
warnings.warn(
|
| 136 |
+
"PyTorch was compiled without cuDNN/MIOpen support. To use cuDNN/MIOpen, rebuild "
|
| 137 |
+
"PyTorch making sure the library is visible to the build system.",
|
| 138 |
+
stacklevel=2,
|
| 139 |
+
)
|
| 140 |
+
return False
|
| 141 |
+
if not _init():
|
| 142 |
+
warnings.warn(
|
| 143 |
+
"cuDNN/MIOpen library not found. Check your {libpath}".format(
|
| 144 |
+
libpath={"darwin": "DYLD_LIBRARY_PATH", "win32": "PATH"}.get(
|
| 145 |
+
sys.platform, "LD_LIBRARY_PATH"
|
| 146 |
+
)
|
| 147 |
+
),
|
| 148 |
+
stacklevel=2,
|
| 149 |
+
)
|
| 150 |
+
return False
|
| 151 |
+
return True
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def set_flags(
|
| 155 |
+
_enabled=None,
|
| 156 |
+
_benchmark=None,
|
| 157 |
+
_benchmark_limit=None,
|
| 158 |
+
_deterministic=None,
|
| 159 |
+
_allow_tf32=None,
|
| 160 |
+
_fp32_precision="none",
|
| 161 |
+
_depthwise_kernel=None,
|
| 162 |
+
):
|
| 163 |
+
orig_flags = (
|
| 164 |
+
torch._C._get_cudnn_enabled(),
|
| 165 |
+
torch._C._get_cudnn_benchmark(),
|
| 166 |
+
None if not is_available() else torch._C._cuda_get_cudnn_benchmark_limit(),
|
| 167 |
+
torch._C._get_cudnn_deterministic(),
|
| 168 |
+
torch._C._get_cudnn_allow_tf32(),
|
| 169 |
+
torch._C._get_fp32_precision_getter("cuda", "all"),
|
| 170 |
+
torch._C._get_cudnn_depthwise_kernel(),
|
| 171 |
+
)
|
| 172 |
+
if _enabled is not None:
|
| 173 |
+
torch._C._set_cudnn_enabled(_enabled)
|
| 174 |
+
if _benchmark is not None:
|
| 175 |
+
torch._C._set_cudnn_benchmark(_benchmark)
|
| 176 |
+
if _benchmark_limit is not None and is_available():
|
| 177 |
+
torch._C._cuda_set_cudnn_benchmark_limit(_benchmark_limit)
|
| 178 |
+
if _deterministic is not None:
|
| 179 |
+
torch._C._set_cudnn_deterministic(_deterministic)
|
| 180 |
+
if _allow_tf32 is not None:
|
| 181 |
+
torch._C._set_cudnn_allow_tf32(_allow_tf32)
|
| 182 |
+
if _fp32_precision is not None:
|
| 183 |
+
torch._C._set_fp32_precision_setter("cuda", "all", _fp32_precision)
|
| 184 |
+
if _depthwise_kernel is not None:
|
| 185 |
+
torch._C._set_cudnn_depthwise_kernel(_depthwise_kernel)
|
| 186 |
+
return orig_flags
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@contextmanager
|
| 190 |
+
def flags(
|
| 191 |
+
enabled=False,
|
| 192 |
+
benchmark=False,
|
| 193 |
+
benchmark_limit=10,
|
| 194 |
+
deterministic=False,
|
| 195 |
+
allow_tf32=True,
|
| 196 |
+
fp32_precision="none",
|
| 197 |
+
depthwise_kernel="auto",
|
| 198 |
+
):
|
| 199 |
+
with __allow_nonbracketed_mutation():
|
| 200 |
+
orig_flags = set_flags(
|
| 201 |
+
enabled,
|
| 202 |
+
benchmark,
|
| 203 |
+
benchmark_limit,
|
| 204 |
+
deterministic,
|
| 205 |
+
allow_tf32,
|
| 206 |
+
fp32_precision,
|
| 207 |
+
depthwise_kernel,
|
| 208 |
+
)
|
| 209 |
+
try:
|
| 210 |
+
yield
|
| 211 |
+
finally:
|
| 212 |
+
# recover the previous values
|
| 213 |
+
with __allow_nonbracketed_mutation():
|
| 214 |
+
set_flags(*orig_flags)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
# The magic here is to allow us to intercept code like this:
|
| 218 |
+
#
|
| 219 |
+
# torch.backends.<cudnn|mkldnn>.enabled = True
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class CudnnModule(PropModule):
|
| 223 |
+
enabled = ContextProp(torch._C._get_cudnn_enabled, torch._C._set_cudnn_enabled)
|
| 224 |
+
deterministic = ContextProp(
|
| 225 |
+
torch._C._get_cudnn_deterministic, torch._C._set_cudnn_deterministic
|
| 226 |
+
)
|
| 227 |
+
benchmark = ContextProp(
|
| 228 |
+
torch._C._get_cudnn_benchmark, torch._C._set_cudnn_benchmark
|
| 229 |
+
)
|
| 230 |
+
benchmark_limit = None
|
| 231 |
+
if is_available():
|
| 232 |
+
benchmark_limit = ContextProp(
|
| 233 |
+
torch._C._cuda_get_cudnn_benchmark_limit,
|
| 234 |
+
torch._C._cuda_set_cudnn_benchmark_limit,
|
| 235 |
+
)
|
| 236 |
+
allow_tf32 = ContextProp(
|
| 237 |
+
torch._C._get_cudnn_allow_tf32, torch._C._set_cudnn_allow_tf32
|
| 238 |
+
)
|
| 239 |
+
conv = _FP32Precision("cuda", "conv")
|
| 240 |
+
fp32_precision = ContextProp(
|
| 241 |
+
_get_fp32_precision_getter("cuda", "all"),
|
| 242 |
+
_set_fp32_precision_setter("cuda", "all"),
|
| 243 |
+
)
|
| 244 |
+
depthwise_kernel = ContextProp(
|
| 245 |
+
torch._C._get_cudnn_depthwise_kernel,
|
| 246 |
+
torch._C._set_cudnn_depthwise_kernel,
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# This is the sys.modules replacement trick, see
|
| 251 |
+
# https://stackoverflow.com/questions/2447353/getattr-on-a-module/7668273#7668273
|
| 252 |
+
sys.modules[__name__] = CudnnModule(sys.modules[__name__], __name__)
|
| 253 |
+
|
| 254 |
+
# Add type annotation for the replaced module
|
| 255 |
+
enabled: bool
|
| 256 |
+
deterministic: bool
|
| 257 |
+
benchmark: bool
|
| 258 |
+
allow_tf32: bool
|
| 259 |
+
fp32_precision: str
|
| 260 |
+
benchmark_limit: int
|
| 261 |
+
depthwise_kernel: str
|
.venv/lib/python3.12/site-packages/torch/backends/cudnn/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (9.56 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/cudnn/__pycache__/rnn.cpython-312.pyc
ADDED
|
Binary file (5.07 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/cudnn/rnn.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
import torch._C
|
| 5 |
+
import torch.cuda
|
| 6 |
+
from torch.backends import (
|
| 7 |
+
_get_fp32_precision_getter,
|
| 8 |
+
_set_fp32_precision_setter,
|
| 9 |
+
PropModule,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
from torch._C import _cudnn
|
| 15 |
+
except ImportError:
|
| 16 |
+
# Uses of all the functions below should be guarded by torch.backends.cudnn.is_available(),
|
| 17 |
+
# so it's safe to not emit any checks here.
|
| 18 |
+
_cudnn = None # type: ignore[assignment]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def get_cudnn_mode(mode):
|
| 22 |
+
if mode == "RNN_RELU":
|
| 23 |
+
# pyrefly: ignore [missing-attribute]
|
| 24 |
+
return int(_cudnn.RNNMode.rnn_relu)
|
| 25 |
+
elif mode == "RNN_TANH":
|
| 26 |
+
# pyrefly: ignore [missing-attribute]
|
| 27 |
+
return int(_cudnn.RNNMode.rnn_tanh)
|
| 28 |
+
elif mode == "LSTM":
|
| 29 |
+
# pyrefly: ignore [missing-attribute]
|
| 30 |
+
return int(_cudnn.RNNMode.lstm)
|
| 31 |
+
elif mode == "GRU":
|
| 32 |
+
# pyrefly: ignore [missing-attribute]
|
| 33 |
+
return int(_cudnn.RNNMode.gru)
|
| 34 |
+
else:
|
| 35 |
+
raise ValueError(f"Unknown mode: {mode}")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# NB: We don't actually need this class anymore (in fact, we could serialize the
|
| 39 |
+
# dropout state for even better reproducibility), but it is kept for backwards
|
| 40 |
+
# compatibility for old models.
|
| 41 |
+
class Unserializable:
|
| 42 |
+
def __init__(self, inner):
|
| 43 |
+
self.inner = inner
|
| 44 |
+
|
| 45 |
+
def get(self):
|
| 46 |
+
return self.inner
|
| 47 |
+
|
| 48 |
+
def __getstate__(self):
|
| 49 |
+
return "<unserializable>"
|
| 50 |
+
|
| 51 |
+
def __setstate__(self, state):
|
| 52 |
+
self.inner = None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# we would like to use ContextProp from backends here but the
|
| 56 |
+
# frozen flags appears to be overzealous
|
| 57 |
+
class ContextProp:
|
| 58 |
+
def __init__(self, getter, setter):
|
| 59 |
+
self.getter = getter
|
| 60 |
+
self.setter = setter
|
| 61 |
+
|
| 62 |
+
def __get__(self, obj, objtype):
|
| 63 |
+
return self.getter()
|
| 64 |
+
|
| 65 |
+
def __set__(self, obj, val):
|
| 66 |
+
self.setter(val)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def init_dropout_state(dropout, train, dropout_seed, dropout_state):
|
| 70 |
+
dropout_desc_name = "desc_" + str(torch.cuda.current_device())
|
| 71 |
+
dropout_p = dropout if train else 0
|
| 72 |
+
if (dropout_desc_name not in dropout_state) or (
|
| 73 |
+
dropout_state[dropout_desc_name].get() is None
|
| 74 |
+
):
|
| 75 |
+
if dropout_p == 0:
|
| 76 |
+
dropout_state[dropout_desc_name] = Unserializable(None)
|
| 77 |
+
else:
|
| 78 |
+
dropout_state[dropout_desc_name] = Unserializable(
|
| 79 |
+
torch._cudnn_init_dropout_state( # type: ignore[call-arg]
|
| 80 |
+
dropout_p,
|
| 81 |
+
train,
|
| 82 |
+
dropout_seed,
|
| 83 |
+
# pyrefly: ignore [unexpected-keyword]
|
| 84 |
+
self_ty=torch.uint8,
|
| 85 |
+
device=torch.device("cuda"),
|
| 86 |
+
)
|
| 87 |
+
)
|
| 88 |
+
dropout_ts = dropout_state[dropout_desc_name].get()
|
| 89 |
+
return dropout_ts
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class CudnnRNNModule(PropModule):
|
| 93 |
+
def __init__(self, m, name):
|
| 94 |
+
super().__init__(m, name)
|
| 95 |
+
self.m.Unserializable = Unserializable
|
| 96 |
+
self.m.get_cudnn_mode = get_cudnn_mode
|
| 97 |
+
self.m.init_dropout_state = init_dropout_state
|
| 98 |
+
|
| 99 |
+
@staticmethod
|
| 100 |
+
def init_dropout_state(dropout, train, dropout_seed, dropout_state):
|
| 101 |
+
dropout_desc_name = "desc_" + str(torch.cuda.current_device())
|
| 102 |
+
dropout_p = dropout if train else 0
|
| 103 |
+
if (dropout_desc_name not in dropout_state) or (
|
| 104 |
+
dropout_state[dropout_desc_name].get() is None
|
| 105 |
+
):
|
| 106 |
+
if dropout_p == 0:
|
| 107 |
+
dropout_state[dropout_desc_name] = Unserializable(None)
|
| 108 |
+
else:
|
| 109 |
+
dropout_state[dropout_desc_name] = Unserializable(
|
| 110 |
+
torch._cudnn_init_dropout_state( # type: ignore[call-arg]
|
| 111 |
+
dropout_p,
|
| 112 |
+
train,
|
| 113 |
+
dropout_seed,
|
| 114 |
+
# pyrefly: ignore [unexpected-keyword]
|
| 115 |
+
self_ty=torch.uint8,
|
| 116 |
+
device=torch.device("cuda"),
|
| 117 |
+
)
|
| 118 |
+
)
|
| 119 |
+
dropout_ts = dropout_state[dropout_desc_name].get()
|
| 120 |
+
return dropout_ts
|
| 121 |
+
|
| 122 |
+
fp32_precision = ContextProp(
|
| 123 |
+
_get_fp32_precision_getter("cuda", "rnn"),
|
| 124 |
+
_set_fp32_precision_setter("cuda", "rnn"),
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
sys.modules[__name__] = CudnnRNNModule(sys.modules[__name__], __name__)
|
.venv/lib/python3.12/site-packages/torch/backends/cusparselt/__init__.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Optional
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
"version",
|
| 8 |
+
"is_available",
|
| 9 |
+
"get_max_alg_id",
|
| 10 |
+
]
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from torch._C import _cusparselt
|
| 14 |
+
except ImportError:
|
| 15 |
+
_cusparselt = None # type: ignore[assignment]
|
| 16 |
+
|
| 17 |
+
__cusparselt_version: int | None = None
|
| 18 |
+
__MAX_ALG_ID: int | None = None
|
| 19 |
+
|
| 20 |
+
if _cusparselt is not None:
|
| 21 |
+
|
| 22 |
+
def _init() -> bool:
|
| 23 |
+
global __cusparselt_version
|
| 24 |
+
global __MAX_ALG_ID
|
| 25 |
+
if __cusparselt_version is None:
|
| 26 |
+
# pyrefly: ignore [missing-attribute]
|
| 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() -> bool:
|
| 39 |
+
return False
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def version() -> int | None:
|
| 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() -> int | None:
|
| 55 |
+
if not _init():
|
| 56 |
+
return None
|
| 57 |
+
return __MAX_ALG_ID
|
.venv/lib/python3.12/site-packages/torch/backends/cusparselt/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.74 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/kleidiai/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def is_available():
|
| 6 |
+
r"""Return whether PyTorch is built with KleidiAI support."""
|
| 7 |
+
return torch._C._has_kleidiai
|
.venv/lib/python3.12/site-packages/torch/backends/kleidiai/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (464 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/mha/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Config options to enable/disable C++ kernel for nn.functional.MHA
|
| 2 |
+
# and nn.TransformerEncoder
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
_is_fastpath_enabled: bool = True
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def get_fastpath_enabled() -> bool:
|
| 10 |
+
"""Returns whether fast path for TransformerEncoder and MultiHeadAttention
|
| 11 |
+
is enabled, or ``True`` if jit is scripting.
|
| 12 |
+
|
| 13 |
+
.. note::
|
| 14 |
+
The fastpath might not be run even if ``get_fastpath_enabled`` returns
|
| 15 |
+
``True`` unless all conditions on inputs are met.
|
| 16 |
+
"""
|
| 17 |
+
if not torch.jit.is_scripting():
|
| 18 |
+
return _is_fastpath_enabled
|
| 19 |
+
return True
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def set_fastpath_enabled(value: bool) -> None:
|
| 23 |
+
"""Sets whether fast path is enabled"""
|
| 24 |
+
global _is_fastpath_enabled
|
| 25 |
+
_is_fastpath_enabled = value
|
.venv/lib/python3.12/site-packages/torch/backends/mha/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.03 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/miopen/__init__.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import sys
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
from torch.backends import __allow_nonbracketed_mutation, ContextProp, PropModule
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def set_flags(
|
| 10 |
+
_immediate=None,
|
| 11 |
+
):
|
| 12 |
+
orig_flags = (torch._C._get_miopen_immediate(),)
|
| 13 |
+
if _immediate is not None:
|
| 14 |
+
torch._C._set_miopen_immediate(_immediate)
|
| 15 |
+
return orig_flags
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@contextmanager
|
| 19 |
+
def flags(
|
| 20 |
+
immediate=False,
|
| 21 |
+
):
|
| 22 |
+
with __allow_nonbracketed_mutation():
|
| 23 |
+
orig_flags = set_flags(
|
| 24 |
+
immediate,
|
| 25 |
+
)
|
| 26 |
+
try:
|
| 27 |
+
yield
|
| 28 |
+
finally:
|
| 29 |
+
# recover the previous values
|
| 30 |
+
with __allow_nonbracketed_mutation():
|
| 31 |
+
set_flags(*orig_flags)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
# The magic here is to allow us to intercept code like this:
|
| 35 |
+
#
|
| 36 |
+
# torch.backends.<miopen|mkldnn>.immediate = True
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class MiopenModule(PropModule):
|
| 40 |
+
immediate = ContextProp(
|
| 41 |
+
torch._C._get_miopen_immediate, torch._C._set_miopen_immediate
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# This is the sys.modules replacement trick, see
|
| 46 |
+
# https://stackoverflow.com/questions/2447353/getattr-on-a-module/7668273#7668273
|
| 47 |
+
sys.modules[__name__] = MiopenModule(sys.modules[__name__], __name__)
|
| 48 |
+
|
| 49 |
+
# Add type annotation for the replaced module
|
| 50 |
+
immediate: bool
|
.venv/lib/python3.12/site-packages/torch/backends/miopen/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.92 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/mkl/__init__.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def is_available():
|
| 6 |
+
r"""Return whether PyTorch is built with MKL support."""
|
| 7 |
+
return torch._C.has_mkl
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
VERBOSE_OFF = 0
|
| 11 |
+
VERBOSE_ON = 1
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class verbose:
|
| 15 |
+
"""
|
| 16 |
+
On-demand oneMKL verbosing functionality.
|
| 17 |
+
|
| 18 |
+
To make it easier to debug performance issues, oneMKL can dump verbose
|
| 19 |
+
messages containing execution information like duration while executing
|
| 20 |
+
the kernel. The verbosing functionality can be invoked via an environment
|
| 21 |
+
variable named `MKL_VERBOSE`. However, this methodology dumps messages in
|
| 22 |
+
all steps. Those are a large amount of verbose messages. Moreover, for
|
| 23 |
+
investigating the performance issues, generally taking verbose messages
|
| 24 |
+
for one single iteration is enough. This on-demand verbosing functionality
|
| 25 |
+
makes it possible to control scope for verbose message dumping. In the
|
| 26 |
+
following example, verbose messages will be dumped out for the second
|
| 27 |
+
inference only.
|
| 28 |
+
|
| 29 |
+
.. highlight:: python
|
| 30 |
+
.. code-block:: python
|
| 31 |
+
|
| 32 |
+
import torch
|
| 33 |
+
|
| 34 |
+
model(data)
|
| 35 |
+
with torch.backends.mkl.verbose(torch.backends.mkl.VERBOSE_ON):
|
| 36 |
+
model(data)
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
level: Verbose level
|
| 40 |
+
- ``VERBOSE_OFF``: Disable verbosing
|
| 41 |
+
- ``VERBOSE_ON``: Enable verbosing
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, enable):
|
| 45 |
+
self.enable = enable
|
| 46 |
+
|
| 47 |
+
def __enter__(self):
|
| 48 |
+
if self.enable == VERBOSE_OFF:
|
| 49 |
+
return
|
| 50 |
+
st = torch._C._verbose.mkl_set_verbose(self.enable)
|
| 51 |
+
if not st:
|
| 52 |
+
raise AssertionError(
|
| 53 |
+
"Failed to set MKL into verbose mode. Please consider to disable this verbose scope."
|
| 54 |
+
)
|
| 55 |
+
return self
|
| 56 |
+
|
| 57 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 58 |
+
torch._C._verbose.mkl_set_verbose(VERBOSE_OFF)
|
| 59 |
+
return False
|
.venv/lib/python3.12/site-packages/torch/backends/mkl/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (2.72 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/mkldnn/__init__.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import sys
|
| 3 |
+
from contextlib import contextmanager
|
| 4 |
+
from typing import TYPE_CHECKING
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
from torch.backends import (
|
| 8 |
+
__allow_nonbracketed_mutation,
|
| 9 |
+
_FP32Precision,
|
| 10 |
+
_get_fp32_precision_getter,
|
| 11 |
+
_set_fp32_precision_setter,
|
| 12 |
+
ContextProp,
|
| 13 |
+
PropModule,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def is_available():
|
| 18 |
+
r"""Return whether PyTorch is built with MKL-DNN support."""
|
| 19 |
+
return torch._C._has_mkldnn
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def is_acl_available():
|
| 23 |
+
r"""Return whether PyTorch is built with MKL-DNN + ACL support."""
|
| 24 |
+
# pyrefly: ignore [missing-attribute]
|
| 25 |
+
return torch._C._has_mkldnn_acl
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
VERBOSE_OFF = 0
|
| 29 |
+
VERBOSE_ON = 1
|
| 30 |
+
VERBOSE_ON_CREATION = 2
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class verbose:
|
| 34 |
+
"""
|
| 35 |
+
On-demand oneDNN (former MKL-DNN) verbosing functionality.
|
| 36 |
+
|
| 37 |
+
To make it easier to debug performance issues, oneDNN can dump verbose
|
| 38 |
+
messages containing information like kernel size, input data size and
|
| 39 |
+
execution duration while executing the kernel. The verbosing functionality
|
| 40 |
+
can be invoked via an environment variable named `DNNL_VERBOSE`. However,
|
| 41 |
+
this methodology dumps messages in all steps. Those are a large amount of
|
| 42 |
+
verbose messages. Moreover, for investigating the performance issues,
|
| 43 |
+
generally taking verbose messages for one single iteration is enough.
|
| 44 |
+
This on-demand verbosing functionality makes it possible to control scope
|
| 45 |
+
for verbose message dumping. In the following example, verbose messages
|
| 46 |
+
will be dumped out for the second inference only.
|
| 47 |
+
|
| 48 |
+
.. highlight:: python
|
| 49 |
+
.. code-block:: python
|
| 50 |
+
|
| 51 |
+
import torch
|
| 52 |
+
|
| 53 |
+
model(data)
|
| 54 |
+
with torch.backends.mkldnn.verbose(torch.backends.mkldnn.VERBOSE_ON):
|
| 55 |
+
model(data)
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
level: Verbose level
|
| 59 |
+
- ``VERBOSE_OFF``: Disable verbosing
|
| 60 |
+
- ``VERBOSE_ON``: Enable verbosing
|
| 61 |
+
- ``VERBOSE_ON_CREATION``: Enable verbosing, including oneDNN kernel creation
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
def __init__(self, level):
|
| 65 |
+
self.level = level
|
| 66 |
+
|
| 67 |
+
def __enter__(self):
|
| 68 |
+
if self.level == VERBOSE_OFF:
|
| 69 |
+
return
|
| 70 |
+
st = torch._C._verbose.mkldnn_set_verbose(self.level)
|
| 71 |
+
if not st:
|
| 72 |
+
raise AssertionError(
|
| 73 |
+
"Failed to set MKLDNN into verbose mode. Please consider to disable this verbose scope."
|
| 74 |
+
)
|
| 75 |
+
return self
|
| 76 |
+
|
| 77 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 78 |
+
torch._C._verbose.mkldnn_set_verbose(VERBOSE_OFF)
|
| 79 |
+
return False
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def set_flags(
|
| 83 |
+
_enabled=None, _deterministic=None, _allow_tf32=None, _fp32_precision="none"
|
| 84 |
+
):
|
| 85 |
+
orig_flags = (
|
| 86 |
+
torch._C._get_mkldnn_enabled(),
|
| 87 |
+
torch._C._get_mkldnn_deterministic(),
|
| 88 |
+
torch._C._get_onednn_allow_tf32(),
|
| 89 |
+
torch._C._get_fp32_precision_getter("mkldnn", "all"),
|
| 90 |
+
)
|
| 91 |
+
if _enabled is not None:
|
| 92 |
+
torch._C._set_mkldnn_enabled(_enabled)
|
| 93 |
+
if _deterministic is not None:
|
| 94 |
+
torch._C._set_mkldnn_deterministic(_deterministic)
|
| 95 |
+
if _allow_tf32 is not None:
|
| 96 |
+
torch._C._set_onednn_allow_tf32(_allow_tf32)
|
| 97 |
+
if _fp32_precision is not None:
|
| 98 |
+
torch._C._set_fp32_precision_setter("mkldnn", "all", _fp32_precision)
|
| 99 |
+
return orig_flags
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@contextmanager
|
| 103 |
+
def flags(enabled=False, deterministic=False, allow_tf32=True, fp32_precision="none"):
|
| 104 |
+
with __allow_nonbracketed_mutation():
|
| 105 |
+
orig_flags = set_flags(enabled, deterministic, allow_tf32, fp32_precision)
|
| 106 |
+
try:
|
| 107 |
+
yield
|
| 108 |
+
finally:
|
| 109 |
+
with __allow_nonbracketed_mutation():
|
| 110 |
+
set_flags(*orig_flags)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class MkldnnModule(PropModule):
|
| 114 |
+
def is_available(self):
|
| 115 |
+
return is_available()
|
| 116 |
+
|
| 117 |
+
enabled = ContextProp(torch._C._get_mkldnn_enabled, torch._C._set_mkldnn_enabled)
|
| 118 |
+
deterministic = ContextProp(
|
| 119 |
+
torch._C._get_mkldnn_deterministic, torch._C._set_mkldnn_deterministic
|
| 120 |
+
)
|
| 121 |
+
allow_tf32 = ContextProp(
|
| 122 |
+
torch._C._get_onednn_allow_tf32, torch._C._set_onednn_allow_tf32
|
| 123 |
+
)
|
| 124 |
+
matmul = _FP32Precision("mkldnn", "matmul")
|
| 125 |
+
conv = _FP32Precision("mkldnn", "conv")
|
| 126 |
+
rnn = _FP32Precision("mkldnn", "rnn")
|
| 127 |
+
fp32_precision = ContextProp(
|
| 128 |
+
_get_fp32_precision_getter("mkldnn", "all"),
|
| 129 |
+
_set_fp32_precision_setter("generic", "all"),
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
if TYPE_CHECKING:
|
| 134 |
+
enabled: ContextProp
|
| 135 |
+
deterministic: ContextProp
|
| 136 |
+
allow_tf32: ContextProp
|
| 137 |
+
fp32_precision: str
|
| 138 |
+
|
| 139 |
+
sys.modules[__name__] = MkldnnModule(sys.modules[__name__], __name__)
|
.venv/lib/python3.12/site-packages/torch/backends/mkldnn/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (6.52 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/mps/__init__.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import lru_cache as _lru_cache
|
| 2 |
+
from typing import Optional, TYPE_CHECKING
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch.library import Library as _Library
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"get_core_count",
|
| 10 |
+
"get_name",
|
| 11 |
+
"is_built",
|
| 12 |
+
"is_available",
|
| 13 |
+
"is_macos13_or_newer",
|
| 14 |
+
"is_macos_or_newer",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def is_built() -> bool:
|
| 19 |
+
r"""Return whether PyTorch is built with MPS support.
|
| 20 |
+
|
| 21 |
+
Note that this doesn't necessarily mean MPS is available; just that
|
| 22 |
+
if this PyTorch binary were run on a machine with working MPS drivers
|
| 23 |
+
and devices, we would be able to use it.
|
| 24 |
+
"""
|
| 25 |
+
return torch._C._has_mps
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@_lru_cache
|
| 29 |
+
def is_available() -> bool:
|
| 30 |
+
r"""Return a bool indicating if MPS is currently available."""
|
| 31 |
+
return torch._C._mps_is_available()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@_lru_cache
|
| 35 |
+
def is_macos_or_newer(major: int, minor: int) -> bool:
|
| 36 |
+
r"""Return a bool indicating whether MPS is running on given MacOS or newer."""
|
| 37 |
+
return torch._C._mps_is_on_macos_or_newer(major, minor)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
@_lru_cache
|
| 41 |
+
def is_macos13_or_newer(minor: int = 0) -> bool:
|
| 42 |
+
r"""Return a bool indicating whether MPS is running on MacOS 13 or newer."""
|
| 43 |
+
return torch._C._mps_is_on_macos_or_newer(13, minor)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@_lru_cache
|
| 47 |
+
def get_name() -> str:
|
| 48 |
+
r"""Return Metal device name"""
|
| 49 |
+
return torch._C._mps_get_name()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@_lru_cache
|
| 53 |
+
def get_core_count() -> int:
|
| 54 |
+
r"""Return GPU core count.
|
| 55 |
+
|
| 56 |
+
According to the documentation, one core is comprised of 16 Execution Units.
|
| 57 |
+
One execution Unit has 8 ALUs.
|
| 58 |
+
And one ALU can run 24 threads, i.e. one core is capable of executing 3072 threads concurrently.
|
| 59 |
+
"""
|
| 60 |
+
return torch._C._mps_get_core_count()
|
.venv/lib/python3.12/site-packages/torch/backends/mps/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (2.7 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/nnpack/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
from contextlib import contextmanager
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
from torch.backends import __allow_nonbracketed_mutation, ContextProp, PropModule
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
__all__ = ["is_available", "flags", "set_flags"]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def is_available():
|
| 12 |
+
r"""Return whether PyTorch is built with NNPACK support."""
|
| 13 |
+
return torch._nnpack_available()
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def set_flags(_enabled):
|
| 17 |
+
r"""Set if nnpack is enabled globally"""
|
| 18 |
+
orig_flags = (torch._C._get_nnpack_enabled(),)
|
| 19 |
+
torch._C._set_nnpack_enabled(_enabled)
|
| 20 |
+
return orig_flags
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@contextmanager
|
| 24 |
+
def flags(enabled=False):
|
| 25 |
+
r"""Context manager for setting if nnpack is enabled globally"""
|
| 26 |
+
with __allow_nonbracketed_mutation():
|
| 27 |
+
orig_flags = set_flags(enabled)
|
| 28 |
+
try:
|
| 29 |
+
yield
|
| 30 |
+
finally:
|
| 31 |
+
with __allow_nonbracketed_mutation():
|
| 32 |
+
set_flags(orig_flags[0])
|
.venv/lib/python3.12/site-packages/torch/backends/nnpack/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.76 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/openmp/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import torch
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def is_available():
|
| 6 |
+
r"""Return whether PyTorch is built with OpenMP support."""
|
| 7 |
+
return torch._C.has_openmp
|
.venv/lib/python3.12/site-packages/torch/backends/openmp/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (457 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/opt_einsum/__init__.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import sys
|
| 3 |
+
import warnings
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from functools import lru_cache as _lru_cache
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from torch.backends import __allow_nonbracketed_mutation, ContextProp, PropModule
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
import opt_einsum as _opt_einsum # type: ignore[import]
|
| 13 |
+
except ImportError:
|
| 14 |
+
_opt_einsum = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@_lru_cache
|
| 18 |
+
def is_available() -> bool:
|
| 19 |
+
r"""Return a bool indicating if opt_einsum is currently available.
|
| 20 |
+
|
| 21 |
+
You must install opt-einsum in order for torch to automatically optimize einsum. To
|
| 22 |
+
make opt-einsum available, you can install it along with torch: ``pip install torch[opt-einsum]``
|
| 23 |
+
or by itself: ``pip install opt-einsum``. If the package is installed, torch will import
|
| 24 |
+
it automatically and use it accordingly. Use this function to check whether opt-einsum
|
| 25 |
+
was installed and properly imported by torch.
|
| 26 |
+
"""
|
| 27 |
+
return _opt_einsum is not None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def get_opt_einsum() -> Any:
|
| 31 |
+
r"""Return the opt_einsum package if opt_einsum is currently available, else None."""
|
| 32 |
+
return _opt_einsum
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _set_enabled(_enabled: bool) -> None:
|
| 36 |
+
if not is_available() and _enabled:
|
| 37 |
+
raise ValueError(
|
| 38 |
+
f"opt_einsum is not available, so setting `enabled` to {_enabled} will not reap "
|
| 39 |
+
"the benefits of calculating an optimal path for einsum. torch.einsum will "
|
| 40 |
+
"fall back to contracting from left to right. To enable this optimal path "
|
| 41 |
+
"calculation, please install opt-einsum."
|
| 42 |
+
)
|
| 43 |
+
global enabled
|
| 44 |
+
enabled = _enabled
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _get_enabled() -> bool:
|
| 48 |
+
return enabled
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _set_strategy(_strategy: str) -> None:
|
| 52 |
+
if not is_available():
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"opt_einsum is not available, so setting `strategy` to {_strategy} will not be meaningful. "
|
| 55 |
+
"torch.einsum will bypass path calculation and simply contract from left to right. "
|
| 56 |
+
"Please install opt_einsum or unset `strategy`."
|
| 57 |
+
)
|
| 58 |
+
if not enabled:
|
| 59 |
+
raise ValueError(
|
| 60 |
+
f"opt_einsum is not enabled, so setting a `strategy` to {_strategy} will not be meaningful. "
|
| 61 |
+
"torch.einsum will bypass path calculation and simply contract from left to right. "
|
| 62 |
+
"Please set `enabled` to `True` as well or unset `strategy`."
|
| 63 |
+
)
|
| 64 |
+
if _strategy not in ["auto", "greedy", "optimal"]:
|
| 65 |
+
raise ValueError(
|
| 66 |
+
f"`strategy` must be one of the following: [auto, greedy, optimal] but is {_strategy}"
|
| 67 |
+
)
|
| 68 |
+
global strategy
|
| 69 |
+
strategy = _strategy
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _get_strategy() -> str:
|
| 73 |
+
# pyrefly: ignore [bad-return]
|
| 74 |
+
return strategy
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def set_flags(_enabled=None, _strategy=None):
|
| 78 |
+
orig_flags = (enabled, None if not is_available() else strategy)
|
| 79 |
+
if _enabled is not None:
|
| 80 |
+
_set_enabled(_enabled)
|
| 81 |
+
if _strategy is not None:
|
| 82 |
+
_set_strategy(_strategy)
|
| 83 |
+
return orig_flags
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@contextmanager
|
| 87 |
+
def flags(enabled=None, strategy=None):
|
| 88 |
+
with __allow_nonbracketed_mutation():
|
| 89 |
+
orig_flags = set_flags(enabled, strategy)
|
| 90 |
+
try:
|
| 91 |
+
yield
|
| 92 |
+
finally:
|
| 93 |
+
# recover the previous values
|
| 94 |
+
with __allow_nonbracketed_mutation():
|
| 95 |
+
set_flags(*orig_flags)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# The magic here is to allow us to intercept code like this:
|
| 99 |
+
#
|
| 100 |
+
# torch.backends.opt_einsum.enabled = True
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class OptEinsumModule(PropModule):
|
| 104 |
+
global enabled
|
| 105 |
+
enabled = ContextProp(_get_enabled, _set_enabled)
|
| 106 |
+
global strategy
|
| 107 |
+
strategy = None
|
| 108 |
+
if is_available():
|
| 109 |
+
strategy = ContextProp(_get_strategy, _set_strategy)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# This is the sys.modules replacement trick, see
|
| 113 |
+
# https://stackoverflow.com/questions/2447353/getattr-on-a-module/7668273#7668273
|
| 114 |
+
sys.modules[__name__] = OptEinsumModule(sys.modules[__name__], __name__)
|
| 115 |
+
|
| 116 |
+
enabled = bool(is_available())
|
| 117 |
+
strategy = "auto" if is_available() else None
|
.venv/lib/python3.12/site-packages/torch/backends/opt_einsum/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (4.73 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/python_native/__init__.py
ADDED
|
@@ -0,0 +1,395 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
User-facing API for controlling DSL operation overrides.
|
| 3 |
+
|
| 4 |
+
The torch.backends.python_native module provides control over DSL (Domain Specific Language)
|
| 5 |
+
operation overrides defined in torch._native. This allows users to selectively enable or disable
|
| 6 |
+
high-performance implementations from various DSLs like Triton and CuteDSL.
|
| 7 |
+
|
| 8 |
+
The module supports both coarse-grained control (entire DSLs) and fine-grained control
|
| 9 |
+
(individual operations or dispatch keys). All control operations support context managers
|
| 10 |
+
for temporary state changes.
|
| 11 |
+
|
| 12 |
+
Example usage::
|
| 13 |
+
|
| 14 |
+
import torch.backends.python_native as pn
|
| 15 |
+
|
| 16 |
+
# DSL-level control
|
| 17 |
+
pn.triton.enabled = False # Disable all triton ops
|
| 18 |
+
pn.cutedsl.enabled = True # Enable all cutedsl ops
|
| 19 |
+
|
| 20 |
+
# Individual operation control
|
| 21 |
+
pn.disable_operations("scaled_mm") # Disable specific op across all DSLs
|
| 22 |
+
pn.enable_operations("scaled_mm") # Re-enable specific op
|
| 23 |
+
|
| 24 |
+
# Context manager support
|
| 25 |
+
with pn.triton.disabled():
|
| 26 |
+
result = some_computation() # Triton ops disabled here
|
| 27 |
+
|
| 28 |
+
# Query capabilities
|
| 29 |
+
print(pn.available_dsls) # ['triton', 'cutedsl']
|
| 30 |
+
print(pn.get_dsl_operations("triton")) # Operations for triton
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
import functools
|
| 34 |
+
import sys
|
| 35 |
+
import types
|
| 36 |
+
from contextlib import contextmanager
|
| 37 |
+
|
| 38 |
+
from torch.backends import ContextProp, flags_frozen, PropModule
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@contextmanager
|
| 42 |
+
def _preserve_filter_state():
|
| 43 |
+
"""Context manager to save and restore registry filter state."""
|
| 44 |
+
filter_state = _get_filter_state()
|
| 45 |
+
|
| 46 |
+
# Save original state
|
| 47 |
+
original_state = (
|
| 48 |
+
set(filter_state._dsl_names),
|
| 49 |
+
set(filter_state._op_symbols),
|
| 50 |
+
set(filter_state._dispatch_keys),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
yield filter_state
|
| 55 |
+
finally:
|
| 56 |
+
# Restore original state
|
| 57 |
+
filter_state._dsl_names.clear()
|
| 58 |
+
filter_state._op_symbols.clear()
|
| 59 |
+
filter_state._dispatch_keys.clear()
|
| 60 |
+
|
| 61 |
+
filter_state._dsl_names.update(original_state[0])
|
| 62 |
+
filter_state._op_symbols.update(original_state[1])
|
| 63 |
+
filter_state._dispatch_keys.update(original_state[2])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _get_dsl_registry():
|
| 67 |
+
"""Lazy import to avoid circular imports."""
|
| 68 |
+
from torch._native.dsl_registry import dsl_registry
|
| 69 |
+
|
| 70 |
+
return dsl_registry
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _get_registry_functions():
|
| 74 |
+
"""Lazy import of registry functions."""
|
| 75 |
+
from torch._native.registry import (
|
| 76 |
+
_filter_state,
|
| 77 |
+
_graphs,
|
| 78 |
+
deregister_op_overrides,
|
| 79 |
+
reenable_op_overrides,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
return deregister_op_overrides, reenable_op_overrides, _graphs, _filter_state
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _get_filter_state():
|
| 86 |
+
"""Direct access to filter state."""
|
| 87 |
+
return _get_registry_functions()[3]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _get_dsl_module(dsl_name: str):
|
| 91 |
+
"""Get the registered DSL module for direct control.
|
| 92 |
+
|
| 93 |
+
Uses the DSL registry to dynamically look up DSL modules instead of
|
| 94 |
+
hard-coding the mapping. This makes the function automatically extensible
|
| 95 |
+
for new DSLs without code changes.
|
| 96 |
+
|
| 97 |
+
Args:
|
| 98 |
+
dsl_name (str): Name of the DSL to retrieve.
|
| 99 |
+
|
| 100 |
+
Returns:
|
| 101 |
+
DSLModuleProtocol: The registered DSL module.
|
| 102 |
+
|
| 103 |
+
Raises:
|
| 104 |
+
ValueError: If the DSL is not registered.
|
| 105 |
+
"""
|
| 106 |
+
registry = _get_dsl_registry()
|
| 107 |
+
|
| 108 |
+
# Use the public API to get the DSL module
|
| 109 |
+
dsl_module = registry.get_dsl_module(dsl_name)
|
| 110 |
+
if dsl_module is not None:
|
| 111 |
+
return dsl_module
|
| 112 |
+
else:
|
| 113 |
+
raise ValueError(
|
| 114 |
+
f"Unknown DSL: {dsl_name}. Available DSLs: {registry.list_all_dsls()}"
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class DSLController:
|
| 119 |
+
"""Controller for a specific DSL."""
|
| 120 |
+
|
| 121 |
+
def __init__(self, dsl_name: str):
|
| 122 |
+
self._dsl_name = dsl_name
|
| 123 |
+
|
| 124 |
+
@property
|
| 125 |
+
def name(self) -> str:
|
| 126 |
+
return self._dsl_name
|
| 127 |
+
|
| 128 |
+
@property
|
| 129 |
+
def available(self) -> bool:
|
| 130 |
+
"""Check if DSL runtime is available."""
|
| 131 |
+
registry = _get_dsl_registry()
|
| 132 |
+
return registry.is_dsl_available(self._dsl_name)
|
| 133 |
+
|
| 134 |
+
@property
|
| 135 |
+
def version(self):
|
| 136 |
+
"""Get DSL version."""
|
| 137 |
+
registry = _get_dsl_registry()
|
| 138 |
+
return registry.get_dsl_version(self._dsl_name)
|
| 139 |
+
|
| 140 |
+
@property
|
| 141 |
+
def backend(self) -> str:
|
| 142 |
+
"""Chosen lowering backend for DSLs that have one (e.g. helion)."""
|
| 143 |
+
chosen = getattr(_get_dsl_module(self._dsl_name), "_chosen_backend", None)
|
| 144 |
+
if chosen is None:
|
| 145 |
+
raise AttributeError(f"{self._dsl_name} DSL has no configurable backend")
|
| 146 |
+
return chosen()
|
| 147 |
+
|
| 148 |
+
@property
|
| 149 |
+
def enabled(self) -> bool:
|
| 150 |
+
"""Check if DSL is currently enabled."""
|
| 151 |
+
filter_state = _get_filter_state()
|
| 152 |
+
return self._dsl_name not in filter_state._dsl_names
|
| 153 |
+
|
| 154 |
+
@enabled.setter
|
| 155 |
+
def enabled(self, value: bool):
|
| 156 |
+
"""Enable or disable the DSL."""
|
| 157 |
+
if flags_frozen():
|
| 158 |
+
raise RuntimeError(
|
| 159 |
+
f"not allowed to set {self._dsl_name} DSL flags "
|
| 160 |
+
"after disable_global_flags; please use flags() context manager instead"
|
| 161 |
+
)
|
| 162 |
+
if value:
|
| 163 |
+
self.enable()
|
| 164 |
+
else:
|
| 165 |
+
self.disable()
|
| 166 |
+
|
| 167 |
+
def disable(self):
|
| 168 |
+
"""Disable all operations for this DSL."""
|
| 169 |
+
dsl_module = _get_dsl_module(self._dsl_name)
|
| 170 |
+
dsl_module.deregister_op_overrides()
|
| 171 |
+
|
| 172 |
+
def enable(self):
|
| 173 |
+
"""Re-enable all operations for this DSL."""
|
| 174 |
+
reenable_op_overrides = _get_registry_functions()[1]
|
| 175 |
+
reenable_op_overrides(enable_dsl_names=self._dsl_name)
|
| 176 |
+
|
| 177 |
+
@contextmanager
|
| 178 |
+
def disabled(self):
|
| 179 |
+
"""Context manager to temporarily disable DSL."""
|
| 180 |
+
original_state = self.enabled
|
| 181 |
+
try:
|
| 182 |
+
self.disable()
|
| 183 |
+
yield
|
| 184 |
+
finally:
|
| 185 |
+
if original_state:
|
| 186 |
+
self.enable()
|
| 187 |
+
|
| 188 |
+
def __repr__(self):
|
| 189 |
+
status = "available" if self.available else "unavailable"
|
| 190 |
+
enabled_status = "enabled" if self.enabled else "disabled"
|
| 191 |
+
return f"DSLController({self._dsl_name}, {status}, {enabled_status})"
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class PythonNativeModule(PropModule):
|
| 195 |
+
"""Main module for python_native DSL control."""
|
| 196 |
+
|
| 197 |
+
def __init__(self, original_module):
|
| 198 |
+
super().__init__(original_module, original_module.__name__)
|
| 199 |
+
|
| 200 |
+
@property
|
| 201 |
+
def available_dsls(self) -> list[str]:
|
| 202 |
+
"""Get list of available DSLs."""
|
| 203 |
+
registry = _get_dsl_registry()
|
| 204 |
+
result = registry.list_available_dsls()
|
| 205 |
+
return list(result) if not isinstance(result, list) else result
|
| 206 |
+
|
| 207 |
+
@property
|
| 208 |
+
def all_dsls(self) -> list[str]:
|
| 209 |
+
"""Get list of all registered DSLs."""
|
| 210 |
+
registry = _get_dsl_registry()
|
| 211 |
+
result = registry.list_all_dsls()
|
| 212 |
+
return list(result) if not isinstance(result, list) else result
|
| 213 |
+
|
| 214 |
+
def get_dsl_operations(self, dsl_name: str) -> list[str]:
|
| 215 |
+
"""Get list of operations registered by a specific DSL.
|
| 216 |
+
|
| 217 |
+
Args:
|
| 218 |
+
dsl_name (str): Name of the DSL to query (e.g., 'triton', 'cutedsl').
|
| 219 |
+
|
| 220 |
+
Returns:
|
| 221 |
+
list[str]: Sorted list of operation names registered by the DSL.
|
| 222 |
+
|
| 223 |
+
Example::
|
| 224 |
+
|
| 225 |
+
ops = torch.backends.python_native.get_dsl_operations("triton")
|
| 226 |
+
print(ops) # ['triton_to_mxfp8_dim0', ...]
|
| 227 |
+
"""
|
| 228 |
+
from torch._native.registry import get_dsl_operations
|
| 229 |
+
|
| 230 |
+
return get_dsl_operations(dsl_name)
|
| 231 |
+
|
| 232 |
+
def disable_operations(self, *op_symbols: str):
|
| 233 |
+
"""Disable specific operations across all DSLs.
|
| 234 |
+
|
| 235 |
+
Args:
|
| 236 |
+
*op_symbols (str): Names of operations to disable.
|
| 237 |
+
|
| 238 |
+
Example::
|
| 239 |
+
|
| 240 |
+
# Disable scaled matrix multiply across all DSLs
|
| 241 |
+
torch.backends.python_native.disable_operations("scaled_mm")
|
| 242 |
+
|
| 243 |
+
# Disable multiple operations
|
| 244 |
+
torch.backends.python_native.disable_operations(
|
| 245 |
+
"scaled_mm", "flash_attention"
|
| 246 |
+
)
|
| 247 |
+
"""
|
| 248 |
+
deregister_op_overrides = _get_registry_functions()[0]
|
| 249 |
+
deregister_op_overrides(disable_op_symbols=list(op_symbols))
|
| 250 |
+
|
| 251 |
+
def enable_operations(self, *op_symbols: str):
|
| 252 |
+
"""Re-enable specific operations across all DSLs.
|
| 253 |
+
|
| 254 |
+
Args:
|
| 255 |
+
*op_symbols (str): Names of operations to re-enable.
|
| 256 |
+
|
| 257 |
+
Example::
|
| 258 |
+
|
| 259 |
+
# Re-enable previously disabled operations
|
| 260 |
+
torch.backends.python_native.enable_operations(
|
| 261 |
+
"scaled_mm", "flash_attention"
|
| 262 |
+
)
|
| 263 |
+
"""
|
| 264 |
+
reenable_op_overrides = _get_registry_functions()[1]
|
| 265 |
+
reenable_op_overrides(enable_op_symbols=list(op_symbols))
|
| 266 |
+
|
| 267 |
+
def disable_dispatch_keys(self, *dispatch_keys: str):
|
| 268 |
+
"""Disable operations at specific dispatch keys.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
*dispatch_keys (str): Dispatch keys to disable (e.g., 'CUDA', 'CPU').
|
| 272 |
+
|
| 273 |
+
Example::
|
| 274 |
+
|
| 275 |
+
# Disable all native operations on CUDA
|
| 276 |
+
torch.backends.python_native.disable_dispatch_keys("CUDA")
|
| 277 |
+
"""
|
| 278 |
+
deregister_op_overrides = _get_registry_functions()[0]
|
| 279 |
+
deregister_op_overrides(disable_dispatch_keys=list(dispatch_keys))
|
| 280 |
+
|
| 281 |
+
def enable_dispatch_keys(self, *dispatch_keys: str):
|
| 282 |
+
"""Re-enable operations at specific dispatch keys.
|
| 283 |
+
|
| 284 |
+
Args:
|
| 285 |
+
*dispatch_keys (str): Dispatch keys to re-enable (e.g., 'CUDA', 'CPU').
|
| 286 |
+
|
| 287 |
+
Example::
|
| 288 |
+
|
| 289 |
+
# Re-enable native operations on CUDA
|
| 290 |
+
torch.backends.python_native.enable_dispatch_keys("CUDA")
|
| 291 |
+
"""
|
| 292 |
+
reenable_op_overrides = _get_registry_functions()[1]
|
| 293 |
+
reenable_op_overrides(enable_dispatch_keys=list(dispatch_keys))
|
| 294 |
+
|
| 295 |
+
@contextmanager
|
| 296 |
+
def operations_disabled(self, *op_symbols: str):
|
| 297 |
+
"""Context manager to temporarily disable operations.
|
| 298 |
+
|
| 299 |
+
Args:
|
| 300 |
+
*op_symbols (str): Names of operations to temporarily disable.
|
| 301 |
+
|
| 302 |
+
Example::
|
| 303 |
+
|
| 304 |
+
with torch.backends.python_native.operations_disabled("scaled_mm"):
|
| 305 |
+
# scaled_mm is disabled across all DSLs
|
| 306 |
+
result = model(input)
|
| 307 |
+
# scaled_mm is automatically re-enabled here
|
| 308 |
+
"""
|
| 309 |
+
filter_state = _get_filter_state()
|
| 310 |
+
previously_disabled_ops = {
|
| 311 |
+
op for op in op_symbols if op in filter_state._op_symbols
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
self.disable_operations(*op_symbols)
|
| 315 |
+
try:
|
| 316 |
+
yield
|
| 317 |
+
finally:
|
| 318 |
+
# Only re-enable operations that weren't already disabled
|
| 319 |
+
ops_to_reenable = [
|
| 320 |
+
op for op in op_symbols if op not in previously_disabled_ops
|
| 321 |
+
]
|
| 322 |
+
if ops_to_reenable:
|
| 323 |
+
self.enable_operations(*ops_to_reenable)
|
| 324 |
+
|
| 325 |
+
@functools.lru_cache(maxsize=16) # noqa: B019
|
| 326 |
+
def _get_dsl_controller(self, name: str) -> "DSLController":
|
| 327 |
+
"""Get or create a DSL controller (cached)."""
|
| 328 |
+
return DSLController(name)
|
| 329 |
+
|
| 330 |
+
def _get_registry_functions(self):
|
| 331 |
+
"""Expose registry functions for testing."""
|
| 332 |
+
return _get_registry_functions()
|
| 333 |
+
|
| 334 |
+
def is_operation_disabled(self, op_symbol: str) -> bool:
|
| 335 |
+
"""Check if an operation is currently disabled."""
|
| 336 |
+
filter_state = _get_filter_state()
|
| 337 |
+
return op_symbol in filter_state._op_symbols
|
| 338 |
+
|
| 339 |
+
def is_dsl_disabled(self, dsl_name: str) -> bool:
|
| 340 |
+
"""Check if a DSL is currently disabled."""
|
| 341 |
+
filter_state = _get_filter_state()
|
| 342 |
+
return dsl_name in filter_state._dsl_names
|
| 343 |
+
|
| 344 |
+
def __getattr__(self, name: str):
|
| 345 |
+
"""Dynamic attribute access for DSL controllers."""
|
| 346 |
+
# Skip dunder attributes to avoid triggering DSL registry lookups
|
| 347 |
+
# during torch initialization. inspect.getmodule() calls
|
| 348 |
+
# hasattr(module, '__file__') which would otherwise cause a circular
|
| 349 |
+
# import through _get_dsl_registry() while torch is still loading.
|
| 350 |
+
if name.startswith("__") and name.endswith("__"):
|
| 351 |
+
raise AttributeError(f"module '{self.__name__}' has no attribute '{name}'")
|
| 352 |
+
|
| 353 |
+
if name in self.all_dsls:
|
| 354 |
+
return self._get_dsl_controller(name)
|
| 355 |
+
|
| 356 |
+
# Expose private functions for testing
|
| 357 |
+
if name == "_get_dsl_module":
|
| 358 |
+
return _get_dsl_module
|
| 359 |
+
if name == "_get_registry_functions":
|
| 360 |
+
return self._get_registry_functions
|
| 361 |
+
if name == "_get_filter_state":
|
| 362 |
+
return _get_filter_state
|
| 363 |
+
|
| 364 |
+
raise AttributeError(f"module '{self.__name__}' has no attribute '{name}'")
|
| 365 |
+
|
| 366 |
+
def __dir__(self):
|
| 367 |
+
"""Return available attributes including DSL names."""
|
| 368 |
+
attrs = set(super().__dir__())
|
| 369 |
+
attrs.update(
|
| 370 |
+
{
|
| 371 |
+
"available_dsls",
|
| 372 |
+
"all_dsls",
|
| 373 |
+
"get_dsl_operations",
|
| 374 |
+
"disable_operations",
|
| 375 |
+
"enable_operations",
|
| 376 |
+
"disable_dispatch_keys",
|
| 377 |
+
"enable_dispatch_keys",
|
| 378 |
+
"operations_disabled",
|
| 379 |
+
"is_operation_disabled",
|
| 380 |
+
"is_dsl_disabled",
|
| 381 |
+
}
|
| 382 |
+
)
|
| 383 |
+
|
| 384 |
+
# Add DSL names
|
| 385 |
+
try:
|
| 386 |
+
attrs.update(self.all_dsls)
|
| 387 |
+
except Exception:
|
| 388 |
+
# If registry not available yet, skip DSL names
|
| 389 |
+
pass
|
| 390 |
+
|
| 391 |
+
return sorted(attrs)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
# Replace the current module with our enhanced version
|
| 395 |
+
sys.modules[__name__] = PythonNativeModule(sys.modules[__name__])
|
.venv/lib/python3.12/site-packages/torch/backends/python_native/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (17.4 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/quantized/__init__.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import sys
|
| 3 |
+
import types
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
# This function should correspond to the enums present in c10/core/QEngine.h
|
| 9 |
+
def _get_qengine_id(qengine: str) -> int:
|
| 10 |
+
if qengine == "none" or qengine == "" or qengine is None:
|
| 11 |
+
ret = 0
|
| 12 |
+
elif qengine == "fbgemm":
|
| 13 |
+
ret = 1
|
| 14 |
+
elif qengine == "qnnpack":
|
| 15 |
+
ret = 2
|
| 16 |
+
elif qengine == "onednn":
|
| 17 |
+
ret = 3
|
| 18 |
+
elif qengine == "x86":
|
| 19 |
+
ret = 4
|
| 20 |
+
else:
|
| 21 |
+
ret = -1
|
| 22 |
+
raise RuntimeError(f"{qengine} is not a valid value for quantized engine")
|
| 23 |
+
return ret
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# This function should correspond to the enums present in c10/core/QEngine.h
|
| 27 |
+
def _get_qengine_str(qengine: int) -> str:
|
| 28 |
+
all_engines = {0: "none", 1: "fbgemm", 2: "qnnpack", 3: "onednn", 4: "x86"}
|
| 29 |
+
return all_engines.get(qengine, "*undefined")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class _QEngineProp:
|
| 33 |
+
def __get__(self, obj, objtype) -> str:
|
| 34 |
+
return _get_qengine_str(torch._C._get_qengine())
|
| 35 |
+
|
| 36 |
+
def __set__(self, obj, val: str) -> None:
|
| 37 |
+
torch._C._set_qengine(_get_qengine_id(val))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class _SupportedQEnginesProp:
|
| 41 |
+
def __get__(self, obj, objtype) -> list[str]:
|
| 42 |
+
qengines = torch._C._supported_qengines()
|
| 43 |
+
return [_get_qengine_str(qe) for qe in qengines]
|
| 44 |
+
|
| 45 |
+
def __set__(self, obj, val) -> None:
|
| 46 |
+
raise RuntimeError("Assignment not supported")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class QuantizedEngine(types.ModuleType):
|
| 50 |
+
def __init__(self, m, name):
|
| 51 |
+
super().__init__(name)
|
| 52 |
+
self.m = m
|
| 53 |
+
|
| 54 |
+
def __getattr__(self, attr):
|
| 55 |
+
return self.m.__getattribute__(attr)
|
| 56 |
+
|
| 57 |
+
engine = _QEngineProp()
|
| 58 |
+
supported_engines = _SupportedQEnginesProp()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# This is the sys.modules replacement trick, see
|
| 62 |
+
# https://stackoverflow.com/questions/2447353/getattr-on-a-module/7668273#7668273
|
| 63 |
+
sys.modules[__name__] = QuantizedEngine(sys.modules[__name__], __name__)
|
| 64 |
+
engine: str
|
| 65 |
+
supported_engines: list[str]
|
.venv/lib/python3.12/site-packages/torch/backends/quantized/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (3.58 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/xeon/__init__.py
ADDED
|
File without changes
|
.venv/lib/python3.12/site-packages/torch/backends/xeon/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (194 Bytes). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/backends/xeon/__pycache__/run_cpu.cp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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
"""
|
| 3 |
+
This is a script for launching PyTorch inference on Intel(R) Xeon(R) Scalable Processors with optimal configurations.
|
| 4 |
+
|
| 5 |
+
Single instance inference, multi-instance inference are enabled.
|
| 6 |
+
|
| 7 |
+
Note: term "instance" here doesn't refer to a cloud instance. This script is executed as a single process. It invokes
|
| 8 |
+
multiple "instances" which are formed from multiple threads for each. "instance" is kind of group of threads in this
|
| 9 |
+
context.
|
| 10 |
+
|
| 11 |
+
Illustrated as below:
|
| 12 |
+
|
| 13 |
+
::
|
| 14 |
+
|
| 15 |
+
+-----------------------------+----------------------+-------+
|
| 16 |
+
| process | thread | core |
|
| 17 |
+
+=============================+======================+=======+
|
| 18 |
+
| torch.backends.xeon.run_cpu | instance 0: thread 0 | 0 |
|
| 19 |
+
| | thread 1 | 1 |
|
| 20 |
+
| +----------------------+-------+
|
| 21 |
+
| | instance 1: thread 0 | 2 |
|
| 22 |
+
| | thread 1 | 3 |
|
| 23 |
+
| +----------------------+-------+
|
| 24 |
+
| | ... | ... |
|
| 25 |
+
| +----------------------+-------+
|
| 26 |
+
| | instance N: thread 0 | M |
|
| 27 |
+
| | thread 1 | M+1 |
|
| 28 |
+
+-----------------------------+----------------------+-------+
|
| 29 |
+
|
| 30 |
+
To get the peak performance on Intel(R) Xeon(R) Scalable Processors, the script optimizes the configuration of thread and memory
|
| 31 |
+
management. For thread management, the script configures thread affinity and the preload of Intel OMP library.
|
| 32 |
+
For memory management, it configures NUMA binding and preload optimized memory allocation library (e.g. tcmalloc, jemalloc).
|
| 33 |
+
|
| 34 |
+
Environment variables that will be set by this script:
|
| 35 |
+
|
| 36 |
+
+------------------+-------------------------------------------------------------------------------------------------+
|
| 37 |
+
| Environ Variable | Value |
|
| 38 |
+
+==================+=================================================================================================+
|
| 39 |
+
| LD_PRELOAD | Depending on knobs you set, <lib>/libiomp5.so, <lib>/libjemalloc.so, <lib>/libtcmalloc.so might |
|
| 40 |
+
| | be appended to LD_PRELOAD. |
|
| 41 |
+
+------------------+-------------------------------------------------------------------------------------------------+
|
| 42 |
+
| KMP_AFFINITY | If libiomp5.so is preloaded, KMP_AFFINITY could be set to "granularity=fine,compact,1,0". |
|
| 43 |
+
+------------------+-------------------------------------------------------------------------------------------------+
|
| 44 |
+
| KMP_BLOCKTIME | If libiomp5.so is preloaded, KMP_BLOCKTIME is set to "1". |
|
| 45 |
+
+------------------+-------------------------------------------------------------------------------------------------+
|
| 46 |
+
| OMP_NUM_THREADS | value of ncores_per_instance |
|
| 47 |
+
+------------------+-------------------------------------------------------------------------------------------------+
|
| 48 |
+
| MALLOC_CONF | If libjemalloc.so is preloaded, MALLOC_CONF will be set to |
|
| 49 |
+
| | "oversize_threshold:1,background_thread:true,metadata_thp:auto". |
|
| 50 |
+
+------------------+-------------------------------------------------------------------------------------------------+
|
| 51 |
+
|
| 52 |
+
*Note*: This script respects environment variables set preliminarily. I.e. If you set the environment variables
|
| 53 |
+
mentioned above before running the script, the script will not overwrite the values in the script.
|
| 54 |
+
|
| 55 |
+
How to use this module:
|
| 56 |
+
~~~~~~~~~~~~~~~~~~~~~~~
|
| 57 |
+
|
| 58 |
+
Single instance inference
|
| 59 |
+
-------------------------
|
| 60 |
+
|
| 61 |
+
1. Run single-instance inference on a single node with all CPU nodes.
|
| 62 |
+
|
| 63 |
+
::
|
| 64 |
+
|
| 65 |
+
python -m torch.backends.xeon.run_cpu --throughput-mode script.py args
|
| 66 |
+
|
| 67 |
+
2. Run single-instance inference on a single CPU node.
|
| 68 |
+
|
| 69 |
+
::
|
| 70 |
+
|
| 71 |
+
python -m torch.backends.xeon.run_cpu --node-id 1 script.py args
|
| 72 |
+
|
| 73 |
+
Multi-instance inference
|
| 74 |
+
------------------------
|
| 75 |
+
|
| 76 |
+
1. Multi-instance
|
| 77 |
+
By default this tool runs one process per node. If you want to set the instance numbers and core per instance,
|
| 78 |
+
--ninstances and --ncores-per-instance should be set.
|
| 79 |
+
|
| 80 |
+
::
|
| 81 |
+
|
| 82 |
+
python -m torch.backends.xeon.run_cpu -- python_script args
|
| 83 |
+
|
| 84 |
+
eg: on an Intel(R) Xeon(R) Scalable Processor with 14 instance, 4 cores per instance
|
| 85 |
+
|
| 86 |
+
::
|
| 87 |
+
|
| 88 |
+
python -m torch.backends.xeon.run_cpu --ninstances 14 --ncores-per-instance 4 python_script args
|
| 89 |
+
|
| 90 |
+
2. Run single-instance inference among multiple instances.
|
| 91 |
+
By default, runs all ninstances. If you want to independently run a single instance among ninstances, specify rank.
|
| 92 |
+
|
| 93 |
+
eg: run 0th instance on an Intel(R) Xeon(R) Scalable Processor with 2 instance (i.e., numactl -C 0-27)
|
| 94 |
+
|
| 95 |
+
::
|
| 96 |
+
|
| 97 |
+
python -m torch.backends.xeon.run_cpu --ninstances 2 --rank 0 python_script args
|
| 98 |
+
|
| 99 |
+
eg: run 1st instance on an Intel(R) Xeon(R) Scalable Processor with 2 instance (i.e., numactl -C 28-55)
|
| 100 |
+
|
| 101 |
+
::
|
| 102 |
+
|
| 103 |
+
python -m torch.backends.xeon.run_cpu --ninstances 2 --rank 1 python_script args
|
| 104 |
+
|
| 105 |
+
eg: run 0th instance on an Intel(R) Xeon(R) Scalable Processor with 2 instance, 2 cores per instance,
|
| 106 |
+
first four cores (i.e., numactl -C 0-1)
|
| 107 |
+
|
| 108 |
+
::
|
| 109 |
+
|
| 110 |
+
python -m torch.backends.xeon.run_cpu --core-list "0, 1, 2, 3" --ninstances 2 --ncores-per-instance 2
|
| 111 |
+
--rank 0 python_script args
|
| 112 |
+
|
| 113 |
+
3. To look up what optional arguments this module offers:
|
| 114 |
+
|
| 115 |
+
::
|
| 116 |
+
|
| 117 |
+
python -m torch.backends.xeon.run_cpu --help
|
| 118 |
+
|
| 119 |
+
Memory allocator
|
| 120 |
+
----------------
|
| 121 |
+
|
| 122 |
+
"--enable-tcmalloc" and "--enable-jemalloc" can be used to enable different memory allocator.
|
| 123 |
+
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
import glob
|
| 127 |
+
import logging
|
| 128 |
+
import os
|
| 129 |
+
import platform
|
| 130 |
+
import re
|
| 131 |
+
import subprocess
|
| 132 |
+
import sys
|
| 133 |
+
from argparse import ArgumentParser, RawTextHelpFormatter, REMAINDER
|
| 134 |
+
from os.path import expanduser
|
| 135 |
+
|
| 136 |
+
from torch.distributed.elastic.multiprocessing import (
|
| 137 |
+
DefaultLogsSpecs as _DefaultLogsSpecs,
|
| 138 |
+
start_processes,
|
| 139 |
+
Std,
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
format_str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
| 144 |
+
logging.basicConfig(level=logging.INFO, format=format_str)
|
| 145 |
+
logger = logging.getLogger(__name__)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
class _CPUinfo:
|
| 149 |
+
"""Get CPU information, such as cores list and NUMA information."""
|
| 150 |
+
|
| 151 |
+
def __init__(self, test_input=""):
|
| 152 |
+
self.cpuinfo = []
|
| 153 |
+
if platform.system() in ["Windows", "Darwin"]:
|
| 154 |
+
raise RuntimeError(f"{platform.system()} is not supported!!!")
|
| 155 |
+
elif platform.system() == "Linux":
|
| 156 |
+
# Sample output of: `lscpu --parse=CPU,Core,Socket,Node`
|
| 157 |
+
#
|
| 158 |
+
# # The following is the parsable format, which can be fed to other
|
| 159 |
+
# # programs. Each different item in every column has a unique ID
|
| 160 |
+
# # starting from zero.
|
| 161 |
+
# # CPU,Core,Socket,Node
|
| 162 |
+
# 0,0,0,0
|
| 163 |
+
# 1,1,0,0
|
| 164 |
+
# ...
|
| 165 |
+
if test_input == "":
|
| 166 |
+
lscpu_cmd = ["lscpu", "--parse=CPU,Core,Socket,Node"]
|
| 167 |
+
lscpu_info = subprocess.check_output(
|
| 168 |
+
lscpu_cmd, universal_newlines=True
|
| 169 |
+
).split("\n")
|
| 170 |
+
else:
|
| 171 |
+
lscpu_info = test_input.split("\n")
|
| 172 |
+
|
| 173 |
+
# Get information about cpu, core, socket and node
|
| 174 |
+
for line in lscpu_info:
|
| 175 |
+
pattern = r"^([\d]+,[\d]+,[\d]+,[\d]?)"
|
| 176 |
+
regex_out = re.search(pattern, line)
|
| 177 |
+
if regex_out:
|
| 178 |
+
self.cpuinfo.append(regex_out.group(1).strip().split(","))
|
| 179 |
+
|
| 180 |
+
# physical cores := core column in lscpu output
|
| 181 |
+
# logical cores := cPU column in lscpu output
|
| 182 |
+
self.node_nums = int(max(line[3] for line in self.cpuinfo)) + 1
|
| 183 |
+
self.node_physical_cores: list[list[int]] = [] # node_id is index
|
| 184 |
+
self.node_logical_cores: list[list[int]] = [] # node_id is index
|
| 185 |
+
self.physical_core_node_map = {} # physical core to numa node id
|
| 186 |
+
self.logical_core_node_map = {} # logical core to numa node id
|
| 187 |
+
|
| 188 |
+
for node_id in range(self.node_nums):
|
| 189 |
+
cur_node_physical_core = []
|
| 190 |
+
cur_node_logical_core = []
|
| 191 |
+
for cpuinfo in self.cpuinfo:
|
| 192 |
+
nid = cpuinfo[3] if cpuinfo[3] != "" else "0"
|
| 193 |
+
if node_id == int(nid):
|
| 194 |
+
if int(cpuinfo[1]) not in cur_node_physical_core:
|
| 195 |
+
cur_node_physical_core.append(int(cpuinfo[1]))
|
| 196 |
+
self.physical_core_node_map[int(cpuinfo[1])] = int(node_id)
|
| 197 |
+
cur_node_logical_core.append(int(cpuinfo[0]))
|
| 198 |
+
self.logical_core_node_map[int(cpuinfo[0])] = int(node_id)
|
| 199 |
+
self.node_physical_cores.append(cur_node_physical_core)
|
| 200 |
+
self.node_logical_cores.append(cur_node_logical_core)
|
| 201 |
+
|
| 202 |
+
def _physical_core_nums(self):
|
| 203 |
+
overall_core_num = 0
|
| 204 |
+
for phycisal_core_list in self.node_physical_cores:
|
| 205 |
+
overall_core_num += len(phycisal_core_list)
|
| 206 |
+
return overall_core_num
|
| 207 |
+
|
| 208 |
+
def _logical_core_nums(self):
|
| 209 |
+
overall_core_num = 0
|
| 210 |
+
for logical_core_list in self.node_logical_cores:
|
| 211 |
+
overall_core_num += len(logical_core_list)
|
| 212 |
+
return overall_core_num
|
| 213 |
+
|
| 214 |
+
def get_node_physical_cores(self, node_id):
|
| 215 |
+
if node_id < 0 or node_id > self.node_nums - 1:
|
| 216 |
+
raise ValueError(
|
| 217 |
+
f"Invalid node id: {node_id}. Valid node ids: {list(range(len(self.node_physical_cores)))}"
|
| 218 |
+
)
|
| 219 |
+
return self.node_physical_cores[node_id]
|
| 220 |
+
|
| 221 |
+
def get_node_logical_cores(self, node_id):
|
| 222 |
+
if node_id < 0 or node_id > self.node_nums - 1:
|
| 223 |
+
raise ValueError(
|
| 224 |
+
f"Invalid node id: {node_id}. Valid node ids: {list(range(len(self.node_physical_cores)))}"
|
| 225 |
+
)
|
| 226 |
+
return self.node_logical_cores[node_id]
|
| 227 |
+
|
| 228 |
+
def get_all_physical_cores(self):
|
| 229 |
+
all_cores = []
|
| 230 |
+
for cores in self.node_physical_cores:
|
| 231 |
+
all_cores.extend(cores)
|
| 232 |
+
return all_cores
|
| 233 |
+
|
| 234 |
+
def get_all_logical_cores(self):
|
| 235 |
+
all_cores = []
|
| 236 |
+
for cores in self.node_logical_cores:
|
| 237 |
+
all_cores.extend(cores)
|
| 238 |
+
return all_cores
|
| 239 |
+
|
| 240 |
+
def numa_aware_check(self, core_list):
|
| 241 |
+
"""
|
| 242 |
+
Check whether all cores in core_list are in the same NUMA node.
|
| 243 |
+
|
| 244 |
+
Cross NUMA will reduce performance.
|
| 245 |
+
We strongly advise to not use cores on different nodes.
|
| 246 |
+
"""
|
| 247 |
+
cores_numa_map = self.logical_core_node_map
|
| 248 |
+
numa_ids = []
|
| 249 |
+
for core in core_list:
|
| 250 |
+
numa_id = cores_numa_map[core]
|
| 251 |
+
if numa_id not in numa_ids:
|
| 252 |
+
numa_ids.append(numa_id)
|
| 253 |
+
if len(numa_ids) > 1:
|
| 254 |
+
logger.warning(
|
| 255 |
+
"Numa Aware: cores:%s on different NUMA nodes:%s. To avoid \
|
| 256 |
+
this behavior, please use --ncores-per-instance knob to make sure number of cores is divisible by --ncores-per-\
|
| 257 |
+
instance. Alternatively, please use --skip-cross-node-cores knob.",
|
| 258 |
+
core_list,
|
| 259 |
+
numa_ids,
|
| 260 |
+
)
|
| 261 |
+
if len(numa_ids) == 0:
|
| 262 |
+
raise RuntimeError(
|
| 263 |
+
"invalid number of NUMA nodes; please make sure numa_ids >= 1"
|
| 264 |
+
)
|
| 265 |
+
return numa_ids
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class _Launcher:
|
| 269 |
+
r"""Class for launcher."""
|
| 270 |
+
|
| 271 |
+
msg_lib_notfound = (
|
| 272 |
+
f"Unable to find the {{0}} library file lib{{1}}.so in $CONDA_PREFIX/lib or $VIRTUAL_ENV/lib \
|
| 273 |
+
or /.local/lib/ or /usr/local/lib/ or /usr/local/lib64/ or /usr/lib or /usr/lib64 or \
|
| 274 |
+
{expanduser('~')}/.local/lib/ so the LD_PRELOAD environment variable will not be set."
|
| 275 |
+
)
|
| 276 |
+
|
| 277 |
+
def __init__(self) -> None:
|
| 278 |
+
self.cpuinfo = _CPUinfo()
|
| 279 |
+
|
| 280 |
+
def add_lib_preload(self, lib_type):
|
| 281 |
+
"""Enable TCMalloc/JeMalloc/intel OpenMP."""
|
| 282 |
+
library_paths = []
|
| 283 |
+
if "CONDA_PREFIX" in os.environ:
|
| 284 |
+
library_paths.append(f"{os.environ['CONDA_PREFIX']}/lib")
|
| 285 |
+
if "VIRTUAL_ENV" in os.environ:
|
| 286 |
+
library_paths.append(f"{os.environ['VIRTUAL_ENV']}/lib")
|
| 287 |
+
|
| 288 |
+
library_paths += [
|
| 289 |
+
f"{expanduser('~')}/.local/lib",
|
| 290 |
+
"/usr/local/lib",
|
| 291 |
+
"/usr/local/lib64",
|
| 292 |
+
"/usr/lib",
|
| 293 |
+
"/usr/lib64",
|
| 294 |
+
]
|
| 295 |
+
|
| 296 |
+
lib_find = False
|
| 297 |
+
lib_set = False
|
| 298 |
+
for item in os.getenv("LD_PRELOAD", "").split(":"):
|
| 299 |
+
if item.endswith(f"lib{lib_type}.so"):
|
| 300 |
+
lib_set = True
|
| 301 |
+
break
|
| 302 |
+
if not lib_set:
|
| 303 |
+
for lib_path in library_paths:
|
| 304 |
+
# pyrefly: ignore [unbound-name]
|
| 305 |
+
library_file = os.path.join(lib_path, f"lib{lib_type}.so")
|
| 306 |
+
matches = glob.glob(library_file)
|
| 307 |
+
if len(matches) > 0:
|
| 308 |
+
# pyrefly: ignore [unbound-name]
|
| 309 |
+
ld_preloads = [f"{matches[0]}", os.getenv("LD_PRELOAD", "")]
|
| 310 |
+
# pyrefly: ignore [unbound-name]
|
| 311 |
+
os.environ["LD_PRELOAD"] = os.pathsep.join(
|
| 312 |
+
# pyrefly: ignore [unbound-name]
|
| 313 |
+
[p.strip(os.pathsep) for p in ld_preloads if p]
|
| 314 |
+
)
|
| 315 |
+
lib_find = True
|
| 316 |
+
break
|
| 317 |
+
return lib_set or lib_find
|
| 318 |
+
|
| 319 |
+
def is_numactl_available(self):
|
| 320 |
+
numactl_available = False
|
| 321 |
+
try:
|
| 322 |
+
cmd = ["numactl", "-C", "0", "-m", "0", "hostname"]
|
| 323 |
+
r = subprocess.run(
|
| 324 |
+
cmd,
|
| 325 |
+
env=os.environ,
|
| 326 |
+
stdout=subprocess.DEVNULL,
|
| 327 |
+
stderr=subprocess.DEVNULL,
|
| 328 |
+
check=False,
|
| 329 |
+
)
|
| 330 |
+
if r.returncode == 0:
|
| 331 |
+
numactl_available = True
|
| 332 |
+
except Exception:
|
| 333 |
+
pass
|
| 334 |
+
return numactl_available
|
| 335 |
+
|
| 336 |
+
def set_memory_allocator(
|
| 337 |
+
self, enable_tcmalloc=True, enable_jemalloc=False, use_default_allocator=False
|
| 338 |
+
):
|
| 339 |
+
"""
|
| 340 |
+
Enable TCMalloc/JeMalloc with LD_PRELOAD and set configuration for JeMalloc.
|
| 341 |
+
|
| 342 |
+
By default, PTMalloc will be used for PyTorch, but TCMalloc and JeMalloc can get better
|
| 343 |
+
memory reuse and reduce page fault to improve performance.
|
| 344 |
+
"""
|
| 345 |
+
if enable_tcmalloc and enable_jemalloc:
|
| 346 |
+
raise RuntimeError(
|
| 347 |
+
"Unable to enable TCMalloc and JEMalloc at the same time."
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
if enable_tcmalloc:
|
| 351 |
+
find_tc = self.add_lib_preload(lib_type="tcmalloc")
|
| 352 |
+
if not find_tc:
|
| 353 |
+
msg = f'{self.msg_lib_notfound} you can use "conda install -c conda-forge gperftools" to install {{0}}'
|
| 354 |
+
logger.warning(msg.format("TCmalloc", "tcmalloc"))
|
| 355 |
+
else:
|
| 356 |
+
logger.info("Use TCMalloc memory allocator")
|
| 357 |
+
|
| 358 |
+
elif enable_jemalloc:
|
| 359 |
+
find_je = self.add_lib_preload(lib_type="jemalloc")
|
| 360 |
+
if not find_je:
|
| 361 |
+
msg = f'{self.msg_lib_notfound} you can use "conda install -c conda-forge jemalloc" to install {{0}}'
|
| 362 |
+
logger.warning(msg.format("Jemalloc", "jemalloc"))
|
| 363 |
+
else:
|
| 364 |
+
logger.info("Use JeMalloc memory allocator")
|
| 365 |
+
self.set_env(
|
| 366 |
+
"MALLOC_CONF",
|
| 367 |
+
"oversize_threshold:1,background_thread:true,metadata_thp:auto",
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
elif use_default_allocator:
|
| 371 |
+
pass
|
| 372 |
+
|
| 373 |
+
else:
|
| 374 |
+
find_tc = self.add_lib_preload(lib_type="tcmalloc")
|
| 375 |
+
if find_tc:
|
| 376 |
+
logger.info("Use TCMalloc memory allocator")
|
| 377 |
+
return
|
| 378 |
+
find_je = self.add_lib_preload(lib_type="jemalloc")
|
| 379 |
+
if find_je:
|
| 380 |
+
logger.info("Use JeMalloc memory allocator")
|
| 381 |
+
return
|
| 382 |
+
logger.warning(
|
| 383 |
+
"""Neither TCMalloc nor JeMalloc is found in $CONDA_PREFIX/lib or $VIRTUAL_ENV/lib
|
| 384 |
+
or /.local/lib/ or /usr/local/lib/ or /usr/local/lib64/ or /usr/lib or /usr/lib64 or
|
| 385 |
+
%s/.local/lib/ so the LD_PRELOAD environment variable will not be set.
|
| 386 |
+
This may drop the performance""",
|
| 387 |
+
expanduser("~"),
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
def log_env_var(self, env_var_name=""):
|
| 391 |
+
if env_var_name in os.environ:
|
| 392 |
+
logger.info("%s=%s", env_var_name, os.environ[env_var_name])
|
| 393 |
+
|
| 394 |
+
def set_env(self, env_name, env_value):
|
| 395 |
+
if not env_value:
|
| 396 |
+
logger.warning("%s is None", env_name)
|
| 397 |
+
if env_name not in os.environ:
|
| 398 |
+
os.environ[env_name] = env_value
|
| 399 |
+
elif os.environ[env_name] != env_value:
|
| 400 |
+
logger.warning(
|
| 401 |
+
"Overriding value with the one set in environment variable: %s. \
|
| 402 |
+
Value applied: %s. Value ignored: %s",
|
| 403 |
+
env_name,
|
| 404 |
+
os.environ[env_name],
|
| 405 |
+
env_value,
|
| 406 |
+
)
|
| 407 |
+
self.log_env_var(env_name)
|
| 408 |
+
|
| 409 |
+
# set_kmp_affinity is used to control whether to set KMP_AFFINITY or not.
|
| 410 |
+
# In scenario that use all cores on all nodes, including logical cores, setting KMP_AFFINITY disables logical cores.
|
| 411 |
+
# In this case, KMP_AFFINITY should not be set.
|
| 412 |
+
def set_multi_thread_and_allocator(
|
| 413 |
+
self,
|
| 414 |
+
disable_iomp=False,
|
| 415 |
+
set_kmp_affinity=True,
|
| 416 |
+
enable_tcmalloc=True,
|
| 417 |
+
enable_jemalloc=False,
|
| 418 |
+
use_default_allocator=False,
|
| 419 |
+
):
|
| 420 |
+
"""
|
| 421 |
+
Set multi-thread configuration and enable Intel openMP and TCMalloc/JeMalloc.
|
| 422 |
+
|
| 423 |
+
By default, GNU openMP and PTMalloc are used in PyTorch. but Intel openMP and TCMalloc/JeMalloc are better alternatives
|
| 424 |
+
to get performance benefit.
|
| 425 |
+
"""
|
| 426 |
+
self.set_memory_allocator(
|
| 427 |
+
enable_tcmalloc, enable_jemalloc, use_default_allocator
|
| 428 |
+
)
|
| 429 |
+
if not disable_iomp:
|
| 430 |
+
find_iomp = self.add_lib_preload(lib_type="iomp5")
|
| 431 |
+
if not find_iomp:
|
| 432 |
+
msg = f'{self.msg_lib_notfound} you can use "conda install mkl" to install {{0}}'
|
| 433 |
+
logger.warning(msg.format("iomp", "iomp5"))
|
| 434 |
+
else:
|
| 435 |
+
logger.info("Using Intel OpenMP")
|
| 436 |
+
if set_kmp_affinity:
|
| 437 |
+
self.set_env("KMP_AFFINITY", "granularity=fine,compact,1,0")
|
| 438 |
+
self.set_env("KMP_BLOCKTIME", "1")
|
| 439 |
+
self.log_env_var("LD_PRELOAD")
|
| 440 |
+
|
| 441 |
+
r"""
|
| 442 |
+
Launcher for single instance and multi-instance
|
| 443 |
+
"""
|
| 444 |
+
|
| 445 |
+
def launch(self, args):
|
| 446 |
+
cores = []
|
| 447 |
+
set_kmp_affinity = True
|
| 448 |
+
enable_taskset = False
|
| 449 |
+
# ncores_per_instance param check and expand for multi-instance
|
| 450 |
+
if not isinstance(args.ncores_per_instance, list):
|
| 451 |
+
args.ncores_per_instance = [args.ncores_per_instance]
|
| 452 |
+
args.ncores_per_instance = [int(x) for x in args.ncores_per_instance]
|
| 453 |
+
if args.ncores_per_instance != [-1]:
|
| 454 |
+
if args.ninstances > 0:
|
| 455 |
+
if len(args.ncores_per_instance) == 1:
|
| 456 |
+
args.ncores_per_instance = (
|
| 457 |
+
args.ncores_per_instance * args.ninstances
|
| 458 |
+
)
|
| 459 |
+
if len(args.ncores_per_instance) != args.ninstances:
|
| 460 |
+
raise ValueError(
|
| 461 |
+
'Mismatch for "--ninstances" and "--ncores-per-instance" settings.'
|
| 462 |
+
)
|
| 463 |
+
elif len(args.ncores_per_instance) > 1:
|
| 464 |
+
args.ninstances = len(args.ncores_per_instance)
|
| 465 |
+
if args.core_list: # user specify what cores will be used by params
|
| 466 |
+
cores = [int(x) for x in args.core_list.split(",")]
|
| 467 |
+
if args.ncores_per_instance == [-1]:
|
| 468 |
+
raise RuntimeError(
|
| 469 |
+
'please specify the "--ncores-per-instance" if you have pass the --core-list params'
|
| 470 |
+
)
|
| 471 |
+
if args.ninstances > 0 and sum(args.ncores_per_instance) < len(cores):
|
| 472 |
+
logger.warning(
|
| 473 |
+
"only first %s cores will be used, \
|
| 474 |
+
but you specify %s cores in core_list",
|
| 475 |
+
sum(args.ncores_per_instance),
|
| 476 |
+
len(cores),
|
| 477 |
+
)
|
| 478 |
+
else:
|
| 479 |
+
if args.use_logical_core:
|
| 480 |
+
if args.node_id != -1:
|
| 481 |
+
cores = self.cpuinfo.get_node_logical_cores(args.node_id)
|
| 482 |
+
else:
|
| 483 |
+
cores = self.cpuinfo.get_all_logical_cores()
|
| 484 |
+
# When using all cores on all nodes, including logical cores,
|
| 485 |
+
# setting KMP_AFFINITY disables logical cores. Thus, KMP_AFFINITY should not be set.
|
| 486 |
+
set_kmp_affinity = False
|
| 487 |
+
else:
|
| 488 |
+
if args.node_id != -1:
|
| 489 |
+
cores = self.cpuinfo.get_node_physical_cores(args.node_id)
|
| 490 |
+
else:
|
| 491 |
+
cores = self.cpuinfo.get_all_physical_cores()
|
| 492 |
+
if (
|
| 493 |
+
not args.multi_instance
|
| 494 |
+
and args.ninstances == -1
|
| 495 |
+
and args.ncores_per_instance == [-1]
|
| 496 |
+
):
|
| 497 |
+
args.ninstances = 1
|
| 498 |
+
args.ncores_per_instance = [len(cores)]
|
| 499 |
+
elif (
|
| 500 |
+
args.multi_instance
|
| 501 |
+
and args.ninstances == -1
|
| 502 |
+
and args.ncores_per_instance == [-1]
|
| 503 |
+
):
|
| 504 |
+
args.throughput_mode = True
|
| 505 |
+
elif args.ncores_per_instance == [-1] and args.ninstances != -1:
|
| 506 |
+
if args.ninstances > len(cores):
|
| 507 |
+
raise RuntimeError(
|
| 508 |
+
f"there are {len(cores)} total cores but you specify {args.ninstances} ninstances; \
|
| 509 |
+
please make sure ninstances <= total_cores)"
|
| 510 |
+
)
|
| 511 |
+
if args.skip_cross_node_cores:
|
| 512 |
+
logger.warning(
|
| 513 |
+
"with --skip-cross-node-cores set, the first %d sub-numa node(s) will be used \
|
| 514 |
+
to launch the instance(s), each node for 1 instance.",
|
| 515 |
+
args.ninstances,
|
| 516 |
+
)
|
| 517 |
+
if args.ninstances > self.cpuinfo.node_nums:
|
| 518 |
+
raise ValueError(
|
| 519 |
+
"--ninstances should not be larger than numa node number \
|
| 520 |
+
when --skip-cross-node-cores is set"
|
| 521 |
+
)
|
| 522 |
+
cores.clear()
|
| 523 |
+
args.ncores_per_instance.clear()
|
| 524 |
+
for i in range(args.ninstances):
|
| 525 |
+
per_node_cores = self.cpuinfo.get_node_physical_cores(i)
|
| 526 |
+
cores.extend(per_node_cores)
|
| 527 |
+
args.ncores_per_instance.append(len(per_node_cores))
|
| 528 |
+
else:
|
| 529 |
+
logger.warning(
|
| 530 |
+
"all the CPU cores on the machine will be distributed \
|
| 531 |
+
as evenly as possible to each instance. It is possible that some cores in an instance may cross the numa node."
|
| 532 |
+
)
|
| 533 |
+
args.ncores_per_instance = [
|
| 534 |
+
len(cores) // args.ninstances
|
| 535 |
+
] * args.ninstances
|
| 536 |
+
elif args.ncores_per_instance != [-1]:
|
| 537 |
+
if args.skip_cross_node_cores:
|
| 538 |
+
utilized_node_cores = (
|
| 539 |
+
self.cpuinfo.node_logical_cores
|
| 540 |
+
if args.use_logical_core
|
| 541 |
+
else self.cpuinfo.node_physical_cores
|
| 542 |
+
)
|
| 543 |
+
ncore_per_node = [len(c) for c in utilized_node_cores]
|
| 544 |
+
if len(args.ncores_per_instance) > len(ncore_per_node):
|
| 545 |
+
# too many ncores_per_instance to skip cross-node cores
|
| 546 |
+
raise ValueError(
|
| 547 |
+
"there are %s nodes, but %s ncores-per-instance elements and \
|
| 548 |
+
--skip-cross-node-cores is specified.",
|
| 549 |
+
len(ncore_per_node),
|
| 550 |
+
len(args.ncores_per_instance),
|
| 551 |
+
)
|
| 552 |
+
leftover_cores = list()
|
| 553 |
+
for i, core_num in enumerate(args.ncores_per_instance):
|
| 554 |
+
leftover_num = core_num - ncore_per_node[i]
|
| 555 |
+
if leftover_num > 0:
|
| 556 |
+
# too many ncores_per_instance for a node
|
| 557 |
+
raise ValueError(
|
| 558 |
+
"there are %s core(s) in node %s, but specified %s cores for \
|
| 559 |
+
this node and --skip-cross-node-cores is specified.",
|
| 560 |
+
ncore_per_node[i],
|
| 561 |
+
i,
|
| 562 |
+
core_num,
|
| 563 |
+
)
|
| 564 |
+
elif leftover_num < 0:
|
| 565 |
+
# Exclude excessive cores from largest core IDs
|
| 566 |
+
leftover_cores.extend(utilized_node_cores[i][leftover_num:])
|
| 567 |
+
# used node num < total node num, mark the rest node cores as unused
|
| 568 |
+
for j in range(i + 1, len(ncore_per_node)):
|
| 569 |
+
leftover_cores.extend(utilized_node_cores[j][:])
|
| 570 |
+
for core_rm in leftover_cores:
|
| 571 |
+
if core_rm in cores:
|
| 572 |
+
cores.remove(core_rm)
|
| 573 |
+
args.ninstances = len(args.ncores_per_instance)
|
| 574 |
+
else:
|
| 575 |
+
if sum(args.ncores_per_instance) > len(cores):
|
| 576 |
+
raise RuntimeError(
|
| 577 |
+
"Please make sure the sum up of ncores_per_instance <= total_cores"
|
| 578 |
+
)
|
| 579 |
+
if args.latency_mode:
|
| 580 |
+
logger.warning(
|
| 581 |
+
"--latency-mode is exclusive to --ninstances, --ncores-per-instance, --node-id and \
|
| 582 |
+
--use-logical-core. They won't take effect even they are set explicitly."
|
| 583 |
+
)
|
| 584 |
+
core_num_per_instance = 4
|
| 585 |
+
cores = list()
|
| 586 |
+
args.ninstances = 0
|
| 587 |
+
if args.skip_cross_node_cores:
|
| 588 |
+
# Per-numa core allocation, the remainder cores are not used
|
| 589 |
+
for node_id, node_core_list in enumerate(
|
| 590 |
+
self.cpuinfo.node_physical_cores
|
| 591 |
+
):
|
| 592 |
+
node_core_num = len(node_core_list)
|
| 593 |
+
for i in range(
|
| 594 |
+
core_num_per_instance,
|
| 595 |
+
node_core_num + 1,
|
| 596 |
+
core_num_per_instance,
|
| 597 |
+
):
|
| 598 |
+
args.ninstances += 1
|
| 599 |
+
cores.extend(node_core_list[i - core_num_per_instance : i])
|
| 600 |
+
if i < node_core_num:
|
| 601 |
+
logger.warning(
|
| 602 |
+
"With --skip-cross-node-cores set, not all the cores on node %d is used \
|
| 603 |
+
because the core number on this node is not dividable by %d.",
|
| 604 |
+
node_id,
|
| 605 |
+
core_num_per_instance,
|
| 606 |
+
)
|
| 607 |
+
args.ncores_per_instance = [core_num_per_instance] * args.ninstances
|
| 608 |
+
else:
|
| 609 |
+
# Compact allocation of all physical cores, regardless of numa
|
| 610 |
+
cores = self.cpuinfo.get_all_physical_cores()
|
| 611 |
+
args.ninstances = len(cores) // core_num_per_instance
|
| 612 |
+
args.ncores_per_instance = [core_num_per_instance] * args.ninstances
|
| 613 |
+
remainder = len(cores) % core_num_per_instance
|
| 614 |
+
if remainder > 0:
|
| 615 |
+
args.ninstances += 1
|
| 616 |
+
args.ncores_per_instance.append(remainder)
|
| 617 |
+
if args.throughput_mode:
|
| 618 |
+
logger.warning(
|
| 619 |
+
"--throughput-mode is exclusive to --ninstances, --ncores-per-instance, --node-id and \
|
| 620 |
+
--use-logical-core. They won't take effect even they are set explicitly."
|
| 621 |
+
)
|
| 622 |
+
args.ninstances = self.cpuinfo.node_nums
|
| 623 |
+
cores = self.cpuinfo.get_all_physical_cores()
|
| 624 |
+
args.ncores_per_instance.clear()
|
| 625 |
+
for node_core_list in self.cpuinfo.node_physical_cores:
|
| 626 |
+
args.ncores_per_instance.append(len(node_core_list))
|
| 627 |
+
|
| 628 |
+
if args.ninstances > 1 and args.rank != -1:
|
| 629 |
+
logger.info(
|
| 630 |
+
"assigning %s cores for instance %s",
|
| 631 |
+
args.ncores_per_instance[args.rank],
|
| 632 |
+
args.rank,
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
if not args.disable_numactl:
|
| 636 |
+
numactl_available = self.is_numactl_available()
|
| 637 |
+
if not numactl_available:
|
| 638 |
+
if not args.disable_taskset:
|
| 639 |
+
logger.warning(
|
| 640 |
+
"Core binding with numactl is not available. Disabling numactl and using taskset instead. \
|
| 641 |
+
This may affect performance in multi-socket system; please use numactl if memory binding is needed."
|
| 642 |
+
)
|
| 643 |
+
args.disable_numactl = True
|
| 644 |
+
enable_taskset = True
|
| 645 |
+
else:
|
| 646 |
+
logger.warning(
|
| 647 |
+
"Core binding with numactl is not available, and --disable_taskset is set. \
|
| 648 |
+
Please unset --disable_taskset to use taskset instead of numactl."
|
| 649 |
+
)
|
| 650 |
+
sys.exit(-1)
|
| 651 |
+
|
| 652 |
+
if not args.disable_taskset:
|
| 653 |
+
enable_taskset = True
|
| 654 |
+
|
| 655 |
+
self.set_multi_thread_and_allocator(
|
| 656 |
+
args.disable_iomp,
|
| 657 |
+
set_kmp_affinity,
|
| 658 |
+
args.enable_tcmalloc,
|
| 659 |
+
args.enable_jemalloc,
|
| 660 |
+
args.use_default_allocator,
|
| 661 |
+
)
|
| 662 |
+
entrypoint = ""
|
| 663 |
+
launch_args = {}
|
| 664 |
+
launch_envs: dict[int, dict] = {}
|
| 665 |
+
launch_tee = {}
|
| 666 |
+
# check whether is launched from torchrun with --nproc-per-node <num workers>
|
| 667 |
+
local_size = int(os.environ.get("LOCAL_WORLD_SIZE", 1))
|
| 668 |
+
local_rank = int(os.environ.get("LOCAL_RANK", 0))
|
| 669 |
+
cores = sorted(cores)
|
| 670 |
+
for i in range(args.ninstances):
|
| 671 |
+
cmd = []
|
| 672 |
+
cur_process_cores = ""
|
| 673 |
+
if not args.disable_numactl or enable_taskset:
|
| 674 |
+
if not args.disable_numactl:
|
| 675 |
+
cmd = ["numactl"]
|
| 676 |
+
elif enable_taskset:
|
| 677 |
+
cmd = ["taskset"]
|
| 678 |
+
core_index_start = 0
|
| 679 |
+
if (
|
| 680 |
+
args.rank == -1
|
| 681 |
+
): # sequentially assign ncores_per_instance to ninstances
|
| 682 |
+
for j in range(i):
|
| 683 |
+
core_index_start += args.ncores_per_instance[j]
|
| 684 |
+
core_list = cores[
|
| 685 |
+
core_index_start : core_index_start
|
| 686 |
+
+ args.ncores_per_instance[i]
|
| 687 |
+
]
|
| 688 |
+
else: # assign ncores_per_instance from rank
|
| 689 |
+
for j in range(args.rank):
|
| 690 |
+
core_index_start += args.ncores_per_instance[j]
|
| 691 |
+
core_list = cores[
|
| 692 |
+
core_index_start : core_index_start
|
| 693 |
+
+ args.ncores_per_instance[args.rank]
|
| 694 |
+
]
|
| 695 |
+
|
| 696 |
+
core_ranges: list[dict] = []
|
| 697 |
+
if local_size > 1:
|
| 698 |
+
total_num_cores = len(core_list)
|
| 699 |
+
cores_per_rank = total_num_cores // local_size
|
| 700 |
+
if cores_per_rank < 1:
|
| 701 |
+
raise AssertionError(
|
| 702 |
+
f"At least one core needs to be assigned to each rank, "
|
| 703 |
+
f"got {total_num_cores} cores for {local_size} ranks"
|
| 704 |
+
)
|
| 705 |
+
core_list = core_list[
|
| 706 |
+
cores_per_rank * local_rank : cores_per_rank * (local_rank + 1)
|
| 707 |
+
]
|
| 708 |
+
for core in core_list:
|
| 709 |
+
if len(core_ranges) == 0:
|
| 710 |
+
range_elem = {"start": core, "end": core}
|
| 711 |
+
core_ranges.append(range_elem)
|
| 712 |
+
else:
|
| 713 |
+
if core - core_ranges[-1]["end"] == 1:
|
| 714 |
+
core_ranges[-1]["end"] = core
|
| 715 |
+
else:
|
| 716 |
+
range_elem = {"start": core, "end": core}
|
| 717 |
+
core_ranges.append(range_elem)
|
| 718 |
+
for r in core_ranges:
|
| 719 |
+
cur_process_cores = f"{cur_process_cores}{r['start']}-{r['end']},"
|
| 720 |
+
cur_process_cores = cur_process_cores[:-1]
|
| 721 |
+
if not args.disable_numactl:
|
| 722 |
+
numa_params = f"-C {cur_process_cores} "
|
| 723 |
+
numa_ids = ",".join(
|
| 724 |
+
[
|
| 725 |
+
str(numa_id)
|
| 726 |
+
for numa_id in self.cpuinfo.numa_aware_check(core_list)
|
| 727 |
+
]
|
| 728 |
+
)
|
| 729 |
+
numa_params += f"-m {numa_ids}"
|
| 730 |
+
cmd.extend(numa_params.split())
|
| 731 |
+
elif enable_taskset:
|
| 732 |
+
taskset_params = f"-c {cur_process_cores} "
|
| 733 |
+
cmd.extend(taskset_params.split())
|
| 734 |
+
with_python = not args.no_python
|
| 735 |
+
if with_python:
|
| 736 |
+
cmd.append(sys.executable)
|
| 737 |
+
cmd.append("-u")
|
| 738 |
+
if args.module:
|
| 739 |
+
cmd.append("-m")
|
| 740 |
+
cmd.append(args.program)
|
| 741 |
+
cmd.extend(args.program_args)
|
| 742 |
+
cmd_s = " ".join(cmd)
|
| 743 |
+
logger.info(cmd_s)
|
| 744 |
+
if entrypoint == "":
|
| 745 |
+
entrypoint = cmd[0]
|
| 746 |
+
del cmd[0]
|
| 747 |
+
launch_args[i] = tuple(cmd)
|
| 748 |
+
# Use user defined OMP_NUM_THREADS if set explicitly in prior
|
| 749 |
+
# Else set it as ncores-per-instance of the current instance
|
| 750 |
+
predef_omp_thr_num = os.environ.get("OMP_NUM_THREADS")
|
| 751 |
+
launch_envs[i] = (
|
| 752 |
+
{"OMP_NUM_THREADS": str(args.ncores_per_instance[i])}
|
| 753 |
+
if predef_omp_thr_num is None
|
| 754 |
+
else {}
|
| 755 |
+
)
|
| 756 |
+
launch_tee[i] = Std.ALL
|
| 757 |
+
|
| 758 |
+
if args.rank != -1: # launches single instance, rank, only
|
| 759 |
+
break
|
| 760 |
+
|
| 761 |
+
ctx = start_processes(
|
| 762 |
+
name=args.log_file_prefix,
|
| 763 |
+
entrypoint=entrypoint,
|
| 764 |
+
args=launch_args,
|
| 765 |
+
envs=launch_envs,
|
| 766 |
+
logs_specs=_DefaultLogsSpecs(log_dir=args.log_path, tee=launch_tee),
|
| 767 |
+
)
|
| 768 |
+
ctx.wait()
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def _add_memory_allocator_params(parser):
|
| 772 |
+
group = parser.add_argument_group("Memory Allocator Parameters")
|
| 773 |
+
# allocator control
|
| 774 |
+
group.add_argument(
|
| 775 |
+
"--enable-tcmalloc",
|
| 776 |
+
"--enable_tcmalloc",
|
| 777 |
+
action="store_true",
|
| 778 |
+
default=False,
|
| 779 |
+
help="Enable tcmalloc allocator",
|
| 780 |
+
)
|
| 781 |
+
group.add_argument(
|
| 782 |
+
"--enable-jemalloc",
|
| 783 |
+
"--enable_jemalloc",
|
| 784 |
+
action="store_true",
|
| 785 |
+
default=False,
|
| 786 |
+
help="Enable jemalloc allocator",
|
| 787 |
+
)
|
| 788 |
+
group.add_argument(
|
| 789 |
+
"--use-default-allocator",
|
| 790 |
+
"--use_default_allocator",
|
| 791 |
+
action="store_true",
|
| 792 |
+
default=False,
|
| 793 |
+
help="Use default memory allocator",
|
| 794 |
+
)
|
| 795 |
+
|
| 796 |
+
|
| 797 |
+
def _add_multi_instance_params(parser):
|
| 798 |
+
group = parser.add_argument_group("Multi-instance Parameters")
|
| 799 |
+
# multi-instance control
|
| 800 |
+
group.add_argument(
|
| 801 |
+
"--ncores-per-instance",
|
| 802 |
+
"--ncores_per_instance",
|
| 803 |
+
metavar="\b",
|
| 804 |
+
default=-1,
|
| 805 |
+
type=int,
|
| 806 |
+
nargs="+",
|
| 807 |
+
help="Cores per instance",
|
| 808 |
+
)
|
| 809 |
+
group.add_argument(
|
| 810 |
+
"--ninstances",
|
| 811 |
+
metavar="\b",
|
| 812 |
+
default=-1,
|
| 813 |
+
type=int,
|
| 814 |
+
help="For multi-instance, you should give the cores number you used for per instance.",
|
| 815 |
+
)
|
| 816 |
+
group.add_argument(
|
| 817 |
+
"--skip-cross-node-cores",
|
| 818 |
+
"--skip_cross_node_cores",
|
| 819 |
+
action="store_true",
|
| 820 |
+
default=False,
|
| 821 |
+
help="If specified --ncores-per-instance, skips cross-node cores.",
|
| 822 |
+
)
|
| 823 |
+
group.add_argument(
|
| 824 |
+
"--rank",
|
| 825 |
+
metavar="\b",
|
| 826 |
+
default="-1",
|
| 827 |
+
type=int,
|
| 828 |
+
help="Specify instance index to assign ncores_per_instance for rank; \
|
| 829 |
+
otherwise ncores_per_instance will be assigned sequentially to ninstances. Please refer to \
|
| 830 |
+
https://github.com/intel/intel-extension-for-pytorch/blob/master/docs/tutorials/performance_tuning/launch_script.md",
|
| 831 |
+
)
|
| 832 |
+
group.add_argument(
|
| 833 |
+
"--latency-mode",
|
| 834 |
+
"--latency_mode",
|
| 835 |
+
action="store_true",
|
| 836 |
+
default=False,
|
| 837 |
+
help="By default 4 core per instance and use all physical cores",
|
| 838 |
+
)
|
| 839 |
+
group.add_argument(
|
| 840 |
+
"--throughput-mode",
|
| 841 |
+
"--throughput_mode",
|
| 842 |
+
action="store_true",
|
| 843 |
+
default=False,
|
| 844 |
+
help="By default one instance per node and use all physical cores",
|
| 845 |
+
)
|
| 846 |
+
group.add_argument(
|
| 847 |
+
"--node-id",
|
| 848 |
+
"--node_id",
|
| 849 |
+
metavar="\b",
|
| 850 |
+
default=-1,
|
| 851 |
+
type=int,
|
| 852 |
+
help="node id for multi-instance, by default all nodes will be used",
|
| 853 |
+
)
|
| 854 |
+
group.add_argument(
|
| 855 |
+
"--use-logical-core",
|
| 856 |
+
"--use_logical_core",
|
| 857 |
+
action="store_true",
|
| 858 |
+
default=False,
|
| 859 |
+
help="Whether only use physical cores",
|
| 860 |
+
)
|
| 861 |
+
group.add_argument(
|
| 862 |
+
"--disable-numactl",
|
| 863 |
+
"--disable_numactl",
|
| 864 |
+
action="store_true",
|
| 865 |
+
default=False,
|
| 866 |
+
help="Disable numactl",
|
| 867 |
+
)
|
| 868 |
+
group.add_argument(
|
| 869 |
+
"--disable-taskset",
|
| 870 |
+
"--disable_taskset",
|
| 871 |
+
action="store_true",
|
| 872 |
+
default=False,
|
| 873 |
+
help="Disable taskset",
|
| 874 |
+
)
|
| 875 |
+
group.add_argument(
|
| 876 |
+
"--core-list",
|
| 877 |
+
"--core_list",
|
| 878 |
+
metavar="\b",
|
| 879 |
+
default=None,
|
| 880 |
+
type=str,
|
| 881 |
+
help='Specify the core list as "core_id, core_id, ....", otherwise, all the cores will be used.',
|
| 882 |
+
)
|
| 883 |
+
group.add_argument(
|
| 884 |
+
"--log-path",
|
| 885 |
+
"--log_path",
|
| 886 |
+
metavar="\b",
|
| 887 |
+
default="",
|
| 888 |
+
type=str,
|
| 889 |
+
help="The log file directory. Default path is "
|
| 890 |
+
", which means disable logging to files.",
|
| 891 |
+
)
|
| 892 |
+
group.add_argument(
|
| 893 |
+
"--log-file-prefix",
|
| 894 |
+
"--log_file_prefix",
|
| 895 |
+
metavar="\b",
|
| 896 |
+
default="run",
|
| 897 |
+
type=str,
|
| 898 |
+
help="log file prefix",
|
| 899 |
+
)
|
| 900 |
+
|
| 901 |
+
|
| 902 |
+
def _add_kmp_iomp_params(parser):
|
| 903 |
+
group = parser.add_argument_group("IOMP Parameters")
|
| 904 |
+
group.add_argument(
|
| 905 |
+
"--disable-iomp",
|
| 906 |
+
"--disable_iomp",
|
| 907 |
+
action="store_true",
|
| 908 |
+
default=False,
|
| 909 |
+
help="By default, we use Intel OpenMP and libiomp5.so will be add to LD_PRELOAD",
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
|
| 913 |
+
def create_args(parser=None):
|
| 914 |
+
"""
|
| 915 |
+
Parse the command line options.
|
| 916 |
+
|
| 917 |
+
@retval ArgumentParser
|
| 918 |
+
"""
|
| 919 |
+
# pyrefly: ignore [missing-attribute]
|
| 920 |
+
parser.add_argument(
|
| 921 |
+
"--multi-instance",
|
| 922 |
+
"--multi_instance",
|
| 923 |
+
action="store_true",
|
| 924 |
+
default=False,
|
| 925 |
+
help="Enable multi-instance, by default one instance per node",
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
# pyrefly: ignore [missing-attribute]
|
| 929 |
+
parser.add_argument(
|
| 930 |
+
"-m",
|
| 931 |
+
"--module",
|
| 932 |
+
default=False,
|
| 933 |
+
action="store_true",
|
| 934 |
+
help="Changes each process to interpret the launch script "
|
| 935 |
+
"as a python module, executing with the same behavior as"
|
| 936 |
+
'"python -m".',
|
| 937 |
+
)
|
| 938 |
+
|
| 939 |
+
# pyrefly: ignore [missing-attribute]
|
| 940 |
+
parser.add_argument(
|
| 941 |
+
"--no-python",
|
| 942 |
+
"--no_python",
|
| 943 |
+
default=False,
|
| 944 |
+
action="store_true",
|
| 945 |
+
help='Do not prepend the --program script with "python" - just exec '
|
| 946 |
+
"it directly. Useful when the script is not a Python script.",
|
| 947 |
+
)
|
| 948 |
+
|
| 949 |
+
_add_memory_allocator_params(parser)
|
| 950 |
+
_add_kmp_iomp_params(parser)
|
| 951 |
+
|
| 952 |
+
_add_multi_instance_params(parser)
|
| 953 |
+
# positional
|
| 954 |
+
# pyrefly: ignore [missing-attribute]
|
| 955 |
+
parser.add_argument(
|
| 956 |
+
"program",
|
| 957 |
+
type=str,
|
| 958 |
+
help="The full path to the program/script to be launched. "
|
| 959 |
+
"followed by all the arguments for the script",
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
# rest from the training program
|
| 963 |
+
# pyrefly: ignore [missing-attribute]
|
| 964 |
+
parser.add_argument("program_args", nargs=REMAINDER)
|
| 965 |
+
|
| 966 |
+
|
| 967 |
+
def main(args):
|
| 968 |
+
env_before = set(os.environ.keys())
|
| 969 |
+
if platform.system() in ["Windows", "Darwin"]:
|
| 970 |
+
raise RuntimeError(f"{platform.system()} is not supported!!!")
|
| 971 |
+
|
| 972 |
+
if args.log_path:
|
| 973 |
+
os.makedirs(args.log_path, exist_ok=True)
|
| 974 |
+
else:
|
| 975 |
+
args.log_path = os.devnull
|
| 976 |
+
|
| 977 |
+
if args.latency_mode and args.throughput_mode:
|
| 978 |
+
raise RuntimeError(
|
| 979 |
+
"Either args.latency_mode or args.throughput_mode should be set"
|
| 980 |
+
)
|
| 981 |
+
|
| 982 |
+
if not args.no_python and not args.program.endswith(".py"):
|
| 983 |
+
raise RuntimeError(
|
| 984 |
+
'For non Python script, you should use "--no-python" parameter.'
|
| 985 |
+
)
|
| 986 |
+
|
| 987 |
+
# Verify LD_PRELOAD
|
| 988 |
+
if "LD_PRELOAD" in os.environ:
|
| 989 |
+
lst_valid = []
|
| 990 |
+
tmp_ldpreload = os.environ["LD_PRELOAD"]
|
| 991 |
+
for item in tmp_ldpreload.split(":"):
|
| 992 |
+
matches = glob.glob(item)
|
| 993 |
+
if len(matches) > 0:
|
| 994 |
+
lst_valid.append(item)
|
| 995 |
+
else:
|
| 996 |
+
logger.warning("%s doesn't exist. Removing it from LD_PRELOAD.", item)
|
| 997 |
+
if len(lst_valid) > 0:
|
| 998 |
+
os.environ["LD_PRELOAD"] = ":".join(lst_valid)
|
| 999 |
+
else:
|
| 1000 |
+
os.environ["LD_PRELOAD"] = ""
|
| 1001 |
+
|
| 1002 |
+
launcher = _Launcher()
|
| 1003 |
+
launcher.launch(args)
|
| 1004 |
+
for x in sorted(set(os.environ.keys()) - env_before):
|
| 1005 |
+
logger.debug("%s=%s", x, os.environ[x])
|
| 1006 |
+
|
| 1007 |
+
|
| 1008 |
+
if __name__ == "__main__":
|
| 1009 |
+
parser = ArgumentParser(
|
| 1010 |
+
description="This is a script for launching PyTorch inference on Intel(R) Xeon(R) Scalable "
|
| 1011 |
+
"Processors with optimal configurations. Single instance inference, "
|
| 1012 |
+
"multi-instance inference are enable. To get the peak performance on Intel(R) "
|
| 1013 |
+
"Xeon(R) Scalable Processors, the script optimizes the configuration "
|
| 1014 |
+
"of thread and memory management. For thread management, the script configures thread "
|
| 1015 |
+
"affinity and the preload of Intel OMP library. For memory management, it configures "
|
| 1016 |
+
"NUMA binding and preload optimized memory allocation library (e.g. tcmalloc, jemalloc) "
|
| 1017 |
+
"\n################################# Basic usage ############################# \n"
|
| 1018 |
+
"\n 1. single instance\n"
|
| 1019 |
+
"\n >>> python -m torch.backends.xeon.run_cpu python_script args \n"
|
| 1020 |
+
"\n2. multi-instance \n"
|
| 1021 |
+
"\n >>> python -m torch.backends.xeon.run_cpu --ninstances xxx "
|
| 1022 |
+
"--ncores-per-instance xx python_script args\n"
|
| 1023 |
+
"\n############################################################################# \n",
|
| 1024 |
+
formatter_class=RawTextHelpFormatter,
|
| 1025 |
+
)
|
| 1026 |
+
create_args(parser)
|
| 1027 |
+
args = parser.parse_args()
|
| 1028 |
+
main(args)
|
.venv/lib/python3.12/site-packages/torch/backends/xnnpack/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# mypy: allow-untyped-defs
|
| 2 |
+
import sys
|
| 3 |
+
import types
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class _XNNPACKEnabled:
|
| 9 |
+
def __get__(self, obj, objtype):
|
| 10 |
+
return torch._C._is_xnnpack_enabled()
|
| 11 |
+
|
| 12 |
+
def __set__(self, obj, val):
|
| 13 |
+
raise RuntimeError("Assignment not supported")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class XNNPACKEngine(types.ModuleType):
|
| 17 |
+
def __init__(self, m, name):
|
| 18 |
+
super().__init__(name)
|
| 19 |
+
self.m = m
|
| 20 |
+
|
| 21 |
+
def __getattr__(self, attr):
|
| 22 |
+
return self.m.__getattribute__(attr)
|
| 23 |
+
|
| 24 |
+
enabled = _XNNPACKEnabled()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
# This is the sys.modules replacement trick, see
|
| 28 |
+
# https://stackoverflow.com/questions/2447353/getattr-on-a-module/7668273#7668273
|
| 29 |
+
sys.modules[__name__] = XNNPACKEngine(sys.modules[__name__], __name__)
|
.venv/lib/python3.12/site-packages/torch/backends/xnnpack/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.71 kB). View file
|
|
|
.venv/lib/python3.12/site-packages/torch/bin/FileStoreTest
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ae4c542a0d5d348da76f4c30101d7fdcb97751119ca5c69d288e85ed3cb7497
|
| 3 |
+
size 623896
|
.venv/lib/python3.12/site-packages/torch/bin/HashStoreTest
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a31476781197a2bd434f659316b8ca878324366236a12281a13e808588e3fc62
|
| 3 |
+
size 629792
|
.venv/lib/python3.12/site-packages/torch/bin/TCPStoreTest
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a1d18dd894ae438f20946dfdb3c10f30652fc8552857194f0a5a30b5b07cd5de
|
| 3 |
+
size 687304
|
.venv/lib/python3.12/site-packages/torch/bin/protoc
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:866a9e66a42b2764b5f9d60bcb5e9fbd370a9bbc9fc0a1621cd54d245ce6e703
|
| 3 |
+
size 5463672
|