algo.py 43.1 KB
Newer Older
yan.yan's avatar
yan.yan committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Copyright 2021 Yan Yan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

yan.yan's avatar
sync  
yan.yan committed
15
import contextlib
yan.yan's avatar
yan.yan committed
16
import time
yan.yan's avatar
sync  
yan.yan committed
17
from enum import Enum
yan.yan's avatar
v2.1  
yan.yan committed
18
from threading import Lock
yan.yan's avatar
sync  
yan.yan committed
19
from typing import Dict, List, Optional, Set, Tuple, Union
yan.yan's avatar
yan.yan committed
20
from spconv.core_cc.cumm.common import CompileInfo
yan.yan's avatar
yan.yan committed
21
import numpy as np
yan.yan's avatar
sync  
yan.yan committed
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
from cumm import tensorview as tv
from cumm.conv.bases import ConvLayout, ConvLayoutType, ConvOpType
from cumm.conv.kernel import ConvKernel
from cumm.gemm.kernel import GemmKernel

from cumm.gemm.algospec.core import (GemmAlgo, ShuffleStrideType,
                                     get_available_algo_str_from_arch,
                                     get_min_arch_of_algo_str)
from cumm.gemm.codeops import div_up, group_by
from cumm.nvrtc import CummNVRTCModule, get_cudadevrt_path
from cumm.tensorview.gemm import ConvAlgoDesp
from cumm.tensorview.gemm import ConvOpType as ConvOpTypeCpp

from cumm.tensorview.gemm import ConvParams, GemmAlgoDesp, GemmParams
from cumm import dtypes

from spconv.constants import (NDIM_DONT_CARE, SPCONV_BWD_SPLITK,
                              SPCONV_NVRTC_MODE, SPCONV_DEBUG_NVRTC_KERNELS)
yan.yan's avatar
yan.yan committed
40
from spconv.core import ALL_IMPGEMM_PARAMS, AlgoHint, ConvAlgo, ALL_NATIVE_PARAMS
yan.yan's avatar
sync  
yan.yan committed
41
42
from spconv.core_cc.cumm.conv.main import ConvMainUnitTest
from spconv.core_cc.cumm.gemm.main import GemmMainUnitTest
yan.yan's avatar
yan.yan committed
43
from spconv.cppconstants import COMPILED_CUDA_GEMM_ARCHS
yan.yan's avatar
sync  
yan.yan committed
44
from cumm.tensorview.gemm import NVRTCParams
45
from spconv.tools import CUDAKernelTimer
yan.yan's avatar
sync  
yan.yan committed
46
47
48
49
50
51
from cumm.gemm.constants import NVRTCConstants, NVRTCMode

from spconv import algocore

from cumm.conv.main import gen_gemm_kernels as gen_conv_kernels
from cumm.gemm.main import gen_gemm_kernels
yan.yan's avatar
yan.yan committed
52
53
54
from spconv.core_cc.csrc.sparse.convops import GemmTuneResult, ConvTuneResult
from spconv.core_cc.csrc.sparse.convops.gemmops import GemmTunerSimple as GemmTunerSimpleBase
from spconv.core_cc.csrc.sparse.convops.convops import ConvTunerSimple as ConvTunerSimpleBase
yan.yan's avatar
yan.yan committed
55
56

ALL_ALGO_DESPS = GemmMainUnitTest.get_all_algo_desp()
yan.yan's avatar
v2.1  
yan.yan committed
57
ALL_CONV_ALGO_DESPS = ConvMainUnitTest.get_all_conv_algo_desp()
yan.yan's avatar
yan.yan committed
58

yan.yan's avatar
sync  
yan.yan committed
59

yan.yan's avatar
yan.yan committed
60
class SimpleGemmAlgoMeta:
yan.yan's avatar
yan.yan committed
61

yan.yan's avatar
yan.yan committed
62
63
64
65
66
67
68
69
70
71
    def __init__(self, tile_ms: List[int], tile_ns: List[int],
                 tile_ks: List[int],
                 tile_shape_to_algos: Dict[int, List[int]]) -> None:
        self.tile_shape_to_algos = tile_shape_to_algos
        self.tile_ms = tile_ms
        self.tile_ns = tile_ns
        self.tile_ks = tile_ks


class BestAlgoByProfile:
yan.yan's avatar
yan.yan committed
72
73
74
75
76

    def __init__(self,
                 algo_desp: GemmAlgoDesp,
                 arch: Tuple[int, int],
                 splitk: int = 1) -> None:
yan.yan's avatar
v2.1  
yan.yan committed
77
78
        self.algo_desp = algo_desp
        self.splitk = splitk
yan.yan's avatar
sync  
yan.yan committed
79
        self.arch = arch
yan.yan's avatar
v2.1  
yan.yan committed
80
81
82


class BestConvAlgoByProfile:
yan.yan's avatar
yan.yan committed
83
84
85
86
87

    def __init__(self,
                 algo_desp: ConvAlgoDesp,
                 arch: Tuple[int, int],
                 splitk: int = 1) -> None:
yan.yan's avatar
yan.yan committed
88
89
        self.algo_desp = algo_desp
        self.splitk = splitk
yan.yan's avatar
sync  
yan.yan committed
90
91
        self.arch = arch

yan.yan's avatar
yan.yan committed
92
93
94

def _get_nvrtc_params(mod: CummNVRTCModule, ker: Union[GemmKernel, ConvKernel],
                      kernel_name: str):
yan.yan's avatar
sync  
yan.yan committed
95
96
97
98
99
100
101
102
103
    nvrtc_mode = SPCONV_NVRTC_MODE
    nvrtc_params = tv.gemm.NVRTCParams()
    nvrtc_params.cumodule = mod.get_cpp_object()
    nvrtc_params.mode = nvrtc_mode.value
    nvrtc_params.num_threads = ker.num_threads
    nvrtc_params.smem_size = ker.smem_size
    ns = ker.namespace

    if nvrtc_mode == NVRTCMode.DynamicParallism:
yan.yan's avatar
yan.yan committed
104
        nvrtc_params.kernel_name = mod.get_lowered_name(f"{ns}::nvrtc_kernel")
yan.yan's avatar
sync  
yan.yan committed
105
106
107
108
109
110
111
112
113

    elif nvrtc_mode == NVRTCMode.KernelAndCPU:
        nvrtc_params.kernel_name = mod.get_lowered_name(f"{ns}::{kernel_name}")
        nvrtc_params.init_kernel_name = mod.get_lowered_name(
            f"{ns}::nvrtc_kernel_cpu_out")
        nvrtc_params.param_size = mod.const_values[
            f"{ns}::{NVRTCConstants.SIZEOF_KEY}"]

        nvrtc_params.param_storage = tv.empty([nvrtc_params.param_size],
yan.yan's avatar
yan.yan committed
114
115
116
117
118
                                              tv.uint8, 0)
        nvrtc_params.param_storage_cpu = tv.empty([nvrtc_params.param_size],
                                                  tv.uint8,
                                                  -1,
                                                  pinned=True)
yan.yan's avatar
sync  
yan.yan committed
119
120
121
122
123
124
125
126
127
128
129
130

    elif nvrtc_mode == NVRTCMode.Direct:
        nvrtc_params.kernel_name = mod.get_lowered_name(f"{ns}::{kernel_name}")
    elif nvrtc_mode == NVRTCMode.ConstantMemory:
        nvrtc_params.kernel_name = mod.get_lowered_name(f"{ns}::{kernel_name}")
        nvrtc_params.init_kernel_name = mod.get_lowered_name(
            f"{ns}::nvrtc_kernel_cpu_out")
        nvrtc_params.param_size = mod.const_values[
            f"{ns}::{NVRTCConstants.SIZEOF_KEY}"]
        nvrtc_params.constant_name = mod.get_lowered_name(
            f"&{ns}::{NVRTCConstants.CONSTANT_PARAM_KEY}")
        nvrtc_params.param_storage = tv.empty([nvrtc_params.param_size],
yan.yan's avatar
yan.yan committed
131
                                              tv.uint8, 0)
yan.yan's avatar
sync  
yan.yan committed
132
133
134
    else:
        raise NotImplementedError
    return nvrtc_params
yan.yan's avatar
yan.yan committed
135

yan.yan's avatar
yan.yan committed
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
class GemmTunerSimple(GemmTunerSimpleBase):
    def __init__(self, desps: List[GemmAlgoDesp]) -> None:
        super().__init__(desps)
        self._nvrtc_caches: Dict[Tuple[str, Tuple[int, int], int], NVRTCParams] = {}
    
    def _compile_nvrtc_module(self, desp: GemmAlgoDesp):
        params = algocore.get_gemm_param_from_desp(desp)
        kernel = gen_gemm_kernels(params, SPCONV_NVRTC_MODE)
        kernel.namespace = "spconv"
        custom_names = []
        if SPCONV_NVRTC_MODE == NVRTCMode.ConstantMemory:
            custom_names = [
                f"&{kernel.namespace}::{NVRTCConstants.CONSTANT_PARAM_KEY}"
            ]
        cudadevrt = ""
        if SPCONV_NVRTC_MODE == NVRTCMode.DynamicParallism:
            cudadevrt_p = get_cudadevrt_path()
            assert cudadevrt_p is not None, "DynamicParallism must have cudadevrt"
            cudadevrt = str(cudadevrt_p)
        mod = CummNVRTCModule([kernel],
                              cudadevrt_path=cudadevrt,
                              custom_names=custom_names)
        mod.load()
        return mod, kernel

    def cached_get_nvrtc_params(self, desp: GemmAlgoDesp, arch: Tuple[int, int], stream_int: int) -> NVRTCParams:
        
        key = (str(desp), arch, stream_int)
        if key in self._nvrtc_caches:
            return self._nvrtc_caches[key]
        mod, ker = self._compile_nvrtc_module(desp)
yan.yan's avatar
yan.yan committed
167
        print(f"Can't find algo {desp} in prebuilt. compile with nvrtc...")
yan.yan's avatar
yan.yan committed
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
        nvrtc_params = _get_nvrtc_params(mod, ker, "gemm_kernel")
        self._nvrtc_caches[key] = nvrtc_params
        return nvrtc_params

class ConvTunerSimple(ConvTunerSimpleBase):
    def __init__(self, desps: List[ConvAlgoDesp]) -> None:
        super().__init__(desps)
        self._nvrtc_caches: Dict[Tuple[str, Tuple[int, int], int], NVRTCParams] = {}
    
    def _compile_nvrtc_module(self, desp: ConvAlgoDesp):
        params = algocore.get_conv_param_from_desp(desp)
        kernel = gen_conv_kernels(params, SPCONV_NVRTC_MODE)
        kernel.namespace = "spconv"
        custom_names = []
        if SPCONV_NVRTC_MODE == NVRTCMode.ConstantMemory:
            custom_names = [
                f"&{kernel.namespace}::{NVRTCConstants.CONSTANT_PARAM_KEY}"
            ]
        cudadevrt = ""
        if SPCONV_NVRTC_MODE == NVRTCMode.DynamicParallism:
            cudadevrt_p = get_cudadevrt_path()
            assert cudadevrt_p is not None, "DynamicParallism must have cudadevrt"
            cudadevrt = str(cudadevrt_p)
        mod = CummNVRTCModule([kernel],
                              cudadevrt_path=cudadevrt,
                              verbose=False,
                              custom_names=custom_names)
        mod.load()
        return mod, kernel

    def cached_get_nvrtc_params(self, desp: ConvAlgoDesp, arch: Tuple[int, int], stream_int: int) -> NVRTCParams:
        key = (str(desp), arch, stream_int)
        if key in self._nvrtc_caches:
            return self._nvrtc_caches[key]
        mod, ker = self._compile_nvrtc_module(desp)
        print(f"Can't find algo {desp} in prebuilt. compile with nvrtc...")
        nvrtc_params = _get_nvrtc_params(mod, ker, "conv_kernel")
        self._nvrtc_caches[key] = nvrtc_params
        return nvrtc_params

208
209
_GEMM_STATIC_KEY = Tuple[bool, bool, bool, int, int, int, int]

yan.yan's avatar
yan.yan committed
210
class SimpleGemm:
yan.yan's avatar
yan.yan committed
211

yan.yan's avatar
sync  
yan.yan committed
212
    def __init__(self, prebuilt_desps: List[GemmAlgoDesp]) -> None:
yan.yan's avatar
yan.yan committed
213
214
215
216
        all_desps = [
            algocore.get_gemm_algo_desp_from_param(p)
            for p in ALL_NATIVE_PARAMS
        ]
yan.yan's avatar
sync  
yan.yan committed
217
218
219
220
        self.prebuilt_desps = prebuilt_desps
        self.prebuilt_desp_names = {str(d) for d in prebuilt_desps}
        if SPCONV_DEBUG_NVRTC_KERNELS:
            self.prebuilt_desp_names.clear()
yan.yan's avatar
v2.1  
yan.yan committed
221
        self.lock = Lock()
yan.yan's avatar
sync  
yan.yan committed
222
        self.static_key_to_desps = group_by(self.get_static_key, all_desps)
yan.yan's avatar
yan.yan committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
        self.static_key_to_meta: Dict[_GEMM_STATIC_KEY,
                                      SimpleGemmAlgoMeta] = {}
        for k, static_desps in self.static_key_to_desps.items():
            tile_shape_to_algos: Dict[int, List[int]] = {}
            tile_ms: Set[int] = set()
            tile_ns: Set[int] = set()
            tile_ks: Set[int] = set()
            for i, desp in enumerate(static_desps):
                ts = desp.tile_shape
                tile_ms.add(ts[0])
                tile_ns.add(ts[1])
                tile_ks.add(ts[2])
                tile_key = ts[0] | (ts[1] << 20) | (ts[2] << 40)
                if tile_key not in tile_shape_to_algos:
                    tile_shape_to_algos[tile_key] = []
                tile_shape_to_algos[tile_key].append(i)
yan.yan's avatar
yan.yan committed
239
240
241
242
243
244
            tile_ms_list = list(tile_ms)
            tile_ns_list = list(tile_ns)
            tile_ks_list = list(tile_ks)
            tile_ms_list.sort()
            tile_ns_list.sort()
            tile_ks_list.sort()
yan.yan's avatar
yan.yan committed
245
246
247
            self.static_key_to_meta[k] = SimpleGemmAlgoMeta(
                tile_ms_list, tile_ns_list, tile_ks_list, tile_shape_to_algos)

yan.yan's avatar
v2.1  
yan.yan committed
248
249
250
251
252
        self.nk_forward_cache: Dict[Tuple[int, int, int, int, int],
                                    BestAlgoByProfile] = {}  # for forward
        self.nk_dgrad_cache: Dict[Tuple[int, int,
                                        int, int, int], BestAlgoByProfile] = {
                                        }  # for backward weight
yan.yan's avatar
yan.yan committed
253

yan.yan's avatar
v2.1  
yan.yan committed
254
        self.mn_cache: Dict[Tuple[int, int, int, int, int],
yan.yan's avatar
yan.yan committed
255
                            BestAlgoByProfile] = {}  # for backward weight
yan.yan's avatar
sync  
yan.yan committed
256
        self._nvrtc_caches: Dict[Tuple[str, Tuple[int, int]], NVRTCParams] = {}
yan.yan's avatar
yan.yan committed
257
258
259
260

    @staticmethod
    def get_static_key(d: GemmAlgoDesp) -> _GEMM_STATIC_KEY:
        return (d.trans_a, d.trans_b, d.trans_c, d.dtype_a, d.dtype_b,
261
                d.dtype_c, d.shuffle_type.value)
yan.yan's avatar
yan.yan committed
262
263
264
265

    def device_synchronize(self):
        return GemmMainUnitTest.device_synchronize()

yan.yan's avatar
sync  
yan.yan committed
266
267
268
269
270
271
    def _compile_nvrtc_module(self, desp: GemmAlgoDesp):
        params = algocore.get_gemm_param_from_desp(desp)
        kernel = gen_gemm_kernels(params, SPCONV_NVRTC_MODE)
        kernel.namespace = "spconv"
        custom_names = []
        if SPCONV_NVRTC_MODE == NVRTCMode.ConstantMemory:
yan.yan's avatar
yan.yan committed
272
273
274
            custom_names = [
                f"&{kernel.namespace}::{NVRTCConstants.CONSTANT_PARAM_KEY}"
            ]
yan.yan's avatar
sync  
yan.yan committed
275
276
277
278
279
280
        cudadevrt = ""
        if SPCONV_NVRTC_MODE == NVRTCMode.DynamicParallism:
            cudadevrt_p = get_cudadevrt_path()
            assert cudadevrt_p is not None, "DynamicParallism must have cudadevrt"
            cudadevrt = str(cudadevrt_p)
        mod = CummNVRTCModule([kernel],
yan.yan's avatar
yan.yan committed
281
282
                              cudadevrt_path=cudadevrt,
                              custom_names=custom_names)
yan.yan's avatar
sync  
yan.yan committed
283
284
285
        mod.load()
        return mod, kernel

yan.yan's avatar
yan.yan committed
286
287
    def _cached_get_nvrtc_params(self, desp: GemmAlgoDesp, arch: Tuple[int,
                                                                       int]):
yan.yan's avatar
sync  
yan.yan committed
288
289
290
291
        key = (str(desp), arch)
        if key in self._nvrtc_caches:
            return self._nvrtc_caches[key]
        mod, ker = self._compile_nvrtc_module(desp)
yan.yan's avatar
yan.yan committed
292
        print(f"Can't find algo {desp} in prebuilt. compile with nvrtc...")
yan.yan's avatar
sync  
yan.yan committed
293
294
        nvrtc_params = _get_nvrtc_params(mod, ker, "gemm_kernel")
        self._nvrtc_caches[key] = nvrtc_params
yan.yan's avatar
yan.yan committed
295
        return nvrtc_params
yan.yan's avatar
sync  
yan.yan committed
296

yan.yan's avatar
yan.yan committed
297
298
299
300
301
302
303
304
305
    def get_all_available(
            self,
            a: tv.Tensor,
            b: tv.Tensor,
            c: tv.Tensor,
            trans_a: bool,
            trans_b: bool,
            trans_c: bool,
            arch: Tuple[int, int],
yan.yan's avatar
yan.yan committed
306
307
            shuffle_type: ShuffleStrideType = ShuffleStrideType.NoShuffle,
            use_tf32: bool = True):
yan.yan's avatar
yan.yan committed
308
309
310
311
312
313
314
315
        if trans_c:
            trans_a = not trans_a
            trans_b = not trans_b
            trans_a, trans_b = trans_b, trans_a
            a, b = b, a
            trans_c = False
        avail_algos = get_available_algo_str_from_arch(arch)
        finally_algos: List[GemmAlgoDesp] = []
yan.yan's avatar
yan.yan committed
316
        # print(self.static_key_to_desps)
317
318
319
320
321
        static_key = (trans_a, trans_b, trans_c, a.dtype, b.dtype, c.dtype,
                        shuffle_type.value)
        # for algo in avail_algos:
        #     static_key = (trans_a, trans_b, trans_c, a.dtype, b.dtype, c.dtype,
        #                   shuffle_type.value)
yan.yan's avatar
yan.yan committed
322
            # print(static_key)
323
324
325
326
327
328
        desps = self.static_key_to_desps.get(static_key, None)
        if desps is None or len(desps) == 0:
            return finally_algos
        # print(desps)
        for desp in desps:
            if arch < desp.min_arch:
yan.yan's avatar
yan.yan committed
329
                continue
330
331
332
            # skip volta tensor op since it is very slow in architectures except volta.
            if arch >= (7, 5) and desp.algo == GemmAlgo.Volta.value:
                continue
yan.yan's avatar
yan.yan committed
333
334
335
            if not use_tf32:
                if desp.tensorop[0] > 0 and a.dtype == tv.float32 and b.dtype == tv.float32:
                    continue
336
337
338
339
            lda = a.stride[0]
            ldb = b.stride[0]
            ldc = c.stride[0]
            if desp.supported_ldx(lda, ldb, ldc):
yan.yan's avatar
yan.yan committed
340
341
342
343
344
345
346
347
348
349
350
351
352
353
                if desp.is_nvrtc:
                    if not CompileInfo.algo_can_be_nvrtc_compiled(desp.min_arch):
                        continue
                if not CompileInfo.arch_is_compiled_gemm(arch):
                    # use PTX of possible
                    if not CompileInfo.gemm_algo_can_use_ptx(desp.min_arch, arch):
                        if CompileInfo.algo_can_be_nvrtc_compiled(desp.min_arch):
                            # compiled kernel can't use PTX, for example, desp need at least sm_80 and only sm_75+PTX is compiled
                            # all sm_80 code of this desp is invalid, we must use nvrtc.
                            # only desp <= sm_75 can use virtual PTX code to generate sm_80 code.
                            desp = desp.copy()
                            desp.is_nvrtc = True
                        else:
                            continue
354
355
356
                if SPCONV_DEBUG_NVRTC_KERNELS:
                    desp.is_nvrtc = True
                finally_algos.append(desp)
yan.yan's avatar
yan.yan committed
357
358
359
        return finally_algos


yan.yan's avatar
v2.1  
yan.yan committed
360
    def get_tuned_algo(
yan.yan's avatar
yan.yan committed
361
            self,
yan.yan's avatar
v2.1  
yan.yan committed
362
363
364
            a_dtype: int,
            b_dtype: int,
            c_dtype: int,
yan.yan's avatar
yan.yan committed
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
            a_shape: List[int],
            b_shape: List[int],
            c_shape: List[int],
            trans_a: bool,
            trans_b: bool,
            trans_c: bool,
            arch: Tuple[int, int],
            shuffle_type: ShuffleStrideType = ShuffleStrideType.NoShuffle,
            a_inds_shape: Optional[List[int]] = None,
            b_inds_shape: Optional[List[int]] = None,
            c_inds_shape: Optional[List[int]] = None,
            hint: int = AlgoHint.NoHint.value):
        if a_inds_shape is None:
            a_inds_shape = []
        if b_inds_shape is None:
            b_inds_shape = []
        if c_inds_shape is None:
            c_inds_shape = []
yan.yan's avatar
v2.1  
yan.yan committed
383
384
        m, n, k = GemmMainUnitTest.extract_mnk(a_shape, b_shape, trans_a,
                                               trans_b, trans_c,
yan.yan's avatar
yan.yan committed
385
386
387
388
                                               shuffle_type.value,
                                               a_inds_shape, b_inds_shape,
                                               c_inds_shape)
        if hint & AlgoHint.BackwardWeight.value:
yan.yan's avatar
v2.1  
yan.yan committed
389
            key = (a_dtype, b_dtype, c_dtype, m, n)
yan.yan's avatar
yan.yan committed
390
391
            return self.mn_cache.get(key, None)
        elif hint & AlgoHint.BackwardInput.value:
yan.yan's avatar
v2.1  
yan.yan committed
392
            key = (a_dtype, b_dtype, c_dtype, n, k)
yan.yan's avatar
yan.yan committed
393
394
            return self.nk_dgrad_cache.get(key, None)
        elif hint & AlgoHint.Fowrard.value:
yan.yan's avatar
v2.1  
yan.yan committed
395
            key = (a_dtype, b_dtype, c_dtype, n, k)
yan.yan's avatar
yan.yan committed
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
            return self.nk_forward_cache.get(key, None)
        raise NotImplementedError

    def extract_mnk(
            self,
            a_shape: List[int],
            b_shape: List[int],
            trans_a: bool,
            trans_b: bool,
            trans_c: bool,
            arch: Tuple[int, int],
            shuffle_type: ShuffleStrideType = ShuffleStrideType.NoShuffle,
            a_inds_shape: Optional[List[int]] = None,
            b_inds_shape: Optional[List[int]] = None,
            c_inds_shape: Optional[List[int]] = None,
            hint: int = AlgoHint.NoHint.value):
        if a_inds_shape is None:
            a_inds_shape = []
        if b_inds_shape is None:
            b_inds_shape = []
        if c_inds_shape is None:
            c_inds_shape = []
yan.yan's avatar
v2.1  
yan.yan committed
418
419
        m, n, k = GemmMainUnitTest.extract_mnk(a_shape, b_shape, trans_a,
                                               trans_b, trans_c,
yan.yan's avatar
yan.yan committed
420
421
422
423
424
                                               shuffle_type.value,
                                               a_inds_shape, b_inds_shape,
                                               c_inds_shape)
        return m, n, k

yan.yan's avatar
v2.1  
yan.yan committed
425
    def tune_and_cache(
yan.yan's avatar
yan.yan committed
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
            self,
            a: tv.Tensor,
            b: tv.Tensor,
            c: tv.Tensor,
            trans_a: bool,
            trans_b: bool,
            trans_c: bool,
            arch: Tuple[int, int],
            shuffle_type: ShuffleStrideType = ShuffleStrideType.NoShuffle,
            a_inds: tv.Tensor = tv.Tensor(),
            b_inds: tv.Tensor = tv.Tensor(),
            c_inds: tv.Tensor = tv.Tensor(),
            hint: int = AlgoHint.NoHint.value,
            alpha: float = 1.0,
            beta: float = 0.0,
            gather_data: tv.Tensor = tv.Tensor(),
            scatter_data: tv.Tensor = tv.Tensor(),
            # mm_func
yan.yan's avatar
yan.yan committed
444
445
            stream: int = 0,
            use_tf32: bool = True):
yan.yan's avatar
v2.1  
yan.yan committed
446
447
        m, n, k = GemmMainUnitTest.extract_mnk(a.shape, b.shape, trans_a,
                                               trans_b, trans_c,
yan.yan's avatar
yan.yan committed
448
449
450
451
                                               shuffle_type.value,
                                               a_inds.shape, b_inds.shape,
                                               c_inds.shape)
        avail = self.get_all_available(a, b, c, trans_a, trans_b, trans_c,
yan.yan's avatar
yan.yan committed
452
                                       arch, shuffle_type, use_tf32)
yan.yan's avatar
yan.yan committed
453
454
455
        # c may be weight, may non-contiguous.
        # cumm.tensorview.Tensor don't support non-contiguous clone
        c_ = c.clone_whole_storage()
yan.yan's avatar
yan.yan committed
456
457
458
459
460
        times: List[float] = []
        best_gather_params = (-1, -1, -1, -1)
        best_scatter_params = (-1, -1, -1, -1)

        all_profile_res: List[BestAlgoByProfile] = []
yan.yan's avatar
yan.yan committed
461
        # print(avail)
yan.yan's avatar
yan.yan committed
462
        for desp in avail:
yan.yan's avatar
yan.yan committed
463
            c_.zero_whole_storage_()
yan.yan's avatar
yan.yan committed
464
465
466
467
468
            split_k_slices = 1
            # TODO better splitk selection
            if desp.split_k_serial and hint & AlgoHint.BackwardWeight.value:
                split_k_slices = max(min(32, k // 128), 1)
            params = GemmParams()
yan.yan's avatar
yan.yan committed
469
            if desp.is_nvrtc or str(desp) not in self.prebuilt_desp_names:
yan.yan's avatar
sync  
yan.yan committed
470
                params.nvrtc_params = self._cached_get_nvrtc_params(desp, arch)
yan.yan's avatar
yan.yan committed
471
472
473
474
475
476
477
478
479
480
481
            params.a = a
            params.b = b
            params.c = c_
            params.a_inds = a_inds
            params.b_inds = b_inds
            params.c_inds = c_inds
            params.algo_desp = desp
            params.alpha = alpha
            params.beta = beta
            params.stream = stream
            if desp.split_k_serial and hint & AlgoHint.BackwardWeight.value:
yan.yan's avatar
yan.yan committed
482
                splitk_tests = SPCONV_BWD_SPLITK
yan.yan's avatar
yan.yan committed
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
            else:
                splitk_tests = [1]
            spk_speeds = []
            for spk in splitk_tests:
                this_times = []
                for j in range(3):
                    GemmMainUnitTest.stream_synchronize(stream)
                    t = time.time()
                    params.split_k_slices = spk
                    GemmMainUnitTest.matmul2(params)
                    GemmMainUnitTest.stream_synchronize(stream)
                    this_times.append(time.time() - t)
                times.append(np.mean(this_times[1:]))
                spk_speeds.append(times[-1])

yan.yan's avatar
yan.yan committed
498
499
                all_profile_res.append(
                    BestAlgoByProfile(desp, arch, splitk=spk))
yan.yan's avatar
yan.yan committed
500
501
502
503
504
505
506
507

        min_time = 1000
        min_idx = -1
        for i, t in enumerate(times):
            if t < min_time:
                min_time = t
                min_idx = i
        res = all_profile_res[min_idx]
yan.yan's avatar
v2.1  
yan.yan committed
508
509
510
511
512
513
514
515
516
517
518
519
        with self.lock:
            if hint & AlgoHint.BackwardWeight.value:
                key = (a.dtype, b.dtype, c.dtype, m, n)
                self.mn_cache[key] = res
            elif hint & AlgoHint.BackwardInput.value:
                key = (a.dtype, b.dtype, c.dtype, n, k)
                self.nk_dgrad_cache[key] = res
            elif hint & AlgoHint.Fowrard.value:
                key = (a.dtype, b.dtype, c.dtype, n, k)
                self.nk_forward_cache[key] = res
            else:
                raise NotImplementedError
yan.yan's avatar
yan.yan committed
520
521
522

        return res, min_time

yan.yan's avatar
yan.yan committed
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
    def run_with_tuned_result(self,
                              profile_res: BestAlgoByProfile,
                              a: tv.Tensor,
                              b: tv.Tensor,
                              c: tv.Tensor,
                              trans_a: bool,
                              trans_b: bool,
                              trans_c: bool,
                              arch: Tuple[int, int],
                              stream: int,
                              shuffle_type: ShuffleStrideType,
                              a_inds: tv.Tensor = tv.Tensor(),
                              b_inds: tv.Tensor = tv.Tensor(),
                              c_inds: tv.Tensor = tv.Tensor(),
                              hint: int = AlgoHint.NoHint.value,
                              alpha: float = 1.0,
                              beta: float = 0.0,
                              gather_data: tv.Tensor = tv.Tensor(),
                              workspace: tv.Tensor = tv.Tensor(),
                              timer: CUDAKernelTimer = CUDAKernelTimer(False),
yan.yan's avatar
yan.yan committed
543
544
545
546
547
                              force_nvrtc: bool = False,
                              bias: Optional[tv.Tensor] = None,
                              act_alpha: float = 0.0,
                              act_beta: float = 0.0,
                              act_type: tv.gemm.Activation = tv.gemm.Activation.None_):
yan.yan's avatar
v2.1  
yan.yan committed
548
549
        m, n, k = GemmMainUnitTest.extract_mnk(a.shape, b.shape, trans_a,
                                               trans_b, trans_c,
yan.yan's avatar
yan.yan committed
550
551
552
553
554
555
556
557
558
559
560
561
562
                                               shuffle_type.value,
                                               a_inds.shape, b_inds.shape,
                                               c_inds.shape)
        # GemmMainUnitTest.stream_synchronize(stream)
        algo_desp = profile_res.algo_desp
        assert algo_desp is not None
        split_k_slices = 1
        # TODO better splitk selection
        # if algo_desp.split_k_serial and hint & AlgoHint.BackwardWeight.value:
        #     split_k_slices = max(min(32, k // 128), 1)
        if profile_res.splitk > 1:
            split_k_slices = profile_res.splitk
        params = GemmParams()
yan.yan's avatar
yan.yan committed
563
        is_not_static = str(algo_desp) not in self.prebuilt_desp_names
yan.yan's avatar
yan.yan committed
564
        if algo_desp.is_nvrtc or is_not_static or force_nvrtc:
yan.yan's avatar
yan.yan committed
565
566
            params.nvrtc_params = self._cached_get_nvrtc_params(
                algo_desp, profile_res.arch)
yan.yan's avatar
sync  
yan.yan committed
567

yan.yan's avatar
yan.yan committed
568
569
570
        params.a = a
        params.b = b
        params.c = c
yan.yan's avatar
yan.yan committed
571
572
        if bias is not None:
            params.d = bias
yan.yan's avatar
yan.yan committed
573
574
575
576
577
578
579
580
        params.a_inds = a_inds
        params.b_inds = b_inds
        params.c_inds = c_inds
        params.algo_desp = algo_desp
        params.split_k_slices = split_k_slices
        params.stream = stream
        params.alpha = alpha
        params.beta = beta
yan.yan's avatar
yan.yan committed
581
582
583
        params.act_alpha = act_alpha
        params.act_beta = act_beta
        params.act_type = act_type
yan.yan's avatar
yan.yan committed
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
        params.workspace = workspace
        # gather = 0
        # if profile_res.external_gather and not gather_data.empty():
        #     GemmMainUnitTest.stream_synchronize(stream)
        #     tt = time.time()
        #     assert not gather_data.empty()
        #     params.a_inds = tv.Tensor()
        #     params.a = gather_data
        #     # print(profile_res.gather_params, gather_data.shape, a.shape, a_inds.shape)
        #     GATHER.gather(gather_data,
        #                    a,
        #                    a_inds,
        #                    *profile_res.gather_params,
        #                    stream=stream)
        #     GemmMainUnitTest.stream_synchronize(stream)
        #     gather = time.time() - tt
600
601
602
        if timer.enable:
            assert timer._timer is not None
            params.timer = timer._timer
yan.yan's avatar
yan.yan committed
603
604
605
606
607
608

        GemmMainUnitTest.matmul2(params)
        # GemmMainUnitTest.stream_synchronize(stream)
        return algo_desp


609
_CONV_STATIC_KEY = Tuple[int, int, int, int, int, int, int, int, int, int]
yan.yan's avatar
v2.1  
yan.yan committed
610
611
612


class SimpleConv:
yan.yan's avatar
yan.yan committed
613

yan.yan's avatar
sync  
yan.yan committed
614
    def __init__(self, prebuilt_desps: List[ConvAlgoDesp]) -> None:
yan.yan's avatar
yan.yan committed
615
616
617
618
        all_desps = [
            algocore.get_conv_algo_desp_from_param(p)
            for p in ALL_IMPGEMM_PARAMS
        ]
yan.yan's avatar
sync  
yan.yan committed
619
620
621
        self.prebuilt_desps = prebuilt_desps
        self.prebuilt_desp_names = {str(d) for d in prebuilt_desps}
        self.prebuilt_desp_names.clear()
yan.yan's avatar
v2.1  
yan.yan committed
622
623
        self.lock = Lock()

yan.yan's avatar
sync  
yan.yan committed
624
        self.static_key_to_desps = group_by(self.get_static_key, all_desps)
yan.yan's avatar
v2.1  
yan.yan committed
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
        self.static_key_to_meta: Dict[_CONV_STATIC_KEY,
                                      SimpleGemmAlgoMeta] = {}
        for k, static_desps in self.static_key_to_desps.items():
            tile_shape_to_algos: Dict[int, List[int]] = {}
            tile_ms: Set[int] = set()
            tile_ns: Set[int] = set()
            tile_ks: Set[int] = set()
            for i, desp in enumerate(static_desps):
                ts = desp.tile_shape
                tile_ms.add(ts[0])
                tile_ns.add(ts[1])
                tile_ks.add(ts[2])
                tile_key = ts[0] | (ts[1] << 20) | (ts[2] << 40)
                if tile_key not in tile_shape_to_algos:
                    tile_shape_to_algos[tile_key] = []
                tile_shape_to_algos[tile_key].append(i)
yan.yan's avatar
yan.yan committed
641
642
643
644
645
646
            tile_ms_list = list(tile_ms)
            tile_ns_list = list(tile_ns)
            tile_ks_list = list(tile_ks)
            tile_ms_list.sort()
            tile_ns_list.sort()
            tile_ks_list.sort()
yan.yan's avatar
v2.1  
yan.yan committed
647
648
649
650
651
652
653
654
655
656
657
658
            self.static_key_to_meta[k] = SimpleGemmAlgoMeta(
                tile_ms_list, tile_ns_list, tile_ks_list, tile_shape_to_algos)

        self.kc_forward_cache: Dict[Tuple[int, int, int, int, int, int, int,
                                          int],
                                    BestConvAlgoByProfile] = {}  # for forward
        self.kc_dgrad_cache: Dict[Tuple[int, int, int, int, int, int, int,
                                        int], BestConvAlgoByProfile] = {
                                        }  # for backward weight
        self.kc_wgrad_cache: Dict[Tuple[int, int, int, int, int, int, int,
                                        int], BestConvAlgoByProfile] = {
                                        }  # for backward weight
yan.yan's avatar
yan.yan committed
659

yan.yan's avatar
sync  
yan.yan committed
660
        self._nvrtc_caches: Dict[Tuple[str, Tuple[int, int]], NVRTCParams] = {}
yan.yan's avatar
v2.1  
yan.yan committed
661
662
663

    @staticmethod
    def get_static_key(d: ConvAlgoDesp) -> _CONV_STATIC_KEY:
yan.yan's avatar
sync  
yan.yan committed
664
665
        return (d.layout_i.value, d.layout_w.value, d.layout_o.value,
                d.interleave_i, d.interleave_w, d.interleave_o, d.dtype_input,
666
                d.dtype_weight, d.dtype_output, d.op_type.value)
yan.yan's avatar
v2.1  
yan.yan committed
667
668
669
670

    def device_synchronize(self):
        return GemmMainUnitTest.device_synchronize()

yan.yan's avatar
sync  
yan.yan committed
671
672
673
674
675
676
677
678
679
680
    def get_all_available(self,
                          inp: tv.Tensor,
                          weight: tv.Tensor,
                          out: tv.Tensor,
                          layout_i: ConvLayout,
                          layout_w: ConvLayout,
                          layout_o: ConvLayout,
                          arch: Tuple[int, int],
                          op_type: ConvOpType,
                          mask_width: int,
yan.yan's avatar
yan.yan committed
681
682
                          fp32_accum: Optional[bool] = None,
                          use_tf32: bool = True):
yan.yan's avatar
v2.1  
yan.yan committed
683
684
685

        avail_algos = get_available_algo_str_from_arch(arch)
        finally_algos: List[ConvAlgoDesp] = []
yan.yan's avatar
yan.yan committed
686
687
688
        is_fp16 = inp.dtype == tv.float16 and weight.dtype == tv.float16 and out.dtype == tv.float16
        use_f32_as_accum = False
        kv = int(np.prod(weight.shape[1:-1]))
yan.yan's avatar
sync  
yan.yan committed
689
        # for 3d conv, if reduce axis is too large, may cause nan during
yan.yan's avatar
yan.yan committed
690
691
692
693
694
695
696
697
698
        # forward.
        if is_fp16:
            if fp32_accum is None:
                if op_type == ConvOpType.kForward:
                    use_f32_as_accum = weight.dim(-1) * kv > 128 * 27
                elif op_type == ConvOpType.kBackwardInput:
                    use_f32_as_accum = weight.dim(0) * kv > 128 * 27
            else:
                use_f32_as_accum = fp32_accum
yan.yan's avatar
yan.yan committed
699
        # use_f32_as_accum = False
700
701
702
703
704
705
706
707
708
709
        static_key = (layout_i.layout_type.value,
                        layout_w.layout_type.value,
                        layout_o.layout_type.value, layout_i.interleave,
                        layout_w.interleave, layout_o.interleave, inp.dtype,
                        weight.dtype, out.dtype, op_type.value)
        desps = self.static_key_to_desps.get(static_key, None)
        if desps is None or len(desps) == 0:
            return finally_algos
        for desp in desps:
            if arch < desp.min_arch:
yan.yan's avatar
v2.1  
yan.yan committed
710
                continue
711
712
713
            # skip volta tensor op since it is very slow in architectures except volta.
            if arch >= (7, 5) and desp.algo == GemmAlgo.Volta.value:
                continue
yan.yan's avatar
yan.yan committed
714
715
716
717
            if not use_tf32:
                if (desp.tensorop[0] > 0 and inp.dtype == tv.float32 
                        and weight.dtype == tv.float32 and out.dtype == tv.float32):
                    continue
718
719
            if arch >= (7, 0) and is_fp16:
                if desp.algo == GemmAlgo.Simt:
yan.yan's avatar
v2.1  
yan.yan committed
720
                    continue
721
722
                if use_f32_as_accum:
                    if desp.dacc == tv.float16:
yan.yan's avatar
yan.yan committed
723
                        continue
724
725
726
727
728

            ldi = inp.dim(-1)
            ldw = weight.dim(-1)
            ldo = out.dim(-1)
            mask_width_valid = True
yan.yan's avatar
yan.yan committed
729
730
            
            if desp.op_type.value == ConvOpType.kBackwardWeight.value:
731
732
733
                assert mask_width > 0
                mask_width_valid = mask_width % desp.tile_shape[2] == 0
            if desp.supported_ldx_conv(ldi, ldw, ldo) and mask_width_valid:
yan.yan's avatar
yan.yan committed
734
735
736
737
738
739
740
741
742
743
744
745
746
747
                if desp.is_nvrtc:
                    if not CompileInfo.algo_can_be_nvrtc_compiled(desp.min_arch):
                        continue
                if not CompileInfo.arch_is_compiled_gemm(arch):
                    # use PTX of possible
                    if not CompileInfo.gemm_algo_can_use_ptx(desp.min_arch, arch):
                        if CompileInfo.algo_can_be_nvrtc_compiled(desp.min_arch):
                            # compiled kernel can't use PTX, for example, desp need at least sm_80 and only sm_75+PTX is compiled
                            # all sm_80 code of this desp is invalid, we must use nvrtc.
                            # only desp <= sm_75 can use virtual PTX code to generate sm_80 code.
                            desp = desp.copy()
                            desp.is_nvrtc = True
                        else:
                            continue
748
749
750
                if SPCONV_DEBUG_NVRTC_KERNELS:
                    desp.is_nvrtc = True
                finally_algos.append(desp)
yan.yan's avatar
v2.1  
yan.yan committed
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
        return finally_algos

    def get_tuned_algo(self,
                       op_type: ConvOpType,
                       i_dtype: int,
                       w_dtype: int,
                       o_dtype: int,
                       k: int,
                       c: int,
                       arch: Tuple[int, int],
                       mask_width: int = -1):
        if not op_type == ConvOpType.kBackwardWeight:
            # fwd and dgrad don't need
            mask_width = -1
        key = (i_dtype, w_dtype, o_dtype, k, c, arch[0], arch[1], mask_width)
        if op_type == ConvOpType.kForward:
            return self.kc_forward_cache.get(key, None)
        elif op_type == ConvOpType.kBackwardInput:
            return self.kc_dgrad_cache.get(key, None)
        elif op_type == ConvOpType.kBackwardWeight:
            return self.kc_wgrad_cache.get(key, None)
        raise NotImplementedError

    def query_workspace_size(self, desp: ConvAlgoDesp, splitk: int,
                             op_type: ConvOpType, N: int, C: int, K: int,
                             kv: int):
        mnk = ConvMainUnitTest.extract_mnk(op_type.value, N, C, K, kv, -1, -1,
                                           True)
        return desp.query_conv_workspace_size(mnk[0], mnk[1], mnk[2], splitk,
                                              kv)

yan.yan's avatar
sync  
yan.yan committed
782
783
784
785
786
787
    def _compile_nvrtc_module(self, desp: ConvAlgoDesp):
        params = algocore.get_conv_param_from_desp(desp)
        kernel = gen_conv_kernels(params, SPCONV_NVRTC_MODE)
        kernel.namespace = "spconv"
        custom_names = []
        if SPCONV_NVRTC_MODE == NVRTCMode.ConstantMemory:
yan.yan's avatar
yan.yan committed
788
789
790
            custom_names = [
                f"&{kernel.namespace}::{NVRTCConstants.CONSTANT_PARAM_KEY}"
            ]
yan.yan's avatar
sync  
yan.yan committed
791
792
793
794
795
796
        cudadevrt = ""
        if SPCONV_NVRTC_MODE == NVRTCMode.DynamicParallism:
            cudadevrt_p = get_cudadevrt_path()
            assert cudadevrt_p is not None, "DynamicParallism must have cudadevrt"
            cudadevrt = str(cudadevrt_p)
        mod = CummNVRTCModule([kernel],
yan.yan's avatar
yan.yan committed
797
798
799
                              cudadevrt_path=cudadevrt,
                              verbose=False,
                              custom_names=custom_names)
yan.yan's avatar
sync  
yan.yan committed
800
801
802
        mod.load()
        return mod, kernel

yan.yan's avatar
yan.yan committed
803
804
    def _cached_get_nvrtc_params(self, desp: ConvAlgoDesp, arch: Tuple[int,
                                                                       int]):
yan.yan's avatar
sync  
yan.yan committed
805
806
807
        key = (str(desp), arch)
        if key in self._nvrtc_caches:
            return self._nvrtc_caches[key]
yan.yan's avatar
yan.yan committed
808
        print(f"Can't find algo {desp} in prebuilt. compile with nvrtc...")
yan.yan's avatar
sync  
yan.yan committed
809
810
811
        mod, ker = self._compile_nvrtc_module(desp)
        nvrtc_params = _get_nvrtc_params(mod, ker, "conv_kernel")
        self._nvrtc_caches[key] = nvrtc_params
yan.yan's avatar
yan.yan committed
812
        return nvrtc_params
yan.yan's avatar
sync  
yan.yan committed
813

yan.yan's avatar
v2.1  
yan.yan committed
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
    def tune_and_cache(self,
                       op_type: ConvOpType,
                       inp: tv.Tensor,
                       weight: tv.Tensor,
                       output: tv.Tensor,
                       layout_i: ConvLayout,
                       layout_w: ConvLayout,
                       layout_o: ConvLayout,
                       arch: Tuple[int, int],
                       mask: tv.Tensor,
                       mask_argsort: tv.Tensor,
                       indices: tv.Tensor,
                       reverse_mask: bool,
                       mask_filter: int = 0xffffffff,
                       mask_width: int = -1,
                       mask_output: tv.Tensor = tv.Tensor(),
                       alpha: float = 1.0,
                       beta: float = 0.0,
yan.yan's avatar
yan.yan committed
832
                       stream: int = 0,
yan.yan's avatar
yan.yan committed
833
834
                       fp32_accum: Optional[bool] = None,
                        use_tf32: bool = True):
yan.yan's avatar
v2.1  
yan.yan committed
835
        avail = self.get_all_available(inp, weight, output, layout_i, layout_w,
yan.yan's avatar
sync  
yan.yan committed
836
                                       layout_o, arch, op_type, mask_width,
yan.yan's avatar
yan.yan committed
837
                                       fp32_accum, use_tf32)
yan.yan's avatar
v2.1  
yan.yan committed
838
839
840
841
842
843
844
845
846
        inp = inp.clone()
        weight = weight.clone()
        output = output.clone()

        channel_k = output.dim(1)
        channel_c = inp.dim(1)

        times: List[float] = []
        all_profile_res: List[BestConvAlgoByProfile] = []
yan.yan's avatar
yan.yan committed
847
        group_by_algo = {}
yan.yan's avatar
v2.1  
yan.yan committed
848
849
        for desp in avail:
            # for sparse conv, ndim isn't used, so we just provide a constant value.
yan.yan's avatar
sync  
yan.yan committed
850
            params = ConvParams(NDIM_DONT_CARE, ConvOpTypeCpp(op_type.value))
yan.yan's avatar
yan.yan committed
851
            if desp.is_nvrtc or str(desp) not in self.prebuilt_desp_names:
yan.yan's avatar
sync  
yan.yan committed
852
853
                params.nvrtc_params = self._cached_get_nvrtc_params(desp, arch)

yan.yan's avatar
v2.1  
yan.yan committed
854
855
856
857
858
859
860
861
862
863
864
865
866
            params.conv_algo_desp = desp
            params.input = inp
            params.weight = weight.view([channel_k, -1, channel_c])
            params.output = output

            params.mask_width = mask_width
            params.alpha = alpha
            params.beta = beta
            params.stream = stream
            params.mask_argsort = mask_argsort
            params.indices = indices
            params.mask = mask
            params.mask_output = mask_output
yan.yan's avatar
yan.yan committed
867
868
            # if op_type == ConvOpType.kBackwardWeight:
            #     assert not mask_output.empty()
yan.yan's avatar
v2.1  
yan.yan committed
869
870
871
872
            if op_type == ConvOpType.kBackwardInput:
                params.reverse_mask = reverse_mask
            params.mask_filter = mask_filter
            if desp.split_k_serial and op_type == ConvOpType.kBackwardWeight:
yan.yan's avatar
yan.yan committed
873
                splitk_tests = SPCONV_BWD_SPLITK
yan.yan's avatar
v2.1  
yan.yan committed
874
875
876
877
878
879
                # splitk_tests = [1]
            else:
                splitk_tests = [1]
            spk_speeds = []
            for spk in splitk_tests:
                this_times = []
yan.yan's avatar
yan.yan committed
880
                for j in range(4):
yan.yan's avatar
v2.1  
yan.yan committed
881
                    params.split_k_slices = spk
yan.yan's avatar
yan.yan committed
882
883
884
885
886
887
888
                    with tv.measure_duration(stream=stream) as measure:
                        if desp.is_nvrtc and str(
                                desp) not in self.prebuilt_desp_names:
                            tv.gemm.run_nvrtc_conv_kernel(params)
                        else:
                            ConvMainUnitTest.implicit_gemm2(params)
                    this_times.append(measure.duration)
yan.yan's avatar
v2.1  
yan.yan committed
889
890
                times.append(np.mean(this_times[1:]))
                spk_speeds.append(times[-1])
yan.yan's avatar
yan.yan committed
891
892
893
                if desp.algo not in group_by_algo:
                    group_by_algo[desp.algo] = 10000.0
                group_by_algo[desp.algo] = min(times[-1], group_by_algo[desp.algo])
yan.yan's avatar
yan.yan committed
894
895
                all_profile_res.append(
                    BestConvAlgoByProfile(desp, arch, splitk=spk))
yan.yan's avatar
v2.1  
yan.yan committed
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
        if not all_profile_res:
            raise ValueError("can't find suitable algorithm for", op_type)
        min_time = 1000
        min_idx = -1
        for i, t in enumerate(times):
            if t < min_time:
                min_time = t
                min_idx = i
        res = all_profile_res[min_idx]
        if not op_type == ConvOpType.kBackwardWeight:
            # fwd and dgrad don't need
            mask_width = -1
        key = (inp.dtype, weight.dtype, output.dtype, channel_k, channel_c,
               arch[0], arch[1], mask_width)
        with self.lock:
            if op_type == ConvOpType.kForward:
                self.kc_forward_cache[key] = res
            elif op_type == ConvOpType.kBackwardInput:
                self.kc_dgrad_cache[key] = res
            elif op_type == ConvOpType.kBackwardWeight:
                self.kc_wgrad_cache[key] = res
            else:
                raise NotImplementedError
        return res, min_time

    def run_with_tuned_result(self,
                              profile_res: BestConvAlgoByProfile,
                              op_type: Union[ConvOpType, int],
                              inp: tv.Tensor,
                              weight: tv.Tensor,
                              output: tv.Tensor,
                              mask: tv.Tensor,
                              mask_argsort: tv.Tensor,
                              mask_output: tv.Tensor,
                              indices: tv.Tensor,
                              reverse_mask: bool,
                              mask_filter: int = 0xffffffff,
                              mask_width: int = -1,
                              alpha: float = 1.0,
                              beta: float = 0.0,
                              stream: int = 0,
                              workspace: tv.Tensor = tv.Tensor(),
938
                              verbose: bool = False,
yan.yan's avatar
yan.yan committed
939
                              timer: CUDAKernelTimer = CUDAKernelTimer(False),
yan.yan's avatar
yan.yan committed
940
941
942
943
944
                              force_nvrtc: bool = False,
                              bias: Optional[tv.Tensor] = None,
                              act_alpha: float = 0.0,
                              act_beta: float = 0.0,
                              act_type: tv.gemm.Activation = tv.gemm.Activation.None_):
yan.yan's avatar
v2.1  
yan.yan committed
945
946
947
948
949
950
951
952
953
954
955
956
        channel_k = output.dim(1)
        channel_c = inp.dim(1)
        # GemmMainUnitTest.stream_synchronize(stream)
        algo_desp = profile_res.algo_desp
        assert algo_desp is not None
        split_k_slices = 1
        if profile_res.splitk > 1:
            split_k_slices = profile_res.splitk
        if isinstance(op_type, int):
            op_type_value = op_type
        else:
            op_type_value = op_type.value
yan.yan's avatar
sync  
yan.yan committed
957
        params = ConvParams(NDIM_DONT_CARE, ConvOpTypeCpp(op_type_value))
yan.yan's avatar
yan.yan committed
958
959
        is_not_static = str(
                algo_desp) not in self.prebuilt_desp_names
yan.yan's avatar
yan.yan committed
960
        if force_nvrtc or algo_desp.is_nvrtc or is_not_static:
yan.yan's avatar
yan.yan committed
961
962
            params.nvrtc_params = self._cached_get_nvrtc_params(
                algo_desp, profile_res.arch)
yan.yan's avatar
v2.1  
yan.yan committed
963
964
965
966
967
        params.conv_algo_desp = profile_res.algo_desp
        params.input = inp
        params.verbose = verbose
        params.weight = weight.view([channel_k, -1, channel_c])
        params.output = output
yan.yan's avatar
yan.yan committed
968

yan.yan's avatar
v2.1  
yan.yan committed
969
970
971
        params.split_k_slices = split_k_slices
        params.alpha = alpha
        params.beta = beta
yan.yan's avatar
yan.yan committed
972
973
974
        params.act_alpha = act_alpha
        params.act_beta = act_beta
        params.act_type = act_type
yan.yan's avatar
v2.1  
yan.yan committed
975
976
977
978
        params.stream = stream
        params.mask_argsort = mask_argsort
        params.indices = indices
        params.mask = mask
yan.yan's avatar
yan.yan committed
979

yan.yan's avatar
v2.1  
yan.yan committed
980
981
982
983
984
        params.mask_filter = mask_filter
        params.mask_width = mask_width
        params.mask_filter = mask_filter
        params.mask_output = mask_output
        params.reverse_mask = reverse_mask
yan.yan's avatar
yan.yan committed
985
986
        if bias is not None:
            params.bias = bias
987
988
989
        if timer.enable:
            assert timer._timer is not None
            params.timer = timer._timer
yan.yan's avatar
v2.1  
yan.yan committed
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
        # torch.cuda.synchronize()
        # t = time.time()
        params.workspace = workspace
        ConvMainUnitTest.implicit_gemm2(params)
        # torch.cuda.synchronize()
        # dura = time.time() - t
        # print("F", algo_desp, dura)

        # GemmMainUnitTest.stream_synchronize(stream)
        return algo_desp

    def stream_synchronize(self, stream: int):
        return GemmMainUnitTest.stream_synchronize(stream)

1004

yan.yan's avatar
yan.yan committed
1005
GEMM = SimpleGemm(ALL_ALGO_DESPS)
yan.yan's avatar
v2.1  
yan.yan committed
1006
CONV = SimpleConv(ALL_CONV_ALGO_DESPS)
yan.yan's avatar
yan.yan committed
1007

yan.yan's avatar
yan.yan committed
1008
1009
1010
1011
1012
1013
1014
GEMM_CPP = GemmTunerSimple([
            algocore.get_gemm_algo_desp_from_param(p)
            for p in ALL_NATIVE_PARAMS])
CONV_CPP = ConvTunerSimple([
            algocore.get_conv_algo_desp_from_param(p)
            for p in ALL_IMPGEMM_PARAMS])

yan.yan's avatar
yan.yan committed
1015
if __name__ == "__main__":
1016
1017
    for desp in ALL_CONV_ALGO_DESPS:
        print(desp, desp.min_arch)