nvmath-python 0.9.0__cp314-cp314-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nvmath/__init__.pxd +0 -0
- nvmath/__init__.py +45 -0
- nvmath/_internal/__init__.py +0 -0
- nvmath/_internal/attribute_ifc_factory.py +330 -0
- nvmath/_internal/layout.py +70 -0
- nvmath/_internal/templates.py +383 -0
- nvmath/_utils.py +150 -0
- nvmath/bindings/__init__.py +51 -0
- nvmath/bindings/_internal/__init__.pxd +0 -0
- nvmath/bindings/_internal/__init__.py +0 -0
- nvmath/bindings/_internal/cublas.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/cublas.pxd +530 -0
- nvmath/bindings/_internal/cublasLt.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/cublasLt.pxd +59 -0
- nvmath/bindings/_internal/cublasMp.pxd +52 -0
- nvmath/bindings/_internal/cudss.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/cudss.pxd +47 -0
- nvmath/bindings/_internal/cufft.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/cufft.pxd +70 -0
- nvmath/bindings/_internal/cufftMp.pxd +77 -0
- nvmath/bindings/_internal/curand.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/curand.pxd +42 -0
- nvmath/bindings/_internal/cusolver.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/cusolver.pxd +15 -0
- nvmath/bindings/_internal/cusolverDn.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/cusolverDn.pxd +406 -0
- nvmath/bindings/_internal/cusparse.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/cusparse.pxd +277 -0
- nvmath/bindings/_internal/cusparseLt.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/cusparseLt.pxd +48 -0
- nvmath/bindings/_internal/cutensor.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/cutensor.pxd +58 -0
- nvmath/bindings/_internal/mathdx.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/mathdx.pxd +116 -0
- nvmath/bindings/_internal/nvshmem.pxd +29 -0
- nvmath/bindings/_internal/utils.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/_internal/utils.pxd +179 -0
- nvmath/bindings/_internal/utils.pyi +10 -0
- nvmath/bindings/cublas.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cublas.pxd +558 -0
- nvmath/bindings/cublas.pyi +746 -0
- nvmath/bindings/cublasLt.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cublasLt.pxd +109 -0
- nvmath/bindings/cublasLt.pyi +1337 -0
- nvmath/bindings/cublasMp.pxd +85 -0
- nvmath/bindings/cublasMp.pyi +219 -0
- nvmath/bindings/cudss.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cudss.pxd +86 -0
- nvmath/bindings/cudss.pyi +282 -0
- nvmath/bindings/cufft.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cufft.pxd +118 -0
- nvmath/bindings/cufft.pyi +241 -0
- nvmath/bindings/cufftMp.pxd +124 -0
- nvmath/bindings/cufftMp.pyi +260 -0
- nvmath/bindings/curand.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/curand.pxd +71 -0
- nvmath/bindings/curand.pyi +159 -0
- nvmath/bindings/cusolver.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cusolver.pxd +62 -0
- nvmath/bindings/cusolver.pyi +242 -0
- nvmath/bindings/cusolverDn.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cusolverDn.pxd +430 -0
- nvmath/bindings/cusolverDn.pyi +416 -0
- nvmath/bindings/cusparse.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cusparse.pxd +338 -0
- nvmath/bindings/cusparse.pyi +659 -0
- nvmath/bindings/cusparseLt.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cusparseLt.pxd +99 -0
- nvmath/bindings/cusparseLt.pyi +198 -0
- nvmath/bindings/cutensor.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cutensor.pxd +98 -0
- nvmath/bindings/cutensor.pyi +294 -0
- nvmath/bindings/cycublas.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cycublas.pxd +684 -0
- nvmath/bindings/cycublasLt.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cycublasLt.pxd +1055 -0
- nvmath/bindings/cycublasMp.pxd +183 -0
- nvmath/bindings/cycudss.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cycudss.pxd +224 -0
- nvmath/bindings/cycufft.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cycufft.pxd +326 -0
- nvmath/bindings/cycufftMp.pxd +334 -0
- nvmath/bindings/cycurand.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cycurand.pxd +146 -0
- nvmath/bindings/cycusolver.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cycusolver.pxd +154 -0
- nvmath/bindings/cycusolverDn.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cycusolverDn.pxd +446 -0
- nvmath/bindings/cycusparse.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cycusparse.pxd +470 -0
- nvmath/bindings/cycusparseLt.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cycusparseLt.pxd +150 -0
- nvmath/bindings/cycutensor.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cycutensor.pxd +192 -0
- nvmath/bindings/cymathdx.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/cymathdx.pxd +552 -0
- nvmath/bindings/cynvshmem.pxd +126 -0
- nvmath/bindings/mathdx.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/mathdx.pxd +182 -0
- nvmath/bindings/mathdx.pyi +1244 -0
- nvmath/bindings/nvpl/__init__.pxd +0 -0
- nvmath/bindings/nvpl/__init__.py +13 -0
- nvmath/bindings/nvpl/_internal/__init__.pxd +0 -0
- nvmath/bindings/nvpl/_internal/__init__.py +0 -0
- nvmath/bindings/nvpl/_internal/blas.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/nvpl/_internal/blas.pxd +125 -0
- nvmath/bindings/nvpl/_internal/fft.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/nvpl/_internal/fft.pxd +36 -0
- nvmath/bindings/nvpl/blas.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/nvpl/blas.pxd +85 -0
- nvmath/bindings/nvpl/blas.pyi +122 -0
- nvmath/bindings/nvpl/cyblas.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/nvpl/cyblas.pxd +166 -0
- nvmath/bindings/nvpl/cyfft.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/nvpl/cyfft.pxd +92 -0
- nvmath/bindings/nvpl/fft.cp314-win_amd64.pyd +0 -0
- nvmath/bindings/nvpl/fft.pxd +100 -0
- nvmath/bindings/nvpl/fft.pyi +100 -0
- nvmath/bindings/nvshmem.pxd +54 -0
- nvmath/bindings/nvshmem.pyi +179 -0
- nvmath/device/__init__.py +21 -0
- nvmath/device/_deprecated.py +33 -0
- nvmath/device/common.py +313 -0
- nvmath/device/common_backend.py +131 -0
- nvmath/device/common_cuda.py +201 -0
- nvmath/device/common_numba.py +310 -0
- nvmath/device/common_opaque_tensor.py +201 -0
- nvmath/device/cublasdx.py +1805 -0
- nvmath/device/cublasdx_backend.py +807 -0
- nvmath/device/cublasdx_numba.py +1612 -0
- nvmath/device/cufftdx.py +510 -0
- nvmath/device/cufftdx_backend.py +196 -0
- nvmath/device/cufftdx_numba.py +196 -0
- nvmath/device/curand_kernel.py +9147 -0
- nvmath/device/cusolverdx.py +2690 -0
- nvmath/device/cusolverdx_backend.py +440 -0
- nvmath/device/cusolverdx_numba.py +1624 -0
- nvmath/device/llvm_array.py +29 -0
- nvmath/device/random.py +445 -0
- nvmath/device/random_helpers.py +23 -0
- nvmath/device/random_states.py +187 -0
- nvmath/device/types.py +147 -0
- nvmath/device/vector_types_numba.py +203 -0
- nvmath/distributed/__init__.py +205 -0
- nvmath/distributed/_internal/__init__.py +0 -0
- nvmath/distributed/_internal/nvshmem.py +302 -0
- nvmath/distributed/_internal/tensor_ifc.py +67 -0
- nvmath/distributed/_internal/tensor_ifc_cupy.py +62 -0
- nvmath/distributed/_internal/tensor_ifc_host_device.py +165 -0
- nvmath/distributed/_internal/tensor_ifc_numpy.py +41 -0
- nvmath/distributed/_internal/tensor_ifc_torch.py +141 -0
- nvmath/distributed/_internal/tensor_wrapper.py +78 -0
- nvmath/distributed/_utils.py +167 -0
- nvmath/distributed/distribution.py +770 -0
- nvmath/distributed/fft/__init__.py +7 -0
- nvmath/distributed/fft/_configuration.py +79 -0
- nvmath/distributed/fft/fft.py +2801 -0
- nvmath/distributed/linalg/__init__.py +12 -0
- nvmath/distributed/linalg/_internal/__init__.py +3 -0
- nvmath/distributed/linalg/_internal/epilog_protocol.py +496 -0
- nvmath/distributed/linalg/_internal/matmul_desc_ifc.py +28 -0
- nvmath/distributed/linalg/advanced/__init__.py +8 -0
- nvmath/distributed/linalg/advanced/_configuration.py +166 -0
- nvmath/distributed/linalg/advanced/matmulmod.py +2908 -0
- nvmath/distributed/process_group.py +408 -0
- nvmath/distributed/reshape/__init__.py +6 -0
- nvmath/distributed/reshape/_configuration.py +39 -0
- nvmath/distributed/reshape/reshape.py +1256 -0
- nvmath/fft/__init__.py +7 -0
- nvmath/fft/_configuration.py +208 -0
- nvmath/fft/_exec_utils.py +109 -0
- nvmath/fft/_helpers.py +237 -0
- nvmath/fft/fft.py +2903 -0
- nvmath/internal/__init__.pxd +3 -0
- nvmath/internal/__init__.py +10 -0
- nvmath/internal/_bindings.cp314-win_amd64.pyd +0 -0
- nvmath/internal/_bindings.pxd +12 -0
- nvmath/internal/_device_utils.py +54 -0
- nvmath/internal/enum_utils.py +142 -0
- nvmath/internal/formatters.py +87 -0
- nvmath/internal/mem_limit.py +51 -0
- nvmath/internal/memory.cp314-win_amd64.pyd +0 -0
- nvmath/internal/memory.pxd +10 -0
- nvmath/internal/memory.pyi +46 -0
- nvmath/internal/ndbuffer/__init__.pxd +3 -0
- nvmath/internal/ndbuffer/__init__.py +7 -0
- nvmath/internal/ndbuffer/copy_kernel/args.h +34 -0
- nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/array_view.h +52 -0
- nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/elementwise.h +68 -0
- nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/grid_indexer.h +69 -0
- nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/transposed.h +240 -0
- nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/type_utils.h +39 -0
- nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/utils.h +132 -0
- nvmath/internal/ndbuffer/copy_kernel/copy_kernel_impl/vec.h +159 -0
- nvmath/internal/ndbuffer/copy_kernel/elementwise.h +53 -0
- nvmath/internal/ndbuffer/copy_kernel/transposed.h +58 -0
- nvmath/internal/ndbuffer/copy_kernel.cp314-win_amd64.pyd +0 -0
- nvmath/internal/ndbuffer/copy_kernel.pxd +9 -0
- nvmath/internal/ndbuffer/copy_kernel.pyi +9 -0
- nvmath/internal/ndbuffer/data_layout.cp314-win_amd64.pyd +0 -0
- nvmath/internal/ndbuffer/data_layout.pxd +72 -0
- nvmath/internal/ndbuffer/data_layout.pyi +23 -0
- nvmath/internal/ndbuffer/jit.cp314-win_amd64.pyd +0 -0
- nvmath/internal/ndbuffer/jit.pxd +7 -0
- nvmath/internal/ndbuffer/jit.pyi +6 -0
- nvmath/internal/ndbuffer/ndbuffer.cp314-win_amd64.pyd +0 -0
- nvmath/internal/ndbuffer/ndbuffer.pxd +36 -0
- nvmath/internal/ndbuffer/ndbuffer.pyi +41 -0
- nvmath/internal/ndbuffer/package_utils.cp314-win_amd64.pyd +0 -0
- nvmath/internal/ndbuffer/package_utils.pxd +11 -0
- nvmath/internal/ndbuffer/package_utils.pyi +12 -0
- nvmath/internal/package_ifc.py +147 -0
- nvmath/internal/package_ifc_cuda.py +49 -0
- nvmath/internal/package_ifc_cupy.py +49 -0
- nvmath/internal/package_ifc_torch.py +31 -0
- nvmath/internal/package_wrapper.py +14 -0
- nvmath/internal/tensor_ifc.py +194 -0
- nvmath/internal/tensor_ifc_cupy.py +241 -0
- nvmath/internal/tensor_ifc_ndbuffer.py +153 -0
- nvmath/internal/tensor_ifc_numpy.py +183 -0
- nvmath/internal/tensor_ifc_torch.py +176 -0
- nvmath/internal/tensor_wrapper.py +157 -0
- nvmath/internal/typemaps.py +162 -0
- nvmath/internal/utils.py +771 -0
- nvmath/linalg/__init__.py +46 -0
- nvmath/linalg/_internal/__init__.py +3 -0
- nvmath/linalg/_internal/algo_cap_ifc.py +82 -0
- nvmath/linalg/_internal/algo_config_ifc.py +43 -0
- nvmath/linalg/_internal/batch.py +217 -0
- nvmath/linalg/_internal/enum_to_tuples.py +64 -0
- nvmath/linalg/_internal/epilog_protocol.py +766 -0
- nvmath/linalg/_internal/layout.py +624 -0
- nvmath/linalg/_internal/matmul_desc_ifc.py +28 -0
- nvmath/linalg/_internal/matmul_pref_ifc.py +27 -0
- nvmath/linalg/_internal/matrix_layout_ifc.py +26 -0
- nvmath/linalg/_internal/typemaps.py +144 -0
- nvmath/linalg/_internal/utils.py +134 -0
- nvmath/linalg/advanced/__init__.py +8 -0
- nvmath/linalg/advanced/_algorithmmod.py +149 -0
- nvmath/linalg/advanced/_configuration.py +349 -0
- nvmath/linalg/advanced/helpers/__init__.py +5 -0
- nvmath/linalg/advanced/helpers/matmul.py +1348 -0
- nvmath/linalg/advanced/matmulmod.py +3937 -0
- nvmath/linalg/generic/__init__.py +43 -0
- nvmath/linalg/generic/_configuration/__init__.py +37 -0
- nvmath/linalg/generic/_configuration/layout.py +263 -0
- nvmath/linalg/generic/_configuration/match.py +609 -0
- nvmath/linalg/generic/_configuration/qualifiers.py +494 -0
- nvmath/linalg/generic/_configuration/wrap.py +217 -0
- nvmath/linalg/generic/_dtype.py +15 -0
- nvmath/linalg/generic/matmulmod.py +1060 -0
- nvmath/memory.py +282 -0
- nvmath/sparse/__init__.py +38 -0
- nvmath/sparse/_internal/__init__.py +21 -0
- nvmath/sparse/_internal/common_utils.py +144 -0
- nvmath/sparse/_internal/cudss_config_ifc.py +741 -0
- nvmath/sparse/_internal/cudss_data_ifc.py +399 -0
- nvmath/sparse/_internal/cudss_utils.py +445 -0
- nvmath/sparse/_internal/cusparse_utils.py +382 -0
- nvmath/sparse/_internal/sparse_bsc_ifc.py +300 -0
- nvmath/sparse/_internal/sparse_bsr_ifc.py +303 -0
- nvmath/sparse/_internal/sparse_coo_ifc.py +254 -0
- nvmath/sparse/_internal/sparse_csc_ifc.py +266 -0
- nvmath/sparse/_internal/sparse_csr_ifc.py +266 -0
- nvmath/sparse/_internal/sparse_dia_ifc.py +239 -0
- nvmath/sparse/_internal/sparse_format_helpers.py +601 -0
- nvmath/sparse/_internal/sparse_tensor_ifc.py +121 -0
- nvmath/sparse/_internal/sparse_ust_ifc.py +146 -0
- nvmath/sparse/_internal/utils.py +56 -0
- nvmath/sparse/advanced/__init__.py +7 -0
- nvmath/sparse/advanced/_configuration.py +230 -0
- nvmath/sparse/advanced/direct_solver.py +1884 -0
- nvmath/sparse/generic/__init__.py +7 -0
- nvmath/sparse/generic/_configuration.py +129 -0
- nvmath/sparse/generic/_helpers.py +137 -0
- nvmath/sparse/generic/_thunks.py +21 -0
- nvmath/sparse/generic/matmulmod.py +2426 -0
- nvmath/sparse/ust/__init__.py +7 -0
- nvmath/sparse/ust/_converters.py +378 -0
- nvmath/sparse/ust/_drawer.py +552 -0
- nvmath/sparse/ust/_emitter.py +553 -0
- nvmath/sparse/ust/_jit.py +212 -0
- nvmath/sparse/ust/_kernel.py +346 -0
- nvmath/sparse/ust/_semiring.py +71 -0
- nvmath/sparse/ust/_utils.py +102 -0
- nvmath/sparse/ust/interfaces/__init__.py +0 -0
- nvmath/sparse/ust/interfaces/torch_interface.py +476 -0
- nvmath/sparse/ust/semiring_ops.py +71 -0
- nvmath/sparse/ust/tensor.py +1027 -0
- nvmath/sparse/ust/tensor_drawer.py +552 -0
- nvmath/sparse/ust/tensor_emitter.py +558 -0
- nvmath/sparse/ust/tensor_format.py +935 -0
- nvmath/sparse/ust/tensor_jit.py +212 -0
- nvmath/sparse/ust/tensor_kernel.py +348 -0
- nvmath/sparse/ust/tensor_utils.py +380 -0
- nvmath/tensor/__init__.py +6 -0
- nvmath/tensor/_configuration.py +95 -0
- nvmath/tensor/_internal/__init__.py +3 -0
- nvmath/tensor/_internal/cutensor_config_ifc.py +247 -0
- nvmath/tensor/_internal/cutensor_utils.py +162 -0
- nvmath/tensor/_internal/data.py +43 -0
- nvmath/tensor/_internal/einsum_parser.py +444 -0
- nvmath/tensor/_internal/typemaps.py +96 -0
- nvmath/tensor/contract.py +1861 -0
- nvmath_python-0.9.0.dist-info/METADATA +127 -0
- nvmath_python-0.9.0.dist-info/RECORD +309 -0
- nvmath_python-0.9.0.dist-info/WHEEL +5 -0
- nvmath_python-0.9.0.dist-info/licenses/LICENSE +177 -0
- nvmath_python-0.9.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,1256 @@
|
|
|
1
|
+
# Copyright (c) 2025-2026, NVIDIA CORPORATION & AFFILIATES. ALL RIGHTS RESERVED.
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
|
|
5
|
+
__all__ = ["Reshape", "reshape"]
|
|
6
|
+
|
|
7
|
+
import logging
|
|
8
|
+
import math
|
|
9
|
+
from collections.abc import Sequence
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from typing import Final, Literal, cast
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
import nvmath.distributed
|
|
16
|
+
from nvmath.bindings import (
|
|
17
|
+
cufftMp, # type: ignore
|
|
18
|
+
nvshmem, # type: ignore
|
|
19
|
+
)
|
|
20
|
+
from nvmath.distributed._internal import tensor_wrapper
|
|
21
|
+
from nvmath.distributed._internal.nvshmem import NvshmemMemoryManager
|
|
22
|
+
from nvmath.distributed._internal.tensor_ifc import DistributedTensor
|
|
23
|
+
from nvmath.distributed.distribution import Box
|
|
24
|
+
from nvmath.internal import formatters, utils
|
|
25
|
+
from nvmath.internal.package_wrapper import AnyStream, StreamHolder
|
|
26
|
+
|
|
27
|
+
from ._configuration import ReshapeOptions
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class TensorLayout:
|
|
32
|
+
"""An internal data class for capturing the tensor layout."""
|
|
33
|
+
|
|
34
|
+
shape: Sequence[int]
|
|
35
|
+
strides: Sequence[int]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass
|
|
39
|
+
class _ProblemSpec:
|
|
40
|
+
"""This is used in a custom reduction to check that the Reshape problem specification
|
|
41
|
+
is consistent across processes, and to infer global information (e.g shape and memory
|
|
42
|
+
layout)."""
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class Options:
|
|
46
|
+
"""
|
|
47
|
+
This is used for _ProblemSpec instead of ._configuration.ReshapeOptions
|
|
48
|
+
because it's going to be serialized as part of the custom reduction of the
|
|
49
|
+
_ProblemSpec, and we want to control which fields are included (for example
|
|
50
|
+
we don't need the logger).
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, options: ReshapeOptions):
|
|
54
|
+
self.blocking = options.blocking
|
|
55
|
+
|
|
56
|
+
blocking: Literal[True, "auto"]
|
|
57
|
+
|
|
58
|
+
shape: tuple[int, ...] # operand shape
|
|
59
|
+
is_F: bool # Is Fortran memory layout
|
|
60
|
+
is_C: bool # Is C memory layout
|
|
61
|
+
operand_dtype: str # str because TensorHolder.dtype returns str
|
|
62
|
+
package: Literal["numpy", "cupy", "torch"] # operand package
|
|
63
|
+
memory_space: Literal["cuda", "cpu"] # operand memory space
|
|
64
|
+
boxes: list[Box] # Reshape input and output box
|
|
65
|
+
options: Options # Reshape options
|
|
66
|
+
|
|
67
|
+
# Global number of elements in the operand (calculated as part of the reduction).
|
|
68
|
+
global_size: int = 0
|
|
69
|
+
# is_leaf=True means that this is the _ProblemSpec of a process before reducing
|
|
70
|
+
# with that of another process.
|
|
71
|
+
is_leaf: bool = True
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
SHARED_RESHAPE_DOCUMENTATION = utils.COMMON_SHARED_DOC_MAP.copy()
|
|
75
|
+
SHARED_RESHAPE_DOCUMENTATION.update(
|
|
76
|
+
{
|
|
77
|
+
"operand": SHARED_RESHAPE_DOCUMENTATION["operand"],
|
|
78
|
+
#
|
|
79
|
+
"operand_admonitions": """
|
|
80
|
+
.. important::
|
|
81
|
+
GPU operands must be on the symmetric heap (for example, allocated with
|
|
82
|
+
``nvmath.distributed.allocate_symmetric_memory()``).
|
|
83
|
+
""",
|
|
84
|
+
#
|
|
85
|
+
"options": """\
|
|
86
|
+
Specify options for the Reshape as a :class:`ReshapeOptions` object. Alternatively, a `dict` containing the parameters for the
|
|
87
|
+
``ReshapeOptions`` constructor can also be provided. If not specified, the value will be set to the default-constructed
|
|
88
|
+
``ReshapeOptions`` object.""".replace("\n", " "),
|
|
89
|
+
#
|
|
90
|
+
"input_box": """\
|
|
91
|
+
The box specifying the distribution of the input operand across processes, where each process
|
|
92
|
+
specifies which portion of the global array it holds. A box is a pair of coordinates specifying
|
|
93
|
+
the lower and upper extent for each dimension.""".replace("\n", " "),
|
|
94
|
+
#
|
|
95
|
+
"output_box": """\
|
|
96
|
+
The box specifying the distribution of the result across processes, where each process
|
|
97
|
+
specifies which portion of the global array it will hold after reshaping. A box is a pair
|
|
98
|
+
of coordinates specifying the lower and upper extent for each dimension.""".replace("\n", " "),
|
|
99
|
+
#
|
|
100
|
+
"sync_symmetric_memory": """\
|
|
101
|
+
Indicates whether to issue a symmetric memory synchronization operation on the execute stream
|
|
102
|
+
before the reshape operation. Note that before the Reshape starts executing, it is
|
|
103
|
+
required that the source operand be ready on all processes. A symmetric memory synchronization
|
|
104
|
+
ensures completion and visibility by all processes of previously issued local stores to
|
|
105
|
+
symmetric memory. Advanced users who choose to manage the synchronization on their own using
|
|
106
|
+
the appropriate NVSHMEM API, or who know that GPUs are already synchronized on the source
|
|
107
|
+
operand, can set this to False.""".replace("\n", " "),
|
|
108
|
+
#
|
|
109
|
+
"function_signature": """\
|
|
110
|
+
operand,
|
|
111
|
+
input_box: Box,
|
|
112
|
+
output_box: Box,
|
|
113
|
+
sync_symmetric_memory: bool = True,
|
|
114
|
+
options: ReshapeOptions | None = None,
|
|
115
|
+
stream: AnyStream | None = None
|
|
116
|
+
""".replace("\n", " "),
|
|
117
|
+
}
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _calculate_strides(shape, axis_order):
|
|
122
|
+
"""
|
|
123
|
+
Calculate the strides for the provided shape and axis order.
|
|
124
|
+
"""
|
|
125
|
+
strides = [None] * len(shape)
|
|
126
|
+
|
|
127
|
+
stride = 1
|
|
128
|
+
for axis in axis_order:
|
|
129
|
+
strides[axis] = stride
|
|
130
|
+
stride *= shape[axis]
|
|
131
|
+
|
|
132
|
+
return strides
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _copy_operand_perhaps(
|
|
136
|
+
operand: DistributedTensor,
|
|
137
|
+
stream_holder,
|
|
138
|
+
execution_space,
|
|
139
|
+
memory_space,
|
|
140
|
+
device_id: int | Literal["cpu"],
|
|
141
|
+
):
|
|
142
|
+
if execution_space == memory_space:
|
|
143
|
+
return operand, None
|
|
144
|
+
else:
|
|
145
|
+
# Copy the `operand` to memory that matches the exec space.
|
|
146
|
+
# Currently, reshape only runs on GPU.
|
|
147
|
+
assert execution_space == "cuda"
|
|
148
|
+
exec_space_copy = operand.to(device_id, stream_holder, symmetric_memory=True)
|
|
149
|
+
return exec_space_copy, operand
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _problem_spec_reducer(p1: _ProblemSpec, p2: _ProblemSpec):
|
|
153
|
+
try:
|
|
154
|
+
if isinstance(p1, Exception):
|
|
155
|
+
return p1 # propagate exception
|
|
156
|
+
|
|
157
|
+
if isinstance(p2, Exception):
|
|
158
|
+
return p2 # propagate exception
|
|
159
|
+
|
|
160
|
+
if len(p1.shape) != len(p2.shape):
|
|
161
|
+
return ValueError("The number of dimensions of the input operand is inconsistent across processes")
|
|
162
|
+
|
|
163
|
+
if len(p1.shape) <= 0 or len(p1.shape) > 3:
|
|
164
|
+
return ValueError(
|
|
165
|
+
"Reshape currently only supports 1-D, 2-D and 3-D tensors."
|
|
166
|
+
f" The number of dimensions of the operand is {len(p1.shape)}."
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
if p1.operand_dtype != p2.operand_dtype:
|
|
170
|
+
return ValueError("The operand dtype is inconsistent across processes")
|
|
171
|
+
|
|
172
|
+
if p1.package != p2.package:
|
|
173
|
+
return ValueError("operand doesn't belong to the same package on all processes")
|
|
174
|
+
|
|
175
|
+
if p1.memory_space != p2.memory_space:
|
|
176
|
+
return ValueError('operand is not on the same memory space ("cpu", "cuda") on all processes')
|
|
177
|
+
|
|
178
|
+
if p1.options != p2.options:
|
|
179
|
+
return ValueError(f"options are inconsistent across processes: {p1.options} != {p2.options}")
|
|
180
|
+
|
|
181
|
+
# Determine the memory layout shared by all processes. Note that it's possible for
|
|
182
|
+
# a process to have both C and F layout (e.g. (2, 1) input shape).
|
|
183
|
+
p1.is_C &= p2.is_C
|
|
184
|
+
p1.is_F &= p2.is_F
|
|
185
|
+
if not p1.is_F and not p1.is_C:
|
|
186
|
+
return ValueError("The input memory layout is not C or Fortran, or is inconsistent across processes")
|
|
187
|
+
|
|
188
|
+
for p_spec in (p1, p2):
|
|
189
|
+
if p_spec.is_leaf:
|
|
190
|
+
for box in p_spec.boxes:
|
|
191
|
+
if not isinstance(box, Box):
|
|
192
|
+
return ValueError(f"{box} is not a Box distribution")
|
|
193
|
+
if box.ndim != len(p_spec.shape):
|
|
194
|
+
return ValueError(
|
|
195
|
+
f"The dimensionality of {box} doesn't match the dimensionality of "
|
|
196
|
+
f"the reshape operand ({len(p_spec.shape)})"
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
if p1 is not p2: # with nranks=1 p1 is p2
|
|
200
|
+
p1.global_size += p2.global_size
|
|
201
|
+
|
|
202
|
+
def reduce_boxes(box1, box2):
|
|
203
|
+
"""This function returns the smallest box that encompasses `box1` and `box2`"""
|
|
204
|
+
lower = np.minimum(np.array(box1.lower), np.array(box2.lower)).tolist()
|
|
205
|
+
upper = np.maximum(np.array(box1.upper), np.array(box2.upper)).tolist()
|
|
206
|
+
return Box(lower, upper)
|
|
207
|
+
|
|
208
|
+
# Merge the boxes to get the global operand shape. Note that this is applied
|
|
209
|
+
# progressively throughout the reduction, starting with the local boxes.
|
|
210
|
+
p1.boxes = [reduce_boxes(p1.boxes[0], p2.boxes[0]), reduce_boxes(p1.boxes[1], p2.boxes[1])]
|
|
211
|
+
|
|
212
|
+
except Exception as e:
|
|
213
|
+
return e
|
|
214
|
+
p1.is_leaf = False
|
|
215
|
+
return p1
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
class InvalidReshapeState(Exception):
|
|
219
|
+
pass
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@utils.docstring_decorator(SHARED_RESHAPE_DOCUMENTATION, skip_missing=False)
|
|
223
|
+
class Reshape:
|
|
224
|
+
"""
|
|
225
|
+
Create a stateful object that encapsulates the specified distributed Reshape
|
|
226
|
+
and required resources. This object ensures the validity of resources during use and
|
|
227
|
+
releases them when they are no longer needed to prevent misuse.
|
|
228
|
+
|
|
229
|
+
This object encompasses all functionalities of the function-form API :func:`reshape`,
|
|
230
|
+
which is a convenience wrapper around it. The stateful object also allows for the
|
|
231
|
+
amortization of preparatory costs when the same Reshape operation is to be performed
|
|
232
|
+
on multiple operands with the same problem specification (see :meth:`reset_operand`
|
|
233
|
+
for more details).
|
|
234
|
+
|
|
235
|
+
Using the stateful object typically involves the following steps:
|
|
236
|
+
|
|
237
|
+
1. **Problem Specification**: Initialize the object with a defined operation and
|
|
238
|
+
options.
|
|
239
|
+
2. **Preparation**: Use :meth:`plan` to determine the best distributed algorithmic
|
|
240
|
+
implementation for this specific Reshape operation.
|
|
241
|
+
3. **Execution**: Perform the Reshape with :meth:`execute`.
|
|
242
|
+
4. **Resource Management**: Ensure all resources are released either by explicitly
|
|
243
|
+
calling :meth:`free` or by managing the stateful object within a context manager.
|
|
244
|
+
|
|
245
|
+
Detailed information on each step described above can be obtained by passing in a
|
|
246
|
+
:class:`logging.Logger` object to :class:`ReshapeOptions` or by setting the appropriate
|
|
247
|
+
options in the root logger object, which is used by default:
|
|
248
|
+
|
|
249
|
+
>>> import logging
|
|
250
|
+
>>> logging.basicConfig(
|
|
251
|
+
... level=logging.INFO,
|
|
252
|
+
... format="%(asctime)s %(levelname)-8s %(message)s",
|
|
253
|
+
... datefmt="%m-%d %H:%M:%S",
|
|
254
|
+
... )
|
|
255
|
+
|
|
256
|
+
Args:
|
|
257
|
+
operand: {operand}
|
|
258
|
+
{operand_admonitions}
|
|
259
|
+
|
|
260
|
+
input_box: {input_box}
|
|
261
|
+
|
|
262
|
+
output_box: {output_box}
|
|
263
|
+
|
|
264
|
+
options: {options}
|
|
265
|
+
|
|
266
|
+
stream: {stream}
|
|
267
|
+
|
|
268
|
+
.. seealso::
|
|
269
|
+
:meth:`plan`, :meth:`reset_operand`, :meth:`execute`,
|
|
270
|
+
:meth:`release_operand`
|
|
271
|
+
|
|
272
|
+
Examples:
|
|
273
|
+
|
|
274
|
+
>>> import cupy as cp
|
|
275
|
+
>>> import nvmath.distributed
|
|
276
|
+
|
|
277
|
+
Get process group used to initialize nvmath.distributed (for information on
|
|
278
|
+
initializing nvmath.distributed, you can refer to the documentation or to the
|
|
279
|
+
Reshape examples in `nvmath/examples/distributed/reshape
|
|
280
|
+
<https://github.com/NVIDIA/nvmath-python/tree/main/examples/distributed/reshape>`_):
|
|
281
|
+
|
|
282
|
+
>>> process_group = nvmath.distributed.get_context().process_group
|
|
283
|
+
|
|
284
|
+
Let's create a 3D floating-point ndarray on GPU, distributed across a certain number
|
|
285
|
+
of processes, with each holding a portion of the ndarray. As an example, process 0
|
|
286
|
+
holds a 3D box of the global 3D array of shape (4, 4, 4).
|
|
287
|
+
|
|
288
|
+
>>> shape = 4, 4, 4
|
|
289
|
+
|
|
290
|
+
Reshape uses the NVSHMEM PGAS model, which requires GPU operands to be on the
|
|
291
|
+
symmetric heap:
|
|
292
|
+
|
|
293
|
+
>>> if process_group.rank == 0:
|
|
294
|
+
... a[:] = cp.random.rand(*shape)
|
|
295
|
+
... else:
|
|
296
|
+
... a = ... # each process holds a different section of the global array.
|
|
297
|
+
... a = nvmath.distributed.allocate_symmetric_memory(shape, cp)
|
|
298
|
+
|
|
299
|
+
With Reshape, we will change how the ndarray is distributed, by having each
|
|
300
|
+
process specify the input and output section of the global array. For process 0,
|
|
301
|
+
let's assume that it holds the 3D box that goes from the lower corner given by
|
|
302
|
+
coordinates (0, 0, 0) to the upper corner (4, 4, 4).
|
|
303
|
+
|
|
304
|
+
NOTE: each process has its own input and output boxes which are different to those
|
|
305
|
+
of other processes, as each holds a different section of the global array.
|
|
306
|
+
|
|
307
|
+
>>> from nvmath.distributed.distribution import Box
|
|
308
|
+
>>> if process_group.rank == 0:
|
|
309
|
+
... input_lower = (0, 0, 0)
|
|
310
|
+
... input_upper = (4, 4, 4)
|
|
311
|
+
... input_box = Box(input_lower, input_upper)
|
|
312
|
+
... output_box = ...
|
|
313
|
+
... else:
|
|
314
|
+
... input_box = ... # the input box depends on the process.
|
|
315
|
+
... output_box = ... # the output box depends on the process.
|
|
316
|
+
|
|
317
|
+
Create a Reshape object encapsulating the problem specification above:
|
|
318
|
+
|
|
319
|
+
>>> r = nvmath.distributed.reshape.Reshape(a, input_box, output_box)
|
|
320
|
+
|
|
321
|
+
Options can be provided above to control the behavior of the operation using the
|
|
322
|
+
`options` argument (see :class:`ReshapeOptions`).
|
|
323
|
+
|
|
324
|
+
Next, plan the Reshape:
|
|
325
|
+
|
|
326
|
+
>>> r.plan()
|
|
327
|
+
|
|
328
|
+
Now execute the Reshape, and obtain the result `b` as a CuPy ndarray. Reshape always
|
|
329
|
+
performs the distributed operation on the GPU.
|
|
330
|
+
|
|
331
|
+
>>> b = r.execute()
|
|
332
|
+
|
|
333
|
+
Finally, free the Reshape object's resources. To avoid this explicit call, it's
|
|
334
|
+
recommended to use the Reshape object as a context manager as shown below, if
|
|
335
|
+
possible.
|
|
336
|
+
|
|
337
|
+
>>> r.free()
|
|
338
|
+
|
|
339
|
+
Any symmetric memory that is owned by the user must be deleted explicitly (this is
|
|
340
|
+
a collective call and must be called by all processes):
|
|
341
|
+
|
|
342
|
+
>>> nvmath.distributed.free_symmetric_memory(a, b)
|
|
343
|
+
|
|
344
|
+
Note that all :class:`Reshape` methods execute on the current stream by default.
|
|
345
|
+
Alternatively, the `stream` argument can be used to run a method on a specified
|
|
346
|
+
stream.
|
|
347
|
+
|
|
348
|
+
Let's now look at the same problem with NumPy ndarrays on the CPU.
|
|
349
|
+
|
|
350
|
+
>>> import numpy as np
|
|
351
|
+
>>> a = np.random.rand(*shape) # each process holds a different section
|
|
352
|
+
|
|
353
|
+
Create a Reshape object encapsulating the problem specification described earlier
|
|
354
|
+
and use it as a context manager.
|
|
355
|
+
|
|
356
|
+
>>> with nvmath.distributed.reshape.Reshape(a, input_box, output_box) as r:
|
|
357
|
+
... r.plan()
|
|
358
|
+
...
|
|
359
|
+
... # Execute the Reshape to redistribute the ndarray.
|
|
360
|
+
... b = r.execute()
|
|
361
|
+
|
|
362
|
+
All the resources used by the object are released at the end of the block.
|
|
363
|
+
|
|
364
|
+
Reshape always executes on the GPU. In this case, because ``a`` resides in host
|
|
365
|
+
memory, the NumPy array is temporarily copied to device memory (on the symmetric
|
|
366
|
+
memory heap), re-distributed on the GPU, and the result is copied to host memory
|
|
367
|
+
as a NumPy array.
|
|
368
|
+
|
|
369
|
+
Further examples can be found in the `nvmath/examples/distributed/reshape
|
|
370
|
+
<https://github.com/NVIDIA/nvmath-python/tree/main/examples/distributed/reshape>`_
|
|
371
|
+
directory.
|
|
372
|
+
"""
|
|
373
|
+
|
|
374
|
+
def _free_internal_sheap(self, exception: Exception | None = None) -> bool:
|
|
375
|
+
# This is a fail-safe to free NVSHMEM internal memory in case of invalid
|
|
376
|
+
# state (Reshape constructor fails). Since we might call nvshmem_free here, we're
|
|
377
|
+
# assuming that all processes equally failed in the ctor, which might not be true,
|
|
378
|
+
# but if it weren't true they would end up in deadlock most likely anyway.
|
|
379
|
+
if (
|
|
380
|
+
hasattr(self, "memory_space")
|
|
381
|
+
and self.memory_space == "cpu"
|
|
382
|
+
and self.operand is not None
|
|
383
|
+
and self.operand.device == "cuda"
|
|
384
|
+
):
|
|
385
|
+
with utils.device_ctx(self.device_id):
|
|
386
|
+
self.operand.free_symmetric()
|
|
387
|
+
return True
|
|
388
|
+
|
|
389
|
+
@utils.atomic(_free_internal_sheap, method=True)
|
|
390
|
+
def __init__(
|
|
391
|
+
self,
|
|
392
|
+
operand,
|
|
393
|
+
/,
|
|
394
|
+
input_box: Box,
|
|
395
|
+
output_box: Box,
|
|
396
|
+
*,
|
|
397
|
+
options: ReshapeOptions | None = None,
|
|
398
|
+
stream: AnyStream | None = None,
|
|
399
|
+
):
|
|
400
|
+
distributed_ctx = nvmath.distributed.get_context()
|
|
401
|
+
if distributed_ctx is None:
|
|
402
|
+
raise RuntimeError(
|
|
403
|
+
"nvmath.distributed has not been initialized. Refer to "
|
|
404
|
+
"https://docs.nvidia.com/cuda/nvmath-python/latest/distributed-apis/runtime.html"
|
|
405
|
+
" for more information."
|
|
406
|
+
)
|
|
407
|
+
if not distributed_ctx.nvshmem_available:
|
|
408
|
+
raise RuntimeError("nvmath.distributed wasn't initialized with NVSHMEM backend")
|
|
409
|
+
self.process_group = distributed_ctx.process_group
|
|
410
|
+
nranks = self.process_group.nranks
|
|
411
|
+
|
|
412
|
+
self.operand = operand = tensor_wrapper.wrap_operand(operand)
|
|
413
|
+
self.options = options = cast(
|
|
414
|
+
ReshapeOptions, utils.check_or_create_options(ReshapeOptions, options, "Distributed Reshape options")
|
|
415
|
+
)
|
|
416
|
+
self.package = operand.name
|
|
417
|
+
|
|
418
|
+
is_C = sorted(operand.strides, reverse=True) == list(operand.strides)
|
|
419
|
+
is_F = sorted(operand.strides) == list(operand.strides)
|
|
420
|
+
|
|
421
|
+
input_box = cast(Box, input_box.copy())
|
|
422
|
+
output_box = cast(Box, output_box.copy())
|
|
423
|
+
|
|
424
|
+
# Merge the problem specification across processes to make sure that there are no
|
|
425
|
+
# inconsistencies and to calculate the global shape. Importantly, this also does
|
|
426
|
+
# collective error checking of the Reshape input parameters, to ensure that all
|
|
427
|
+
# processes fail on error of any one process, thus preventing deadlock.
|
|
428
|
+
problem_spec = _ProblemSpec(
|
|
429
|
+
boxes=[input_box, output_box],
|
|
430
|
+
shape=tuple(operand.shape),
|
|
431
|
+
operand_dtype=operand.dtype,
|
|
432
|
+
options=_ProblemSpec.Options(options),
|
|
433
|
+
package=self.package,
|
|
434
|
+
memory_space=operand.device,
|
|
435
|
+
global_size=math.prod(operand.shape),
|
|
436
|
+
is_C=is_C,
|
|
437
|
+
is_F=is_F,
|
|
438
|
+
)
|
|
439
|
+
if nranks > 1:
|
|
440
|
+
problem_spec = self.process_group.allreduce_object(problem_spec, op=_problem_spec_reducer)
|
|
441
|
+
else:
|
|
442
|
+
# Ensure we error-check with one rank.
|
|
443
|
+
problem_spec = _problem_spec_reducer(problem_spec, problem_spec)
|
|
444
|
+
if isinstance(problem_spec, Exception):
|
|
445
|
+
# There is an error or inconsistency in the problem spec across processes.
|
|
446
|
+
# Note that since this comes from an allreduce, all processes will have
|
|
447
|
+
# received the same exception.
|
|
448
|
+
raise problem_spec
|
|
449
|
+
|
|
450
|
+
if problem_spec.is_C:
|
|
451
|
+
self.layout: Final = "C"
|
|
452
|
+
else:
|
|
453
|
+
assert problem_spec.is_F, "Internal Error." # The reducer is supposed to have detected this
|
|
454
|
+
self.layout: Final = "F" # type: ignore
|
|
455
|
+
|
|
456
|
+
self.operand_dim = len(operand.shape)
|
|
457
|
+
|
|
458
|
+
self.logger = options.logger if options.logger is not None else logging.getLogger()
|
|
459
|
+
|
|
460
|
+
# The merged (global) input and output box must be the same.
|
|
461
|
+
if problem_spec.boxes[0] != problem_spec.boxes[1]:
|
|
462
|
+
raise ValueError(
|
|
463
|
+
"The global box derived from the input and output boxes doesn't match: "
|
|
464
|
+
f"{problem_spec.boxes[0]} != {problem_spec.boxes[1]}"
|
|
465
|
+
)
|
|
466
|
+
|
|
467
|
+
# Infer the global shape from the global input box. Note that cuFFTMp does not
|
|
468
|
+
# disallow lower coordinates for the merged (global) boxes that are not 0.
|
|
469
|
+
lower, upper = problem_spec.boxes[0]
|
|
470
|
+
global_shape = tuple(int(upper[i] - lower[i]) for i in range(self.operand_dim))
|
|
471
|
+
self.logger.info(f"The global shape of the operand is {global_shape}.")
|
|
472
|
+
|
|
473
|
+
# This can't throw error since the local operand shape was already checked
|
|
474
|
+
# against the box shape in the ProblemSpec reducer.
|
|
475
|
+
input_box._bind(global_shape, shape=operand.shape)
|
|
476
|
+
|
|
477
|
+
# The global number of elements must be compatible with the global shape.
|
|
478
|
+
if problem_spec.global_size != math.prod(global_shape):
|
|
479
|
+
raise ValueError(f"The global number of elements is incompatible with the inferred global shape {global_shape}")
|
|
480
|
+
|
|
481
|
+
# Store the local input and output box.
|
|
482
|
+
self.input_box: Box = input_box
|
|
483
|
+
self.output_box: Box = output_box
|
|
484
|
+
|
|
485
|
+
self.operand_data_type = operand.dtype
|
|
486
|
+
# TODO: change to `operand.dtype.itemsize` once operand is StridedMemoryView.
|
|
487
|
+
itemsize = operand.itemsize
|
|
488
|
+
if itemsize not in (4, 8, 16):
|
|
489
|
+
raise ValueError(
|
|
490
|
+
f"Reshape only supports element sizes in (4, 8, 16) bytes. The operand's element size is {itemsize}"
|
|
491
|
+
)
|
|
492
|
+
|
|
493
|
+
self.logger.info(f"The Reshape data type is {self.operand_data_type}.")
|
|
494
|
+
|
|
495
|
+
# Infer execution and memory space.
|
|
496
|
+
execution_device_id: int = distributed_ctx.device_id
|
|
497
|
+
if operand.device_id != "cpu": # exec space matches the mem space
|
|
498
|
+
self.memory_space = "cuda"
|
|
499
|
+
self.device_id = operand.device_id
|
|
500
|
+
assert operand.device_id == execution_device_id
|
|
501
|
+
else: # we need to move inputs cpu -> gpu and outputs gpu -> cpu
|
|
502
|
+
self.memory_space = "cpu"
|
|
503
|
+
self.device_id = execution_device_id
|
|
504
|
+
self.execution_space = "cuda"
|
|
505
|
+
self.operand_device_id = operand.device_id
|
|
506
|
+
self.internal_op_package = self._internal_operand_package(self.package)
|
|
507
|
+
stream_holder: StreamHolder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
|
|
508
|
+
|
|
509
|
+
if self.memory_space == "cuda" and not operand.is_symmetric_memory:
|
|
510
|
+
raise TypeError("Distributed reshape requires GPU operand to be on symmetric memory")
|
|
511
|
+
|
|
512
|
+
self.logger.info(
|
|
513
|
+
f"The input tensor's memory space is {self.memory_space}, and the execution space "
|
|
514
|
+
f"is {self.execution_space}, with device {self.device_id}."
|
|
515
|
+
)
|
|
516
|
+
|
|
517
|
+
self.logger.info(f"The specified stream for the Reshape ctor is {stream_holder and stream_holder.obj}")
|
|
518
|
+
|
|
519
|
+
# Copy the operand to execution_space's device if needed.
|
|
520
|
+
self.operand, self.operand_backup = _copy_operand_perhaps(
|
|
521
|
+
operand,
|
|
522
|
+
stream_holder,
|
|
523
|
+
self.execution_space,
|
|
524
|
+
self.memory_space,
|
|
525
|
+
self.device_id,
|
|
526
|
+
)
|
|
527
|
+
operand = self.operand
|
|
528
|
+
# Capture operand layout for consistency checks when resetting operands.
|
|
529
|
+
self.operand_layout = TensorLayout(shape=operand.shape, strides=operand.strides)
|
|
530
|
+
|
|
531
|
+
self.result_layout: TensorLayout | None = None
|
|
532
|
+
# We'll infer the result layout at plan time.
|
|
533
|
+
self.result_class: DistributedTensor = operand.__class__
|
|
534
|
+
self.result_data_type = operand.dtype
|
|
535
|
+
|
|
536
|
+
# Set blocking or non-blocking behavior.
|
|
537
|
+
self.blocking = self.options.blocking is True or self.memory_space == "cpu"
|
|
538
|
+
if self.blocking:
|
|
539
|
+
self.call_prologue = "This call is blocking and will return only after the operation is complete."
|
|
540
|
+
else:
|
|
541
|
+
self.call_prologue = (
|
|
542
|
+
"This call is non-blocking and will return immediately after the operation is launched on the device."
|
|
543
|
+
)
|
|
544
|
+
|
|
545
|
+
# Set memory allocator.
|
|
546
|
+
self.allocator = NvshmemMemoryManager(self.device_id, self.logger)
|
|
547
|
+
|
|
548
|
+
# Create handle.
|
|
549
|
+
with utils.device_ctx(self.device_id):
|
|
550
|
+
self.handle = cufftMp.create_reshape()
|
|
551
|
+
|
|
552
|
+
self.reshape_planned = False
|
|
553
|
+
|
|
554
|
+
# Workspace attributes.
|
|
555
|
+
self.workspace_ptr, self.workspace_size = None, None
|
|
556
|
+
self._workspace_allocated_here = False
|
|
557
|
+
|
|
558
|
+
# Attributes to establish stream ordering.
|
|
559
|
+
self.workspace_stream = None
|
|
560
|
+
self.last_compute_event = None
|
|
561
|
+
|
|
562
|
+
# Track whether the user has called release_operand(). This flag is
|
|
563
|
+
# checked in _check_valid_operand to prevent execution after the user
|
|
564
|
+
# has released their operand. It is cleared by reset_operand().
|
|
565
|
+
self._operand_released = False
|
|
566
|
+
|
|
567
|
+
self.valid_state = True
|
|
568
|
+
self.logger.info("The distributed Reshape operation has been created.")
|
|
569
|
+
|
|
570
|
+
def __enter__(self):
|
|
571
|
+
return self
|
|
572
|
+
|
|
573
|
+
def __exit__(self, exc_type, exc_value, traceback):
|
|
574
|
+
self.free()
|
|
575
|
+
|
|
576
|
+
def _check_valid_reshape(self, *args, **kwargs):
|
|
577
|
+
"""
|
|
578
|
+
Check if Reshape object is alive and well.
|
|
579
|
+
"""
|
|
580
|
+
if not self.valid_state:
|
|
581
|
+
raise InvalidReshapeState("The Reshape object cannot be used after resources are free'd")
|
|
582
|
+
|
|
583
|
+
def _free_plan_resources(self, exception: Exception | None = None) -> bool:
|
|
584
|
+
"""
|
|
585
|
+
Free resources allocated in planning.
|
|
586
|
+
"""
|
|
587
|
+
self.reshape_planned = False
|
|
588
|
+
return True
|
|
589
|
+
|
|
590
|
+
def _internal_operand_package(self, package_name):
|
|
591
|
+
return package_name if package_name != "numpy" else "cuda"
|
|
592
|
+
|
|
593
|
+
def _allocate_result_operand(self, exec_stream_holder, log_debug):
|
|
594
|
+
if log_debug:
|
|
595
|
+
self.logger.debug("Beginning output (empty) tensor creation...")
|
|
596
|
+
self.logger.debug(
|
|
597
|
+
f"The output tensor shape = {self.result_layout.shape} with strides = "
|
|
598
|
+
f"{self.result_layout.strides} and data type '{self.result_data_type}'."
|
|
599
|
+
)
|
|
600
|
+
result = utils.create_empty_tensor(
|
|
601
|
+
self.result_class,
|
|
602
|
+
self.result_layout.shape,
|
|
603
|
+
self.result_data_type,
|
|
604
|
+
self.device_id,
|
|
605
|
+
exec_stream_holder,
|
|
606
|
+
verify_strides=False,
|
|
607
|
+
strides=self.result_layout.strides,
|
|
608
|
+
symmetric_memory=True,
|
|
609
|
+
make_symmetric=True,
|
|
610
|
+
logger=self.logger,
|
|
611
|
+
)
|
|
612
|
+
if log_debug:
|
|
613
|
+
self.logger.debug("The output (empty) tensor has been created.")
|
|
614
|
+
return result
|
|
615
|
+
|
|
616
|
+
@utils.precondition(_check_valid_reshape)
|
|
617
|
+
@utils.atomic(_free_plan_resources, method=True)
|
|
618
|
+
def plan(self, stream: AnyStream | None = None):
|
|
619
|
+
"""Plan the Reshape.
|
|
620
|
+
|
|
621
|
+
Args:
|
|
622
|
+
stream: {stream}
|
|
623
|
+
"""
|
|
624
|
+
log_info = self.logger.isEnabledFor(logging.INFO)
|
|
625
|
+
|
|
626
|
+
if self.reshape_planned:
|
|
627
|
+
self.logger.debug("The Reshape has already been planned, and redoing the plan is not supported.")
|
|
628
|
+
return
|
|
629
|
+
|
|
630
|
+
stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
|
|
631
|
+
self.workspace_stream = stream_holder.obj
|
|
632
|
+
|
|
633
|
+
if log_info:
|
|
634
|
+
self.logger.info("Starting distributed Reshape planning...")
|
|
635
|
+
|
|
636
|
+
lower_input, upper_input = self.input_box
|
|
637
|
+
lower_output, upper_output = self.output_box
|
|
638
|
+
|
|
639
|
+
def calculate_reshape_params(lower, upper, operand, order: Literal["C", "F"]):
|
|
640
|
+
"""Calculate shape and strides for input or output of Reshape."""
|
|
641
|
+
local_shape = tuple(upper[i] - lower[i] for i in range(self.operand_dim))
|
|
642
|
+
if operand is not None:
|
|
643
|
+
# Take the strides from the operand.
|
|
644
|
+
strides = operand.strides
|
|
645
|
+
elif order == "F":
|
|
646
|
+
# This is out=None with F layout.
|
|
647
|
+
strides = _calculate_strides(local_shape, range(self.operand_dim))
|
|
648
|
+
else:
|
|
649
|
+
# This is out=None with C layout.
|
|
650
|
+
strides = _calculate_strides(local_shape, reversed(range(self.operand_dim)))
|
|
651
|
+
return local_shape, strides
|
|
652
|
+
|
|
653
|
+
input_local_shape, strides_input = calculate_reshape_params(lower_input, upper_input, self.operand, self.layout)
|
|
654
|
+
output_local_shape, strides_output = calculate_reshape_params(lower_output, upper_output, None, self.layout)
|
|
655
|
+
self.result_layout = TensorLayout(shape=output_local_shape, strides=strides_output)
|
|
656
|
+
|
|
657
|
+
if self.operand_dim < 3:
|
|
658
|
+
# cufftMp.make_reshape only supports 3D, so we broadcast the local operands.
|
|
659
|
+
N = 3 - self.operand_dim
|
|
660
|
+
lower_input = tuple(lower_input) + (0,) * N
|
|
661
|
+
upper_input = tuple(upper_input) + (1,) * N
|
|
662
|
+
lower_output = tuple(lower_output) + (0,) * N
|
|
663
|
+
upper_output = tuple(upper_output) + (1,) * N
|
|
664
|
+
|
|
665
|
+
strides_input = self.operand.reshape(input_local_shape + (1,) * N, copy=False).strides
|
|
666
|
+
if self.layout == "F":
|
|
667
|
+
strides_output = _calculate_strides(output_local_shape + (1,) * N, (0, 1, 2))
|
|
668
|
+
else:
|
|
669
|
+
strides_output = _calculate_strides(output_local_shape + (1,) * N, (2, 1, 0))
|
|
670
|
+
|
|
671
|
+
# cuFFTMp only supports decreasing strides. To support increasing strides, we'll
|
|
672
|
+
# pass the required metadata to cuFFTMp with axes transposed (but won't touch
|
|
673
|
+
# the data).
|
|
674
|
+
if self.layout == "F":
|
|
675
|
+
lower_input = tuple(reversed(lower_input))
|
|
676
|
+
upper_input = tuple(reversed(upper_input))
|
|
677
|
+
strides_input = tuple(reversed(strides_input))
|
|
678
|
+
lower_output = tuple(reversed(lower_output))
|
|
679
|
+
upper_output = tuple(reversed(upper_output))
|
|
680
|
+
strides_output = tuple(reversed(strides_output))
|
|
681
|
+
|
|
682
|
+
with utils.host_call_ctx(timing=log_info) as elapsed, utils.device_ctx(self.device_id):
|
|
683
|
+
nullptr = 0
|
|
684
|
+
cufftMp.make_reshape(
|
|
685
|
+
self.handle,
|
|
686
|
+
# TODO: change to `operand.dtype.itemsize` once operand is StridedMemoryView
|
|
687
|
+
self.operand.itemsize,
|
|
688
|
+
3,
|
|
689
|
+
lower_input,
|
|
690
|
+
upper_input,
|
|
691
|
+
strides_input,
|
|
692
|
+
lower_output,
|
|
693
|
+
upper_output,
|
|
694
|
+
strides_output,
|
|
695
|
+
nullptr,
|
|
696
|
+
cufftMp.MpCommType.COMM_NONE,
|
|
697
|
+
)
|
|
698
|
+
self.workspace_size = cufftMp.get_reshape_size(self.handle)
|
|
699
|
+
|
|
700
|
+
self.reshape_planned = True
|
|
701
|
+
|
|
702
|
+
if log_info and elapsed.data is not None:
|
|
703
|
+
self.logger.info(f"The Reshape planning phase took {elapsed.data:.3f} ms to complete.")
|
|
704
|
+
|
|
705
|
+
@utils.precondition(_check_valid_reshape)
|
|
706
|
+
def reset_operand(self, operand, *, stream: AnyStream | None = None):
|
|
707
|
+
"""
|
|
708
|
+
Reset the operand held by this :class:`Reshape` instance. This method is used
|
|
709
|
+
to provide a new operand for execution.
|
|
710
|
+
|
|
711
|
+
Args:
|
|
712
|
+
operand: A tensor (ndarray-like object) compatible with the previous one.
|
|
713
|
+
The new operand is considered compatible if all the following properties
|
|
714
|
+
match with the previous one:
|
|
715
|
+
|
|
716
|
+
- The operand distribution, which must be (input_box, output_box)
|
|
717
|
+
where input_box and output_box are the boxes specified at plan time.
|
|
718
|
+
- The package that the new operand belongs to.
|
|
719
|
+
- The dtype of the new operand.
|
|
720
|
+
- The shape and strides of the new operand.
|
|
721
|
+
- The memory space of the new operand (CPU or GPU).
|
|
722
|
+
- The device that new operand belongs to if it is on GPU.
|
|
723
|
+
|
|
724
|
+
stream: {stream}
|
|
725
|
+
|
|
726
|
+
.. seealso::
|
|
727
|
+
:meth:`release_operand`
|
|
728
|
+
|
|
729
|
+
Examples:
|
|
730
|
+
|
|
731
|
+
>>> import cupy as cp
|
|
732
|
+
>>> import nvmath.distributed
|
|
733
|
+
|
|
734
|
+
Get process group used to initialize nvmath.distributed (for information on
|
|
735
|
+
initializing nvmath.distributed, you can refer to the documentation or to the
|
|
736
|
+
Reshape examples in `nvmath/examples/distributed/reshape
|
|
737
|
+
<https://github.com/NVIDIA/nvmath-python/tree/main/examples/distributed/reshape>`_):
|
|
738
|
+
|
|
739
|
+
>>> process_group = nvmath.distributed.get_context().process_group
|
|
740
|
+
>>> nranks = process_group.nranks
|
|
741
|
+
|
|
742
|
+
Create a 3-D complex128 ndarray on GPU symmetric memory, initially partitioned
|
|
743
|
+
on the X axis (the global shape is (128, 128, 128)):
|
|
744
|
+
|
|
745
|
+
>>> shape = 128 // nranks, 128, 128
|
|
746
|
+
>>> dtype = cp.complex128
|
|
747
|
+
>>> a = nvmath.distributed.allocate_symmetric_memory(shape, cp, dtype=dtype)
|
|
748
|
+
>>> a[:] = cp.random.rand(*shape) + 1j * cp.random.rand(*shape)
|
|
749
|
+
|
|
750
|
+
Compute the input and output box for the desired re-distribution:
|
|
751
|
+
|
|
752
|
+
>>> input_box = ...
|
|
753
|
+
>>> output_box = ...
|
|
754
|
+
|
|
755
|
+
Create a Reshape object as a context manager
|
|
756
|
+
|
|
757
|
+
>>> with nvmath.distributed.reshape.Reshape(a, input_box, output_box) as f:
|
|
758
|
+
... # Plan the Reshape
|
|
759
|
+
... r.plan()
|
|
760
|
+
...
|
|
761
|
+
... # Execute the Reshape to get the first result.
|
|
762
|
+
... r1 = r.execute()
|
|
763
|
+
...
|
|
764
|
+
... # Reset the operand to a new CuPy ndarray.
|
|
765
|
+
... b = nvmath.distributed.allocate_symmetric_memory(shape, cp, dtype=dtype)
|
|
766
|
+
... b[:] = cp.random.rand(*shape) + 1j * cp.random.rand(*shape)
|
|
767
|
+
... f.reset_operand(b)
|
|
768
|
+
...
|
|
769
|
+
... # Execute to get the new result corresponding to the updated operand.
|
|
770
|
+
... r2 = f.execute()
|
|
771
|
+
|
|
772
|
+
With :meth:`reset_operand`, minimal overhead is achieved as problem
|
|
773
|
+
specification and planning are only performed once.
|
|
774
|
+
|
|
775
|
+
For the particular example above, explicitly calling :meth:`reset_operand` is
|
|
776
|
+
equivalent to updating the operand in-place, i.e, replacing
|
|
777
|
+
``f.reset_operand(b)`` with ``a[:]=b``. Note that updating the operand in-place
|
|
778
|
+
should be adopted with caution as it can only yield the expected result and
|
|
779
|
+
incur no additional copies under the additional constraints below:
|
|
780
|
+
|
|
781
|
+
- The operand's distribution is the same.
|
|
782
|
+
|
|
783
|
+
For more details, please refer to `inplace update example
|
|
784
|
+
<https://github.com/NVIDIA/nvmath-python/tree/main/examples/distributed/reshape/example05_stateful_reset_inplace.py>`_.
|
|
785
|
+
"""
|
|
786
|
+
|
|
787
|
+
if operand is None:
|
|
788
|
+
raise ValueError("Resetting operand requires a valid operand. Use release_operand() to release the operand.")
|
|
789
|
+
|
|
790
|
+
self.logger.info("Resetting operand...")
|
|
791
|
+
# First wrap operand.
|
|
792
|
+
operand = tensor_wrapper.wrap_operand(operand)
|
|
793
|
+
|
|
794
|
+
# Check package match.
|
|
795
|
+
package = utils.infer_object_package(operand.tensor)
|
|
796
|
+
if self.package != package:
|
|
797
|
+
message = f"Library package mismatch: '{self.package}' => '{package}'"
|
|
798
|
+
raise TypeError(message)
|
|
799
|
+
|
|
800
|
+
# Check the dtype.
|
|
801
|
+
utils.check_attribute_match(self.operand_data_type, operand.dtype, "data type")
|
|
802
|
+
|
|
803
|
+
stream_holder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
|
|
804
|
+
self.logger.info(f"The specified stream for reset_operand() is {stream_holder and stream_holder.obj}.")
|
|
805
|
+
|
|
806
|
+
# In principle, we could support memory_space change,
|
|
807
|
+
# but to handle it properly we need to update self.memory_space and
|
|
808
|
+
# some dependent properties, like self.blocking, which may be error-prone
|
|
809
|
+
# from the user perspective. It would prevent inplace optimizations as well.
|
|
810
|
+
operand_device_id = operand.device_id
|
|
811
|
+
if operand_device_id != self.operand_device_id:
|
|
812
|
+
|
|
813
|
+
def device_str(device_id: int | Literal["cpu"]) -> str:
|
|
814
|
+
return f"cuda:{device_id}" if isinstance(device_id, int) else f"{device_id}"
|
|
815
|
+
|
|
816
|
+
raise ValueError(
|
|
817
|
+
f"The new operand must be on the same device as the original one. "
|
|
818
|
+
f"The new operand's device is {device_str(operand_device_id)}, "
|
|
819
|
+
f"the original device is {device_str(self.operand_device_id)}"
|
|
820
|
+
)
|
|
821
|
+
|
|
822
|
+
if self.memory_space == "cuda" and not operand.is_symmetric_memory:
|
|
823
|
+
raise TypeError("Distributed reshape requires GPU operand to be on symmetric memory")
|
|
824
|
+
|
|
825
|
+
# The plan was made for a specific input box and strides, so the new operand must
|
|
826
|
+
# match.
|
|
827
|
+
if operand.shape != self.operand_layout.shape:
|
|
828
|
+
raise ValueError(
|
|
829
|
+
f"The shape of the new operand ({operand.shape}) does not match "
|
|
830
|
+
f"the original shape ({self.operand_layout.shape})."
|
|
831
|
+
)
|
|
832
|
+
if operand.strides != self.operand_layout.strides:
|
|
833
|
+
raise ValueError(
|
|
834
|
+
f"The strides of the new operand ({operand.strides}) do not match "
|
|
835
|
+
f"the original strides ({self.operand_layout.strides})."
|
|
836
|
+
)
|
|
837
|
+
self.logger.info(f"The reset operand shape = {self.operand_layout.shape}, and strides = {self.operand_layout.strides}.")
|
|
838
|
+
|
|
839
|
+
if self.memory_space == "cpu":
|
|
840
|
+
if self.operand is not None:
|
|
841
|
+
self.operand.copy_(operand, stream_holder=stream_holder)
|
|
842
|
+
self.operand_backup = operand
|
|
843
|
+
else:
|
|
844
|
+
self.operand, self.operand_backup = _copy_operand_perhaps(
|
|
845
|
+
operand,
|
|
846
|
+
stream_holder,
|
|
847
|
+
self.execution_space,
|
|
848
|
+
self.memory_space,
|
|
849
|
+
self.device_id,
|
|
850
|
+
)
|
|
851
|
+
else:
|
|
852
|
+
self.operand = operand
|
|
853
|
+
|
|
854
|
+
self._operand_released = False
|
|
855
|
+
|
|
856
|
+
self.logger.info("The operand has been reset to the specified operand.")
|
|
857
|
+
|
|
858
|
+
@utils.precondition(_check_valid_reshape)
|
|
859
|
+
def release_operand(self):
|
|
860
|
+
"""
|
|
861
|
+
{release_operand}
|
|
862
|
+
"""
|
|
863
|
+
if self._operand_released:
|
|
864
|
+
self.logger.info("Operand has already been released; nothing to do.")
|
|
865
|
+
return
|
|
866
|
+
|
|
867
|
+
if self.memory_space == self.execution_space:
|
|
868
|
+
# Same-space (GPU input): self.operand is the user's tensor.
|
|
869
|
+
self.operand = None
|
|
870
|
+
else:
|
|
871
|
+
# Cross-space (CPU input): self.operand_backup is the user's tensor,
|
|
872
|
+
# self.operand is an internal nvshmem device mirror.
|
|
873
|
+
# Release user reference and free the nvshmem mirror.
|
|
874
|
+
# Cross-space execution is always blocking, so no synchronization
|
|
875
|
+
# is needed before freeing.
|
|
876
|
+
self.operand_backup = None
|
|
877
|
+
with utils.device_ctx(self.device_id):
|
|
878
|
+
self.operand.free_symmetric()
|
|
879
|
+
self.operand = None
|
|
880
|
+
|
|
881
|
+
self._operand_released = True
|
|
882
|
+
self.logger.info("User-provided operand has been released.")
|
|
883
|
+
|
|
884
|
+
def _check_planned(self, *args, **kwargs):
|
|
885
|
+
""" """
|
|
886
|
+
what = kwargs["what"]
|
|
887
|
+
if not self.reshape_planned:
|
|
888
|
+
raise RuntimeError(f"{what} cannot be performed before plan() has been called.")
|
|
889
|
+
|
|
890
|
+
def _check_valid_operand(self, *args, **kwargs):
|
|
891
|
+
""" """
|
|
892
|
+
what = kwargs["what"]
|
|
893
|
+
if self._operand_released:
|
|
894
|
+
raise RuntimeError(
|
|
895
|
+
f"{what} cannot be performed after the operand has been released. Use reset_operand() to provide a new "
|
|
896
|
+
f"operand before performing the {what.lower()}."
|
|
897
|
+
)
|
|
898
|
+
|
|
899
|
+
def _free_workspace_memory(self, exception: Exception | None = None) -> bool:
|
|
900
|
+
"""
|
|
901
|
+
Free workspace by releasing the MemoryPointer object.
|
|
902
|
+
"""
|
|
903
|
+
if self.workspace_ptr is None:
|
|
904
|
+
return True
|
|
905
|
+
|
|
906
|
+
with utils.device_ctx(self.device_id):
|
|
907
|
+
# Calling nvshmem_free on memory that's still in use is not safe
|
|
908
|
+
# (nvshmem_free is not stream-ordered), so we need to wait for the
|
|
909
|
+
# computation to finish.
|
|
910
|
+
if self.workspace_stream is not None:
|
|
911
|
+
self.workspace_stream.sync()
|
|
912
|
+
self.workspace_ptr.free()
|
|
913
|
+
self.workspace_ptr = None
|
|
914
|
+
self.logger.debug("[_free_workspace_memory] The workspace has been released.")
|
|
915
|
+
|
|
916
|
+
return True
|
|
917
|
+
|
|
918
|
+
@utils.precondition(_check_valid_reshape)
|
|
919
|
+
@utils.precondition(_check_planned, "Workspace memory allocation")
|
|
920
|
+
@utils.atomic(_free_workspace_memory, method=True)
|
|
921
|
+
def _allocate_workspace_memory(self, stream_holder):
|
|
922
|
+
"""
|
|
923
|
+
Allocate workspace memory using the specified allocator.
|
|
924
|
+
"""
|
|
925
|
+
|
|
926
|
+
assert self._workspace_allocated_here is False, "Internal Error."
|
|
927
|
+
|
|
928
|
+
self.logger.debug("Allocating workspace for performing the Reshape...")
|
|
929
|
+
with utils.device_ctx(self.device_id), stream_holder.ctx:
|
|
930
|
+
try:
|
|
931
|
+
self.workspace_ptr = self.allocator.memalloc(self.workspace_size)
|
|
932
|
+
self._workspace_allocated_here = True
|
|
933
|
+
except TypeError as e:
|
|
934
|
+
message = (
|
|
935
|
+
"The method 'memalloc' in the allocator object must conform to the interface in the "
|
|
936
|
+
"'BaseCUDAMemoryManager' protocol."
|
|
937
|
+
)
|
|
938
|
+
raise TypeError(message) from e
|
|
939
|
+
|
|
940
|
+
self.workspace_stream = stream_holder.obj
|
|
941
|
+
self.logger.debug(
|
|
942
|
+
f"Finished allocating device workspace of size {formatters.MemoryStr(self.workspace_size)} in the context "
|
|
943
|
+
f"of stream {self.workspace_stream}."
|
|
944
|
+
)
|
|
945
|
+
|
|
946
|
+
def _allocate_workspace_memory_perhaps(self, stream_holder):
|
|
947
|
+
"""
|
|
948
|
+
Allocate workspace memory using the specified allocator, if it hasn't already been
|
|
949
|
+
done.
|
|
950
|
+
"""
|
|
951
|
+
if self.execution_space != "cuda" or self.workspace_ptr is not None:
|
|
952
|
+
return
|
|
953
|
+
|
|
954
|
+
return self._allocate_workspace_memory(stream_holder)
|
|
955
|
+
|
|
956
|
+
@utils.precondition(_check_valid_reshape)
|
|
957
|
+
def _free_workspace_memory_perhaps(self, release_workspace):
|
|
958
|
+
"""
|
|
959
|
+
Free workspace memory if if 'release_workspace' is True.
|
|
960
|
+
"""
|
|
961
|
+
if not release_workspace:
|
|
962
|
+
return
|
|
963
|
+
|
|
964
|
+
# Establish ordering wrt the computation and free workspace if it's more than the
|
|
965
|
+
# specified cache limit.
|
|
966
|
+
if self.last_compute_event is not None:
|
|
967
|
+
with utils.device_ctx(self.device_id):
|
|
968
|
+
self.workspace_stream.wait(self.last_compute_event)
|
|
969
|
+
self.logger.debug("Established ordering with respect to the computation before releasing the workspace.")
|
|
970
|
+
self.last_compute_event = None
|
|
971
|
+
|
|
972
|
+
self.logger.debug("[_free_workspace_memory_perhaps] The workspace memory will be released.")
|
|
973
|
+
self._free_workspace_memory()
|
|
974
|
+
|
|
975
|
+
return True
|
|
976
|
+
|
|
977
|
+
def _release_workspace_memory_perhaps(self, exception: Exception | None = None) -> bool:
|
|
978
|
+
"""
|
|
979
|
+
Free workspace memory if it was allocated in this call
|
|
980
|
+
(self._workspace_allocated_here == True) when an exception occurs.
|
|
981
|
+
"""
|
|
982
|
+
release_workspace = self._workspace_allocated_here
|
|
983
|
+
self.logger.debug(
|
|
984
|
+
f"[_release_workspace_memory_perhaps] The release_workspace flag is set to {release_workspace} based upon "
|
|
985
|
+
"the value of 'workspace_allocated_here'."
|
|
986
|
+
)
|
|
987
|
+
self._free_workspace_memory_perhaps(release_workspace)
|
|
988
|
+
self._workspace_allocated_here = False
|
|
989
|
+
return True
|
|
990
|
+
|
|
991
|
+
@utils.precondition(_check_valid_reshape)
|
|
992
|
+
@utils.precondition(_check_planned, "Execution")
|
|
993
|
+
@utils.precondition(_check_valid_operand, "Execution")
|
|
994
|
+
@utils.atomic(_release_workspace_memory_perhaps, method=True)
|
|
995
|
+
def execute(self, stream: AnyStream | None = None, release_workspace: bool = False, sync_symmetric_memory: bool = True):
|
|
996
|
+
"""
|
|
997
|
+
Execute the Reshape operation.
|
|
998
|
+
|
|
999
|
+
Args:
|
|
1000
|
+
stream: {stream}
|
|
1001
|
+
|
|
1002
|
+
release_workspace: A value of `True` specifies that the Reshape object
|
|
1003
|
+
should release workspace memory back to the symmetric memory pool on
|
|
1004
|
+
function return, while a value of `False` specifies that the object
|
|
1005
|
+
should retain the memory. This option may be set to `True` if the
|
|
1006
|
+
application performs other operations that consume a lot of memory between
|
|
1007
|
+
successive calls to the (same or different) :meth:`execute` API, but incurs
|
|
1008
|
+
an overhead due to obtaining and releasing workspace memory from and
|
|
1009
|
+
to the symmetric memory pool on every call. The default is `False`.
|
|
1010
|
+
**NOTE: All processes must use the same value or the application can
|
|
1011
|
+
deadlock.**
|
|
1012
|
+
|
|
1013
|
+
sync_symmetric_memory: {sync_symmetric_memory}
|
|
1014
|
+
|
|
1015
|
+
Returns:
|
|
1016
|
+
The reshaped operand, which remains on the same device and utilizes the same
|
|
1017
|
+
package as the input operand. For GPU operands, the result will be in symmetric
|
|
1018
|
+
memory and the user is responsible for explicitly deallocating it (for example,
|
|
1019
|
+
using ``nvmath.distributed.free_symmetric_memory(tensor)``).
|
|
1020
|
+
"""
|
|
1021
|
+
|
|
1022
|
+
log_info = self.logger.isEnabledFor(logging.INFO)
|
|
1023
|
+
log_debug = self.logger.isEnabledFor(logging.DEBUG)
|
|
1024
|
+
|
|
1025
|
+
stream_holder: StreamHolder = utils.get_or_create_stream(self.device_id, stream, self.internal_op_package)
|
|
1026
|
+
|
|
1027
|
+
# Allocate workspace if needed.
|
|
1028
|
+
self._allocate_workspace_memory_perhaps(stream_holder)
|
|
1029
|
+
|
|
1030
|
+
# Allocate output operand.
|
|
1031
|
+
with utils.device_ctx(self.device_id):
|
|
1032
|
+
result = self._allocate_result_operand(stream_holder, log_debug)
|
|
1033
|
+
|
|
1034
|
+
if log_info:
|
|
1035
|
+
self.logger.info("Starting distributed Reshape...")
|
|
1036
|
+
self.logger.info(f"{self.call_prologue}")
|
|
1037
|
+
|
|
1038
|
+
with utils.cuda_call_ctx(stream_holder, self.blocking, timing=log_info) as (
|
|
1039
|
+
self.last_compute_event,
|
|
1040
|
+
elapsed,
|
|
1041
|
+
):
|
|
1042
|
+
raw_workspace_ptr = utils.get_ptr_from_memory_pointer(self.workspace_ptr)
|
|
1043
|
+
if sync_symmetric_memory:
|
|
1044
|
+
nvshmem.sync_all_on_stream(stream_holder.ptr)
|
|
1045
|
+
if log_info:
|
|
1046
|
+
self.logger.info(
|
|
1047
|
+
"sync_symmetric_memory is enabled (this may incur redundant multi-GPU "
|
|
1048
|
+
"synchronization, please refer to the documentation for more information)"
|
|
1049
|
+
)
|
|
1050
|
+
elif log_info:
|
|
1051
|
+
self.logger.info("sync_symmetric_memory is disabled")
|
|
1052
|
+
cufftMp.exec_reshape_async(
|
|
1053
|
+
self.handle, result.data_ptr, self.operand.data_ptr, raw_workspace_ptr, stream_holder.ptr
|
|
1054
|
+
)
|
|
1055
|
+
|
|
1056
|
+
if log_info and elapsed.data is not None:
|
|
1057
|
+
self.logger.info(f"The distributed Reshape took {elapsed.data:.3f} ms to complete.")
|
|
1058
|
+
|
|
1059
|
+
# Establish ordering wrt the computation and free workspace if it's more than the
|
|
1060
|
+
# specified cache limit.
|
|
1061
|
+
self._free_workspace_memory_perhaps(release_workspace)
|
|
1062
|
+
|
|
1063
|
+
# reset workspace allocation tracking to False at the end of the methods where
|
|
1064
|
+
# workspace memory is potentially allocated. This is necessary to prevent any
|
|
1065
|
+
# exceptions raised before method entry from using stale tracking values.
|
|
1066
|
+
self._workspace_allocated_here = False
|
|
1067
|
+
|
|
1068
|
+
if self.memory_space == "cpu":
|
|
1069
|
+
out = result.to("cpu", stream_holder=stream_holder).tensor
|
|
1070
|
+
with utils.device_ctx(self.device_id):
|
|
1071
|
+
# Since the execution when user passes CPU operands is blocking, it's
|
|
1072
|
+
# safe to call nvshmem_free here without additional synchronization.
|
|
1073
|
+
result.free_symmetric()
|
|
1074
|
+
else:
|
|
1075
|
+
out = result.tensor
|
|
1076
|
+
|
|
1077
|
+
return out
|
|
1078
|
+
|
|
1079
|
+
def free(self):
|
|
1080
|
+
"""Free Reshape resources.
|
|
1081
|
+
|
|
1082
|
+
It is recommended that the :class:`Reshape` object be used within a context, but if
|
|
1083
|
+
it is not possible then this method must be called explicitly to ensure that the
|
|
1084
|
+
Reshape resources (especially internal library objects) are properly cleaned up.
|
|
1085
|
+
"""
|
|
1086
|
+
|
|
1087
|
+
if not self.valid_state:
|
|
1088
|
+
return
|
|
1089
|
+
|
|
1090
|
+
try:
|
|
1091
|
+
# Future operations on the workspace stream should be ordered after the
|
|
1092
|
+
# computation.
|
|
1093
|
+
if self.last_compute_event is not None and self.workspace_stream is not None:
|
|
1094
|
+
with utils.device_ctx(self.device_id):
|
|
1095
|
+
self.workspace_stream.wait(self.last_compute_event)
|
|
1096
|
+
self.last_compute_event = None
|
|
1097
|
+
|
|
1098
|
+
self._free_workspace_memory()
|
|
1099
|
+
|
|
1100
|
+
with utils.device_ctx(self.device_id):
|
|
1101
|
+
if self.handle is not None:
|
|
1102
|
+
cufftMp.destroy_reshape(self.handle)
|
|
1103
|
+
self.handle = None
|
|
1104
|
+
|
|
1105
|
+
if self.memory_space == "cpu" and self.operand is not None:
|
|
1106
|
+
# In this case, self.operand is an internal GPU operand owned by Reshape
|
|
1107
|
+
# Since the execution when user passes CPU operands is blocking, it's
|
|
1108
|
+
# safe to call nvshmem_free here without additional synchronization.
|
|
1109
|
+
self.operand.free_symmetric()
|
|
1110
|
+
|
|
1111
|
+
# Set all attributes to None except for logger and valid_state
|
|
1112
|
+
_keep = {"logger", "valid_state"}
|
|
1113
|
+
for attr in list(vars(self)):
|
|
1114
|
+
if attr not in _keep:
|
|
1115
|
+
setattr(self, attr, None)
|
|
1116
|
+
|
|
1117
|
+
except Exception as e:
|
|
1118
|
+
self.logger.critical("Internal error: only part of the Reshape object's resources have been released.")
|
|
1119
|
+
self.logger.critical(str(e))
|
|
1120
|
+
raise e
|
|
1121
|
+
finally:
|
|
1122
|
+
self.valid_state = False
|
|
1123
|
+
|
|
1124
|
+
self.logger.info("The Reshape object's resources have been released.")
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
@utils.docstring_decorator(SHARED_RESHAPE_DOCUMENTATION, skip_missing=False)
|
|
1128
|
+
def reshape(
|
|
1129
|
+
operand,
|
|
1130
|
+
/,
|
|
1131
|
+
input_box: Box,
|
|
1132
|
+
output_box: Box,
|
|
1133
|
+
*,
|
|
1134
|
+
sync_symmetric_memory: bool = True,
|
|
1135
|
+
options: ReshapeOptions | None = None,
|
|
1136
|
+
stream: AnyStream | None = None,
|
|
1137
|
+
):
|
|
1138
|
+
r"""
|
|
1139
|
+
reshape({function_signature})
|
|
1140
|
+
|
|
1141
|
+
Perform a distributed reshape on the provided operand to change its distribution across
|
|
1142
|
+
processes.
|
|
1143
|
+
|
|
1144
|
+
Args:
|
|
1145
|
+
operand: {operand}
|
|
1146
|
+
{operand_admonitions}
|
|
1147
|
+
|
|
1148
|
+
input_box: {input_box}
|
|
1149
|
+
|
|
1150
|
+
output_box: {output_box}
|
|
1151
|
+
|
|
1152
|
+
sync_symmetric_memory: {sync_symmetric_memory}
|
|
1153
|
+
|
|
1154
|
+
options: {options}
|
|
1155
|
+
|
|
1156
|
+
stream: {stream}
|
|
1157
|
+
|
|
1158
|
+
Returns:
|
|
1159
|
+
A tensor that remains on the same device and belongs to the same package as
|
|
1160
|
+
the input operand, with shape according to output_box.
|
|
1161
|
+
|
|
1162
|
+
.. seealso::
|
|
1163
|
+
:class:`Reshape`.
|
|
1164
|
+
|
|
1165
|
+
Examples:
|
|
1166
|
+
|
|
1167
|
+
>>> import cupy as cp
|
|
1168
|
+
>>> import nvmath.distributed
|
|
1169
|
+
|
|
1170
|
+
Get process group used to initialize nvmath.distributed (for information on
|
|
1171
|
+
initializing nvmath.distributed, you can refer to the documentation or to the
|
|
1172
|
+
Reshape examples in `nvmath/examples/distributed/reshape
|
|
1173
|
+
<https://github.com/NVIDIA/nvmath-python/tree/main/examples/distributed/reshape>`_):
|
|
1174
|
+
|
|
1175
|
+
>>> process_group = nvmath.distributed.get_context().process_group
|
|
1176
|
+
|
|
1177
|
+
Let's create a 3D floating-point ndarray on GPU, distributed across a certain number
|
|
1178
|
+
of processes, with each holding a portion of the ndarray. As an example, process 0
|
|
1179
|
+
holds a 3D box of the global 3D array of shape (4, 4, 4).
|
|
1180
|
+
|
|
1181
|
+
>>> shape = 4, 4, 4
|
|
1182
|
+
|
|
1183
|
+
Reshape uses the NVSHMEM PGAS model, which requires GPU operands to be on the
|
|
1184
|
+
symmetric heap:
|
|
1185
|
+
|
|
1186
|
+
>>> if process_group.rank == 0:
|
|
1187
|
+
... a[:] = cp.random.rand(*shape)
|
|
1188
|
+
... else:
|
|
1189
|
+
... a = ... # each process holds a different section of the global array.
|
|
1190
|
+
... a = nvmath.distributed.allocate_symmetric_memory(shape, cp)
|
|
1191
|
+
|
|
1192
|
+
With Reshape, we will change how the ndarray is distributed, by having each
|
|
1193
|
+
process specify the input and output section of the global array. For process 0,
|
|
1194
|
+
let's assume that it holds the 3D box that goes from the lower corner given by
|
|
1195
|
+
coordinates (0, 0, 0) to the upper corner (4, 4, 4).
|
|
1196
|
+
|
|
1197
|
+
NOTE: each process has its own input and output boxes which are different to those
|
|
1198
|
+
of other processes, as each holds a different section of the global array.
|
|
1199
|
+
|
|
1200
|
+
>>> from nvmath.distributed.distribution import Box
|
|
1201
|
+
>>> if process_group.rank == 0:
|
|
1202
|
+
... input_lower = (0, 0, 0)
|
|
1203
|
+
... input_upper = (4, 4, 4)
|
|
1204
|
+
... input_box = Box(input_lower, input_upper)
|
|
1205
|
+
... output_box = ...
|
|
1206
|
+
... else:
|
|
1207
|
+
... input_box = ... # the input box depends on the process.
|
|
1208
|
+
... output_box = ... # the output box depends on the process.
|
|
1209
|
+
|
|
1210
|
+
Perform the distributed reshape using :func:`reshape`:
|
|
1211
|
+
|
|
1212
|
+
>>> r = nvmath.distributed.reshape.reshape(a, input_box, output_box)
|
|
1213
|
+
|
|
1214
|
+
See :class:`ReshapeOptions` for the complete list of available options.
|
|
1215
|
+
|
|
1216
|
+
The package current stream is used by default, but a stream can be explicitly
|
|
1217
|
+
provided to the Reshape operation. This can be done if the Reshape operand is
|
|
1218
|
+
computed on a different stream, for example:
|
|
1219
|
+
|
|
1220
|
+
>>> s = cp.cuda.Stream()
|
|
1221
|
+
>>> with s:
|
|
1222
|
+
... a = nvmath.distributed.allocate_symmetric_memory(shape, cp)
|
|
1223
|
+
... a[:] = cp.random.rand(*shape)
|
|
1224
|
+
>>> r = nvmath.distributed.reshape.reshape(a, stream=s)
|
|
1225
|
+
|
|
1226
|
+
The operation above runs on stream `s` and is ordered with respect to the input
|
|
1227
|
+
computation.
|
|
1228
|
+
|
|
1229
|
+
Create a NumPy ndarray on the CPU.
|
|
1230
|
+
|
|
1231
|
+
>>> import numpy as np
|
|
1232
|
+
>>> b = np.random.rand(*shape)
|
|
1233
|
+
|
|
1234
|
+
Provide the NumPy ndarray to :func:`reshape`, with the result also being a NumPy
|
|
1235
|
+
ndarray:
|
|
1236
|
+
|
|
1237
|
+
>>> r = nvmath.distributed.reshape.reshape(b, input_box, output_box)
|
|
1238
|
+
|
|
1239
|
+
Notes:
|
|
1240
|
+
- This function is a convenience wrapper around :class:`Reshape` and is
|
|
1241
|
+
specifically meant for *single* use. The same computation can be performed
|
|
1242
|
+
with the stateful API.
|
|
1243
|
+
|
|
1244
|
+
Further examples can be found in the `nvmath/examples/distributed/reshape
|
|
1245
|
+
<https://github.com/NVIDIA/nvmath-python/tree/main/examples/distributed/reshape>`_
|
|
1246
|
+
directory.
|
|
1247
|
+
"""
|
|
1248
|
+
|
|
1249
|
+
with Reshape(operand, input_box, output_box, options=options, stream=stream) as reshape_obj:
|
|
1250
|
+
# Plan the Reshape.
|
|
1251
|
+
reshape_obj.plan(stream=stream)
|
|
1252
|
+
|
|
1253
|
+
# Execute the Reshape.
|
|
1254
|
+
result = reshape_obj.execute(sync_symmetric_memory=sync_symmetric_memory, stream=stream)
|
|
1255
|
+
|
|
1256
|
+
return result
|