conv2d_operation.py 29.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#
# \file generator.py
#
# \brief Generates the CUTLASS Library's instances
#
#

import enum
import os.path
import shutil
from typing import Tuple, List

from library import *

###################################################################################################

#
class Conv2dOperation:
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
    #
    def __init__(
        self,
        conv_kind,
        conv_type,
        arch,
        tile_description,
        src,
        flt,
        bias,
        dst,
        element_epilogue,
        epilogue_functor=EpilogueFunctor.LinearCombination,
        swizzling_functor=SwizzlingFunctor.Identity4,
        special_optimization=SpecialOptimizeDesc.NoneSpecialOpt,
        implicit_gemm_mode=ImplicitGemmMode.GemmNT,
        without_shared_load=False,
        required_cuda_ver_major=9,
        required_cuda_ver_minor=2,
    ):

        self.operation_kind = OperationKind.Conv2d
        self.conv_kind = conv_kind
        self.arch = arch
        self.tile_description = tile_description
        self.conv_type = conv_type
        self.src = src
        self.flt = flt
        self.bias = bias
        self.dst = dst
        self.element_epilogue = element_epilogue
        self.epilogue_functor = epilogue_functor
        self.swizzling_functor = swizzling_functor
        self.special_optimization = special_optimization
        self.implicit_gemm_mode = implicit_gemm_mode
        self.without_shared_load = without_shared_load
        self.required_cuda_ver_major = required_cuda_ver_major
        self.required_cuda_ver_minor = required_cuda_ver_minor

    #
    def accumulator_type(self):
        accum = self.tile_description.math_instruction.element_accumulator

        return accum

    #
    def core_name(self):
        """ The basic operation kind is prefixed with a letter indicating the accumulation type. """

        intermediate_type = ""

        if self.tile_description.math_instruction.opcode_class == OpcodeClass.TensorOp:
            inst_shape = "%d%d%d" % tuple(
                self.tile_description.math_instruction.instruction_shape
            )
            if (
                self.tile_description.math_instruction.element_a != self.flt.element
                and self.tile_description.math_instruction.element_a
                != self.accumulator_type()
            ):
                intermediate_type = DataTypeNames[
                    self.tile_description.math_instruction.element_a
                ]
        else:
            inst_shape = ""

        special_opt = ""
        if self.special_optimization == SpecialOptimizeDesc.ConvFilterUnity:
            special_opt = "_1x1"
        elif self.special_optimization == SpecialOptimizeDesc.DeconvDoubleUpsampling:
            special_opt = "_s2"

        reorder_k = ""
        if self.without_shared_load:
            reorder_k = "_roc"

        conv_type_name = ""
        if self.conv_type == ConvType.DepthwiseConvolution:
            conv_type_name = "dw"

        return "%s%s%s%s%s%s%s_%s" % (
            ShortDataTypeNames[self.accumulator_type()],
            inst_shape,
            intermediate_type,
            conv_type_name,
            ConvKindNames[self.conv_kind],
            special_opt,
            reorder_k,
            ShortEpilogueNames[self.epilogue_functor],
        )

    #
    def extended_name(self):
        if (
            self.dst.element
            != self.tile_description.math_instruction.element_accumulator
        ):
            if self.src.element != self.flt.element:
                extended_name = (
                    "${element_dst}_${core_name}_${element_src}_${element_flt}"
                )
            elif self.src.element == self.flt.element:
                extended_name = "${element_dst}_${core_name}_${element_src}"
        else:
            if self.src.element != self.flt.element:
                extended_name = "${core_name}_${element_src}_${element_flt}"
            elif self.src.element == self.flt.element:
                extended_name = "${core_name}_${element_src}"

        extended_name = SubstituteTemplate(
            extended_name,
            {
                "element_src": DataTypeNames[self.src.element],
                "element_flt": DataTypeNames[self.flt.element],
                "element_dst": DataTypeNames[self.dst.element],
                "core_name": self.core_name(),
            },
        )

        return extended_name

    #
    def layout_name(self):
        if self.src.layout == self.dst.layout:
            layout_name = "${src_layout}_${flt_layout}"
        else:
            layout_name = "${src_layout}_${flt_layout}_${dst_layout}"

        layout_name = SubstituteTemplate(
            layout_name,
            {
                "src_layout": ShortLayoutTypeNames[self.src.layout],
                "flt_layout": ShortLayoutTypeNames[self.flt.layout],
                "dst_layout": ShortLayoutTypeNames[self.dst.layout],
            },
        )

        return layout_name

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

        opcode_class_name = OpcodeClassNames[
            self.tile_description.math_instruction.opcode_class
        ]

        warp_shape = [
            int(
                self.tile_description.threadblock_shape[idx]
                / self.tile_description.warp_count[idx]
            )
            for idx in range(3)
        ]

        threadblock = "%dx%dx%d_%dx%dx%d_%d" % (
            self.tile_description.threadblock_shape[0],
            self.tile_description.threadblock_shape[1],
            self.tile_description.threadblock_shape[2],
            warp_shape[0],
            warp_shape[1],
            warp_shape[2],
            self.tile_description.stages,
        )

        alignment = "align%dx%d" % (self.src.alignment, self.flt.alignment)

        configuration_name = "cutlass_${opcode_class}_${extended_name}_${threadblock}_${layout}_${alignment}"

        return SubstituteTemplate(
            configuration_name,
            {
                "opcode_class": opcode_class_name,
                "extended_name": self.extended_name(),
                "threadblock": threadblock,
                "layout": self.layout_name(),
                "alignment": alignment,
            },
        )

    #
    def procedural_name(self):
        """ The full procedural name indicates architecture, extended name, tile size, and layout. """
        return self.configuration_name()
203 204 205 206 207 208 209 210


###################################################################################################
#
# Emits single instances of a CUTLASS device-wide operator
#
###################################################################################################

211

212
class EmitConv2dInstance:
213 214
    def __init__(self):
        self.template = """
215 216 217 218 219 220 221 222 223 224 225 226
// kernel instance "${operation_name}" generated by cutlass generator
using Convolution = 
  typename cutlass::conv::device::Convolution<
    ${element_src}, 
    ${layout_src},
    ${element_flt}, 
    ${layout_flt},
    ${element_dst}, 
    ${layout_dst},
    ${element_bias}, 
    ${layout_bias}, 
    ${element_accumulator}, 
227
    ${conv_type},
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
    ${opcode_class},
    ${arch},
    cutlass::gemm::GemmShape<${threadblock_shape_m}, ${threadblock_shape_n}, ${threadblock_shape_k}>,
    cutlass::gemm::GemmShape<${warp_shape_m}, ${warp_shape_n}, ${warp_shape_k}>,
    cutlass::gemm::GemmShape<${instruction_shape_m}, ${instruction_shape_n}, ${instruction_shape_k}>,
    ${epilogue_functor}<
      ${element_dst},
      ${epilogue_vector_length},
      ${element_accumulator}, 
      ${element_bias}, 
      ${element_epilogue}
    >,
    ${swizzling_functor},     
    ${stages},
    ${alignment_src}, 
    ${alignment_filter}, 
244
    ${special_optimization}, 
245
    ${math_operator},
246 247
    ${implicit_gemm_mode}, 
    ${without_shared_load}>;
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
    def emit(self, operation):

        warp_shape = [
            int(
                operation.tile_description.threadblock_shape[idx]
                / operation.tile_description.warp_count[idx]
            )
            for idx in range(3)
        ]

        epilogue_vector_length = int(
            min(operation.dst.alignment * DataTypeSize[operation.dst.element], 128)
            / DataTypeSize[operation.dst.element]
        )

        values = {
            "operation_name": operation.procedural_name(),
            "conv_type": ConvTypeTag[operation.conv_type],
            "element_src": DataTypeTag[operation.src.element],
            "layout_src": LayoutTag[operation.src.layout],
            "element_flt": DataTypeTag[operation.flt.element],
            "layout_flt": LayoutTag[operation.flt.layout],
            "element_dst": DataTypeTag[operation.dst.element],
            "layout_dst": LayoutTag[operation.dst.layout],
            "element_bias": DataTypeTag[operation.bias.element],
            "layout_bias": LayoutTag[operation.bias.layout],
            "element_accumulator": DataTypeTag[operation.accumulator_type()],
            "opcode_class": OpcodeClassTag[
                operation.tile_description.math_instruction.opcode_class
            ],
            "arch": "cutlass::arch::Sm%d" % operation.arch,
            "threadblock_shape_m": str(operation.tile_description.threadblock_shape[0]),
            "threadblock_shape_n": str(operation.tile_description.threadblock_shape[1]),
            "threadblock_shape_k": str(operation.tile_description.threadblock_shape[2]),
            "warp_shape_m": str(warp_shape[0]),
            "warp_shape_n": str(warp_shape[1]),
            "warp_shape_k": str(warp_shape[2]),
            "instruction_shape_m": str(
                operation.tile_description.math_instruction.instruction_shape[0]
            ),
            "instruction_shape_n": str(
                operation.tile_description.math_instruction.instruction_shape[1]
            ),
            "instruction_shape_k": str(
                operation.tile_description.math_instruction.instruction_shape[2]
            ),
            "epilogue_vector_length": str(epilogue_vector_length),
            "epilogue_functor": EpilogueFunctorTag[operation.epilogue_functor],
            "element_epilogue": str(DataTypeTag[operation.element_epilogue]),
            "swizzling_functor": SwizzlingFunctorTag[operation.swizzling_functor],
            "stages": str(operation.tile_description.stages),
            "alignment_src": str(operation.src.alignment),
            "alignment_filter": str(operation.flt.alignment),
            "special_optimization": SpecialOptimizeDescTag[
                operation.special_optimization
            ],
            "math_operator": MathOperationTag[
                operation.tile_description.math_instruction.math_operation
            ],
            "implicit_gemm_mode": ImplicitGemmModeTag[operation.implicit_gemm_mode],
            "without_shared_load": str(operation.without_shared_load).lower(),
        }

        return SubstituteTemplate(self.template, values)
314 315 316


class EmitDeconvInstance:
317 318
    def __init__(self):
        self.template = """
319 320 321 322 323 324 325 326 327 328 329 330
// kernel instance "${operation_name}" generated by cutlass generator
using Deconvolution = 
  typename cutlass::conv::device::Deconvolution<
    ${element_src}, 
    ${layout_src},
    ${element_flt}, 
    ${layout_flt},
    ${element_dst}, 
    ${layout_dst},
    ${element_bias}, 
    ${layout_bias}, 
    ${element_accumulator}, 
331
    ${conv_type},
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
    ${opcode_class},
    ${arch},
    cutlass::gemm::GemmShape<${threadblock_shape_m}, ${threadblock_shape_n}, ${threadblock_shape_k}>,
    cutlass::gemm::GemmShape<${warp_shape_m}, ${warp_shape_n}, ${warp_shape_k}>,
    cutlass::gemm::GemmShape<${instruction_shape_m}, ${instruction_shape_n}, ${instruction_shape_k}>,
    ${epilogue_functor}<
      ${element_dst},
      ${epilogue_vector_length},
      ${element_accumulator}, 
      ${element_bias}, 
      ${element_epilogue}
    >,
    ${swizzling_functor},     
    ${stages},
    ${alignment_src}, 
    ${alignment_filter}, 
348
    ${special_optimization}, 
349 350 351 352
    ${math_operator},
    ${implicit_gemm_mode}>;
"""

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
    def emit(self, operation):

        warp_shape = [
            int(
                operation.tile_description.threadblock_shape[idx]
                / operation.tile_description.warp_count[idx]
            )
            for idx in range(3)
        ]

        epilogue_vector_length = int(
            min(operation.dst.alignment * DataTypeSize[operation.dst.element], 128)
            / DataTypeSize[operation.dst.element]
        )

        values = {
            "operation_name": operation.procedural_name(),
            "conv_type": ConvTypeTag[operation.conv_type],
            "element_src": DataTypeTag[operation.src.element],
            "layout_src": LayoutTag[operation.src.layout],
            "element_flt": DataTypeTag[operation.flt.element],
            "layout_flt": LayoutTag[operation.flt.layout],
            "element_dst": DataTypeTag[operation.dst.element],
            "layout_dst": LayoutTag[operation.dst.layout],
            "element_bias": DataTypeTag[operation.bias.element],
            "layout_bias": LayoutTag[operation.bias.layout],
            "element_accumulator": DataTypeTag[operation.accumulator_type()],
            "opcode_class": OpcodeClassTag[
                operation.tile_description.math_instruction.opcode_class
            ],
            "arch": "cutlass::arch::Sm%d" % operation.arch,
            "threadblock_shape_m": str(operation.tile_description.threadblock_shape[0]),
            "threadblock_shape_n": str(operation.tile_description.threadblock_shape[1]),
            "threadblock_shape_k": str(operation.tile_description.threadblock_shape[2]),
            "warp_shape_m": str(warp_shape[0]),
            "warp_shape_n": str(warp_shape[1]),
            "warp_shape_k": str(warp_shape[2]),
            "instruction_shape_m": str(
                operation.tile_description.math_instruction.instruction_shape[0]
            ),
            "instruction_shape_n": str(
                operation.tile_description.math_instruction.instruction_shape[1]
            ),
            "instruction_shape_k": str(
                operation.tile_description.math_instruction.instruction_shape[2]
            ),
            "epilogue_vector_length": str(epilogue_vector_length),
            "epilogue_functor": EpilogueFunctorTag[operation.epilogue_functor],
            "element_epilogue": str(DataTypeTag[operation.element_epilogue]),
            "swizzling_functor": SwizzlingFunctorTag[operation.swizzling_functor],
            "stages": str(operation.tile_description.stages),
            "alignment_src": str(operation.src.alignment),
            "alignment_filter": str(operation.flt.alignment),
            "special_optimization": SpecialOptimizeDescTag[
                operation.special_optimization
            ],
            "math_operator": MathOperationTag[
                operation.tile_description.math_instruction.math_operation
            ],
            "implicit_gemm_mode": ImplicitGemmModeTag[operation.implicit_gemm_mode],
        }

        return SubstituteTemplate(self.template, values)
416 417 418 419 420 421 422 423 424


###################################################################################################
#
# Generator functions for all layouts
#
###################################################################################################

#
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 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
def GenerateConv2d(
    conv_type,
    conv_kind,
    tile_descriptions,
    src_layout,
    flt_layout,
    dst_layout,
    dst_type,
    min_cc,
    src_align=32,
    flt_align=32,
    dst_align=32,
    use_special_optimization=SpecialOptimizeDesc.NoneSpecialOpt,
    implicit_gemm_mode=ImplicitGemmMode.GemmNT,
    without_shared_load=False,
    required_cuda_ver_major=9,
    required_cuda_ver_minor=2,
):
    operations = []

    element_epilogue = DataType.f32
    if conv_type == ConvType.DepthwiseConvolution:
        if conv_kind == ConvKind.Fprop:
            swizzling_functor = SwizzlingFunctor.DepthwiseConvolutionFprop
        elif conv_kind == ConvKind.Dgrad:
            swizzling_functor = SwizzlingFunctor.DepthwiseConvolutionDgrad
        else:
            assert conv_kind == ConvKind.Wgrad
            swizzling_functor = SwizzlingFunctor.DepthwiseConvolutionWgrad
    elif conv_type == ConvType.Convolution:
        if conv_kind == ConvKind.Fprop:
            if implicit_gemm_mode == ImplicitGemmMode.GemmTN:
                swizzling_functor = SwizzlingFunctor.ConvFpropTrans
            else:
                swizzling_functor = SwizzlingFunctor.ConvFpropNCxHWx
        else:
            if implicit_gemm_mode == ImplicitGemmMode.GemmTN:
                swizzling_functor = SwizzlingFunctor.ConvDgradTrans
            else:
                swizzling_functor = SwizzlingFunctor.ConvDgradNCxHWx

    # skip rule
    def filter_tile_with_layout(tile: TileDescription, layout: LayoutType) -> bool:
        return (
            layout == LayoutType.TensorNC32HW32 and tile.threadblock_shape[0] % 32 != 0
        )

    # rule for bias_type and epilogues
    def get_bias_type_and_epilogues(
        tile: TileDescription, out_dtype: DataType
    ) -> Tuple[DataType, List[EpilogueFunctor]]:
        if (
            tile.math_instruction.element_accumulator == DataType.s32
            and out_dtype != DataType.f32
        ):
            bias_type = DataType.s32
            if tile.math_instruction.element_b == DataType.u4:
                epilogues = [
                    EpilogueFunctor.BiasAddLinearCombinationClamp,
                    EpilogueFunctor.BiasAddLinearCombinationReluClamp,
                ]
            else:
                epilogues = [
                    EpilogueFunctor.BiasAddLinearCombinationClamp,
                    EpilogueFunctor.BiasAddLinearCombinationReluClamp,
                    EpilogueFunctor.BiasAddLinearCombinationHSwishClamp,
                ]
        elif (
            tile.math_instruction.element_accumulator == DataType.f32
            or tile.math_instruction.element_accumulator == DataType.f16
        ) or (
            tile.math_instruction.element_accumulator == DataType.s32
            and out_dtype == DataType.f32
        ):
            bias_type = out_dtype
            epilogues = [
                EpilogueFunctor.BiasAddLinearCombination,
                EpilogueFunctor.BiasAddLinearCombinationRelu,
            ]
            if conv_type == ConvType.Convolution:
                epilogues.append(EpilogueFunctor.BiasAddLinearCombinationHSwish)
        else:
            assert False, "invalid path"
        return bias_type, epilogues

    # rule for filter alignment
    def get_flt_align(tile: TileDescription) -> int:
        nonlocal flt_align
        if (
            tile.math_instruction.opcode_class == OpcodeClass.Simt
            and tile.math_instruction.element_accumulator == DataType.s32
        ):
            thread_num = (
                tile.warp_count[0] * tile.warp_count[1] * tile.warp_count[2] * 32
            )
            flt_block = (
                tile.threadblock_shape[0]
                * tile.threadblock_shape[2]
                * DataTypeSize[tile.math_instruction.element_a]
            )
            load_per_thread = flt_block // thread_num
            if load_per_thread >= 128:
                flt_align = 128
            elif load_per_thread >= 64:
                flt_align = 64
            else:
                assert load_per_thread >= 32
                flt_align = 32
        return flt_align

    def get_dst_align(tile: TileDescription, out_layout: LayoutType) -> int:
        nonlocal dst_align
        if (
            tile.math_instruction.opcode_class == OpcodeClass.TensorOp
            and dst_layout == LayoutType.TensorNC4HW4
        ):
            dst_align = 32
        return dst_align

    def filter_epilogue_with_conv_kind(
        epilogue: EpilogueFunctor, conv_kind: ConvKind
    ) -> bool:
        return (
548
            (conv_kind == ConvKind.Dgrad or conv_kind == ConvKind.Wgrad)
549
            and epilogue != EpilogueFunctor.BiasAddLinearCombinationClamp
550
            and epilogue != EpilogueFunctor.BiasAddLinearCombination
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628
        )

    # loop over all tile descriptions
    for tile in tile_descriptions:
        if filter_tile_with_layout(tile, dst_layout):
            continue

        bias_type, epilogues = get_bias_type_and_epilogues(tile, dst_type)

        flt_align = get_flt_align(tile)

        dst_align = get_dst_align(tile, dst_layout)

        for epilogue in epilogues:
            if filter_epilogue_with_conv_kind(epilogue, conv_kind):
                continue

            if dst_type == DataType.f32:
                bias_type = DataType.f32
            #
            src = TensorDescription(
                tile.math_instruction.element_b,
                src_layout,
                int(src_align / DataTypeSize[tile.math_instruction.element_b]),
            )
            flt = TensorDescription(
                tile.math_instruction.element_a,
                flt_layout,
                int(flt_align / DataTypeSize[tile.math_instruction.element_a]),
            )
            bias = TensorDescription(
                bias_type, dst_layout, max(1, int(32 / DataTypeSize[bias_type]))
            )
            dst = TensorDescription(
                dst_type, dst_layout, int(dst_align / DataTypeSize[dst_type])
            )

            new_operation = Conv2dOperation(
                conv_kind,
                conv_type,
                min_cc,
                tile,
                src,
                flt,
                bias,
                dst,
                element_epilogue,
                epilogue,
                swizzling_functor,
                SpecialOptimizeDesc.NoneSpecialOpt,
                implicit_gemm_mode,
                without_shared_load,
                required_cuda_ver_major,
                required_cuda_ver_minor,
            )
            operations.append(new_operation)
            if use_special_optimization != SpecialOptimizeDesc.NoneSpecialOpt:
                new_operation = Conv2dOperation(
                    conv_kind,
                    conv_type,
                    min_cc,
                    tile,
                    src,
                    flt,
                    bias,
                    dst,
                    element_epilogue,
                    epilogue,
                    swizzling_functor,
                    use_special_optimization,
                    implicit_gemm_mode,
                    without_shared_load,
                    required_cuda_ver_major,
                    required_cuda_ver_minor,
                )
                operations.append(new_operation)
    return operations

629 630 631 632 633 634 635

###################################################################################################
#
# Emitters functions for all targets
#
###################################################################################################

636

637
class EmitConv2dConfigurationLibrary:
638 639 640 641 642
    def __init__(self, operation_path, configuration_name):
        self.configuration_name = configuration_name
        self.configuration_path = os.path.join(
            operation_path, "%s.cu" % configuration_name
        )
643

644
        self.instance_emitter = EmitConv2dInstance()
645

646
        self.instance_template = """
647 648 649 650 651 652 653 654 655
${operation_instance}

// Derived class
struct ${operation_name} : 
  public ${operation_name}_base { };

///////////////////////////////////////////////////////////////////////////////////////////////////

"""
656
        self.header_template = """
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
/*
  Generated by conv2d_operation.py - Do not edit.
*/

///////////////////////////////////////////////////////////////////////////////////////////////////

#include "cutlass/cutlass.h"
#include "cutlass/library/library.h"
#include "cutlass/library/manifest.h"

#include "library_internal.h"
#include "conv2d_operation.h"

///////////////////////////////////////////////////////////////////////////////////////////////////
"""

673
        self.configuration_header = """
674 675 676 677 678 679 680 681 682

namespace cutlass {
namespace library {

// Initialize all instances
void initialize_${configuration_name}(Manifest &manifest) {

"""

683
        self.configuration_instance = """
684 685 686 687 688 689 690 691 692
  using Operation_${operation_name} = cutlass::conv::device::ImplicitGemmConvolution<
    ${operation_name}>;

  manifest.append(new cutlass::library::Conv2dOperation<
    Operation_${operation_name}>(
      "${operation_name}"));

"""

693
        self.configuration_epilogue = """
694 695
}
"""
696
        self.epilogue_template = """
697 698 699 700 701 702 703 704 705 706

///////////////////////////////////////////////////////////////////////////////////////////////////

} // namespace library
} // namespace cutlass

///////////////////////////////////////////////////////////////////////////////////////////////////

"""

707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
    #
    def __enter__(self):
        self.configuration_file = open(self.configuration_path, "w")
        self.configuration_file.write(
            SubstituteTemplate(
                self.header_template, {"configuration_name": self.configuration_name}
            )
        )
        self.operations = []
        return self

    #
    def emit(self, operation):
        self.operations.append(operation)
        self.configuration_file.write(
            SubstituteTemplate(
                self.instance_template,
                {
                    "configuration_name": self.configuration_name,
                    "operation_name": operation.procedural_name(),
                    "operation_instance": self.instance_emitter.emit(operation),
                },
            )
        )

    #
    def __exit__(self, exception_type, exception_value, traceback):

        self.configuration_file.write(
            SubstituteTemplate(
                self.configuration_header,
                {"configuration_name": self.configuration_name},
            )
        )

        for operation in self.operations:
            self.configuration_file.write(
                SubstituteTemplate(
                    self.configuration_instance,
                    {
                        "configuration_name": self.configuration_name,
                        "operation_name": operation.procedural_name(),
                    },
                )
            )

        self.configuration_file.write(self.configuration_epilogue)
        self.configuration_file.write(self.epilogue_template)
        self.configuration_file.close()

757 758 759 760 761 762 763 764

###################################################################################################
###################################################################################################

# Emitters for Conv Kernel Wrapper
#
###################################################################################################

765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780

class EmitConvSingleKernelWrapper:
    def __init__(self, kernel_path, operation, short_path=False):
        self.kernel_path = kernel_path
        self.operation = operation
        self.short_path = short_path

        if self.operation.conv_kind == ConvKind.Fprop:
            self.instance_emitter = EmitConv2dInstance()
            self.convolution_name = "Convolution"
        else:
            assert self.operation.conv_kind == ConvKind.Dgrad
            self.instance_emitter = EmitDeconvInstance()
            self.convolution_name = "Deconvolution"

        self.header_template = """
781
#if __CUDACC_VER_MAJOR__ > ${required_cuda_ver_major} || (__CUDACC_VER_MAJOR__ == ${required_cuda_ver_major} && __CUDACC_VER_MINOR__ >= ${required_cuda_ver_minor})
782 783 784 785
// ignore warning of cutlass
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
786 787 788 789 790 791 792
#pragma GCC diagnostic ignored "-Wuninitialized"
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"

#include "cutlass/convolution/device/convolution.h"

#include "src/cuda/cutlass/manifest.h"
#include "src/cuda/cutlass/convolution_operation.h"
793
"""
794
        self.instance_template = """
795 796
${operation_instance}
"""
797

798
        self.manifest_template = """
799 800 801 802 803 804 805 806 807 808 809
namespace cutlass {
namespace library {

void initialize_${operation_name}(Manifest &manifest) {
  manifest.append(new ConvolutionOperation<${convolution_name}>(
    "${operation_name}"
  ));
}

}  // namespace library
}  // namespace cutlass
810 811
"""

812
        self.epilogue_template = """
813 814 815 816
#pragma GCC diagnostic pop
#endif
"""

817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
    #
    def __enter__(self):
        if self.short_path:
            self.kernel_path = os.path.join(self.kernel_path, "%s.cu" % GlobalCnt.cnt)
            GlobalCnt.cnt += 1
        else:
            self.kernel_path = os.path.join(
                self.kernel_path, "%s.cu" % self.operation.procedural_name()
            )
        self.kernel_file = open(self.kernel_path, "w")
        self.kernel_file.write(
            SubstituteTemplate(
                self.header_template,
                {
                    "required_cuda_ver_major": str(
                        self.operation.required_cuda_ver_major
                    ),
                    "required_cuda_ver_minor": str(
                        self.operation.required_cuda_ver_minor
                    ),
                },
            )
        )
        return self

    #
    def emit(self):
        self.kernel_file.write(
            SubstituteTemplate(
                self.instance_template,
                {"operation_instance": self.instance_emitter.emit(self.operation)},
            )
        )

        # emit manifest helper
        manifest = SubstituteTemplate(
            self.manifest_template,
            {
                "operation_name": self.operation.procedural_name(),
                "convolution_name": self.convolution_name,
            },
        )
        self.kernel_file.write(manifest)

    #
    def __exit__(self, exception_type, exception_value, traceback):
        self.kernel_file.write(self.epilogue_template)
        self.kernel_file.close()
865 866 867 868


###################################################################################################
###################################################################################################