File: reduction_operation.py

package info (click to toggle)
nvidia-cutlass 3.4.1%2Bds-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 48,488 kB
  • sloc: cpp: 206,571; ansic: 69,215; python: 25,487; sh: 16; makefile: 15
file content (452 lines) | stat: -rw-r--r-- 15,701 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
################################################################################
#
# Copyright (c) 2017 - 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
################################################################################

import ctypes
from typing import Union

from cuda import cuda, cudart
import numpy as np

from cutlass_library import (
    DataTypeNames,
    DataTypeSize,
    DataTypeTag,
    LayoutType,
    SubstituteTemplate
)

import cutlass
from cutlass.backend.c_types import MatrixCoord_, TensorRef2D_, get_reduction_params
from cutlass.backend.frontend import NumpyFrontend, TorchFrontend
from cutlass.backend.library import TensorDescription
from cutlass.backend.memory_manager import DevicePtrWrapper
from cutlass.backend.operation import ExecutableOperation, LaunchConfiguration
from cutlass.shape import MatrixCoord
from cutlass.utils.datatypes import is_numpy_tensor, is_torch_tensor


class ReductionOperation:
    pass


class ReductionArguments:
    """
    Arguments of reduction
    """

    def __init__(
        self,
        operation: ReductionOperation,
        problem_size: "list[int]",
        partitions: int,
        workspace: cuda.CUdeviceptr,
        destination: "Union[cuda.CUdeviceptr, np.ndarray, torch.Tensor]",
        source: "Union[cuda.CUdeviceptr, np.ndarray, torch.Tensor]",
        **kwargs,
    ) -> None:
        # tensor_C can be interpreted as the bias with bias=True in keyword args
        if "bias" in kwargs.keys():
            self.bias = kwargs["bias"]
        else:
            # by default, tensor_C is not bias
            self.bias = False
        if "stream" in kwargs.keys():
            self.stream = kwargs["stream"]
        else:
            self.stream = cuda.CUstream(0)

        self.operation = operation
        self.ptr_workspace = workspace

        # number of split-k partitions
        self.partitions = partitions

        if is_numpy_tensor(destination):
            self.host_D = destination
            self.destination_buffer = NumpyFrontend.argument(destination, True)
            self.source_buffer = NumpyFrontend.argument(source, False)
            self.ptr_destination = cuda.CUdeviceptr(self.destination_buffer.ptr)
            self.ptr_source = cuda.CUdeviceptr(self.source_buffer.ptr)
        elif is_torch_tensor(destination):
            self.ptr_destination = TorchFrontend.argument(destination)
            self.ptr_source = TorchFrontend.argument(source)
        elif isinstance(destination, cuda.CUdeviceptr):
            self.ptr_destination = destination
            self.ptr_source = source
        else:
            raise TypeError("unknown Type")

        self.problem_size = MatrixCoord_(problem_size[0], problem_size[1])

        self.partition_stride = (
            problem_size[0] * problem_size[1] * DataTypeSize[operation.C.element] // 8
        )

        if "output_op" in kwargs.keys():
            self.output_op = kwargs["output_op"]
        else:
            self.output_op = self.operation.epilogue_type(1.0, 0.0)

        self.get_arguments()

    @staticmethod
    def get_tensor_ref(
        extent: "tuple[int]",
        device_ptr: cuda.CUdeviceptr,
        layout: LayoutType,
    ):
        if layout == LayoutType.RowMajor:
            return TensorRef2D_(int(device_ptr), extent[1])
        else:
            raise ValueError(f"Unknown layout type {layout}")

    def get_arguments(self):
        ref_workspace = ReductionArguments.get_tensor_ref(
            extent=[
                self.problem_size.row,
                self.problem_size.column,
            ],
            device_ptr=self.ptr_workspace,
            layout=LayoutType.RowMajor,
        )
        if self.bias:
            ref_source = ReductionArguments.get_tensor_ref(
                extent=[0, 0],
                device_ptr=self.ptr_source,
                layout=LayoutType.RowMajor,
            )
        else:
            ref_source = ReductionArguments.get_tensor_ref(
                extent=[
                    self.problem_size.row,
                    self.problem_size.column,
                ],
                device_ptr=self.ptr_source,
                layout=LayoutType.RowMajor,
            )

        ref_destination = ReductionArguments.get_tensor_ref(
            extent=[
                self.problem_size.row,
                self.problem_size.column,
            ],
            device_ptr=self.ptr_destination,
            layout=LayoutType.RowMajor,
        )

        self.c_arguments = self.operation.argument_type(
            self.problem_size,
            self.partitions,
            self.partition_stride,
            ref_workspace,
            ref_destination,
            ref_source,
            self.output_op,
        )

        params_ = self.operation.rt_module.get_args(ctypes.byref(self.c_arguments))
        self.host_workspace = bytearray(params_.contents)

    def sync(self):
        (err,) = cudart.cudaDeviceSynchronize()
        if err != cuda.CUresult.CUDA_SUCCESS:
            raise RuntimeError(f"CUDA Error {str(err)}")

        if hasattr(self, "host_D"):
            (err,) = cuda.cuMemcpyDtoH(
                self.host_D,
                self.ptr_destination,
                self.host_D.size * self.host_D.itemsize,
            )
            if err != cuda.CUresult.CUDA_SUCCESS:
                raise RuntimeError("CUDA Error %s" % str(err))

        self.free()

    def free(self):
        """
        Frees allocated device-side memory
        """
        # Free any device memory allocated manually
        if not cutlass.use_rmm:
            for attr in ["destination_buffer", "source_buffer"]:
                if hasattr(self, attr):
                    buf = getattr(self, attr)
                    if isinstance(buf, DevicePtrWrapper):
                        err, = cudart.cudaFree(buf.ptr)
                        if err != cudart.cudaError_t.cudaSuccess:
                            raise RuntimeError(f"cudaFree failed with error {err}")
                        del buf


class ReductionRT(ExecutableOperation):
    """
    ReductionRT manages the CUTLASS runtime components for reduction
    """

    KernelTemplate = r"""
extern "C"
__global__ void
${operation_name}(${operation_name}${operation_suffix}::Params params) {

  // Dynamic shared memory base pointer
  extern __shared__ int SharedStorageBase[];

  // Declare pointer to dynamic shared memory.
  ${operation_name}${operation_suffix}::SharedStorage *shared_storage =
      reinterpret_cast<${operation_name}${operation_suffix}::SharedStorage *>(SharedStorageBase);

  ${operation_name}${operation_suffix} op;

  op(params, *shared_storage);
}
    """
    HostTemplate = r"""
extern "C" {
  // Get the size of params in bytes
  int ${operation_name}_get_param_size(){
    return sizeof(${operation_name}${operation_suffix}::Params);
  }

  // Get the size of dynamic shared memory in bytes
  int ${operation_name}_shared_memory_size() {
    return int(sizeof(${operation_name}${operation_suffix}::SharedStorage));
  }

  // Get the params as byte array
  char* ${operation_name}_get_params(${operation_name}${operation_suffix}::Params* params){
    char *bytes = ((char*)(params));
    char *output = new char[sizeof(${operation_name}${operation_suffix}::Params)];
    for (unsigned int i = 0; i < sizeof(${operation_name}${operation_suffix}::Params); i ++)
        output[i] = bytes[i];

    return output;
  }
}
    """

    def __init__(self, operation: ReductionOperation):
        super().__init__(operation)

        self.operation: ReductionOperation = operation
        self.emitter = EmitReductionInstance("_type")

        self.elements_per_access = self.operation.count
        (
            self.argument_type,
            self.epilogue_type,
        ) = get_reduction_params(operation.epilogue_functor)
        self.argtype = [ctypes.POINTER(self.argument_type)]

    def emit(self):
        return self.emitter.emit(self.operation)

    def plan(self, arguments: ReductionArguments):
        block_shape = [
            self.operation.shape.column // self.elements_per_access,
            self.operation.shape.row,
            1,
        ]
        grid_shape = [
            (arguments.problem_size.row + self.operation.shape.row - 1)
            // self.operation.shape.row,
            (arguments.problem_size.column + self.operation.shape.column - 1)
            // self.operation.shape.column,
            1,
        ]
        return LaunchConfiguration(
            grid_shape,
            block_shape,
            self.shared_memory_capacity,
        )

    def initialize(self):
        (err,) = cuda.cuFuncSetAttribute(
            self.kernel,
            attrib=cuda.CUfunction_attribute.CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES,
            value=self.shared_memory_capacity,
        )
        if err != cuda.CUresult.CUDA_SUCCESS:
            raise RuntimeError(f"CUDA Error: {err}")


class ReductionOperation:
    """
    CUTLASS reduction Operation
    """

    def __init__(
        self,
        shape: MatrixCoord,
        C: TensorDescription,
        element_accumulator,
        element_workspace=None,
        element_compute=None,
        epilogue_functor=None,
        count: int = 1,
        partitions_per_stage: int = 4,
    ) -> None:
        self.shape = shape
        self.epilogue_functor = epilogue_functor
        self.element_accumulator = element_accumulator

        if element_workspace is None:
            self.element_workspace = element_accumulator
        else:
            self.element_workspace = element_workspace

        if element_compute is None:
            self.element_compute = element_accumulator
        else:
            self.element_compute = element_compute

        self.element_output = C.element
        self.C: TensorDescription = C

        # Reduce op processing size
        self.count: int = count

        # Number of partitions to reduce per stage
        self.partitions_per_stage: int = partitions_per_stage

        self.rt_module: ReductionRT = ReductionRT(self)
        self.argument_type = self.rt_module.argument_type
        self.epilogue_type = self.rt_module.epilogue_type

    def extended_name(self):
        extend_name = "${element_workspace}_${element_accumulator}_${element_compute}_${element_output}"

        return SubstituteTemplate(
            extend_name,
            {
                "element_workspace": DataTypeNames[self.element_workspace],
                "element_accumulator": DataTypeNames[self.element_accumulator],
                "element_compute": DataTypeNames[self.element_compute],
                "element_output": DataTypeNames[self.element_output],
            },
        )

    def configuration_name(self):
        """The full procedural name indicates architecture, extended name, tile size"""

        configuration_name = "cutlass_reduce_split_k_${extended_name}_${threadblock}"

        threadblock = "%dx%d" % (
            self.shape.row,
            self.shape.column,
        )

        return SubstituteTemplate(
            configuration_name,
            {
                "extended_name": self.extended_name(),
                "threadblock": threadblock,
            },
        )

    def procedural_name(self):
        """The full procedural name indicates architeture, extended name, tile size"""
        return self.configuration_name()

    def run(self, arguments: ReductionArguments) -> cuda.CUresult:
        """
        Configure and launch the cuda kernel with input arguments
        """
        launch_config = self.rt_module.plan(arguments)

        host_workspace = arguments.host_workspace
        device_workspace = None

        err = self.rt_module.run(
            host_workspace,
            device_workspace,
            launch_config,
            arguments.stream
        )

        if err != cuda.CUresult.CUDA_SUCCESS:
            raise RuntimeError(f"CUDA Error {str(err)}")

        return err


class EmitReductionInstance:
    def __init__(self, operation_suffix="") -> None:
        self.operation_suffix = operation_suffix
        self.includes = [
            "cutlass/cutlass.h",
            "cutlass/numeric_types.h",
            "cutlass/arch/arch.h",
            "cutlass/arch/mma.h",
            "cutlass/layout/matrix.h",
            "cutlass/gemm/device/gemm.h",
            "cutlass/gemm/device/gemm_universal_adapter.h",
            "cutlass/gemm/kernel/default_gemm_universal.h",
            "cutlass/reduction/kernel/reduce_split_k.h",
            "cutlass/reduction/thread/reduction_operators.h",
        ]
        self.template = """
// Reduction kernel instance
using ${operation_name}_base =
typename cutlass::reduction::kernel::ReduceSplitK<
  cutlass::MatrixShape<${shape_row}, ${shape_column}>,
  ${epilogue_functor},
  cutlass::reduction::thread::ReduceAdd<
    ${element_accumulator},
    ${element_output},
    ${count}>,
  ${partition_per_stage}>;

struct ${operation_name}${operation_suffix}:
  public ${operation_name}_base { };
      """

    def emit(self, operation: ReductionOperation):
        vector_length_bits = min(operation.C.alignment * DataTypeSize[operation.C.element], 128)
        epilogue_vector_length = vector_length_bits // DataTypeSize[operation.C.element]

        values = {
            "operation_name": operation.configuration_name(),
            "operation_suffix": self.operation_suffix,
            "shape_row": str(operation.shape.row),
            "shape_column": str(operation.shape.column),
            "epilogue_functor": operation.epilogue_functor.emit(),
            "element_output": DataTypeTag[operation.element_output],
            "epilogue_vector_length": str(epilogue_vector_length),
            "element_accumulator": DataTypeTag[operation.element_accumulator],
            "element_compute": DataTypeTag[operation.element_compute],
            "element_workspace": DataTypeTag[operation.element_workspace],
            "count": str(operation.count),
            "partition_per_stage": str(operation.partitions_per_stage),
        }

        return SubstituteTemplate(self.template, values)